2 * Copyright (C) 2005-2010 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
21 #include "Database/DatabaseEnv.h"
26 #include "WorldPacket.h"
27 #include "WorldSession.h"
28 #include "UpdateMask.h"
31 #include "SkillDiscovery.h"
33 #include "GossipDef.h"
34 #include "UpdateData.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"
43 #include "ObjectMgr.h"
44 #include "ObjectAccessor.h"
45 #include "ObjectGuid.h"
46 #include "CreatureAI.h"
52 #include "Transports.h"
54 #include "BattleGround.h"
55 #include "BattleGroundAV.h"
56 #include "BattleGroundMgr.h"
57 #include "ArenaTeam.h"
59 #include "Database/DatabaseImpl.h"
61 #include "SocialMgr.h"
62 #include "AchievementMgr.h"
67 #define ZONE_UPDATE_INTERVAL (1*IN_MILLISECONDS)
69 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
70 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
71 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
73 #define SKILL_VALUE(x) PAIR32_LOPART(x)
74 #define SKILL_MAX(x) PAIR32_HIPART(x)
75 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
77 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
78 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
79 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
83 CHARACTER_FLAG_NONE
= 0x00000000,
84 CHARACTER_FLAG_UNK1
= 0x00000001,
85 CHARACTER_FLAG_UNK2
= 0x00000002,
86 CHARACTER_LOCKED_FOR_TRANSFER
= 0x00000004,
87 CHARACTER_FLAG_UNK4
= 0x00000008,
88 CHARACTER_FLAG_UNK5
= 0x00000010,
89 CHARACTER_FLAG_UNK6
= 0x00000020,
90 CHARACTER_FLAG_UNK7
= 0x00000040,
91 CHARACTER_FLAG_UNK8
= 0x00000080,
92 CHARACTER_FLAG_UNK9
= 0x00000100,
93 CHARACTER_FLAG_UNK10
= 0x00000200,
94 CHARACTER_FLAG_HIDE_HELM
= 0x00000400,
95 CHARACTER_FLAG_HIDE_CLOAK
= 0x00000800,
96 CHARACTER_FLAG_UNK13
= 0x00001000,
97 CHARACTER_FLAG_GHOST
= 0x00002000,
98 CHARACTER_FLAG_RENAME
= 0x00004000,
99 CHARACTER_FLAG_UNK16
= 0x00008000,
100 CHARACTER_FLAG_UNK17
= 0x00010000,
101 CHARACTER_FLAG_UNK18
= 0x00020000,
102 CHARACTER_FLAG_UNK19
= 0x00040000,
103 CHARACTER_FLAG_UNK20
= 0x00080000,
104 CHARACTER_FLAG_UNK21
= 0x00100000,
105 CHARACTER_FLAG_UNK22
= 0x00200000,
106 CHARACTER_FLAG_UNK23
= 0x00400000,
107 CHARACTER_FLAG_UNK24
= 0x00800000,
108 CHARACTER_FLAG_LOCKED_BY_BILLING
= 0x01000000,
109 CHARACTER_FLAG_DECLINED
= 0x02000000,
110 CHARACTER_FLAG_UNK27
= 0x04000000,
111 CHARACTER_FLAG_UNK28
= 0x08000000,
112 CHARACTER_FLAG_UNK29
= 0x10000000,
113 CHARACTER_FLAG_UNK30
= 0x20000000,
114 CHARACTER_FLAG_UNK31
= 0x40000000,
115 CHARACTER_FLAG_UNK32
= 0x80000000
118 enum CharacterCustomizeFlags
120 CHAR_CUSTOMIZE_FLAG_NONE
= 0x00000000,
121 CHAR_CUSTOMIZE_FLAG_CUSTOMIZE
= 0x00000001, // name, gender, etc...
122 CHAR_CUSTOMIZE_FLAG_FACTION
= 0x00010000, // name, gender, faction, etc...
123 CHAR_CUSTOMIZE_FLAG_RACE
= 0x00100000 // name, gender, race, etc...
126 // corpse reclaim times
127 #define DEATH_EXPIRE_STEP (5*MINUTE)
128 #define MAX_DEATH_COUNT 3
130 static uint32 copseReclaimDelay
[MAX_DEATH_COUNT
] = { 30, 60, 120 };
132 //== PlayerTaxi ================================================
134 PlayerTaxi::PlayerTaxi()
137 memset(m_taximask
, 0, sizeof(m_taximask
));
140 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race
, uint32 chrClass
, uint32 level
)
142 // class specific initial known nodes
145 case CLASS_DEATH_KNIGHT
:
147 for(int i
= 0; i
< TaxiMaskSize
; ++i
)
148 m_taximask
[i
] |= sOldContinentsNodesMask
[i
];
153 // race specific initial known nodes: capital and taxi hub masks
156 case RACE_HUMAN
: SetTaximaskNode(2); break; // Human
157 case RACE_ORC
: SetTaximaskNode(23); break; // Orc
158 case RACE_DWARF
: SetTaximaskNode(6); break; // Dwarf
159 case RACE_NIGHTELF
: SetTaximaskNode(26);
160 SetTaximaskNode(27); break; // Night Elf
161 case RACE_UNDEAD_PLAYER
: SetTaximaskNode(11); break;// Undead
162 case RACE_TAUREN
: SetTaximaskNode(22); break; // Tauren
163 case RACE_GNOME
: SetTaximaskNode(6); break; // Gnome
164 case RACE_TROLL
: SetTaximaskNode(23); break; // Troll
165 case RACE_BLOODELF
: SetTaximaskNode(82); break; // Blood Elf
166 case RACE_DRAENEI
: SetTaximaskNode(94); break; // Draenei
169 // new continent starting masks (It will be accessible only at new map)
170 switch(Player::TeamForRace(race
))
172 case ALLIANCE
: SetTaximaskNode(100); break;
173 case HORDE
: SetTaximaskNode(99); break;
175 // level dependent taxi hubs
177 SetTaximaskNode(213); //Shattered Sun Staging Area
180 void PlayerTaxi::LoadTaxiMask(const char* data
)
182 Tokens tokens
= StrSplit(data
, " ");
185 Tokens::iterator iter
;
186 for (iter
= tokens
.begin(), index
= 0;
187 (index
< TaxiMaskSize
) && (iter
!= tokens
.end()); ++iter
, ++index
)
189 // load and set bits only for existed taxi nodes
190 m_taximask
[index
] = sTaxiNodesMask
[index
] & uint32(atol((*iter
).c_str()));
194 void PlayerTaxi::AppendTaximaskTo( ByteBuffer
& data
, bool all
)
198 for (uint8 i
=0; i
<TaxiMaskSize
; ++i
)
199 data
<< uint32(sTaxiNodesMask
[i
]); // all existed nodes
203 for (uint8 i
=0; i
<TaxiMaskSize
; ++i
)
204 data
<< uint32(m_taximask
[i
]); // known nodes
208 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string
& values
, uint32 team
)
210 ClearTaxiDestinations();
212 Tokens tokens
= StrSplit(values
," ");
214 for(Tokens::iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
)
216 uint32 node
= uint32(atol(iter
->c_str()));
217 AddTaxiDestination(node
);
220 if(m_TaxiDestinations
.empty())
224 if(m_TaxiDestinations
.size() < 2)
227 for(size_t i
= 1; i
< m_TaxiDestinations
.size(); ++i
)
231 sObjectMgr
.GetTaxiPath(m_TaxiDestinations
[i
-1],m_TaxiDestinations
[i
],path
,cost
);
236 // can't load taxi path without mount set (quest taxi path?)
237 if(!sObjectMgr
.GetTaxiMountDisplayId(GetTaxiSource(),team
,true))
243 std::string
PlayerTaxi::SaveTaxiDestinationsToString()
245 if(m_TaxiDestinations
.empty())
248 std::ostringstream ss
;
250 for(size_t i
=0; i
< m_TaxiDestinations
.size(); ++i
)
251 ss
<< m_TaxiDestinations
[i
] << " ";
256 uint32
PlayerTaxi::GetCurrentTaxiPath() const
258 if(m_TaxiDestinations
.size() < 2)
264 sObjectMgr
.GetTaxiPath(m_TaxiDestinations
[0],m_TaxiDestinations
[1],path
,cost
);
269 std::ostringstream
& operator<< (std::ostringstream
& ss
, PlayerTaxi
const& taxi
)
272 for(int i
= 0; i
< TaxiMaskSize
; ++i
)
273 ss
<< taxi
.m_taximask
[i
] << " ";
278 SpellModifier::SpellModifier( SpellModOp _op
, SpellModType _type
, int32 _value
, SpellEntry
const* spellEntry
, SpellEffectIndex eff
, int16 _charges
/*= 0*/ ) : op(_op
), type(_type
), charges(_charges
), value(_value
), spellId(spellEntry
->Id
), lastAffected(NULL
)
280 uint32
const* ptr
= spellEntry
->GetEffectSpellClassMask(eff
);
281 mask
= uint64(ptr
[0]) | (uint64(ptr
[1]) << 32);
285 SpellModifier::SpellModifier( SpellModOp _op
, SpellModType _type
, int32 _value
, Aura
const* aura
, int16 _charges
/*= 0*/ ) : op(_op
), type(_type
), charges(_charges
), value(_value
), spellId(aura
->GetId()), lastAffected(NULL
)
287 uint32
const* ptr
= aura
->getAuraSpellClassMask();
288 mask
= uint64(ptr
[0]) | (uint64(ptr
[1]) << 32);
292 bool SpellModifier::isAffectedOnSpell( SpellEntry
const *spell
) const
294 SpellEntry
const *affect_spell
= sSpellStore
.LookupEntry(spellId
);
295 // False if affect_spell == NULL or spellFamily not equal
296 if (!affect_spell
|| affect_spell
->SpellFamilyName
!= spell
->SpellFamilyName
)
298 if (mask
& spell
->SpellFamilyFlags
)
300 if (mask2
& spell
->SpellFamilyFlags2
)
305 //== Player ====================================================
307 UpdateMask
Player::updateVisualBits
;
309 Player::Player (WorldSession
*session
): Unit(), m_achievementMgr(this), m_reputationMgr(this)
316 m_objectType
|= TYPEMASK_PLAYER
;
317 m_objectTypeId
= TYPEID_PLAYER
;
319 m_valuesCount
= PLAYER_END
;
326 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER
)
327 SetAcceptTicket(true);
329 // players always accept
330 if(GetSession()->GetSecurity() == SEC_PLAYER
)
331 SetAcceptWhispers(true);
339 m_usedTalentCount
= 0;
340 m_questRewardTalentCount
= 0;
343 m_weaponChangeTimer
= 0;
346 m_zoneUpdateTimer
= 0;
350 m_nextSave
= sWorld
.getConfig(CONFIG_UINT32_INTERVAL_SAVE
);
352 // randomize first save time in range [CONFIG_UINT32_INTERVAL_SAVE] around [CONFIG_UINT32_INTERVAL_SAVE]
353 // this must help in case next save after mass player load after server startup
354 m_nextSave
= urand(m_nextSave
/2,m_nextSave
*3/2);
356 clearResurrectRequestData();
358 m_SpellModRemoveCount
= 0;
360 memset(m_items
, 0, sizeof(Item
*)*PLAYER_SLOTS_COUNT
);
364 // group is initialized in the reference constructor
365 SetGroupInvite(NULL
);
366 m_groupUpdateMask
= 0;
367 m_auraUpdateMask
= 0;
371 m_GuildIdInvited
= 0;
372 m_ArenaTeamIdInvited
= 0;
374 m_atLoginFlags
= AT_LOGIN_NONE
;
376 mSemaphoreTeleport_Near
= false;
377 mSemaphoreTeleport_Far
= false;
379 m_DelayedOperations
= 0;
380 m_bCanDelayTeleport
= false;
381 m_bHasDelayedTeleport
= false;
382 m_teleport_options
= 0;
389 PlayerTalkClass
= new PlayerMenu( GetSession() );
390 m_currentBuybackSlot
= BUYBACK_SLOT_START
;
392 m_DailyQuestChanged
= false;
393 m_lastDailyQuestTime
= 0;
395 for (int i
=0; i
<MAX_TIMERS
; ++i
)
396 m_MirrorTimer
[i
] = DISABLED_MIRROR_TIMER
;
398 m_MirrorTimerFlags
= UNDERWATER_NONE
;
399 m_MirrorTimerFlagsLast
= UNDERWATER_NONE
;
405 m_deathExpireTime
= 0;
409 m_DetectInvTimer
= 1*IN_MILLISECONDS
;
411 for (int j
=0; j
< PLAYER_MAX_BATTLEGROUND_QUEUES
; ++j
)
413 m_bgBattleGroundQueueID
[j
].bgQueueTypeId
= BATTLEGROUND_QUEUE_NONE
;
414 m_bgBattleGroundQueueID
[j
].invitedToInstance
= 0;
417 m_logintime
= time(NULL
);
418 m_Last_tick
= m_logintime
;
419 m_WeaponProficiency
= 0;
420 m_ArmorProficiency
= 0;
423 m_canDualWield
= false;
424 m_canTitanGrip
= false;
427 m_temporaryUnsummonedPetNumber
= 0;
428 //cache for UNIT_CREATED_BY_SPELL to allow
429 //returning reagents for temporarily removed pets
430 //when dying/logging out
433 ////////////////////Rest System/////////////////////
437 rest_type
=REST_TYPE_NO
;
438 ////////////////////Rest System/////////////////////
440 m_mailsUpdated
= false;
442 m_nextMailDelivereTime
= 0;
444 m_resetTalentsCost
= 0;
445 m_resetTalentsTime
= 0;
446 m_itemUpdateQueueBlocked
= false;
448 for (int i
= 0; i
< MAX_MOVE_TYPE
; ++i
)
449 m_forced_speed_changes
[i
] = 0;
453 /////////////////// Instance System /////////////////////
456 m_InstanceValid
= true;
457 m_dungeonDifficulty
= DUNGEON_DIFFICULTY_NORMAL
;
458 m_raidDifficulty
= RAID_DIFFICULTY_10MAN_NORMAL
;
465 for (int i
= 0; i
< BASEMOD_END
; ++i
)
467 m_auraBaseMod
[i
][FLAT_MOD
] = 0.0f
;
468 m_auraBaseMod
[i
][PCT_MOD
] = 1.0f
;
471 for (int i
= 0; i
< MAX_COMBAT_RATING
; ++i
)
472 m_baseRatingValue
[i
] = 0;
474 m_baseSpellPower
= 0;
477 m_armorPenetrationPct
= 0.0f
;
480 m_lastHonorUpdateTime
= time(NULL
);
492 m_contestedPvPTimer
= 0;
494 m_declinedname
= NULL
;
503 CleanupsBeforeDelete();
505 // it must be unloaded already in PlayerLogout and accessed only for loggined player
508 // Note: buy back item already deleted from DB when player was saved
509 for(int i
= 0; i
< PLAYER_SLOTS_COUNT
; ++i
)
516 //all mailed items should be deleted, also all mail should be deallocated
517 for (PlayerMails::const_iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
520 for (ItemMap::const_iterator iter
= mMitems
.begin(); iter
!= mMitems
.end(); ++iter
)
521 delete iter
->second
; //if item is duplicated... then server may crash ... but that item should be deallocated
523 delete PlayerTalkClass
;
527 m_transport
->RemovePassenger(this);
530 for(size_t x
= 0; x
< ItemSetEff
.size(); x
++)
532 delete ItemSetEff
[x
];
534 // clean up player-instance binds, may unload some instance saves
535 for(uint8 i
= 0; i
< MAX_DIFFICULTY
; ++i
)
536 for(BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
537 itr
->second
.save
->RemovePlayer(this);
539 delete m_declinedname
;
543 void Player::CleanupsBeforeDelete()
545 if(m_uint32Values
) // only for fully created Object
548 DuelComplete(DUEL_INTERUPTED
);
550 Unit::CleanupsBeforeDelete();
553 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 */)
555 //FIXME: outfitId not used in player creating
557 Object::_Create(guidlow
, 0, HIGHGUID_PLAYER
);
561 PlayerInfo
const* info
= sObjectMgr
.GetPlayerInfo(race
, class_
);
564 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
568 for (int i
= 0; i
< PLAYER_SLOTS_COUNT
; ++i
)
571 SetLocationMapId(info
->mapId
);
572 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
);
574 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(class_
);
577 sLog
.outError("Class %u not found in DBC (Wrong DBC files?)",class_
);
581 SetMap(sMapMgr
.CreateMap(info
->mapId
, this));
583 uint8 powertype
= cEntry
->powerType
;
585 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, DEFAULT_WORLD_OBJECT_SIZE
);
586 SetFloatValue(UNIT_FIELD_COMBATREACH
, 1.5f
);
588 setFactionForRace(race
);
590 uint32 RaceClassGender
= ( race
) | ( class_
<< 8 ) | ( gender
<< 16 );
592 SetUInt32Value(UNIT_FIELD_BYTES_0
, ( RaceClassGender
| ( powertype
<< 24 ) ) );
594 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_PVP
);
595 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
);
596 SetFlag(UNIT_FIELD_FLAGS_2
, UNIT_FLAG2_REGENERATE_POWER
);
597 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
); // fix cast time showed in spell tooltip on client
598 SetFloatValue(UNIT_FIELD_HOVERHEIGHT
, 1.0f
); // default for players in 3.0.3
600 // -1 is default value
601 SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX
, -1);
603 SetUInt32Value(PLAYER_BYTES
, (skin
| (face
<< 8) | (hairStyle
<< 16) | (hairColor
<< 24)));
604 SetUInt32Value(PLAYER_BYTES_2
, (facialHair
| (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
605 SetByteValue(PLAYER_BYTES_3
, 0, gender
);
607 SetUInt32Value( PLAYER_GUILDID
, 0 );
608 SetUInt32Value( PLAYER_GUILDRANK
, 0 );
609 SetUInt32Value( PLAYER_GUILD_TIMESTAMP
, 0 );
611 for(int i
= 0; i
< KNOWN_TITLES_SIZE
; ++i
)
612 SetUInt64Value(PLAYER__FIELD_KNOWN_TITLES
+ i
, 0); // 0=disabled
613 SetUInt32Value( PLAYER_CHOSEN_TITLE
, 0 );
615 SetUInt32Value( PLAYER_FIELD_KILLS
, 0 );
616 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 0 );
617 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION
, 0 );
618 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0 );
620 // set starting level
621 uint32 start_level
= getClass() != CLASS_DEATH_KNIGHT
622 ? sWorld
.getConfig(CONFIG_UINT32_START_PLAYER_LEVEL
)
623 : sWorld
.getConfig(CONFIG_UINT32_START_HEROIC_PLAYER_LEVEL
);
625 if (GetSession()->GetSecurity() >= SEC_MODERATOR
)
627 uint32 gm_level
= sWorld
.getConfig(CONFIG_UINT32_START_GM_LEVEL
);
628 if(gm_level
> start_level
)
629 start_level
= gm_level
;
632 SetUInt32Value(UNIT_FIELD_LEVEL
, start_level
);
636 SetUInt32Value (PLAYER_FIELD_COINAGE
, sWorld
.getConfig(CONFIG_UINT32_START_PLAYER_MONEY
));
637 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_UINT32_START_HONOR_POINTS
));
638 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_UINT32_START_ARENA_POINTS
));
641 m_Last_tick
= time(NULL
);
642 m_Played_time
[PLAYED_TIME_TOTAL
] = 0;
643 m_Played_time
[PLAYED_TIME_LEVEL
] = 0;
645 // base stats and related field values
647 InitTaxiNodesForLevel();
648 InitGlyphsForLevel();
649 InitTalentForLevel();
650 InitPrimaryProfessions(); // to max set before any spell added
652 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
653 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
654 SetHealth(GetMaxHealth());
655 if (getPowerType()==POWER_MANA
)
657 UpdateMaxPower(POWER_MANA
); // Update max Mana (for add bonus from intellect)
658 SetPower(POWER_MANA
,GetMaxPower(POWER_MANA
));
661 if(getPowerType() == POWER_RUNIC_POWER
)
663 SetPower(POWER_RUNE
, 8);
664 SetMaxPower(POWER_RUNE
, 8);
665 SetPower(POWER_RUNIC_POWER
, 0);
666 SetMaxPower(POWER_RUNIC_POWER
, 1000);
670 learnDefaultSpells();
672 // original action bar
673 for (PlayerCreateInfoActions::const_iterator action_itr
= info
->action
.begin(); action_itr
!= info
->action
.end(); ++action_itr
)
674 addActionButton(0, action_itr
->button
,action_itr
->action
,action_itr
->type
);
677 CharStartOutfitEntry
const* oEntry
= NULL
;
678 for (uint32 i
= 1; i
< sCharStartOutfitStore
.GetNumRows(); ++i
)
680 if(CharStartOutfitEntry
const* entry
= sCharStartOutfitStore
.LookupEntry(i
))
682 if(entry
->RaceClassGender
== RaceClassGender
)
692 for(int j
= 0; j
< MAX_OUTFIT_ITEMS
; ++j
)
694 if(oEntry
->ItemId
[j
] <= 0)
697 uint32 item_id
= oEntry
->ItemId
[j
];
699 // just skip, reported in ObjectMgr::LoadItemPrototypes
700 ItemPrototype
const* iProto
= ObjectMgr::GetItemPrototype(item_id
);
704 // BuyCount by default
705 int32 count
= iProto
->BuyCount
;
707 // special amount for foor/drink
708 if(iProto
->Class
==ITEM_CLASS_CONSUMABLE
&& iProto
->SubClass
==ITEM_SUBCLASS_FOOD
)
710 switch(iProto
->Spells
[0].SpellCategory
)
713 count
= getClass()==CLASS_DEATH_KNIGHT
? 10 : 4;
719 if(iProto
->Stackable
< count
)
720 count
= iProto
->Stackable
;
722 // special amount for daggers
723 else if(iProto
->Class
==ITEM_CLASS_WEAPON
&& iProto
->SubClass
==ITEM_SUBCLASS_WEAPON_DAGGER
)
725 count
= 2; // will placed to 2 slots
728 StoreNewItemInBestSlots(item_id
, count
);
732 for (PlayerCreateInfoItems::const_iterator item_id_itr
= info
->item
.begin(); item_id_itr
!=info
->item
.end(); ++item_id_itr
++)
733 StoreNewItemInBestSlots(item_id_itr
->item_id
, item_id_itr
->item_amount
);
735 // bags and main-hand weapon must equipped at this moment
736 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
737 // or ammo not equipped in special bag
738 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
740 if(Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
743 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
744 uint8 msg
= CanEquipItem( NULL_SLOT
, eDest
, pItem
, false );
745 if( msg
== EQUIP_ERR_OK
)
747 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
748 EquipItem( eDest
, pItem
, true);
750 // move other items to more appropriate slots (ammo not equipped in special bag)
753 ItemPosCountVec sDest
;
754 msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, sDest
, pItem
, false );
755 if( msg
== EQUIP_ERR_OK
)
757 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
758 pItem
= StoreItem( sDest
, pItem
, true);
761 // if this is ammo then use it
762 msg
= CanUseAmmo( pItem
->GetEntry() );
763 if( msg
== EQUIP_ERR_OK
)
764 SetAmmo( pItem
->GetEntry() );
768 // all item positions resolved
773 bool Player::StoreNewItemInBestSlots(uint32 titem_id
, uint32 titem_amount
)
775 sLog
.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id
, titem_amount
);
777 // attempt equip by one
778 while(titem_amount
> 0)
781 uint8 msg
= CanEquipNewItem( NULL_SLOT
, eDest
, titem_id
, false );
782 if( msg
!= EQUIP_ERR_OK
)
785 EquipNewItem( eDest
, titem_id
, true);
786 AutoUnequipOffhandIfNeed();
790 if(titem_amount
== 0)
791 return true; // equipped
794 ItemPosCountVec sDest
;
795 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
796 uint8 msg
= CanStoreNewItem( INVENTORY_SLOT_BAG_0
, NULL_SLOT
, sDest
, titem_id
, titem_amount
);
797 if( msg
== EQUIP_ERR_OK
)
799 StoreNewItem( sDest
, titem_id
, true, Item::GenerateItemRandomPropertyId(titem_id
) );
800 return true; // stored
803 // item can't be added
804 sLog
.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id
,getRace(),getClass(),msg
);
808 // helper function, mainly for script side, but can be used for simple task in mangos also.
809 Item
* Player::StoreNewItemInInventorySlot(uint32 itemEntry
, uint32 amount
)
811 ItemPosCountVec vDest
;
813 uint8 msg
= CanStoreNewItem(INVENTORY_SLOT_BAG_0
, NULL_SLOT
, vDest
, itemEntry
, amount
);
815 if (msg
== EQUIP_ERR_OK
)
817 if (Item
* pItem
= StoreNewItem(vDest
, itemEntry
, true, Item::GenerateItemRandomPropertyId(itemEntry
)))
824 void Player::SendMirrorTimer(MirrorTimerType Type
, uint32 MaxValue
, uint32 CurrentValue
, int32 Regen
)
826 if (int(MaxValue
) == DISABLED_MIRROR_TIMER
)
828 if (int(CurrentValue
) != DISABLED_MIRROR_TIMER
)
829 StopMirrorTimer(Type
);
832 WorldPacket
data(SMSG_START_MIRROR_TIMER
, (21));
833 data
<< (uint32
)Type
;
834 data
<< CurrentValue
;
838 data
<< (uint32
)0; // spell id
839 GetSession()->SendPacket( &data
);
842 void Player::StopMirrorTimer(MirrorTimerType Type
)
844 m_MirrorTimer
[Type
] = DISABLED_MIRROR_TIMER
;
845 WorldPacket
data(SMSG_STOP_MIRROR_TIMER
, 4);
846 data
<< (uint32
)Type
;
847 GetSession()->SendPacket( &data
);
850 uint32
Player::EnvironmentalDamage(EnviromentalDamage type
, uint32 damage
)
852 if(!isAlive() || isGameMaster())
855 // Absorb, resist some environmental damage type
858 if (type
== DAMAGE_LAVA
)
859 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE
, DIRECT_DAMAGE
, damage
, &absorb
, &resist
);
860 else if (type
== DAMAGE_SLIME
)
861 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE
, DIRECT_DAMAGE
, damage
, &absorb
, &resist
);
863 damage
-=absorb
+resist
;
865 DealDamageMods(this,damage
,&absorb
);
867 WorldPacket
data(SMSG_ENVIRONMENTALDAMAGELOG
, (21));
868 data
<< uint64(GetGUID());
869 data
<< uint8(type
!=DAMAGE_FALL_TO_VOID
? type
: DAMAGE_FALL
);
870 data
<< uint32(damage
);
871 data
<< uint32(absorb
);
872 data
<< uint32(resist
);
873 SendMessageToSet(&data
, true);
875 uint32 final_damage
= DealDamage(this, damage
, NULL
, SELF_DAMAGE
, SPELL_SCHOOL_MASK_NORMAL
, NULL
, false);
879 if(type
==DAMAGE_FALL
) // DealDamage not apply item durability loss at self damage
881 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
882 DurabilityLossAll(0.10f
,false);
883 // durability lost message
884 WorldPacket
data2(SMSG_DURABILITY_DAMAGE_DEATH
, 0);
885 GetSession()->SendPacket(&data2
);
888 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM
, 1, type
);
894 int32
Player::getMaxTimer(MirrorTimerType timer
)
899 if (GetSession()->GetSecurity() >= (AccountTypes
)sWorld
.getConfig(CONFIG_UINT32_TIMERBAR_FATIGUE_GMLEVEL
))
900 return DISABLED_MIRROR_TIMER
;
901 return sWorld
.getConfig(CONFIG_UINT32_TIMERBAR_FATIGUE_MAX
)*IN_MILLISECONDS
;
904 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING
) ||
905 GetSession()->GetSecurity() >= (AccountTypes
)sWorld
.getConfig(CONFIG_UINT32_TIMERBAR_BREATH_GMLEVEL
))
906 return DISABLED_MIRROR_TIMER
;
907 int32 UnderWaterTime
= sWorld
.getConfig(CONFIG_UINT32_TIMERBAR_BREATH_MAX
)*IN_MILLISECONDS
;
908 AuraList
const& mModWaterBreathing
= GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING
);
909 for(AuraList::const_iterator i
= mModWaterBreathing
.begin(); i
!= mModWaterBreathing
.end(); ++i
)
910 UnderWaterTime
= uint32(UnderWaterTime
* (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
);
911 return UnderWaterTime
;
915 if (!isAlive() || GetSession()->GetSecurity() >= (AccountTypes
)sWorld
.getConfig(CONFIG_UINT32_TIMERBAR_FIRE_GMLEVEL
))
916 return DISABLED_MIRROR_TIMER
;
917 return sWorld
.getConfig(CONFIG_UINT32_TIMERBAR_FIRE_MAX
)*IN_MILLISECONDS
;
925 void Player::UpdateMirrorTimers()
927 // Desync flags for update on next HandleDrowning
928 if (m_MirrorTimerFlags
)
929 m_MirrorTimerFlagsLast
= ~m_MirrorTimerFlags
;
932 void Player::HandleDrowning(uint32 time_diff
)
934 if (!m_MirrorTimerFlags
)
938 if (m_MirrorTimerFlags
& UNDERWATER_INWATER
)
940 // Breath timer not activated - activate it
941 if (m_MirrorTimer
[BREATH_TIMER
] == DISABLED_MIRROR_TIMER
)
943 m_MirrorTimer
[BREATH_TIMER
] = getMaxTimer(BREATH_TIMER
);
944 SendMirrorTimer(BREATH_TIMER
, m_MirrorTimer
[BREATH_TIMER
], m_MirrorTimer
[BREATH_TIMER
], -1);
946 else // If activated - do tick
948 m_MirrorTimer
[BREATH_TIMER
]-=time_diff
;
949 // Timer limit - need deal damage
950 if (m_MirrorTimer
[BREATH_TIMER
] < 0)
952 m_MirrorTimer
[BREATH_TIMER
]+= 1*IN_MILLISECONDS
;
953 // Calculate and deal damage
954 // TODO: Check this formula
955 uint32 damage
= GetMaxHealth() / 5 + urand(0, getLevel()-1);
956 EnvironmentalDamage(DAMAGE_DROWNING
, damage
);
958 else if (!(m_MirrorTimerFlagsLast
& UNDERWATER_INWATER
)) // Update time in client if need
959 SendMirrorTimer(BREATH_TIMER
, getMaxTimer(BREATH_TIMER
), m_MirrorTimer
[BREATH_TIMER
], -1);
962 else if (m_MirrorTimer
[BREATH_TIMER
] != DISABLED_MIRROR_TIMER
) // Regen timer
964 int32 UnderWaterTime
= getMaxTimer(BREATH_TIMER
);
966 m_MirrorTimer
[BREATH_TIMER
]+=10*time_diff
;
967 if (m_MirrorTimer
[BREATH_TIMER
] >= UnderWaterTime
|| !isAlive())
968 StopMirrorTimer(BREATH_TIMER
);
969 else if (m_MirrorTimerFlagsLast
& UNDERWATER_INWATER
)
970 SendMirrorTimer(BREATH_TIMER
, UnderWaterTime
, m_MirrorTimer
[BREATH_TIMER
], 10);
974 if (m_MirrorTimerFlags
& UNDERWATER_INDARKWATER
)
976 // Fatigue timer not activated - activate it
977 if (m_MirrorTimer
[FATIGUE_TIMER
] == DISABLED_MIRROR_TIMER
)
979 m_MirrorTimer
[FATIGUE_TIMER
] = getMaxTimer(FATIGUE_TIMER
);
980 SendMirrorTimer(FATIGUE_TIMER
, m_MirrorTimer
[FATIGUE_TIMER
], m_MirrorTimer
[FATIGUE_TIMER
], -1);
984 m_MirrorTimer
[FATIGUE_TIMER
]-=time_diff
;
985 // Timer limit - need deal damage or teleport ghost to graveyard
986 if (m_MirrorTimer
[FATIGUE_TIMER
] < 0)
988 m_MirrorTimer
[FATIGUE_TIMER
]+= 1*IN_MILLISECONDS
;
989 if (isAlive()) // Calculate and deal damage
991 uint32 damage
= GetMaxHealth() / 5 + urand(0, getLevel()-1);
992 EnvironmentalDamage(DAMAGE_EXHAUSTED
, damage
);
994 else if (HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
)) // Teleport ghost to graveyard
997 else if (!(m_MirrorTimerFlagsLast
& UNDERWATER_INDARKWATER
))
998 SendMirrorTimer(FATIGUE_TIMER
, getMaxTimer(FATIGUE_TIMER
), m_MirrorTimer
[FATIGUE_TIMER
], -1);
1001 else if (m_MirrorTimer
[FATIGUE_TIMER
] != DISABLED_MIRROR_TIMER
) // Regen timer
1003 int32 DarkWaterTime
= getMaxTimer(FATIGUE_TIMER
);
1004 m_MirrorTimer
[FATIGUE_TIMER
]+=10*time_diff
;
1005 if (m_MirrorTimer
[FATIGUE_TIMER
] >= DarkWaterTime
|| !isAlive())
1006 StopMirrorTimer(FATIGUE_TIMER
);
1007 else if (m_MirrorTimerFlagsLast
& UNDERWATER_INDARKWATER
)
1008 SendMirrorTimer(FATIGUE_TIMER
, DarkWaterTime
, m_MirrorTimer
[FATIGUE_TIMER
], 10);
1011 if (m_MirrorTimerFlags
& (UNDERWATER_INLAVA
|UNDERWATER_INSLIME
))
1013 // Breath timer not activated - activate it
1014 if (m_MirrorTimer
[FIRE_TIMER
] == DISABLED_MIRROR_TIMER
)
1015 m_MirrorTimer
[FIRE_TIMER
] = getMaxTimer(FIRE_TIMER
);
1018 m_MirrorTimer
[FIRE_TIMER
]-=time_diff
;
1019 if (m_MirrorTimer
[FIRE_TIMER
] < 0)
1021 m_MirrorTimer
[FIRE_TIMER
]+= 1*IN_MILLISECONDS
;
1022 // Calculate and deal damage
1023 // TODO: Check this formula
1024 uint32 damage
= urand(600, 700);
1025 if (m_MirrorTimerFlags
&UNDERWATER_INLAVA
)
1026 EnvironmentalDamage(DAMAGE_LAVA
, damage
);
1028 EnvironmentalDamage(DAMAGE_SLIME
, damage
);
1033 m_MirrorTimer
[FIRE_TIMER
] = DISABLED_MIRROR_TIMER
;
1035 // Recheck timers flag
1036 m_MirrorTimerFlags
&=~UNDERWATER_EXIST_TIMERS
;
1037 for (int i
= 0; i
< MAX_TIMERS
; ++i
)
1038 if (m_MirrorTimer
[i
]!=DISABLED_MIRROR_TIMER
)
1040 m_MirrorTimerFlags
|=UNDERWATER_EXIST_TIMERS
;
1043 m_MirrorTimerFlagsLast
= m_MirrorTimerFlags
;
1046 ///The player sobers by 256 every 10 seconds
1047 void Player::HandleSobering()
1051 uint32 drunk
= (m_drunk
<= 256) ? 0 : (m_drunk
- 256);
1052 SetDrunkValue(drunk
);
1055 DrunkenState
Player::GetDrunkenstateByValue(uint16 value
)
1058 return DRUNKEN_SMASHED
;
1060 return DRUNKEN_DRUNK
;
1062 return DRUNKEN_TIPSY
;
1063 return DRUNKEN_SOBER
;
1066 void Player::SetDrunkValue(uint16 newDrunkenValue
, uint32 itemId
)
1068 uint32 oldDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
1070 m_drunk
= newDrunkenValue
;
1071 SetUInt32Value(PLAYER_BYTES_3
,(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFF0001) | (m_drunk
& 0xFFFE));
1073 uint32 newDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
1075 // special drunk invisibility detection
1076 if(newDrunkenState
>= DRUNKEN_DRUNK
)
1077 m_detectInvisibilityMask
|= (1<<6);
1079 m_detectInvisibilityMask
&= ~(1<<6);
1081 if(newDrunkenState
== oldDrunkenState
)
1084 WorldPacket
data(SMSG_CROSSED_INEBRIATION_THRESHOLD
, (8+4+4));
1085 data
<< uint64(GetGUID());
1086 data
<< uint32(newDrunkenState
);
1087 data
<< uint32(itemId
);
1089 SendMessageToSet(&data
, true);
1092 void Player::Update( uint32 p_time
)
1098 if(m_nextMailDelivereTime
&& m_nextMailDelivereTime
<= time(NULL
))
1103 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1104 m_nextMailDelivereTime
= 0;
1107 //used to implement delayed far teleports
1108 SetCanDelayTeleport(true);
1109 Unit::Update( p_time
);
1110 SetCanDelayTeleport(false);
1112 // update player only attacks
1113 if(uint32 ranged_att
= getAttackTimer(RANGED_ATTACK
))
1115 setAttackTimer(RANGED_ATTACK
, (p_time
>= ranged_att
? 0 : ranged_att
- p_time
) );
1118 if(uint32 off_att
= getAttackTimer(OFF_ATTACK
))
1120 setAttackTimer(OFF_ATTACK
, (p_time
>= off_att
? 0 : off_att
- p_time
) );
1123 time_t now
= time (NULL
);
1127 UpdateContestedPvP(p_time
);
1129 UpdateDuelFlag(now
);
1131 CheckDuelDistance(now
);
1133 UpdateAfkReport(now
);
1135 // Update items that have just a limited lifetime
1136 if (now
>m_Last_tick
)
1137 UpdateItemDuration(uint32(now
- m_Last_tick
));
1139 if (!m_timedquests
.empty())
1141 std::set
<uint32
>::iterator iter
= m_timedquests
.begin();
1142 while (iter
!= m_timedquests
.end())
1144 QuestStatusData
& q_status
= mQuestStatus
[*iter
];
1145 if( q_status
.m_timer
<= p_time
)
1147 uint32 quest_id
= *iter
;
1148 ++iter
; // current iter will be removed in FailQuest
1149 FailQuest(quest_id
);
1153 q_status
.m_timer
-= p_time
;
1154 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
1160 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING
))
1162 Unit
*pVictim
= getVictim();
1163 if (pVictim
&& !IsNonMeleeSpellCasted(false))
1165 // default combat reach 10
1166 // TODO add weapon,skill check
1168 float pldistance
= ATTACK_DISTANCE
;
1170 if (isAttackReady(BASE_ATTACK
))
1172 if(!IsWithinDistInMap(pVictim
, pldistance
))
1174 setAttackTimer(BASE_ATTACK
,100);
1175 if(m_swingErrorMsg
!= 1) // send single time (client auto repeat)
1177 SendAttackSwingNotInRange();
1178 m_swingErrorMsg
= 1;
1181 //120 degrees of radiant range
1182 else if( !HasInArc( 2*M_PI_F
/3, pVictim
))
1184 setAttackTimer(BASE_ATTACK
,100);
1185 if(m_swingErrorMsg
!= 2) // send single time (client auto repeat)
1187 SendAttackSwingBadFacingAttack();
1188 m_swingErrorMsg
= 2;
1193 m_swingErrorMsg
= 0; // reset swing error state
1195 // prevent base and off attack in same time, delay attack at 0.2 sec
1196 if(haveOffhandWeapon())
1198 uint32 off_att
= getAttackTimer(OFF_ATTACK
);
1199 if(off_att
< ATTACK_DISPLAY_DELAY
)
1200 setAttackTimer(OFF_ATTACK
,ATTACK_DISPLAY_DELAY
);
1202 AttackerStateUpdate(pVictim
, BASE_ATTACK
);
1203 resetAttackTimer(BASE_ATTACK
);
1207 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK
))
1209 if(!IsWithinDistInMap(pVictim
, pldistance
))
1211 setAttackTimer(OFF_ATTACK
,100);
1213 else if( !HasInArc( 2*M_PI_F
/3, pVictim
))
1215 setAttackTimer(OFF_ATTACK
,100);
1219 // prevent base and off attack in same time, delay attack at 0.2 sec
1220 uint32 base_att
= getAttackTimer(BASE_ATTACK
);
1221 if(base_att
< ATTACK_DISPLAY_DELAY
)
1222 setAttackTimer(BASE_ATTACK
,ATTACK_DISPLAY_DELAY
);
1224 AttackerStateUpdate(pVictim
, OFF_ATTACK
);
1225 resetAttackTimer(OFF_ATTACK
);
1229 Unit
*owner
= pVictim
->GetOwner();
1230 Unit
*u
= owner
? owner
: pVictim
;
1231 if(u
->IsPvP() && (!duel
|| duel
->opponent
!= u
))
1234 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT
);
1239 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
))
1241 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1243 time_t time_inn
= time(NULL
)-GetTimeInnEnter();
1244 if (time_inn
>= 10) //freeze update
1246 float bubble
= 0.125f
*sWorld
.getConfig(CONFIG_FLOAT_RATE_REST_INGAME
);
1247 //speed collect rest bonus (section/in hour)
1248 SetRestBonus( float(GetRestBonus()+ time_inn
*(GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
));
1249 UpdateInnerTime(time(NULL
));
1256 if(p_time
>= m_regenTimer
)
1259 m_regenTimer
-= p_time
;
1262 if (m_weaponChangeTimer
> 0)
1264 if(p_time
>= m_weaponChangeTimer
)
1265 m_weaponChangeTimer
= 0;
1267 m_weaponChangeTimer
-= p_time
;
1270 if (m_zoneUpdateTimer
> 0)
1272 if(p_time
>= m_zoneUpdateTimer
)
1274 uint32 newzone
, newarea
;
1275 GetZoneAndAreaId(newzone
,newarea
);
1277 if( m_zoneUpdateId
!= newzone
)
1278 UpdateZone(newzone
,newarea
); // also update area
1281 // use area updates as well
1282 // needed for free far all arenas for example
1283 if( m_areaUpdateId
!= newarea
)
1284 UpdateArea(newarea
);
1286 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
1290 m_zoneUpdateTimer
-= p_time
;
1295 // if no longer casting, set regen power as soon as it is up.
1296 if (!IsUnderLastManaUseEffect())
1297 SetFlag(UNIT_FIELD_FLAGS_2
, UNIT_FLAG2_REGENERATE_POWER
);
1303 if (m_deathState
== JUST_DIED
)
1310 if(p_time
>= m_nextSave
)
1312 // m_nextSave reseted in SaveToDB call
1314 sLog
.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1318 m_nextSave
-= p_time
;
1322 //Handle Water/drowning
1323 HandleDrowning(p_time
);
1325 //Handle detect stealth players
1326 if (m_DetectInvTimer
> 0)
1328 if (p_time
>= m_DetectInvTimer
)
1330 HandleStealthedUnitsDetection();
1331 m_DetectInvTimer
= 3000;
1334 m_DetectInvTimer
-= p_time
;
1338 if (now
> m_Last_tick
)
1340 uint32 elapsed
= uint32(now
- m_Last_tick
);
1341 m_Played_time
[PLAYED_TIME_TOTAL
] += elapsed
; // Total played time
1342 m_Played_time
[PLAYED_TIME_LEVEL
] += elapsed
; // Level played time
1348 m_drunkTimer
+= p_time
;
1350 if (m_drunkTimer
> 10*IN_MILLISECONDS
)
1354 // not auto-free ghost from body in instances
1355 if(m_deathTimer
> 0 && !GetBaseMap()->Instanceable())
1357 if(p_time
>= m_deathTimer
)
1364 m_deathTimer
-= p_time
;
1367 UpdateEnchantTime(p_time
);
1368 UpdateHomebindTime(p_time
);
1371 SendUpdateToOutOfRangeGroupMembers();
1373 Pet
* pet
= GetPet();
1374 if(pet
&& !pet
->IsWithinDistInMap(this, GetMap()->GetVisibilityDistance()) && (GetCharmGUID() && (pet
->GetGUID() != GetCharmGUID())))
1376 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
, true);
1379 //we should execute delayed teleports only for alive(!) players
1380 //because we don't want player's ghost teleported from graveyard
1381 if(IsHasDelayedTeleport() && isAlive())
1382 TeleportTo(m_teleport_dest
, m_teleport_options
);
1385 void Player::setDeathState(DeathState s
)
1387 uint32 ressSpellId
= 0;
1389 bool cur
= isAlive();
1391 if(s
== JUST_DIED
&& cur
)
1393 // drunken state is cleared on death
1395 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1398 clearResurrectRequestData();
1400 // remove form before other mods to prevent incorrect stats calculation
1401 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId
);
1403 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1404 RemovePet(NULL
, PET_SAVE_NOT_IN_SLOT
, true);
1406 // remove uncontrolled pets
1409 // save value before aura remove in Unit::setDeathState
1410 ressSpellId
= GetUInt32Value(PLAYER_SELF_RES_SPELL
);
1414 ressSpellId
= GetResurrectionSpellId();
1415 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP
, 1);
1416 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH
, 1);
1417 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON
, 1);
1419 Unit::setDeathState(s
);
1421 // restore resurrection spell id for player after aura remove
1422 if(s
== JUST_DIED
&& cur
&& ressSpellId
)
1423 SetUInt32Value(PLAYER_SELF_RES_SPELL
, ressSpellId
);
1425 if(isAlive() && !cur
)
1427 //clear aura case after resurrection by another way (spells will be applied before next death)
1428 SetUInt32Value(PLAYER_SELF_RES_SPELL
, 0);
1430 // restore default warrior stance
1431 if(getClass()== CLASS_WARRIOR
)
1432 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
1436 bool Player::BuildEnumData( QueryResult
* result
, WorldPacket
* p_data
)
1439 // "SELECT characters.guid, characters.name, characters.race, characters.class, characters.gender, characters.playerBytes, characters.playerBytes2, characters.level, "
1440 // 8 9 10 11 12 13 14
1441 // "characters.zone, characters.map, characters.position_x, characters.position_y, characters.position_z, guild_member.guildid, characters.playerFlags, "
1442 // 15 16 17 18 19 20
1443 // "characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, characters.equipmentCache, character_declinedname.genitive "
1445 Field
*fields
= result
->Fetch();
1447 uint32 guid
= fields
[0].GetUInt32();
1448 uint8 pRace
= fields
[2].GetUInt8();
1449 uint8 pClass
= fields
[3].GetUInt8();
1451 PlayerInfo
const *info
= sObjectMgr
.GetPlayerInfo(pRace
, pClass
);
1454 sLog
.outError("Player %u has incorrect race/class pair. Don't build enum.", guid
);
1458 *p_data
<< uint64(MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
1459 *p_data
<< fields
[1].GetString(); // name
1460 *p_data
<< uint8(pRace
); // race
1461 *p_data
<< uint8(pClass
); // class
1462 *p_data
<< uint8(fields
[4].GetUInt8()); // gender
1464 uint32 playerBytes
= fields
[5].GetUInt32();
1465 *p_data
<< uint8(playerBytes
); // skin
1466 *p_data
<< uint8(playerBytes
>> 8); // face
1467 *p_data
<< uint8(playerBytes
>> 16); // hair style
1468 *p_data
<< uint8(playerBytes
>> 24); // hair color
1470 uint32 playerBytes2
= fields
[6].GetUInt32();
1471 *p_data
<< uint8(playerBytes2
& 0xFF); // facial hair
1473 *p_data
<< uint8(fields
[7].GetUInt8()); // level
1474 *p_data
<< uint32(fields
[8].GetUInt32()); // zone
1475 *p_data
<< uint32(fields
[9].GetUInt32()); // map
1477 *p_data
<< fields
[10].GetFloat(); // x
1478 *p_data
<< fields
[11].GetFloat(); // y
1479 *p_data
<< fields
[12].GetFloat(); // z
1481 *p_data
<< uint32(fields
[13].GetUInt32()); // guild id
1483 uint32 char_flags
= 0;
1484 uint32 playerFlags
= fields
[14].GetUInt32();
1485 uint32 atLoginFlags
= fields
[15].GetUInt32();
1486 if(playerFlags
& PLAYER_FLAGS_HIDE_HELM
)
1487 char_flags
|= CHARACTER_FLAG_HIDE_HELM
;
1488 if(playerFlags
& PLAYER_FLAGS_HIDE_CLOAK
)
1489 char_flags
|= CHARACTER_FLAG_HIDE_CLOAK
;
1490 if(playerFlags
& PLAYER_FLAGS_GHOST
)
1491 char_flags
|= CHARACTER_FLAG_GHOST
;
1492 if(atLoginFlags
& AT_LOGIN_RENAME
)
1493 char_flags
|= CHARACTER_FLAG_RENAME
;
1494 if(sWorld
.getConfig(CONFIG_BOOL_DECLINED_NAMES_USED
))
1496 if(!fields
[20].GetCppString().empty())
1497 char_flags
|= CHARACTER_FLAG_DECLINED
;
1500 char_flags
|= CHARACTER_FLAG_DECLINED
;
1502 *p_data
<< uint32(char_flags
); // character flags
1503 // character customize flags
1504 *p_data
<< uint32(atLoginFlags
& AT_LOGIN_CUSTOMIZE
? CHAR_CUSTOMIZE_FLAG_CUSTOMIZE
: CHAR_CUSTOMIZE_FLAG_NONE
);
1506 *p_data
<< uint8(atLoginFlags
& AT_LOGIN_FIRST
? 1 : 0);
1510 uint32 petDisplayId
= 0;
1511 uint32 petLevel
= 0;
1512 uint32 petFamily
= 0;
1514 // show pet at selection character in character list only for non-ghost character
1515 if (result
&& !(playerFlags
& PLAYER_FLAGS_GHOST
) && (pClass
== CLASS_WARLOCK
|| pClass
== CLASS_HUNTER
|| pClass
== CLASS_DEATH_KNIGHT
))
1517 uint32 entry
= fields
[16].GetUInt32();
1518 CreatureInfo
const* cInfo
= sCreatureStorage
.LookupEntry
<CreatureInfo
>(entry
);
1521 petDisplayId
= fields
[17].GetUInt32();
1522 petLevel
= fields
[18].GetUInt32();
1523 petFamily
= cInfo
->family
;
1527 *p_data
<< uint32(petDisplayId
);
1528 *p_data
<< uint32(petLevel
);
1529 *p_data
<< uint32(petFamily
);
1533 Tokens data
= StrSplit(fields
[19].GetCppString(), " ");
1534 for (uint8 slot
= 0; slot
< EQUIPMENT_SLOT_END
; slot
++)
1536 uint32 visualbase
= slot
* 2;
1537 uint32 item_id
= GetUInt32ValueFromArray(data
, visualbase
);
1538 const ItemPrototype
* proto
= ObjectMgr::GetItemPrototype(item_id
);
1541 *p_data
<< uint32(0);
1542 *p_data
<< uint8(0);
1543 *p_data
<< uint32(0);
1547 SpellItemEnchantmentEntry
const *enchant
= NULL
;
1549 uint32 enchants
= GetUInt32ValueFromArray(data
, visualbase
+ 1);
1550 for(uint8 enchantSlot
= PERM_ENCHANTMENT_SLOT
; enchantSlot
<= TEMP_ENCHANTMENT_SLOT
; ++enchantSlot
)
1552 // values stored in 2 uint16
1553 uint32 enchantId
= 0x0000FFFF & (enchants
>> enchantSlot
*16);
1557 if ((enchant
= sSpellItemEnchantmentStore
.LookupEntry(enchantId
)))
1561 *p_data
<< uint32(proto
->DisplayInfoID
);
1562 *p_data
<< uint8(proto
->InventoryType
);
1563 *p_data
<< uint32(enchant
? enchant
->aura_id
: 0);
1565 *p_data
<< uint32(0); // first bag display id
1566 *p_data
<< uint8(0); // first bag inventory type
1567 *p_data
<< uint32(0); // enchant?
1572 bool Player::ToggleAFK()
1574 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1576 bool state
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1578 // afk player not allowed in battleground
1579 if(state
&& InBattleGround())
1580 LeaveBattleground();
1585 bool Player::ToggleDND()
1587 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1589 return HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1592 uint8
Player::chatTag() const
1609 bool Player::TeleportTo(uint32 mapid
, float x
, float y
, float z
, float orientation
, uint32 options
)
1611 if(!MapManager::IsValidMapCoord(mapid
, x
, y
, z
, orientation
))
1613 sLog
.outError("TeleportTo: invalid map %d or absent instance template.", mapid
);
1617 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1618 Pet
* pet
= GetPet();
1620 MapEntry
const* mEntry
= sMapStore
.LookupEntry(mapid
);
1622 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1623 // don't let gm level > 1 either
1624 if(!InBattleGround() && mEntry
->IsBattleGroundOrArena())
1627 // client without expansion support
1628 if(GetSession()->Expansion() < mEntry
->Expansion())
1630 sLog
.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid
);
1633 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1635 SendTransferAborted(mapid
, TRANSFER_ABORT_INSUF_EXPAN_LVL
, mEntry
->Expansion());
1637 return false; // normal client can't teleport to this map...
1641 sLog
.outDebug("Player %s is being teleported to map %u", GetName(), mapid
);
1644 // if we were on a transport, leave
1645 if (!(options
& TELE_TO_NOT_LEAVE_TRANSPORT
) && m_transport
)
1647 m_transport
->RemovePassenger(this);
1649 m_movementInfo
.SetTransportData(0, 0.0f
, 0.0f
, 0.0f
, 0.0f
, 0, -1);
1652 // The player was ported to another map and looses the duel immediately.
1653 // We have to perform this check before the teleport, otherwise the
1654 // ObjectAccessor won't find the flag.
1655 if (duel
&& GetMapId() != mapid
)
1657 GameObject
* obj
= GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER
));
1659 DuelComplete(DUEL_FLED
);
1662 // reset movement flags at teleport, because player will continue move with these flags after teleport
1663 m_movementInfo
.SetMovementFlags(MOVEFLAG_NONE
);
1665 if ((GetMapId() == mapid
) && (!m_transport
))
1667 //lets reset far teleport flag if it wasn't reset during chained teleports
1668 SetSemaphoreTeleportFar(false);
1669 //setup delayed teleport flag
1670 SetDelayedTeleportFlag(IsCanDelayTeleport());
1671 //if teleport spell is casted in Unit::Update() func
1672 //then we need to delay it until update process will be finished
1673 if(IsHasDelayedTeleport())
1675 SetSemaphoreTeleportNear(true);
1676 //lets save teleport destination for player
1677 m_teleport_dest
= WorldLocation(mapid
, x
, y
, z
, orientation
);
1678 m_teleport_options
= options
;
1682 if (!(options
& TELE_TO_NOT_UNSUMMON_PET
))
1684 //same map, only remove pet if out of range for new position
1685 if(pet
&& !pet
->IsWithinDist3d(x
, y
, z
, GetMap()->GetVisibilityDistance()))
1686 UnsummonPetTemporaryIfAny();
1689 if(!(options
& TELE_TO_NOT_LEAVE_COMBAT
))
1692 // this will be used instead of the current location in SaveToDB
1693 m_teleport_dest
= WorldLocation(mapid
, x
, y
, z
, orientation
);
1694 SetFallInformation(0, z
);
1696 // code for finish transfer called in WorldSession::HandleMovementOpcodes()
1697 // at client packet MSG_MOVE_TELEPORT_ACK
1698 SetSemaphoreTeleportNear(true);
1699 // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
1700 if(!GetSession()->PlayerLogout())
1703 BuildTeleportAckMsg(&data
, x
, y
, z
, orientation
);
1704 GetSession()->SendPacket(&data
);
1709 // far teleport to another map
1710 Map
* oldmap
= IsInWorld() ? GetMap() : NULL
;
1711 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1713 // Check enter rights before map getting to avoid creating instance copy for player
1714 // this check not dependent from map instance copy and same for all instance copies of selected map
1715 if (!sMapMgr
.CanPlayerEnter(mapid
, this))
1718 // If the map is not created, assume it is possible to enter it.
1719 // It will be created in the WorldPortAck.
1720 Map
*map
= sMapMgr
.FindMap(mapid
);
1721 if (!map
|| map
->CanEnter(this))
1723 //lets reset near teleport flag if it wasn't reset during chained teleports
1724 SetSemaphoreTeleportNear(false);
1725 //setup delayed teleport flag
1726 SetDelayedTeleportFlag(IsCanDelayTeleport());
1727 //if teleport spell is casted in Unit::Update() func
1728 //then we need to delay it until update process will be finished
1729 if(IsHasDelayedTeleport())
1731 SetSemaphoreTeleportFar(true);
1732 //lets save teleport destination for player
1733 m_teleport_dest
= WorldLocation(mapid
, x
, y
, z
, orientation
);
1734 m_teleport_options
= options
;
1742 ResetContestedPvP();
1744 // remove player from battleground on far teleport (when changing maps)
1745 if(BattleGround
const* bg
= GetBattleGround())
1747 // Note: at battleground join battleground id set before teleport
1748 // and we already will found "current" battleground
1749 // just need check that this is targeted map or leave
1750 if(bg
->GetMapId() != mapid
)
1751 LeaveBattleground(false); // don't teleport to entry point
1754 // remove pet on map change
1756 UnsummonPetTemporaryIfAny();
1758 // remove all dyn objects
1759 RemoveAllDynObjects();
1761 // stop spellcasting
1762 // not attempt interrupt teleportation spell at caster teleport
1763 if(!(options
& TELE_TO_SPELL
))
1764 if(IsNonMeleeSpellCasted(true))
1765 InterruptNonMeleeSpells(true);
1767 //remove auras before removing from map...
1768 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP
| AURA_INTERRUPT_FLAG_MOVE
| AURA_INTERRUPT_FLAG_TURNING
);
1770 if(!GetSession()->PlayerLogout())
1772 // send transfer packets
1773 WorldPacket
data(SMSG_TRANSFER_PENDING
, (4+4+4));
1774 data
<< uint32(mapid
);
1777 data
<< uint32(m_transport
->GetEntry());
1778 data
<< uint32(GetMapId());
1780 GetSession()->SendPacket(&data
);
1782 data
.Initialize(SMSG_NEW_WORLD
, (20));
1785 data
<< uint32(mapid
);
1786 data
<< float(m_movementInfo
.GetTransportPos()->x
);
1787 data
<< float(m_movementInfo
.GetTransportPos()->y
);
1788 data
<< float(m_movementInfo
.GetTransportPos()->z
);
1789 data
<< float(m_movementInfo
.GetTransportPos()->o
);
1793 data
<< uint32(mapid
);
1797 data
<< float(orientation
);
1799 GetSession()->SendPacket( &data
);
1800 SendSavedInstances();
1803 // remove from old map now
1805 oldmap
->Remove(this, false);
1807 // new final coordinates
1811 float final_o
= orientation
;
1815 final_x
+= m_movementInfo
.GetTransportPos()->x
;
1816 final_y
+= m_movementInfo
.GetTransportPos()->y
;
1817 final_z
+= m_movementInfo
.GetTransportPos()->z
;
1818 final_o
+= m_movementInfo
.GetTransportPos()->o
;
1821 m_teleport_dest
= WorldLocation(mapid
, final_x
, final_y
, final_z
, final_o
);
1822 SetFallInformation(0, final_z
);
1823 // if the player is saved before worldport ack (at logout for example)
1824 // this will be used instead of the current location in SaveToDB
1826 // move packet sent by client always after far teleport
1827 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1828 SetSemaphoreTeleportFar(true);
1836 bool Player::TeleportToBGEntryPoint()
1838 ScheduleDelayedOperation(DELAYED_BG_MOUNT_RESTORE
);
1839 ScheduleDelayedOperation(DELAYED_BG_TAXI_RESTORE
);
1840 return TeleportTo(m_bgData
.joinPos
);
1843 void Player::ProcessDelayedOperations()
1845 if(m_DelayedOperations
== 0)
1848 if(m_DelayedOperations
& DELAYED_RESURRECT_PLAYER
)
1850 ResurrectPlayer(0.0f
, false);
1852 if(GetMaxHealth() > m_resurrectHealth
)
1853 SetHealth( m_resurrectHealth
);
1855 SetHealth( GetMaxHealth() );
1857 if(GetMaxPower(POWER_MANA
) > m_resurrectMana
)
1858 SetPower(POWER_MANA
, m_resurrectMana
);
1860 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
) );
1862 SetPower(POWER_RAGE
, 0 );
1863 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
) );
1868 if(m_DelayedOperations
& DELAYED_SAVE_PLAYER
)
1873 if(m_DelayedOperations
& DELAYED_SPELL_CAST_DESERTER
)
1875 CastSpell(this, 26013, true); // Deserter
1878 if (m_DelayedOperations
& DELAYED_BG_MOUNT_RESTORE
)
1880 if (m_bgData
.mountSpell
)
1882 CastSpell(this, m_bgData
.mountSpell
, true);
1883 m_bgData
.mountSpell
= 0;
1887 if (m_DelayedOperations
& DELAYED_BG_TAXI_RESTORE
)
1889 if (m_bgData
.HasTaxiPath())
1891 m_taxi
.AddTaxiDestination(m_bgData
.taxiPath
[0]);
1892 m_taxi
.AddTaxiDestination(m_bgData
.taxiPath
[1]);
1893 m_bgData
.ClearTaxiPath();
1895 ContinueTaxiFlight();
1899 //we have executed ALL delayed ops, so clear the flag
1900 m_DelayedOperations
= 0;
1903 void Player::AddToWorld()
1905 ///- Do not add/remove the player from the object storage
1906 ///- It will crash when updating the ObjectAccessor
1907 ///- The player should only be added when logging in
1910 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; ++i
)
1913 m_items
[i
]->AddToWorld();
1917 void Player::RemoveFromWorld()
1922 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1923 UnsummonAllTotems();
1927 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; ++i
)
1930 m_items
[i
]->RemoveFromWorld();
1933 ///- Do not add/remove the player from the object storage
1934 ///- It will crash when updating the ObjectAccessor
1935 ///- The player should only be removed when logging out
1936 Unit::RemoveFromWorld();
1939 void Player::RewardRage( uint32 damage
, uint32 weaponSpeedHitFactor
, bool attacker
)
1943 float rageconversion
= float((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911f
;
1947 addRage
= ((damage
/rageconversion
*7.5f
+ weaponSpeedHitFactor
)/2.0f
);
1949 // talent who gave more rage on attack
1950 addRage
*= 1.0f
+ GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT
) / 100.0f
;
1954 addRage
= damage
/rageconversion
*2.5f
;
1956 // Berserker Rage effect
1957 if (HasAura(18499, EFFECT_INDEX_0
))
1961 addRage
*= sWorld
.getConfig(CONFIG_FLOAT_RATE_POWER_RAGE_INCOME
);
1963 ModifyPower(POWER_RAGE
, uint32(addRage
*10));
1966 void Player::RegenerateAll(uint32 diff
)
1968 // Not in combat or they have regeneration
1969 if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) ||
1970 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
) || IsPolymorphed() )
1972 RegenerateHealth(diff
);
1973 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN
))
1975 Regenerate(POWER_RAGE
, diff
);
1976 if(getClass() == CLASS_DEATH_KNIGHT
)
1977 Regenerate(POWER_RUNIC_POWER
, diff
);
1981 Regenerate(POWER_ENERGY
, diff
);
1983 Regenerate(POWER_MANA
, diff
);
1985 if (getClass() == CLASS_DEATH_KNIGHT
)
1986 Regenerate(POWER_RUNE
, diff
);
1988 m_regenTimer
= REGEN_TIME_FULL
;
1991 // diff contains the time in milliseconds since last regen.
1992 void Player::Regenerate(Powers power
, uint32 diff
)
1994 uint32 curValue
= GetPower(power
);
1995 uint32 maxValue
= GetMaxPower(power
);
1997 float addvalue
= 0.0f
;
2003 bool recentCast
= IsUnderLastManaUseEffect();
2004 float ManaIncreaseRate
= sWorld
.getConfig(CONFIG_FLOAT_RATE_POWER_MANA
);
2007 // Mangos Updates Mana in intervals of 2s, which is correct
2008 addvalue
= GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER
) * ManaIncreaseRate
* 2.00f
;
2012 addvalue
= GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER
) * ManaIncreaseRate
* 2.00f
;
2015 case POWER_RAGE
: // Regenerate rage
2017 float RageDecreaseRate
= sWorld
.getConfig(CONFIG_FLOAT_RATE_POWER_RAGE_LOSS
);
2018 addvalue
= 20 * RageDecreaseRate
; // 2 rage by tick (= 2 seconds => 1 rage/sec)
2020 case POWER_ENERGY
: // Regenerate energy (rogue)
2023 case POWER_RUNIC_POWER
:
2025 float RunicPowerDecreaseRate
= sWorld
.getConfig(CONFIG_FLOAT_RATE_POWER_RUNICPOWER_LOSS
);
2026 addvalue
= 30 * RunicPowerDecreaseRate
; // 3 RunicPower by tick
2030 if (getClass() != CLASS_DEATH_KNIGHT
)
2033 for(uint32 rune
= 0; rune
< MAX_RUNES
; ++rune
)
2035 if(uint16 cd
= GetRuneCooldown(rune
)) // if we have cooldown, reduce it...
2037 uint32 cd_diff
= diff
;
2038 AuraList
const& ModPowerRegenPCTAuras
= GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT
);
2039 for(AuraList::const_iterator i
= ModPowerRegenPCTAuras
.begin(); i
!= ModPowerRegenPCTAuras
.end(); ++i
)
2040 if ((*i
)->GetModifier()->m_miscvalue
== power
&& (*i
)->GetMiscBValue()==GetCurrentRune(rune
))
2041 cd_diff
= cd_diff
* ((*i
)->GetModifier()->m_amount
+ 100) / 100.0f
;
2043 SetRuneCooldown(rune
, (cd
< cd_diff
) ? 0 : cd
- cd_diff
);
2048 case POWER_HAPPINESS
:
2053 // Mana regen calculated in Player::UpdateManaRegen()
2054 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
2055 if(power
!= POWER_MANA
)
2057 AuraList
const& ModPowerRegenPCTAuras
= GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT
);
2058 for(AuraList::const_iterator i
= ModPowerRegenPCTAuras
.begin(); i
!= ModPowerRegenPCTAuras
.end(); ++i
)
2059 if ((*i
)->GetModifier()->m_miscvalue
== power
)
2060 addvalue
*= ((*i
)->GetModifier()->m_amount
+ 100) / 100.0f
;
2063 // addvalue computed on a 2sec basis. => update to diff time
2064 addvalue
*= float(diff
) / REGEN_TIME_FULL
;
2066 if (power
!= POWER_RAGE
&& power
!= POWER_RUNIC_POWER
)
2068 curValue
+= uint32(addvalue
);
2069 if (curValue
> maxValue
)
2070 curValue
= maxValue
;
2074 if(curValue
<= uint32(addvalue
))
2077 curValue
-= uint32(addvalue
);
2079 SetPower(power
, curValue
);
2082 void Player::RegenerateHealth(uint32 diff
)
2084 uint32 curValue
= GetHealth();
2085 uint32 maxValue
= GetMaxHealth();
2087 if (curValue
>= maxValue
) return;
2089 float HealthIncreaseRate
= sWorld
.getConfig(CONFIG_FLOAT_RATE_HEALTH
);
2091 float addvalue
= 0.0f
;
2094 if ( IsPolymorphed() )
2095 addvalue
= (float)GetMaxHealth()/3;
2096 // normal regen case (maybe partly in combat case)
2097 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) )
2099 addvalue
= OCTRegenHPPerSpirit()* HealthIncreaseRate
;
2102 AuraList
const& mModHealthRegenPct
= GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT
);
2103 for(AuraList::const_iterator i
= mModHealthRegenPct
.begin(); i
!= mModHealthRegenPct
.end(); ++i
)
2104 addvalue
*= (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
;
2106 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
))
2107 addvalue
*= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) / 100.0f
;
2113 // always regeneration bonus (including combat)
2114 addvalue
+= GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
);
2119 addvalue
*= (float)diff
/ REGEN_TIME_FULL
;
2121 ModifyHealth(int32(addvalue
));
2124 Creature
* Player::GetNPCIfCanInteractWith(ObjectGuid guid
, uint32 npcflagmask
)
2126 // some basic checks
2127 if (guid
.IsEmpty() || !IsInWorld() || isInFlight())
2130 // exist (we need look pets also for some interaction (quest/etc)
2131 Creature
*unit
= GetMap()->GetCreatureOrPetOrVehicle(guid
);
2135 // appropriate npc type
2136 if (npcflagmask
&& !unit
->HasFlag( UNIT_NPC_FLAGS
, npcflagmask
))
2139 if (npcflagmask
== UNIT_NPC_FLAG_STABLEMASTER
)
2141 if (getClass() != CLASS_HUNTER
)
2145 // if a dead unit should be able to talk - the creature must be alive and have special flags
2146 if (!unit
->isAlive())
2149 if (isAlive() && unit
->isInvisibleForAlive())
2152 // not allow interaction under control, but allow with own pets
2153 if (unit
->GetCharmerGUID())
2157 if (unit
->IsHostileTo(this))
2161 if(FactionTemplateEntry
const* factionTemplate
= sFactionTemplateStore
.LookupEntry(unit
->getFaction()))
2162 if(factionTemplate
->faction
)
2163 if(FactionEntry
const* faction
= sFactionStore
.LookupEntry(factionTemplate
->faction
))
2164 if(faction
->reputationListID
>= 0 && GetReputationMgr().GetRank(faction
) <= REP_UNFRIENDLY
)
2168 if(!unit
->IsWithinDistInMap(this,INTERACTION_DISTANCE
))
2174 GameObject
* Player::GetGameObjectIfCanInteractWith(ObjectGuid guid
, uint32 gameobject_type
) const
2176 // some basic checks
2177 if (guid
.IsEmpty() || !IsInWorld() || isInFlight())
2180 if (GameObject
*go
= GetMap()->GetGameObject(guid
))
2182 if (uint32(go
->GetGoType()) == gameobject_type
|| gameobject_type
== MAX_GAMEOBJECT_TYPE
)
2185 switch(go
->GetGoType())
2187 // TODO: find out how the client calculates the maximal usage distance to spellless working
2188 // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
2189 case GAMEOBJECT_TYPE_GUILD_BANK
:
2190 case GAMEOBJECT_TYPE_MAILBOX
:
2193 case GAMEOBJECT_TYPE_FISHINGHOLE
:
2194 maxdist
= 20.0f
+CONTACT_DISTANCE
; // max spell range
2197 maxdist
= INTERACTION_DISTANCE
;
2201 if (go
->IsWithinDistInMap(this, maxdist
) && go
->isSpawned())
2204 sLog
.outError("GetGameObjectIfCanInteractWith: 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
,
2205 go
->GetGUIDLow(), GetName(), GetGUIDLow(), go
->GetDistance(this));
2211 bool Player::IsUnderWater() const
2213 return IsInWater() &&
2214 GetPositionZ() < (GetBaseMap()->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2217 void Player::SetInWater(bool apply
)
2219 if(m_isInWater
==apply
)
2222 //define player in water by opcodes
2223 //move player's guid into HateOfflineList of those mobs
2224 //which can't swim and move guid back into ThreatList when
2226 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2227 m_isInWater
= apply
;
2229 // remove auras that need water/land
2230 RemoveAurasWithInterruptFlags(apply
? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER
: AURA_INTERRUPT_FLAG_NOT_UNDERWATER
);
2232 getHostileRefManager().updateThreatTables();
2235 struct SetGameMasterOnHelper
2237 explicit SetGameMasterOnHelper() {}
2238 void operator()(Unit
* unit
) const
2240 unit
->setFaction(35);
2241 unit
->getHostileRefManager().setOnlineOfflineState(false);
2245 struct SetGameMasterOffHelper
2247 explicit SetGameMasterOffHelper(uint32 _faction
) : faction(_faction
) {}
2248 void operator()(Unit
* unit
) const
2250 unit
->setFaction(faction
);
2251 unit
->getHostileRefManager().setOnlineOfflineState(true);
2256 void Player::SetGameMaster(bool on
)
2260 m_ExtraFlags
|= PLAYER_EXTRA_GM_ON
;
2262 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
2264 CallForAllControlledUnits(SetGameMasterOnHelper(),true,true,true,false);
2267 ResetContestedPvP();
2269 getHostileRefManager().setOnlineOfflineState(false);
2270 CombatStopWithPets();
2272 SetPhaseMask(PHASEMASK_ANYWHERE
,false); // see and visible in all phases
2277 AuraList
const& phases
= GetAurasByType(SPELL_AURA_PHASE
);
2278 SetPhaseMask(!phases
.empty() ? phases
.front()->GetMiscValue() : PHASEMASK_NORMAL
,false);
2280 m_ExtraFlags
&= ~ PLAYER_EXTRA_GM_ON
;
2281 setFactionForRace(getRace());
2282 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
2284 CallForAllControlledUnits(SetGameMasterOffHelper(getFaction()),true,true,true,false);
2286 // restore FFA PvP Server state
2287 if(sWorld
.IsFFAPvPRealm())
2290 // restore FFA PvP area state, remove not allowed for GM mounts
2291 UpdateArea(m_areaUpdateId
);
2293 getHostileRefManager().setOnlineOfflineState(true);
2296 UpdateVisibilityForPlayer();
2299 void Player::SetGMVisible(bool on
)
2303 m_ExtraFlags
&= ~PLAYER_EXTRA_GM_INVISIBLE
; //remove flag
2305 // Reapply stealth/invisibility if active or show if not any
2306 if(HasAuraType(SPELL_AURA_MOD_STEALTH
))
2307 SetVisibility(VISIBILITY_GROUP_STEALTH
);
2308 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY
))
2309 SetVisibility(VISIBILITY_GROUP_INVISIBILITY
);
2311 SetVisibility(VISIBILITY_ON
);
2315 m_ExtraFlags
|= PLAYER_EXTRA_GM_INVISIBLE
; //add flag
2317 SetAcceptWhispers(false);
2318 SetGameMaster(true);
2320 SetVisibility(VISIBILITY_OFF
);
2324 bool Player::IsGroupVisibleFor(Player
* p
) const
2326 switch(sWorld
.getConfig(CONFIG_UINT32_GROUP_VISIBILITY
))
2328 default: return IsInSameGroupWith(p
);
2329 case 1: return IsInSameRaidWith(p
);
2330 case 2: return GetTeam()==p
->GetTeam();
2334 bool Player::IsInSameGroupWith(Player
const* p
) const
2336 return (p
==this || (GetGroup() != NULL
&&
2337 GetGroup()->SameSubGroup((Player
*)this, (Player
*)p
)));
2340 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2341 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2342 void Player::UninviteFromGroup()
2344 Group
* group
= GetGroupInvite();
2348 group
->RemoveInvite(this);
2350 if(group
->GetMembersCount() <= 1) // group has just 1 member => disband
2352 if(group
->IsCreated())
2354 group
->Disband(true);
2355 sObjectMgr
.RemoveGroup(group
);
2358 group
->RemoveAllInvites();
2364 void Player::RemoveFromGroup(Group
* group
, uint64 guid
)
2368 if (group
->RemoveMember(guid
, 0) <= 1)
2370 // group->Disband(); already disbanded in RemoveMember
2371 sObjectMgr
.RemoveGroup(group
);
2373 // removemember sets the player's group pointer to NULL
2378 void Player::SendLogXPGain(uint32 GivenXP
, Unit
* victim
, uint32 RestXP
)
2380 WorldPacket
data(SMSG_LOG_XPGAIN
, 21);
2381 data
<< uint64(victim
? victim
->GetGUID() : 0); // guid
2382 data
<< uint32(GivenXP
+RestXP
); // given experience
2383 data
<< uint8(victim
? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2386 data
<< uint32(GivenXP
); // experience without rested bonus
2387 data
<< float(1); // 1 - none 0 - 100% group bonus output
2389 data
<< uint8(0); // new 2.4.0
2390 GetSession()->SendPacket(&data
);
2393 void Player::GiveXP(uint32 xp
, Unit
* victim
)
2401 uint32 level
= getLevel();
2403 // XP to money conversion processed in Player::RewardQuest
2404 if(level
>= sWorld
.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL
))
2409 // handle SPELL_AURA_MOD_KILL_XP_PCT auras
2410 Unit::AuraList
const& ModXPPctAuras
= GetAurasByType(SPELL_AURA_MOD_KILL_XP_PCT
);
2411 for(Unit::AuraList::const_iterator i
= ModXPPctAuras
.begin();i
!= ModXPPctAuras
.end(); ++i
)
2412 xp
= uint32(xp
*(1.0f
+ (*i
)->GetModifier()->m_amount
/ 100.0f
));
2416 // handle SPELL_AURA_MOD_QUEST_XP_PCT auras
2417 Unit::AuraList
const& ModXPPctAuras
= GetAurasByType(SPELL_AURA_MOD_QUEST_XP_PCT
);
2418 for(Unit::AuraList::const_iterator i
= ModXPPctAuras
.begin();i
!= ModXPPctAuras
.end(); ++i
)
2419 xp
= uint32(xp
*(1.0f
+ (*i
)->GetModifier()->m_amount
/ 100.0f
));
2422 // XP resting bonus for kill
2423 uint32 rested_bonus_xp
= victim
? GetXPRestBonus(xp
) : 0;
2425 SendLogXPGain(xp
,victim
,rested_bonus_xp
);
2427 uint32 curXP
= GetUInt32Value(PLAYER_XP
);
2428 uint32 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2429 uint32 newXP
= curXP
+ xp
+ rested_bonus_xp
;
2431 while( newXP
>= nextLvlXP
&& level
< sWorld
.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL
) )
2435 if ( level
< sWorld
.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL
) )
2436 GiveLevel(level
+ 1);
2439 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2442 SetUInt32Value(PLAYER_XP
, newXP
);
2445 // Update player to next level
2446 // Current player experience not update (must be update by caller)
2447 void Player::GiveLevel(uint32 level
)
2449 if ( level
== getLevel() )
2452 PlayerLevelInfo info
;
2453 sObjectMgr
.GetPlayerLevelInfo(getRace(),getClass(),level
,&info
);
2455 PlayerClassLevelInfo classInfo
;
2456 sObjectMgr
.GetPlayerClassLevelInfo(getClass(),level
,&classInfo
);
2458 // send levelup info to client
2459 WorldPacket
data(SMSG_LEVELUP_INFO
, (4+4+MAX_POWERS
*4+MAX_STATS
*4));
2460 data
<< uint32(level
);
2461 data
<< uint32(int32(classInfo
.basehealth
) - int32(GetCreateHealth()));
2462 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2463 data
<< uint32(int32(classInfo
.basemana
) - int32(GetCreateMana()));
2471 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
) // Stats loop (0-4)
2472 data
<< uint32(int32(info
.stats
[i
]) - GetCreateStat(Stats(i
)));
2474 GetSession()->SendPacket(&data
);
2476 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, sObjectMgr
.GetXPForLevel(level
));
2478 //update level, max level of skills
2479 m_Played_time
[PLAYED_TIME_LEVEL
] = 0; // Level Played Time reset
2481 _ApplyAllLevelScaleItemMods(false);
2485 UpdateSkillsForLevel ();
2487 // save base values (bonuses already included in stored stats
2488 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2489 SetCreateStat(Stats(i
), info
.stats
[i
]);
2491 SetCreateHealth(classInfo
.basehealth
);
2492 SetCreateMana(classInfo
.basemana
);
2494 InitTalentForLevel();
2495 InitTaxiNodesForLevel();
2496 InitGlyphsForLevel();
2500 // set current level health and mana/energy to maximum after applying all mods.
2501 SetHealth(GetMaxHealth());
2502 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2503 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2504 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2505 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2506 SetPower(POWER_FOCUS
, 0);
2507 SetPower(POWER_HAPPINESS
, 0);
2509 _ApplyAllLevelScaleItemMods(true);
2511 // update level to hunter/summon pet
2512 if (Pet
* pet
= GetPet())
2513 pet
->SynchronizeLevelWithOwner();
2515 if (MailLevelReward
const* mailReward
= sObjectMgr
.GetMailLevelReward(level
,getRaceMask()))
2516 MailDraft(mailReward
->mailTemplateId
).SendMailTo(this,MailSender(MAIL_CREATURE
,mailReward
->senderEntry
));
2518 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL
);
2521 void Player::UpdateFreeTalentPoints(bool resetIfNeed
)
2523 uint32 level
= getLevel();
2524 // talents base at level diff ( talents = level - 9 but some can be used already)
2527 // Remove all talent points
2528 if (m_usedTalentCount
> 0) // Free any used talents
2532 SetFreeTalentPoints(0);
2537 uint32 talentPointsForLevel
= CalculateTalentsPoints();
2539 // if used more that have then reset
2540 if (m_usedTalentCount
> talentPointsForLevel
)
2542 if (resetIfNeed
&& GetSession()->GetSecurity() < SEC_ADMINISTRATOR
)
2545 SetFreeTalentPoints(0);
2547 // else update amount of free points
2549 SetFreeTalentPoints(talentPointsForLevel
-m_usedTalentCount
);
2553 void Player::InitTalentForLevel()
2555 UpdateFreeTalentPoints();
2557 if (!GetSession()->PlayerLoading())
2558 SendTalentsInfoData(false); // update at client
2561 void Player::InitStatsForLevel(bool reapplyMods
)
2563 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2564 _RemoveAllStatBonuses();
2566 PlayerClassLevelInfo classInfo
;
2567 sObjectMgr
.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo
);
2569 PlayerLevelInfo info
;
2570 sObjectMgr
.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info
);
2572 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL
, sWorld
.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL
) );
2573 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, sObjectMgr
.GetXPForLevel(getLevel()));
2575 // reset before any aura state sources (health set/aura apply)
2576 SetUInt32Value(UNIT_FIELD_AURASTATE
, 0);
2578 UpdateSkillsForLevel ();
2580 // set default cast time multiplier
2581 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
);
2583 // reset size before reapply auras
2584 SetFloatValue(OBJECT_FIELD_SCALE_X
,1.0f
);
2586 // save base values (bonuses already included in stored stats
2587 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2588 SetCreateStat(Stats(i
), info
.stats
[i
]);
2590 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2591 SetStat(Stats(i
), info
.stats
[i
]);
2593 SetCreateHealth(classInfo
.basehealth
);
2596 SetCreateMana(classInfo
.basemana
);
2598 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2602 //reset rating fields values
2603 for(uint16 index
= PLAYER_FIELD_COMBAT_RATING_1
; index
< PLAYER_FIELD_COMBAT_RATING_1
+ MAX_COMBAT_RATING
; ++index
)
2604 SetUInt32Value(index
, 0);
2606 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS
,0);
2607 for (int i
= 0; i
< 7; ++i
)
2609 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG
+i
, 0);
2610 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS
+i
, 0);
2611 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT
+i
, 1.00f
);
2614 //reset attack power, damage and attack speed fields
2615 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
, 2000.0f
);
2616 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
+ 1, 2000.0f
); // offhand attack time
2617 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME
, 2000.0f
);
2619 SetFloatValue(UNIT_FIELD_MINDAMAGE
, 0.0f
);
2620 SetFloatValue(UNIT_FIELD_MAXDAMAGE
, 0.0f
);
2621 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
, 0.0f
);
2622 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
, 0.0f
);
2623 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
, 0.0f
);
2624 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
, 0.0f
);
2626 SetInt32Value(UNIT_FIELD_ATTACK_POWER
, 0 );
2627 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS
, 0 );
2628 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER
,0.0f
);
2629 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER
, 0 );
2630 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS
,0 );
2631 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER
,0.0f
);
2633 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2634 SetFloatValue(PLAYER_CRIT_PERCENTAGE
,0.0f
);
2635 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE
,0.0f
);
2636 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE
,0.0f
);
2638 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2639 for (uint8 i
= 0; i
< 7; ++i
)
2640 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1
+i
, 0.0f
);
2642 SetFloatValue(PLAYER_PARRY_PERCENTAGE
, 0.0f
);
2643 SetFloatValue(PLAYER_BLOCK_PERCENTAGE
, 0.0f
);
2644 SetUInt32Value(PLAYER_SHIELD_BLOCK
, 0);
2647 SetFloatValue(PLAYER_DODGE_PERCENTAGE
, 0.0f
);
2649 // set armor (resistance 0) to original value (create_agility*2)
2650 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2651 SetResistanceBuffMods(SpellSchools(0), true, 0.0f
);
2652 SetResistanceBuffMods(SpellSchools(0), false, 0.0f
);
2653 // set other resistance to original value (0)
2654 for (int i
= 1; i
< MAX_SPELL_SCHOOL
; ++i
)
2656 SetResistance(SpellSchools(i
), 0);
2657 SetResistanceBuffMods(SpellSchools(i
), true, 0.0f
);
2658 SetResistanceBuffMods(SpellSchools(i
), false, 0.0f
);
2661 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE
,0);
2662 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE
,0);
2663 for(int i
= 0; i
< MAX_SPELL_SCHOOL
; ++i
)
2665 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER
+i
,0);
2666 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER
+i
,0.0f
);
2668 // Reset no reagent cost field
2669 for(int i
= 0; i
< 3; ++i
)
2670 SetUInt32Value(PLAYER_NO_REAGENT_COST_1
+ i
, 0);
2671 // Init data for form but skip reapply item mods for form
2672 InitDataForForm(reapplyMods
);
2675 for (int i
= POWER_MANA
; i
< MAX_POWERS
; ++i
)
2676 SetMaxPower(Powers(i
), uint32(GetCreatePowers(Powers(i
))));
2678 SetMaxHealth(classInfo
.basehealth
); // stamina bonus will applied later
2680 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2681 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID
, 0);
2683 // cleanup unit flags (will be re-applied if need at aura load).
2684 RemoveFlag( UNIT_FIELD_FLAGS
,
2685 UNIT_FLAG_NON_ATTACKABLE
| UNIT_FLAG_DISABLE_MOVE
| UNIT_FLAG_NOT_ATTACKABLE_1
|
2686 UNIT_FLAG_OOC_NOT_ATTACKABLE
| UNIT_FLAG_PASSIVE
| UNIT_FLAG_LOOTING
|
2687 UNIT_FLAG_PET_IN_COMBAT
| UNIT_FLAG_SILENCED
| UNIT_FLAG_PACIFIED
|
2688 UNIT_FLAG_STUNNED
| UNIT_FLAG_IN_COMBAT
| UNIT_FLAG_DISARMED
|
2689 UNIT_FLAG_CONFUSED
| UNIT_FLAG_FLEEING
| UNIT_FLAG_NOT_SELECTABLE
|
2690 UNIT_FLAG_SKINNABLE
| UNIT_FLAG_MOUNT
| UNIT_FLAG_TAXI_FLIGHT
);
2691 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
); // must be set
2693 SetFlag(UNIT_FIELD_FLAGS_2
,UNIT_FLAG2_REGENERATE_POWER
);// must be set
2695 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2696 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
| PLAYER_FLAGS_DND
| PLAYER_FLAGS_GM
| PLAYER_FLAGS_GHOST
);
2698 RemoveStandFlags(UNIT_STAND_FLAGS_ALL
); // one form stealth modified bytes
2699 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
| UNIT_BYTE2_FLAG_SANCTUARY
);
2701 // restore if need some important flags
2702 SetUInt32Value(PLAYER_FIELD_BYTES2
, 0 ); // flags empty by default
2704 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2705 _ApplyAllStatBonuses();
2707 // set current level health and mana/energy to maximum after applying all mods.
2708 SetHealth(GetMaxHealth());
2709 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2710 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2711 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2712 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2713 SetPower(POWER_FOCUS
, 0);
2714 SetPower(POWER_HAPPINESS
, 0);
2715 SetPower(POWER_RUNIC_POWER
, 0);
2717 // update level to hunter/summon pet
2718 if (Pet
* pet
= GetPet())
2719 pet
->SynchronizeLevelWithOwner();
2722 void Player::SendInitialSpells()
2724 time_t curTime
= time(NULL
);
2725 time_t infTime
= curTime
+ infinityCooldownDelayCheck
;
2727 uint16 spellCount
= 0;
2729 WorldPacket
data(SMSG_INITIAL_SPELLS
, (1+2+4*m_spells
.size()+2+m_spellCooldowns
.size()*(2+2+2+4+4)));
2732 size_t countPos
= data
.wpos();
2733 data
<< uint16(spellCount
); // spell count placeholder
2735 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2737 if(itr
->second
.state
== PLAYERSPELL_REMOVED
)
2740 if(!itr
->second
.active
|| itr
->second
.disabled
)
2743 data
<< uint32(itr
->first
);
2744 data
<< uint16(0); // it's not slot id
2749 data
.put
<uint16
>(countPos
,spellCount
); // write real count value
2751 uint16 spellCooldowns
= m_spellCooldowns
.size();
2752 data
<< uint16(spellCooldowns
);
2753 for(SpellCooldowns::const_iterator itr
=m_spellCooldowns
.begin(); itr
!=m_spellCooldowns
.end(); ++itr
)
2755 SpellEntry
const *sEntry
= sSpellStore
.LookupEntry(itr
->first
);
2759 data
<< uint32(itr
->first
);
2761 data
<< uint16(itr
->second
.itemid
); // cast item id
2762 data
<< uint16(sEntry
->Category
); // spell category
2764 // send infinity cooldown in special format
2765 if(itr
->second
.end
>= infTime
)
2767 data
<< uint32(1); // cooldown
2768 data
<< uint32(0x80000000); // category cooldown
2772 time_t cooldown
= itr
->second
.end
> curTime
? (itr
->second
.end
-curTime
)*IN_MILLISECONDS
: 0;
2774 if(sEntry
->Category
) // may be wrong, but anyway better than nothing...
2776 data
<< uint32(0); // cooldown
2777 data
<< uint32(cooldown
); // category cooldown
2781 data
<< uint32(cooldown
); // cooldown
2782 data
<< uint32(0); // category cooldown
2786 GetSession()->SendPacket(&data
);
2788 sLog
.outDetail( "CHARACTER: Sent Initial Spells" );
2791 void Player::RemoveMail(uint32 id
)
2793 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
2795 if ((*itr
)->messageID
== id
)
2797 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2804 void Player::SendMailResult(uint32 mailId
, MailResponseType mailAction
, MailResponseResult mailError
, uint32 equipError
, uint32 item_guid
, uint32 item_count
)
2806 WorldPacket
data(SMSG_SEND_MAIL_RESULT
, (4+4+4+(mailError
== MAIL_ERR_EQUIP_ERROR
?4:(mailAction
== MAIL_ITEM_TAKEN
?4+4:0))));
2807 data
<< (uint32
) mailId
;
2808 data
<< (uint32
) mailAction
;
2809 data
<< (uint32
) mailError
;
2810 if ( mailError
== MAIL_ERR_EQUIP_ERROR
)
2811 data
<< (uint32
) equipError
;
2812 else if( mailAction
== MAIL_ITEM_TAKEN
)
2814 data
<< (uint32
) item_guid
; // item guid low?
2815 data
<< (uint32
) item_count
; // item count?
2817 GetSession()->SendPacket(&data
);
2820 void Player::SendNewMail()
2822 // deliver undelivered mail
2823 WorldPacket
data(SMSG_RECEIVED_MAIL
, 4);
2825 GetSession()->SendPacket(&data
);
2828 void Player::UpdateNextMailTimeAndUnreads()
2830 // calculate next delivery time (min. from non-delivered mails
2831 // and recalculate unReadMail
2832 time_t cTime
= time(NULL
);
2833 m_nextMailDelivereTime
= 0;
2835 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
2837 if((*itr
)->deliver_time
> cTime
)
2839 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> (*itr
)->deliver_time
)
2840 m_nextMailDelivereTime
= (*itr
)->deliver_time
;
2842 else if(((*itr
)->checked
& MAIL_CHECK_MASK_READ
) == 0)
2847 void Player::AddNewMailDeliverTime(time_t deliver_time
)
2849 if(deliver_time
<= time(NULL
)) // ready now
2854 else // not ready and no have ready mails
2856 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> deliver_time
)
2857 m_nextMailDelivereTime
= deliver_time
;
2861 bool Player::addSpell(uint32 spell_id
, bool active
, bool learning
, bool dependent
, bool disabled
)
2863 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
2866 // do character spell book cleanup (all characters)
2867 if(!IsInWorld() && !learning
) // spell load case
2869 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id
);
2870 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2873 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id
);
2878 if(!SpellMgr::IsSpellValid(spellInfo
,this,false))
2880 // do character spell book cleanup (all characters)
2881 if(!IsInWorld() && !learning
) // spell load case
2883 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id
);
2884 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2887 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id
);
2892 PlayerSpellState state
= learning
? PLAYERSPELL_NEW
: PLAYERSPELL_UNCHANGED
;
2894 bool dependent_set
= false;
2895 bool disabled_case
= false;
2896 bool superceded_old
= false;
2898 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2899 if (itr
!= m_spells
.end())
2901 uint32 next_active_spell_id
= 0;
2902 // fix activate state for non-stackable low rank (and find next spell for !active case)
2903 if(!SpellMgr::canStackSpellRanks(spellInfo
) && sSpellMgr
.GetSpellRank(spellInfo
->Id
) != 0)
2905 SpellChainMapNext
const& nextMap
= sSpellMgr
.GetSpellChainNext();
2906 for(SpellChainMapNext::const_iterator next_itr
= nextMap
.lower_bound(spell_id
); next_itr
!= nextMap
.upper_bound(spell_id
); ++next_itr
)
2908 if(HasSpell(next_itr
->second
))
2910 // high rank already known so this must !active
2912 next_active_spell_id
= next_itr
->second
;
2918 // not do anything if already known in expected state
2919 if(itr
->second
.state
!= PLAYERSPELL_REMOVED
&& itr
->second
.active
== active
&&
2920 itr
->second
.dependent
== dependent
&& itr
->second
.disabled
== disabled
)
2922 if(!IsInWorld() && !learning
) // explicitly load from DB and then exist in it already and set correctly
2923 itr
->second
.state
= PLAYERSPELL_UNCHANGED
;
2928 // dependent spell known as not dependent, overwrite state
2929 if (itr
->second
.state
!= PLAYERSPELL_REMOVED
&& !itr
->second
.dependent
&& dependent
)
2931 itr
->second
.dependent
= dependent
;
2932 if (itr
->second
.state
!= PLAYERSPELL_NEW
)
2933 itr
->second
.state
= PLAYERSPELL_CHANGED
;
2934 dependent_set
= true;
2937 // update active state for known spell
2938 if(itr
->second
.active
!= active
&& itr
->second
.state
!= PLAYERSPELL_REMOVED
&& !itr
->second
.disabled
)
2940 itr
->second
.active
= active
;
2942 if(!IsInWorld() && !learning
&& !dependent_set
) // explicitly load from DB and then exist in it already and set correctly
2943 itr
->second
.state
= PLAYERSPELL_UNCHANGED
;
2944 else if(itr
->second
.state
!= PLAYERSPELL_NEW
)
2945 itr
->second
.state
= PLAYERSPELL_CHANGED
;
2949 if (IsPassiveSpell(spell_id
) && IsNeedCastPassiveSpellAtLearn(spellInfo
))
2950 CastSpell (this,spell_id
,true);
2952 else if(IsInWorld())
2954 if(next_active_spell_id
)
2956 // update spell ranks in spellbook and action bar
2957 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, 4 + 4);
2958 data
<< uint32(spell_id
);
2959 data
<< uint32(next_active_spell_id
);
2960 GetSession()->SendPacket( &data
);
2964 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
2965 data
<< uint32(spell_id
);
2966 GetSession()->SendPacket(&data
);
2970 return active
; // learn (show in spell book if active now)
2973 if(itr
->second
.disabled
!= disabled
&& itr
->second
.state
!= PLAYERSPELL_REMOVED
)
2975 if(itr
->second
.state
!= PLAYERSPELL_NEW
)
2976 itr
->second
.state
= PLAYERSPELL_CHANGED
;
2977 itr
->second
.disabled
= disabled
;
2982 disabled_case
= true;
2984 else switch(itr
->second
.state
)
2986 case PLAYERSPELL_UNCHANGED
: // known saved spell
2988 case PLAYERSPELL_REMOVED
: // re-learning removed not saved spell
2990 m_spells
.erase(itr
);
2991 state
= PLAYERSPELL_CHANGED
;
2992 break; // need re-add
2994 default: // known not saved yet spell (new or modified)
2996 // can be in case spell loading but learned at some previous spell loading
2997 if(!IsInWorld() && !learning
&& !dependent_set
)
2998 itr
->second
.state
= PLAYERSPELL_UNCHANGED
;
3005 TalentSpellPos
const* talentPos
= GetTalentSpellPos(spell_id
);
3007 if(!disabled_case
) // skip new spell adding if spell already known (disabled spells case)
3009 // talent: unlearn all other talent ranks (high and low)
3012 if(TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry( talentPos
->talent_id
))
3014 for(int i
=0; i
< MAX_TALENT_RANK
; ++i
)
3016 // skip learning spell and no rank spell case
3017 uint32 rankSpellId
= talentInfo
->RankID
[i
];
3018 if(!rankSpellId
|| rankSpellId
==spell_id
)
3021 removeSpell(rankSpellId
,false,false);
3025 // non talent spell: learn low ranks (recursive call)
3026 else if(uint32 prev_spell
= sSpellMgr
.GetPrevSpellInChain(spell_id
))
3028 if(!IsInWorld() || disabled
) // at spells loading, no output, but allow save
3029 addSpell(prev_spell
,active
,true,true,disabled
);
3030 else // at normal learning
3031 learnSpell(prev_spell
,true);
3034 PlayerSpell newspell
;
3035 newspell
.state
= state
;
3036 newspell
.active
= active
;
3037 newspell
.dependent
= dependent
;
3038 newspell
.disabled
= disabled
;
3040 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
3041 if(newspell
.active
&& !newspell
.disabled
&& !SpellMgr::canStackSpellRanks(spellInfo
) && sSpellMgr
.GetSpellRank(spellInfo
->Id
) != 0)
3043 for( PlayerSpellMap::iterator itr2
= m_spells
.begin(); itr2
!= m_spells
.end(); ++itr2
)
3045 if(itr2
->second
.state
== PLAYERSPELL_REMOVED
) continue;
3046 SpellEntry
const *i_spellInfo
= sSpellStore
.LookupEntry(itr2
->first
);
3047 if(!i_spellInfo
) continue;
3049 if( sSpellMgr
.IsRankSpellDueToSpell(spellInfo
,itr2
->first
) )
3051 if(itr2
->second
.active
)
3053 if(sSpellMgr
.IsHighRankOfSpell(spell_id
,itr2
->first
))
3055 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
3057 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, 4 + 4);
3058 data
<< uint32(itr2
->first
);
3059 data
<< uint32(spell_id
);
3060 GetSession()->SendPacket( &data
);
3063 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
3064 itr2
->second
.active
= false;
3065 if(itr2
->second
.state
!= PLAYERSPELL_NEW
)
3066 itr2
->second
.state
= PLAYERSPELL_CHANGED
;
3067 superceded_old
= true; // new spell replace old in action bars and spell book.
3069 else if(sSpellMgr
.IsHighRankOfSpell(itr2
->first
,spell_id
))
3071 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
3073 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, 4 + 4);
3074 data
<< uint32(spell_id
);
3075 data
<< uint32(itr2
->first
);
3076 GetSession()->SendPacket( &data
);
3079 // mark new spell as disable (not learned yet for client and will not learned)
3080 newspell
.active
= false;
3081 if(newspell
.state
!= PLAYERSPELL_NEW
)
3082 newspell
.state
= PLAYERSPELL_CHANGED
;
3089 m_spells
[spell_id
] = newspell
;
3091 // return false if spell disabled
3092 if (newspell
.disabled
)
3098 // update used talent points count
3099 m_usedTalentCount
+= GetTalentSpellCost(talentPos
);
3100 UpdateFreeTalentPoints(false);
3103 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
3104 if (uint32 freeProfs
= GetFreePrimaryProfessionPoints())
3106 if(sSpellMgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
3107 SetFreePrimaryProfessions(freeProfs
-1);
3110 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
3111 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
3112 if (talentPos
&& IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_LEARN_SPELL
))
3114 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
3115 CastSpell(this, spell_id
, true);
3117 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
3118 else if (IsPassiveSpell(spell_id
))
3120 if (IsNeedCastPassiveSpellAtLearn(spellInfo
))
3121 CastSpell(this, spell_id
, true);
3123 else if (IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_SKILL_STEP
))
3125 CastSpell(this, spell_id
, true);
3129 // add dependent skills
3130 uint16 maxskill
= GetMaxSkillValueForLevel();
3132 SpellLearnSkillNode
const* spellLearnSkill
= sSpellMgr
.GetSpellLearnSkill(spell_id
);
3134 SkillLineAbilityMapBounds skill_bounds
= sSpellMgr
.GetSkillLineAbilityMapBounds(spell_id
);
3136 if (spellLearnSkill
)
3138 uint32 skill_value
= GetPureSkillValue(spellLearnSkill
->skill
);
3139 uint32 skill_max_value
= GetPureMaxSkillValue(spellLearnSkill
->skill
);
3141 if (skill_value
< spellLearnSkill
->value
)
3142 skill_value
= spellLearnSkill
->value
;
3144 uint32 new_skill_max_value
= spellLearnSkill
->maxvalue
== 0 ? maxskill
: spellLearnSkill
->maxvalue
;
3146 if (skill_max_value
< new_skill_max_value
)
3147 skill_max_value
= new_skill_max_value
;
3149 SetSkill(spellLearnSkill
->skill
,skill_value
,skill_max_value
);
3153 // not ranked skills
3154 for(SkillLineAbilityMap::const_iterator _spell_idx
= skill_bounds
.first
; _spell_idx
!= skill_bounds
.second
; ++_spell_idx
)
3156 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
3160 if (HasSkill(pSkill
->id
))
3163 if (_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
3164 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3165 ((pSkill
->id
==SKILL_LOCKPICKING
|| pSkill
->id
==SKILL_RUNEFORGING
) && _spell_idx
->second
->max_value
==0))
3167 switch(GetSkillRangeType(pSkill
,_spell_idx
->second
->racemask
!=0))
3169 case SKILL_RANGE_LANGUAGE
:
3170 SetSkill(pSkill
->id
, 300, 300 );
3172 case SKILL_RANGE_LEVEL
:
3173 SetSkill(pSkill
->id
, 1, GetMaxSkillValueForLevel() );
3175 case SKILL_RANGE_MONO
:
3176 SetSkill(pSkill
->id
, 1, 1 );
3185 // learn dependent spells
3186 SpellLearnSpellMapBounds spell_bounds
= sSpellMgr
.GetSpellLearnSpellMapBounds(spell_id
);
3188 for(SpellLearnSpellMap::const_iterator itr2
= spell_bounds
.first
; itr2
!= spell_bounds
.second
; ++itr2
)
3190 if (!itr2
->second
.autoLearned
)
3192 if (!IsInWorld() || !itr2
->second
.active
) // at spells loading, no output, but allow save
3193 addSpell(itr2
->second
.spell
,itr2
->second
.active
,true,true,false);
3194 else // at normal learning
3195 learnSpell(itr2
->second
.spell
,true);
3199 if (!GetSession()->PlayerLoading())
3201 // not ranked skills
3202 for(SkillLineAbilityMap::const_iterator _spell_idx
= skill_bounds
.first
; _spell_idx
!= skill_bounds
.second
; ++_spell_idx
)
3204 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE
,_spell_idx
->second
->skillId
);
3205 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS
,_spell_idx
->second
->skillId
);
3208 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL
,spell_id
);
3211 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
3212 return active
&& !disabled
&& !superceded_old
;
3215 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry
const* spellInfo
) const
3217 // note: form passives activated with shapeshift spells be implemented by HandleShapeshiftBoosts instead of spell_learn_spell
3218 // talent dependent passives activated at form apply have proper stance data
3219 bool need_cast
= (!spellInfo
->Stances
|| (m_form
!= 0 && (spellInfo
->Stances
& (1<<(m_form
-1)))));
3221 //Check CasterAuraStates
3222 return need_cast
&& (!spellInfo
->CasterAuraState
|| HasAuraState(AuraState(spellInfo
->CasterAuraState
)));
3225 void Player::learnSpell(uint32 spell_id
, bool dependent
)
3227 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
3229 bool disabled
= (itr
!= m_spells
.end()) ? itr
->second
.disabled
: false;
3230 bool active
= disabled
? itr
->second
.active
: true;
3232 bool learning
= addSpell(spell_id
,active
,true,dependent
,false);
3234 // learn all disabled higher ranks (recursive)
3237 SpellChainMapNext
const& nextMap
= sSpellMgr
.GetSpellChainNext();
3238 for(SpellChainMapNext::const_iterator i
= nextMap
.lower_bound(spell_id
); i
!= nextMap
.upper_bound(spell_id
); ++i
)
3240 PlayerSpellMap::iterator iter
= m_spells
.find(i
->second
);
3241 if (iter
!= m_spells
.end() && iter
->second
.disabled
)
3242 learnSpell(i
->second
,false);
3246 // prevent duplicated entires in spell book, also not send if not in world (loading)
3247 if(!learning
|| !IsInWorld ())
3250 WorldPacket
data(SMSG_LEARNED_SPELL
, 4);
3251 data
<< uint32(spell_id
);
3252 GetSession()->SendPacket(&data
);
3255 void Player::removeSpell(uint32 spell_id
, bool disabled
, bool learn_low_rank
, bool sendUpdate
)
3257 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
3258 if (itr
== m_spells
.end())
3261 if (itr
->second
.state
== PLAYERSPELL_REMOVED
|| (disabled
&& itr
->second
.disabled
))
3264 // unlearn non talent higher ranks (recursive)
3265 SpellChainMapNext
const& nextMap
= sSpellMgr
.GetSpellChainNext();
3266 for(SpellChainMapNext::const_iterator itr2
= nextMap
.lower_bound(spell_id
); itr2
!= nextMap
.upper_bound(spell_id
); ++itr2
)
3267 if(HasSpell(itr2
->second
) && !GetTalentSpellPos(itr2
->second
))
3268 removeSpell(itr2
->second
,disabled
,false);
3270 // re-search, it can be corrupted in prev loop
3271 itr
= m_spells
.find(spell_id
);
3272 if (itr
== m_spells
.end())
3273 return; // already unleared
3275 bool cur_active
= itr
->second
.active
;
3276 bool cur_dependent
= itr
->second
.dependent
;
3280 itr
->second
.disabled
= disabled
;
3281 if(itr
->second
.state
!= PLAYERSPELL_NEW
)
3282 itr
->second
.state
= PLAYERSPELL_CHANGED
;
3286 if(itr
->second
.state
== PLAYERSPELL_NEW
)
3287 m_spells
.erase(itr
);
3289 itr
->second
.state
= PLAYERSPELL_REMOVED
;
3292 RemoveAurasDueToSpell(spell_id
);
3295 for(int i
= 0; i
< MAX_EFFECT_INDEX
; ++i
)
3296 if(PetAura
const* petSpell
= sSpellMgr
.GetPetAura(spell_id
, SpellEffectIndex(i
)))
3297 RemovePetAura(petSpell
);
3299 TalentSpellPos
const* talentPos
= GetTalentSpellPos(spell_id
);
3302 // free talent points
3303 uint32 talentCosts
= GetTalentSpellCost(talentPos
);
3305 if(talentCosts
< m_usedTalentCount
)
3306 m_usedTalentCount
-= talentCosts
;
3308 m_usedTalentCount
= 0;
3310 UpdateFreeTalentPoints(false);
3313 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3314 if(sSpellMgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
3316 uint32 freeProfs
= GetFreePrimaryProfessionPoints()+1;
3317 if(freeProfs
<= sWorld
.getConfig(CONFIG_UINT32_MAX_PRIMARY_TRADE_SKILL
))
3318 SetFreePrimaryProfessions(freeProfs
);
3321 // remove dependent skill
3322 SpellLearnSkillNode
const* spellLearnSkill
= sSpellMgr
.GetSpellLearnSkill(spell_id
);
3325 uint32 prev_spell
= sSpellMgr
.GetPrevSpellInChain(spell_id
);
3326 if(!prev_spell
) // first rank, remove skill
3327 SetSkill(spellLearnSkill
->skill
,0,0);
3330 // search prev. skill setting by spell ranks chain
3331 SpellLearnSkillNode
const* prevSkill
= sSpellMgr
.GetSpellLearnSkill(prev_spell
);
3332 while(!prevSkill
&& prev_spell
)
3334 prev_spell
= sSpellMgr
.GetPrevSpellInChain(prev_spell
);
3335 prevSkill
= sSpellMgr
.GetSpellLearnSkill(sSpellMgr
.GetFirstSpellInChain(prev_spell
));
3338 if (!prevSkill
) // not found prev skill setting, remove skill
3339 SetSkill(spellLearnSkill
->skill
,0,0);
3340 else // set to prev. skill setting values
3342 uint32 skill_value
= GetPureSkillValue(prevSkill
->skill
);
3343 uint32 skill_max_value
= GetPureMaxSkillValue(prevSkill
->skill
);
3345 if (skill_value
> prevSkill
->value
)
3346 skill_value
= prevSkill
->value
;
3348 uint32 new_skill_max_value
= prevSkill
->maxvalue
== 0 ? GetMaxSkillValueForLevel() : prevSkill
->maxvalue
;
3350 if (skill_max_value
> new_skill_max_value
)
3351 skill_max_value
= new_skill_max_value
;
3353 SetSkill(prevSkill
->skill
,skill_value
,skill_max_value
);
3360 // not ranked skills
3361 SkillLineAbilityMapBounds bounds
= sSpellMgr
.GetSkillLineAbilityMapBounds(spell_id
);
3363 for(SkillLineAbilityMap::const_iterator _spell_idx
= bounds
.first
; _spell_idx
!= bounds
.second
; ++_spell_idx
)
3365 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
3369 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
&&
3370 pSkill
->categoryId
!= SKILL_CATEGORY_CLASS
||// not unlearn class skills (spellbook/talent pages)
3371 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3372 ((pSkill
->id
==SKILL_LOCKPICKING
|| pSkill
->id
==SKILL_RUNEFORGING
) && _spell_idx
->second
->max_value
==0))
3374 // not reset skills for professions and racial abilities
3375 if ((pSkill
->categoryId
==SKILL_CATEGORY_SECONDARY
|| pSkill
->categoryId
==SKILL_CATEGORY_PROFESSION
) &&
3376 (IsProfessionSkill(pSkill
->id
) || _spell_idx
->second
->racemask
!=0))
3379 SetSkill(pSkill
->id
, 0, 0 );
3384 // remove dependent spells
3385 SpellLearnSpellMapBounds spell_bounds
= sSpellMgr
.GetSpellLearnSpellMapBounds(spell_id
);
3387 for(SpellLearnSpellMap::const_iterator itr2
= spell_bounds
.first
; itr2
!= spell_bounds
.second
; ++itr2
)
3388 removeSpell(itr2
->second
.spell
, disabled
);
3390 // activate lesser rank in spellbook/action bar, and cast it if need
3391 bool prev_activate
= false;
3393 if (uint32 prev_id
= sSpellMgr
.GetPrevSpellInChain (spell_id
))
3395 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
3397 // if talent then lesser rank also talent and need learn
3401 learnSpell (prev_id
,false);
3403 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3404 else if (cur_active
&& !SpellMgr::canStackSpellRanks(spellInfo
) && sSpellMgr
.GetSpellRank(spellInfo
->Id
) != 0)
3406 // need manually update dependence state (learn spell ignore like attempts)
3407 PlayerSpellMap::iterator prev_itr
= m_spells
.find(prev_id
);
3408 if (prev_itr
!= m_spells
.end())
3410 if (prev_itr
->second
.dependent
!= cur_dependent
)
3412 prev_itr
->second
.dependent
= cur_dependent
;
3413 if (prev_itr
->second
.state
!= PLAYERSPELL_NEW
)
3414 prev_itr
->second
.state
= PLAYERSPELL_CHANGED
;
3417 // now re-learn if need re-activate
3418 if (cur_active
&& !prev_itr
->second
.active
&& learn_low_rank
)
3420 if (addSpell(prev_id
,true,false,prev_itr
->second
.dependent
,prev_itr
->second
.disabled
))
3422 // downgrade spell ranks in spellbook and action bar
3423 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, 4 + 4);
3424 data
<< uint32(spell_id
);
3425 data
<< uint32(prev_id
);
3426 GetSession()->SendPacket( &data
);
3427 prev_activate
= true;
3434 // remove from spell book if not replaced by lesser rank
3435 if (!prev_activate
&& sendUpdate
)
3437 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
3438 data
<< uint32(spell_id
);
3439 GetSession()->SendPacket(&data
);
3443 void Player::RemoveSpellCooldown( uint32 spell_id
, bool update
/* = false */ )
3445 m_spellCooldowns
.erase(spell_id
);
3448 SendClearCooldown(spell_id
, this);
3451 void Player::RemoveSpellCategoryCooldown(uint32 cat
, bool update
/* = false */)
3453 SpellCategoryStore::const_iterator ct
= sSpellCategoryStore
.find(cat
);
3454 if (ct
== sSpellCategoryStore
.end())
3457 const SpellCategorySet
& ct_set
= ct
->second
;
3458 for (SpellCooldowns::const_iterator i
= m_spellCooldowns
.begin(); i
!= m_spellCooldowns
.end();)
3460 if (ct_set
.find(i
->first
) != ct_set
.end())
3461 RemoveSpellCooldown((i
++)->first
, update
);
3467 void Player::RemoveArenaSpellCooldowns()
3469 // remove cooldowns on spells that has < 15 min CD
3470 SpellCooldowns::iterator itr
, next
;
3471 // iterate spell cooldowns
3472 for(itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); itr
= next
)
3476 SpellEntry
const * entry
= sSpellStore
.LookupEntry(itr
->first
);
3477 // check if spellentry is present and if the cooldown is less than 15 mins
3479 entry
->RecoveryTime
<= 15 * MINUTE
* IN_MILLISECONDS
&&
3480 entry
->CategoryRecoveryTime
<= 15 * MINUTE
* IN_MILLISECONDS
)
3483 RemoveSpellCooldown(itr
->first
, true);
3488 void Player::RemoveAllSpellCooldown()
3490 if(!m_spellCooldowns
.empty())
3492 for(SpellCooldowns::const_iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); ++itr
)
3493 SendClearCooldown(itr
->first
, this);
3495 m_spellCooldowns
.clear();
3499 void Player::_LoadSpellCooldowns(QueryResult
*result
)
3501 // some cooldowns can be already set at aura loading...
3503 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3507 time_t curTime
= time(NULL
);
3511 Field
*fields
= result
->Fetch();
3513 uint32 spell_id
= fields
[0].GetUInt32();
3514 uint32 item_id
= fields
[1].GetUInt32();
3515 time_t db_time
= (time_t)fields
[2].GetUInt64();
3517 if(!sSpellStore
.LookupEntry(spell_id
))
3519 sLog
.outError("Player %u has unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id
);
3523 // skip outdated cooldown
3524 if(db_time
<= curTime
)
3527 AddSpellCooldown(spell_id
, item_id
, db_time
);
3529 sLog
.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id
, item_id
, uint32(db_time
-curTime
));
3531 while( result
->NextRow() );
3537 void Player::_SaveSpellCooldowns()
3539 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3541 time_t curTime
= time(NULL
);
3542 time_t infTime
= curTime
+ infinityCooldownDelayCheck
;
3544 /* copied following sql-code partly from achievementmgr */
3545 bool first_round
= true;
3546 std::ostringstream ss
;
3548 // remove outdated and save active
3549 for(SpellCooldowns::iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end();)
3551 if(itr
->second
.end
<= curTime
)
3552 m_spellCooldowns
.erase(itr
++);
3553 else if(itr
->second
.end
<= infTime
) // not save locked cooldowns, it will be reset or set at reload
3557 ss
<< "INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ";
3558 first_round
= false;
3560 // next new/changed record prefix
3563 ss
<< "(" << GetGUIDLow() << "," << itr
->first
<< "," << itr
->second
.itemid
<< "," << uint64(itr
->second
.end
) << ")";
3570 // if something changed execute
3572 CharacterDatabase
.Execute( ss
.str().c_str() );
3575 uint32
Player::resetTalentsCost() const
3577 // The first time reset costs 1 gold
3578 if(m_resetTalentsCost
< 1*GOLD
)
3581 else if(m_resetTalentsCost
< 5*GOLD
)
3583 // After that it increases in increments of 5 gold
3584 else if(m_resetTalentsCost
< 10*GOLD
)
3588 time_t months
= (sWorld
.GetGameTime() - m_resetTalentsTime
)/MONTH
;
3591 // This cost will be reduced by a rate of 5 gold per month
3592 int32 new_cost
= int32((m_resetTalentsCost
) - 5*GOLD
*months
);
3593 // to a minimum of 10 gold.
3594 return uint32(new_cost
< 10*GOLD
? 10*GOLD
: new_cost
);
3598 // After that it increases in increments of 5 gold
3599 int32 new_cost
= m_resetTalentsCost
+ 5*GOLD
;
3600 // until it hits a cap of 50 gold.
3601 if(new_cost
> 50*GOLD
)
3608 bool Player::resetTalents(bool no_cost
)
3610 // not need after this call
3611 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS
))
3612 RemoveAtLoginFlag(AT_LOGIN_RESET_TALENTS
,true);
3614 uint32 talentPointsForLevel
= CalculateTalentsPoints();
3616 if (m_usedTalentCount
== 0)
3618 SetFreeTalentPoints(talentPointsForLevel
);
3626 cost
= resetTalentsCost();
3628 if (GetMoney() < cost
)
3630 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, 0, 0, 0);
3635 for (unsigned int i
= 0; i
< sTalentStore
.GetNumRows(); ++i
)
3637 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry(i
);
3639 if (!talentInfo
) continue;
3641 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentInfo
->TalentTab
);
3646 // unlearn only talents for character class
3647 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3648 // to prevent unexpected lost normal learned spell skip another class talents
3649 if ((getClassMask() & talentTabInfo
->ClassMask
) == 0)
3652 for (int j
= 0; j
< MAX_TALENT_RANK
; ++j
)
3654 for(PlayerSpellMap::iterator itr
= GetSpellMap().begin(); itr
!= GetSpellMap().end();)
3656 if (itr
->second
.state
== PLAYERSPELL_REMOVED
|| itr
->second
.disabled
)
3662 // remove learned spells (all ranks)
3663 uint32 itrFirstId
= sSpellMgr
.GetFirstSpellInChain(itr
->first
);
3665 // unlearn if first rank is talent or learned by talent
3666 if (itrFirstId
== talentInfo
->RankID
[j
])
3668 removeSpell(itr
->first
,!IsPassiveSpell(itr
->first
),false);
3669 itr
= GetSpellMap().begin();
3672 else if (sSpellMgr
.IsSpellLearnToSpell(talentInfo
->RankID
[j
],itrFirstId
))
3674 removeSpell(itr
->first
,!IsPassiveSpell(itr
->first
));
3675 itr
= GetSpellMap().begin();
3684 SetFreeTalentPoints(talentPointsForLevel
);
3688 ModifyMoney(-(int32
)cost
);
3689 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS
, cost
);
3690 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS
, 1);
3692 m_resetTalentsCost
= cost
;
3693 m_resetTalentsTime
= time(NULL
);
3696 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3697 RemovePet(NULL
,PET_SAVE_NOT_IN_SLOT
, true);
3698 /* when prev line will dropped use next line
3699 if(Pet* pet = GetPet())
3701 if(pet->getPetType()==HUNTER_PET && !pet->GetCreatureInfo()->isTameable(CanTameExoticPets()))
3702 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3709 m_canTitanGrip
= false;
3710 if(sWorld
.getConfig(CONFIG_BOOL_OFFHAND_CHECK_AT_TALENTS_RESET
))
3711 AutoUnequipOffhandIfNeed();
3717 Mail
* Player::GetMail(uint32 id
)
3719 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
3721 if ((*itr
)->messageID
== id
)
3729 void Player::_SetCreateBits(UpdateMask
*updateMask
, Player
*target
) const
3733 Object::_SetCreateBits(updateMask
, target
);
3737 for(uint16 index
= 0; index
< m_valuesCount
; index
++)
3739 if(GetUInt32Value(index
) != 0 && updateVisualBits
.GetBit(index
))
3740 updateMask
->SetBit(index
);
3745 void Player::_SetUpdateBits(UpdateMask
*updateMask
, Player
*target
) const
3749 Object::_SetUpdateBits(updateMask
, target
);
3753 Object::_SetUpdateBits(updateMask
, target
);
3754 *updateMask
&= updateVisualBits
;
3758 void Player::InitVisibleBits()
3760 updateVisualBits
.SetCount(PLAYER_END
);
3762 updateVisualBits
.SetBit(OBJECT_FIELD_GUID
);
3763 updateVisualBits
.SetBit(OBJECT_FIELD_TYPE
);
3764 updateVisualBits
.SetBit(OBJECT_FIELD_ENTRY
);
3765 updateVisualBits
.SetBit(OBJECT_FIELD_SCALE_X
);
3766 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 0);
3767 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 1);
3768 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 0);
3769 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 1);
3770 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 0);
3771 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 1);
3772 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 0);
3773 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 1);
3774 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 0);
3775 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 1);
3776 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_0
);
3777 updateVisualBits
.SetBit(UNIT_FIELD_HEALTH
);
3778 updateVisualBits
.SetBit(UNIT_FIELD_POWER1
);
3779 updateVisualBits
.SetBit(UNIT_FIELD_POWER2
);
3780 updateVisualBits
.SetBit(UNIT_FIELD_POWER3
);
3781 updateVisualBits
.SetBit(UNIT_FIELD_POWER4
);
3782 updateVisualBits
.SetBit(UNIT_FIELD_POWER5
);
3783 updateVisualBits
.SetBit(UNIT_FIELD_POWER6
);
3784 updateVisualBits
.SetBit(UNIT_FIELD_POWER7
);
3785 updateVisualBits
.SetBit(UNIT_FIELD_MAXHEALTH
);
3786 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER1
);
3787 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER2
);
3788 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER3
);
3789 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER4
);
3790 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER5
);
3791 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER6
);
3792 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER7
);
3793 updateVisualBits
.SetBit(UNIT_FIELD_LEVEL
);
3794 updateVisualBits
.SetBit(UNIT_FIELD_FACTIONTEMPLATE
);
3795 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 0);
3796 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 1);
3797 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 2);
3798 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS
);
3799 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS_2
);
3800 updateVisualBits
.SetBit(UNIT_FIELD_AURASTATE
);
3801 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 0);
3802 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 1);
3803 updateVisualBits
.SetBit(UNIT_FIELD_BOUNDINGRADIUS
);
3804 updateVisualBits
.SetBit(UNIT_FIELD_COMBATREACH
);
3805 updateVisualBits
.SetBit(UNIT_FIELD_DISPLAYID
);
3806 updateVisualBits
.SetBit(UNIT_FIELD_NATIVEDISPLAYID
);
3807 updateVisualBits
.SetBit(UNIT_FIELD_MOUNTDISPLAYID
);
3808 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_1
);
3809 updateVisualBits
.SetBit(UNIT_FIELD_PETNUMBER
);
3810 updateVisualBits
.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP
);
3811 updateVisualBits
.SetBit(UNIT_DYNAMIC_FLAGS
);
3812 updateVisualBits
.SetBit(UNIT_CHANNEL_SPELL
);
3813 updateVisualBits
.SetBit(UNIT_MOD_CAST_SPEED
);
3814 updateVisualBits
.SetBit(UNIT_FIELD_BASE_MANA
);
3815 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_2
);
3816 updateVisualBits
.SetBit(UNIT_FIELD_HOVERHEIGHT
);
3818 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 0);
3819 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 1);
3820 updateVisualBits
.SetBit(PLAYER_FLAGS
);
3821 updateVisualBits
.SetBit(PLAYER_GUILDID
);
3822 updateVisualBits
.SetBit(PLAYER_GUILDRANK
);
3823 updateVisualBits
.SetBit(PLAYER_BYTES
);
3824 updateVisualBits
.SetBit(PLAYER_BYTES_2
);
3825 updateVisualBits
.SetBit(PLAYER_BYTES_3
);
3826 updateVisualBits
.SetBit(PLAYER_DUEL_TEAM
);
3827 updateVisualBits
.SetBit(PLAYER_GUILD_TIMESTAMP
);
3829 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3830 for(uint16 i
= PLAYER_QUEST_LOG_1_1
; i
< PLAYER_QUEST_LOG_25_2
; i
+= MAX_QUEST_OFFSET
)
3831 updateVisualBits
.SetBit(i
);
3833 // Players visible items are not inventory stuff
3834 for(uint16 i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
3836 uint32 offset
= i
* 2;
3839 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_ENTRYID
+ offset
);
3841 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT
+ offset
);
3844 updateVisualBits
.SetBit(PLAYER_CHOSEN_TITLE
);
3847 void Player::BuildCreateUpdateBlockForPlayer( UpdateData
*data
, Player
*target
) const
3849 for(int i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
3851 if(m_items
[i
] == NULL
)
3854 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3859 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
3861 if(m_items
[i
] == NULL
)
3864 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3866 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
3868 if(m_items
[i
] == NULL
)
3871 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3875 Unit::BuildCreateUpdateBlockForPlayer( data
, target
);
3878 void Player::DestroyForPlayer( Player
*target
, bool anim
) const
3880 Unit::DestroyForPlayer( target
, anim
);
3882 for(int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
3884 if(m_items
[i
] == NULL
)
3887 m_items
[i
]->DestroyForPlayer( target
);
3892 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
3894 if(m_items
[i
] == NULL
)
3897 m_items
[i
]->DestroyForPlayer( target
);
3899 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
3901 if(m_items
[i
] == NULL
)
3904 m_items
[i
]->DestroyForPlayer( target
);
3909 bool Player::HasSpell(uint32 spell
) const
3911 PlayerSpellMap::const_iterator itr
= m_spells
.find(spell
);
3912 return (itr
!= m_spells
.end() && itr
->second
.state
!= PLAYERSPELL_REMOVED
&&
3913 !itr
->second
.disabled
);
3916 bool Player::HasActiveSpell(uint32 spell
) const
3918 PlayerSpellMap::const_iterator itr
= m_spells
.find(spell
);
3919 return (itr
!= m_spells
.end() && itr
->second
.state
!= PLAYERSPELL_REMOVED
&&
3920 itr
->second
.active
&& !itr
->second
.disabled
);
3923 TrainerSpellState
Player::GetTrainerSpellState(TrainerSpell
const* trainer_spell
) const
3926 return TRAINER_SPELL_RED
;
3928 if (!trainer_spell
->learnedSpell
)
3929 return TRAINER_SPELL_RED
;
3932 if(HasSpell(trainer_spell
->learnedSpell
))
3933 return TRAINER_SPELL_GRAY
;
3935 // check race/class requirement
3936 if(!IsSpellFitByClassAndRace(trainer_spell
->learnedSpell
))
3937 return TRAINER_SPELL_RED
;
3939 // check level requirement
3940 if(getLevel() < trainer_spell
->reqLevel
)
3941 return TRAINER_SPELL_RED
;
3943 if(SpellChainNode
const* spell_chain
= sSpellMgr
.GetSpellChainNode(trainer_spell
->learnedSpell
))
3945 // check prev.rank requirement
3946 if(spell_chain
->prev
&& !HasSpell(spell_chain
->prev
))
3947 return TRAINER_SPELL_RED
;
3949 // check additional spell requirement
3950 if(spell_chain
->req
&& !HasSpell(spell_chain
->req
))
3951 return TRAINER_SPELL_RED
;
3954 // check skill requirement
3955 if(trainer_spell
->reqSkill
&& GetBaseSkillValue(trainer_spell
->reqSkill
) < trainer_spell
->reqSkillValue
)
3956 return TRAINER_SPELL_RED
;
3958 // exist, already checked at loading
3959 SpellEntry
const* spell
= sSpellStore
.LookupEntry(trainer_spell
->learnedSpell
);
3961 // secondary prof. or not prof. spell
3962 uint32 skill
= spell
->EffectMiscValue
[1];
3964 if(spell
->Effect
[1] != SPELL_EFFECT_SKILL
|| !IsPrimaryProfessionSkill(skill
))
3965 return TRAINER_SPELL_GREEN
;
3967 // check primary prof. limit
3968 if(sSpellMgr
.IsPrimaryProfessionFirstRankSpell(spell
->Id
) && GetFreePrimaryProfessionPoints() == 0)
3969 return TRAINER_SPELL_GREEN_DISABLED
;
3971 return TRAINER_SPELL_GREEN
;
3974 void Player::DeleteFromDB(uint64 playerguid
, uint32 accountId
, bool updateRealmChars
)
3976 uint32 guid
= GUID_LOPART(playerguid
);
3978 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3979 // bones will be deleted by corpse/bones deleting thread shortly
3980 sObjectAccessor
.ConvertCorpseForPlayer(playerguid
);
3982 // remove from guild
3983 uint32 guildId
= GetGuildIdFromDB(playerguid
);
3986 Guild
* guild
= sObjectMgr
.GetGuildById(guildId
);
3988 guild
->DelMember(guid
);
3991 // remove from arena teams
3992 LeaveAllArenaTeams(playerguid
);
3994 // the player was uninvited already on logout so just remove from group
3995 QueryResult
*resultGroup
= CharacterDatabase
.PQuery("SELECT groupId FROM group_member WHERE memberGuid='%u'", guid
);
3998 uint32 groupId
= (*resultGroup
)[0].GetUInt32();
4000 if (Group
* group
= sObjectMgr
.GetGroupById(groupId
))
4001 RemoveFromGroup(group
, playerguid
);
4004 // remove signs from petitions (also remove petitions if owner);
4005 RemovePetitionsAndSigns(playerguid
, 10);
4007 // return back all mails with COD and Item 0 1 2 3 4 5 6 7
4008 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
);
4013 Field
*fields
= resultMail
->Fetch();
4015 uint32 mail_id
= fields
[0].GetUInt32();
4016 uint16 mailType
= fields
[1].GetUInt16();
4017 uint16 mailTemplateId
= fields
[2].GetUInt16();
4018 uint32 sender
= fields
[3].GetUInt32();
4019 std::string subject
= fields
[4].GetCppString();
4020 uint32 itemTextId
= fields
[5].GetUInt32();
4021 uint32 money
= fields
[6].GetUInt32();
4022 bool has_items
= fields
[7].GetBool();
4024 //we can return mail now
4025 //so firstly delete the old one
4026 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id
);
4028 // mail not from player
4029 if (mailType
!= MAIL_NORMAL
)
4032 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id
);
4036 MailDraft
draft(subject
, itemTextId
);
4038 draft
= MailDraft(mailTemplateId
,false); // itesm already included
4042 // data needs to be at first place for Item::LoadFromDB
4043 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
);
4048 Field
*fields2
= resultItems
->Fetch();
4050 uint32 item_guidlow
= fields2
[1].GetUInt32();
4051 uint32 item_template
= fields2
[2].GetUInt32();
4053 ItemPrototype
const* itemProto
= ObjectMgr::GetItemPrototype(item_template
);
4056 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow
);
4060 Item
*pItem
= NewItemOrBag(itemProto
);
4061 if(!pItem
->LoadFromDB(item_guidlow
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
),resultItems
))
4063 pItem
->FSetState(ITEM_REMOVED
);
4064 pItem
->SaveToDB(); // it also deletes item object !
4068 draft
.AddItem(pItem
);
4070 while (resultItems
->NextRow());
4076 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id
);
4078 uint32 pl_account
= sObjectMgr
.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
4080 draft
.AddMoney(money
).SendReturnToSender(pl_account
, guid
, sender
);
4082 while (resultMail
->NextRow());
4087 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
4088 // Get guids of character's pets, will deleted in transaction
4089 QueryResult
*resultPets
= CharacterDatabase
.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid
);
4091 // NOW we can finally clear other DB data related to character
4092 CharacterDatabase
.BeginTransaction();
4097 Field
*fields3
= resultPets
->Fetch();
4098 uint32 petguidlow
= fields3
[0].GetUInt32();
4099 Pet::DeleteFromDB(petguidlow
);
4100 } while (resultPets
->NextRow());
4104 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",guid
);
4105 CharacterDatabase
.PExecute("DELETE FROM character_account_data WHERE guid = '%u'",guid
);
4106 CharacterDatabase
.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid
);
4107 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid
);
4108 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid
);
4109 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid
);
4110 CharacterDatabase
.PExecute("DELETE FROM character_glyphs WHERE guid = '%u'",guid
);
4111 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid
);
4112 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid
);
4113 CharacterDatabase
.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid
);
4114 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid
);
4115 CharacterDatabase
.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid
);
4116 CharacterDatabase
.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",guid
);
4117 CharacterDatabase
.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid
);
4118 CharacterDatabase
.PExecute("DELETE FROM character_skills WHERE guid = '%u'",guid
);
4119 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid
);
4120 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid
);
4121 CharacterDatabase
.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid
);
4122 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid
);
4123 CharacterDatabase
.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid
,guid
);
4124 CharacterDatabase
.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid
);
4125 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid
);
4126 CharacterDatabase
.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid
);
4127 CharacterDatabase
.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid
);
4128 CharacterDatabase
.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid
);
4129 CharacterDatabase
.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid
);
4130 CharacterDatabase
.PExecute("DELETE FROM character_equipmentsets WHERE guid = '%u'",guid
);
4131 CharacterDatabase
.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid1 = '%u' OR PlayerGuid2 = '%u'",guid
, guid
);
4132 CharacterDatabase
.PExecute("DELETE FROM guild_bank_eventlog WHERE PlayerGuid = '%u'",guid
);
4133 CharacterDatabase
.CommitTransaction();
4135 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
4136 if(updateRealmChars
) sWorld
.UpdateRealmCharCount(accountId
);
4139 void Player::SetMovement(PlayerMovementType pType
)
4144 case MOVE_ROOT
: data
.Initialize(SMSG_FORCE_MOVE_ROOT
, GetPackGUID().size()+4); break;
4145 case MOVE_UNROOT
: data
.Initialize(SMSG_FORCE_MOVE_UNROOT
, GetPackGUID().size()+4); break;
4146 case MOVE_WATER_WALK
: data
.Initialize(SMSG_MOVE_WATER_WALK
, GetPackGUID().size()+4); break;
4147 case MOVE_LAND_WALK
: data
.Initialize(SMSG_MOVE_LAND_WALK
, GetPackGUID().size()+4); break;
4149 sLog
.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType
);
4152 data
<< GetPackGUID();
4154 GetSession()->SendPacket( &data
);
4158 - a resurrectable corpse must not be loaded for the player (only bones)
4159 - the player must be in world
4161 void Player::BuildPlayerRepop()
4163 WorldPacket
data(SMSG_PRE_RESURRECT
, GetPackGUID().size());
4164 data
<< GetPackGUID();
4165 GetSession()->SendPacket(&data
);
4167 if(getRace() == RACE_NIGHTELF
)
4168 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)
4169 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
4171 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
4172 // there must be SMSG.STOP_MIRROR_TIMER
4173 // there we must send 888 opcode
4175 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
4178 sLog
.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
4182 // create a corpse and place it at the player's location
4183 Corpse
*corpse
= CreateCorpse();
4186 sLog
.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
4189 GetMap()->Add(corpse
);
4191 // convert player body to ghost
4194 SetMovement(MOVE_WATER_WALK
);
4195 if(!GetSession()->isLogingOut())
4196 SetMovement(MOVE_UNROOT
);
4198 // BG - remove insignia related
4199 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_SKINNABLE
);
4201 SendCorpseReclaimDelay();
4203 // to prevent cheating
4204 corpse
->ResetGhostTime();
4206 StopMirrorTimers(); //disable timers(bars)
4208 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, (float)1.0); //see radius of death player?
4210 // set and clear other
4211 SetByteValue(UNIT_FIELD_BYTES_1
, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND
);
4214 void Player::ResurrectPlayer(float restore_percent
, bool applySickness
)
4216 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // remove spirit healer position
4221 GetSession()->SendPacket(&data
);
4223 // speed change, land walk
4225 // remove death flag + set aura
4226 SetByteValue(UNIT_FIELD_BYTES_1
, 3, 0x00);
4227 if(getRace() == RACE_NIGHTELF
)
4228 RemoveAurasDueToSpell(20584); // speed bonuses
4229 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
4231 setDeathState(ALIVE
);
4233 SetMovement(MOVE_LAND_WALK
);
4234 SetMovement(MOVE_UNROOT
);
4238 // set health/powers (0- will be set in caller)
4239 if(restore_percent
>0.0f
)
4241 SetHealth(uint32(GetMaxHealth()*restore_percent
));
4242 SetPower(POWER_MANA
, uint32(GetMaxPower(POWER_MANA
)*restore_percent
));
4243 SetPower(POWER_RAGE
, 0);
4244 SetPower(POWER_ENERGY
, uint32(GetMaxPower(POWER_ENERGY
)*restore_percent
));
4247 // trigger update zone for alive state zone updates
4248 uint32 newzone
, newarea
;
4249 GetZoneAndAreaId(newzone
,newarea
);
4250 UpdateZone(newzone
,newarea
);
4252 // update visibility
4253 UpdateVisibilityForPlayer();
4258 //Characters from level 1-10 are not affected by resurrection sickness.
4259 //Characters from level 11-19 will suffer from one minute of sickness
4260 //for each level they are above 10.
4261 //Characters level 20 and up suffer from ten minutes of sickness.
4262 int32 startLevel
= sWorld
.getConfig(CONFIG_INT32_DEATH_SICKNESS_LEVEL
);
4264 if(int32(getLevel()) >= startLevel
)
4266 // set resurrection sickness
4267 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,true);
4269 // not full duration
4270 if(int32(getLevel()) < startLevel
+9)
4272 int32 delta
= (int32(getLevel()) - startLevel
+ 1)*MINUTE
;
4274 for(int i
= 0; i
< MAX_EFFECT_INDEX
; ++i
)
4276 if(Aura
* Aur
= GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,SpellEffectIndex(i
)))
4278 Aur
->SetAuraDuration(delta
*IN_MILLISECONDS
);
4279 Aur
->SendAuraUpdate(false);
4286 void Player::KillPlayer()
4288 SetMovement(MOVE_ROOT
);
4290 StopMirrorTimers(); //disable timers(bars)
4292 setDeathState(CORPSE
);
4293 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4295 SetFlag(UNIT_DYNAMIC_FLAGS
, 0x00);
4296 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, !sMapStore
.LookupEntry(GetMapId())->Instanceable());
4298 // 6 minutes until repop at graveyard
4299 m_deathTimer
= 6*MINUTE
*IN_MILLISECONDS
;
4301 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4303 // don't create corpse at this moment, player might be falling
4305 // update visibility
4306 UpdateObjectVisibility();
4309 Corpse
* Player::CreateCorpse()
4311 // prevent existence 2 corpse for player
4314 uint32 _uf
, _pb
, _pb2
, _cfb1
, _cfb2
;
4316 Corpse
*corpse
= new Corpse( (m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
) ? CORPSE_RESURRECTABLE_PVP
: CORPSE_RESURRECTABLE_PVE
);
4319 if (!corpse
->Create(sObjectMgr
.GenerateLowGuid(HIGHGUID_CORPSE
), this))
4325 _uf
= GetUInt32Value(UNIT_FIELD_BYTES_0
);
4326 _pb
= GetUInt32Value(PLAYER_BYTES
);
4327 _pb2
= GetUInt32Value(PLAYER_BYTES_2
);
4329 uint8 race
= (uint8
)(_uf
);
4330 uint8 skin
= (uint8
)(_pb
);
4331 uint8 face
= (uint8
)(_pb
>> 8);
4332 uint8 hairstyle
= (uint8
)(_pb
>> 16);
4333 uint8 haircolor
= (uint8
)(_pb
>> 24);
4334 uint8 facialhair
= (uint8
)(_pb2
);
4336 _cfb1
= ((0x00) | (race
<< 8) | (getGender() << 16) | (skin
<< 24));
4337 _cfb2
= ((face
) | (hairstyle
<< 8) | (haircolor
<< 16) | (facialhair
<< 24));
4339 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_1
, _cfb1
);
4340 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_2
, _cfb2
);
4342 uint32 flags
= CORPSE_FLAG_UNK2
;
4343 if (HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
4344 flags
|= CORPSE_FLAG_HIDE_HELM
;
4345 if (HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
4346 flags
|= CORPSE_FLAG_HIDE_CLOAK
;
4347 if (InBattleGround() && !InArena())
4348 flags
|= CORPSE_FLAG_LOOTABLE
; // to be able to remove insignia
4349 corpse
->SetUInt32Value( CORPSE_FIELD_FLAGS
, flags
);
4351 corpse
->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID
, GetNativeDisplayId() );
4353 corpse
->SetUInt32Value( CORPSE_FIELD_GUILD
, GetGuildId() );
4356 uint32 iIventoryType
;
4358 for (int i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
4362 iDisplayID
= m_items
[i
]->GetProto()->DisplayInfoID
;
4363 iIventoryType
= m_items
[i
]->GetProto()->InventoryType
;
4365 _cfi
= iDisplayID
| (iIventoryType
<< 24);
4366 corpse
->SetUInt32Value(CORPSE_FIELD_ITEM
+ i
, _cfi
);
4370 // we not need saved corpses for BG/arenas
4371 if (!GetMap()->IsBattleGroundOrArena())
4374 // register for player, but not show
4375 sObjectAccessor
.AddCorpse(corpse
);
4379 void Player::SpawnCorpseBones()
4381 if(sObjectAccessor
.ConvertCorpseForPlayer(GetGUID()))
4382 if (!GetSession()->PlayerLogoutWithSave()) // at logout we will already store the player
4383 SaveToDB(); // prevent loading as ghost without corpse
4386 Corpse
* Player::GetCorpse() const
4388 return sObjectAccessor
.GetCorpseForPlayerGUID(GetGUID());
4391 void Player::DurabilityLossAll(double percent
, bool inventory
)
4393 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
4394 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4395 DurabilityLoss(pItem
,percent
);
4399 // bags not have durability
4400 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4402 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
4403 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4404 DurabilityLoss(pItem
,percent
);
4406 // keys not have durability
4407 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4409 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
4410 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4411 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
4412 if(Item
* pItem
= GetItemByPos( i
, j
))
4413 DurabilityLoss(pItem
,percent
);
4417 void Player::DurabilityLoss(Item
* item
, double percent
)
4422 uint32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4427 uint32 pDurabilityLoss
= uint32(pMaxDurability
*percent
);
4429 if(pDurabilityLoss
< 1 )
4430 pDurabilityLoss
= 1;
4432 DurabilityPointsLoss(item
,pDurabilityLoss
);
4435 void Player::DurabilityPointsLossAll(int32 points
, bool inventory
)
4437 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
4438 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4439 DurabilityPointsLoss(pItem
,points
);
4443 // bags not have durability
4444 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4446 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
4447 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4448 DurabilityPointsLoss(pItem
,points
);
4450 // keys not have durability
4451 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4453 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
4454 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4455 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
4456 if(Item
* pItem
= GetItemByPos( i
, j
))
4457 DurabilityPointsLoss(pItem
,points
);
4461 void Player::DurabilityPointsLoss(Item
* item
, int32 points
)
4463 int32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4464 int32 pOldDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4465 int32 pNewDurability
= pOldDurability
- points
;
4467 if (pNewDurability
< 0)
4469 else if (pNewDurability
> pMaxDurability
)
4470 pNewDurability
= pMaxDurability
;
4472 if (pOldDurability
!= pNewDurability
)
4474 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4475 if ( pNewDurability
== 0 && pOldDurability
> 0 && item
->IsEquipped())
4476 _ApplyItemMods(item
,item
->GetSlot(), false);
4478 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, pNewDurability
);
4480 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4481 if ( pNewDurability
> 0 && pOldDurability
== 0 && item
->IsEquipped())
4482 _ApplyItemMods(item
,item
->GetSlot(), true);
4484 item
->SetState(ITEM_CHANGED
, this);
4488 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot
)
4490 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
))
4491 DurabilityPointsLoss(pItem
,1);
4494 uint32
Player::DurabilityRepairAll(bool cost
, float discountMod
, bool guildBank
)
4496 uint32 TotalCost
= 0;
4497 // equipped, backpack, bags itself
4498 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
4499 TotalCost
+= DurabilityRepair(( (INVENTORY_SLOT_BAG_0
<< 8) | i
),cost
,discountMod
, guildBank
);
4501 // bank, buyback and keys not repaired
4503 // items in inventory bags
4504 for(int j
= INVENTORY_SLOT_BAG_START
; j
< INVENTORY_SLOT_BAG_END
; ++j
)
4505 for(int i
= 0; i
< MAX_BAG_SIZE
; ++i
)
4506 TotalCost
+= DurabilityRepair(( (j
<< 8) | i
),cost
,discountMod
, guildBank
);
4510 uint32
Player::DurabilityRepair(uint16 pos
, bool cost
, float discountMod
, bool guildBank
)
4512 Item
* item
= GetItemByPos(pos
);
4514 uint32 TotalCost
= 0;
4518 uint32 maxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4522 uint32 curDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4526 uint32 LostDurability
= maxDurability
- curDurability
;
4527 if(LostDurability
>0)
4529 ItemPrototype
const *ditemProto
= item
->GetProto();
4531 DurabilityCostsEntry
const *dcost
= sDurabilityCostsStore
.LookupEntry(ditemProto
->ItemLevel
);
4534 sLog
.outError("RepairDurability: Wrong item lvl %u", ditemProto
->ItemLevel
);
4538 uint32 dQualitymodEntryId
= (ditemProto
->Quality
+1)*2;
4539 DurabilityQualityEntry
const *dQualitymodEntry
= sDurabilityQualityStore
.LookupEntry(dQualitymodEntryId
);
4540 if(!dQualitymodEntry
)
4542 sLog
.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId
);
4546 uint32 dmultiplier
= dcost
->multiplier
[ItemSubClassToDurabilityMultiplierId(ditemProto
->Class
,ditemProto
->SubClass
)];
4547 uint32 costs
= uint32(LostDurability
*dmultiplier
*double(dQualitymodEntry
->quality_mod
));
4549 costs
= uint32(costs
* discountMod
);
4551 if (costs
==0) //fix for ITEM_QUALITY_ARTIFACT
4556 if (GetGuildId()==0)
4558 DEBUG_LOG("You are not member of a guild");
4562 Guild
*pGuild
= sObjectMgr
.GetGuildById(GetGuildId());
4566 if (!pGuild
->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR
))
4568 DEBUG_LOG("You do not have rights to withdraw for repairs");
4572 if (pGuild
->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs
)
4574 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4578 if (pGuild
->GetGuildBankMoney() < costs
)
4580 DEBUG_LOG("There is not enough money in bank");
4584 pGuild
->MemberMoneyWithdraw(costs
, GetGUIDLow());
4587 else if (GetMoney() < costs
)
4589 DEBUG_LOG("You do not have enough money");
4593 ModifyMoney( -int32(costs
) );
4597 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, maxDurability
);
4598 item
->SetState(ITEM_CHANGED
, this);
4600 // reapply mods for total broken and repaired item if equipped
4601 if(IsEquipmentPos(pos
) && !curDurability
)
4602 _ApplyItemMods(item
,pos
& 255, true);
4606 void Player::RepopAtGraveyard()
4608 // note: this can be called also when the player is alive
4609 // for example from WorldSession::HandleMovementOpcodes
4611 AreaTableEntry
const *zone
= GetAreaEntryByAreaID(GetAreaId());
4613 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4614 if ((!isAlive() && zone
&& zone
->flags
& AREA_FLAG_NEED_FLY
) || GetTransport())
4616 ResurrectPlayer(0.5f
);
4620 WorldSafeLocsEntry
const *ClosestGrave
= NULL
;
4622 // Special handle for battleground maps
4623 if( BattleGround
*bg
= GetBattleGround() )
4624 ClosestGrave
= bg
->GetClosestGraveYard(this);
4626 ClosestGrave
= sObjectMgr
.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4628 // stop countdown until repop
4631 // if no grave found, stay at the current location
4632 // and don't show spirit healer location
4635 TeleportTo(ClosestGrave
->map_id
, ClosestGrave
->x
, ClosestGrave
->y
, ClosestGrave
->z
, GetOrientation());
4636 if(isDead()) // not send if alive, because it used in TeleportTo()
4638 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // show spirit healer position on minimap
4639 data
<< ClosestGrave
->map_id
;
4640 data
<< ClosestGrave
->x
;
4641 data
<< ClosestGrave
->y
;
4642 data
<< ClosestGrave
->z
;
4643 GetSession()->SendPacket(&data
);
4648 void Player::JoinedChannel(Channel
*c
)
4650 m_channels
.push_back(c
);
4653 void Player::LeftChannel(Channel
*c
)
4655 m_channels
.remove(c
);
4658 void Player::CleanupChannels()
4660 while(!m_channels
.empty())
4662 Channel
* ch
= *m_channels
.begin();
4663 m_channels
.erase(m_channels
.begin()); // remove from player's channel list
4664 ch
->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4665 if (ChannelMgr
* cMgr
= channelMgr(GetTeam()))
4666 cMgr
->LeftChannel(ch
->GetName()); // deleted channel if empty
4669 sLog
.outDebug("Player: channels cleaned up!");
4672 void Player::UpdateLocalChannels(uint32 newZone
)
4674 if(m_channels
.empty())
4677 AreaTableEntry
const* current_zone
= GetAreaEntryByAreaID(newZone
);
4681 ChannelMgr
* cMgr
= channelMgr(GetTeam());
4685 std::string current_zone_name
= current_zone
->area_name
[GetSession()->GetSessionDbcLocale()];
4687 for(JoinedChannelsList::iterator i
= m_channels
.begin(), next
; i
!= m_channels
.end(); i
= next
)
4691 // skip non built-in channels
4692 if(!(*i
)->IsConstant())
4695 ChatChannelsEntry
const* ch
= GetChannelEntryFor((*i
)->GetChannelId());
4699 if((ch
->flags
& 4) == 4) // global channel without zone name in pattern
4703 char new_channel_name_buf
[100];
4704 snprintf(new_channel_name_buf
,100,ch
->pattern
[m_session
->GetSessionDbcLocale()],current_zone_name
.c_str());
4705 Channel
* new_channel
= cMgr
->GetJoinChannel(new_channel_name_buf
,ch
->ChannelID
);
4707 if((*i
)!=new_channel
)
4709 new_channel
->Join(GetGUID(),""); // will output Changed Channel: N. Name
4711 // leave old channel
4712 (*i
)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4713 std::string name
= (*i
)->GetName(); // store name, (*i)erase in LeftChannel
4714 LeftChannel(*i
); // remove from player's channel list
4715 cMgr
->LeftChannel(name
); // delete if empty
4718 sLog
.outDebug("Player: channels cleaned up!");
4721 void Player::LeaveLFGChannel()
4723 for(JoinedChannelsList::iterator i
= m_channels
.begin(); i
!= m_channels
.end(); ++i
)
4727 (*i
)->Leave(GetGUID());
4733 void Player::UpdateDefense()
4735 uint32 defense_skill_gain
= sWorld
.getConfig(CONFIG_UINT32_SKILL_GAIN_DEFENSE
);
4737 if(UpdateSkill(SKILL_DEFENSE
,defense_skill_gain
))
4739 // update dependent from defense skill part
4740 UpdateDefenseBonusesMod();
4744 void Player::HandleBaseModValue(BaseModGroup modGroup
, BaseModType modType
, float amount
, bool apply
)
4746 if(modGroup
>= BASEMOD_END
|| modType
>= MOD_END
)
4748 sLog
.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4757 m_auraBaseMod
[modGroup
][modType
] += apply
? amount
: -amount
;
4760 if(amount
<= -100.0f
)
4763 val
= (100.0f
+ amount
) / 100.0f
;
4764 m_auraBaseMod
[modGroup
][modType
] *= apply
? val
: (1.0f
/val
);
4768 if(!CanModifyStats())
4773 case CRIT_PERCENTAGE
: UpdateCritPercentage(BASE_ATTACK
); break;
4774 case RANGED_CRIT_PERCENTAGE
: UpdateCritPercentage(RANGED_ATTACK
); break;
4775 case OFFHAND_CRIT_PERCENTAGE
: UpdateCritPercentage(OFF_ATTACK
); break;
4776 case SHIELD_BLOCK_VALUE
: UpdateShieldBlockValue(); break;
4781 float Player::GetBaseModValue(BaseModGroup modGroup
, BaseModType modType
) const
4783 if(modGroup
>= BASEMOD_END
|| modType
> MOD_END
)
4785 sLog
.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4789 if(modType
== PCT_MOD
&& m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4792 return m_auraBaseMod
[modGroup
][modType
];
4795 float Player::GetTotalBaseModValue(BaseModGroup modGroup
) const
4797 if(modGroup
>= BASEMOD_END
)
4799 sLog
.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4803 if(m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4806 return m_auraBaseMod
[modGroup
][FLAT_MOD
] * m_auraBaseMod
[modGroup
][PCT_MOD
];
4809 uint32
Player::GetShieldBlockValue() const
4811 float value
= (m_auraBaseMod
[SHIELD_BLOCK_VALUE
][FLAT_MOD
] + GetStat(STAT_STRENGTH
) * 0.5f
- 10)*m_auraBaseMod
[SHIELD_BLOCK_VALUE
][PCT_MOD
];
4813 value
= (value
< 0) ? 0 : value
;
4815 return uint32(value
);
4818 float Player::GetMeleeCritFromAgility()
4820 uint32 level
= getLevel();
4821 uint32 pclass
= getClass();
4823 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4825 GtChanceToMeleeCritBaseEntry
const *critBase
= sGtChanceToMeleeCritBaseStore
.LookupEntry(pclass
-1);
4826 GtChanceToMeleeCritEntry
const *critRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4827 if (critBase
==NULL
|| critRatio
==NULL
)
4830 float crit
=critBase
->base
+ GetStat(STAT_AGILITY
)*critRatio
->ratio
;
4834 float Player::GetDodgeFromAgility()
4836 // Table for base dodge values
4837 float dodge_base
[MAX_CLASSES
] = {
4839 0.00652f
, // Paladin
4846 0.02011f
, // Warlock
4850 // Crit/agility to dodge/agility coefficient multipliers
4851 float crit_to_dodge
[MAX_CLASSES
] = {
4865 uint32 level
= getLevel();
4866 uint32 pclass
= getClass();
4868 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4870 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4871 GtChanceToMeleeCritEntry
const *dodgeRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4872 if (dodgeRatio
==NULL
|| pclass
> MAX_CLASSES
)
4875 float dodge
=dodge_base
[pclass
-1] + GetStat(STAT_AGILITY
) * dodgeRatio
->ratio
* crit_to_dodge
[pclass
-1];
4876 return dodge
*100.0f
;
4879 float Player::GetSpellCritFromIntellect()
4881 uint32 level
= getLevel();
4882 uint32 pclass
= getClass();
4884 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4886 GtChanceToSpellCritBaseEntry
const *critBase
= sGtChanceToSpellCritBaseStore
.LookupEntry(pclass
-1);
4887 GtChanceToSpellCritEntry
const *critRatio
= sGtChanceToSpellCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4888 if (critBase
==NULL
|| critRatio
==NULL
)
4891 float crit
=critBase
->base
+ GetStat(STAT_INTELLECT
)*critRatio
->ratio
;
4895 float Player::GetRatingCoefficient(CombatRating cr
) const
4897 uint32 level
= getLevel();
4899 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4901 GtCombatRatingsEntry
const *Rating
= sGtCombatRatingsStore
.LookupEntry(cr
*GT_MAX_LEVEL
+level
-1);
4903 return 1.0f
; // By default use minimum coefficient (not must be called)
4905 return Rating
->ratio
;
4908 float Player::GetRatingBonusValue(CombatRating cr
) const
4910 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
)) / GetRatingCoefficient(cr
);
4913 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType
) const
4918 return GetUInt32Value(PLAYER_EXPERTISE
) / 4.0f
;
4920 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE
) / 4.0f
;
4927 float Player::OCTRegenHPPerSpirit()
4929 uint32 level
= getLevel();
4930 uint32 pclass
= getClass();
4932 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4934 GtOCTRegenHPEntry
const *baseRatio
= sGtOCTRegenHPStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4935 GtRegenHPPerSptEntry
const *moreRatio
= sGtRegenHPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4936 if (baseRatio
==NULL
|| moreRatio
==NULL
)
4939 // Formula from PaperDollFrame script
4940 float spirit
= GetStat(STAT_SPIRIT
);
4941 float baseSpirit
= spirit
;
4942 if (baseSpirit
>50) baseSpirit
= 50;
4943 float moreSpirit
= spirit
- baseSpirit
;
4944 float regen
= baseSpirit
* baseRatio
->ratio
+ moreSpirit
* moreRatio
->ratio
;
4948 float Player::OCTRegenMPPerSpirit()
4950 uint32 level
= getLevel();
4951 uint32 pclass
= getClass();
4953 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4955 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4956 GtRegenMPPerSptEntry
const *moreRatio
= sGtRegenMPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4957 if (moreRatio
==NULL
)
4960 // Formula get from PaperDollFrame script
4961 float spirit
= GetStat(STAT_SPIRIT
);
4962 float regen
= spirit
* moreRatio
->ratio
;
4966 void Player::ApplyRatingMod(CombatRating cr
, int32 value
, bool apply
)
4968 m_baseRatingValue
[cr
]+=(apply
? value
: -value
);
4970 // explicit affected values
4973 case CR_HASTE_MELEE
:
4975 float RatingChange
= value
/ GetRatingCoefficient(cr
);
4976 ApplyAttackTimePercentMod(BASE_ATTACK
,RatingChange
,apply
);
4977 ApplyAttackTimePercentMod(OFF_ATTACK
,RatingChange
,apply
);
4980 case CR_HASTE_RANGED
:
4982 float RatingChange
= value
/ GetRatingCoefficient(cr
);
4983 ApplyAttackTimePercentMod(RANGED_ATTACK
, RatingChange
, apply
);
4986 case CR_HASTE_SPELL
:
4988 float RatingChange
= value
/ GetRatingCoefficient(cr
);
4989 ApplyCastTimePercentMod(RatingChange
,apply
);
4997 void Player::UpdateRating(CombatRating cr
)
4999 int32 amount
= m_baseRatingValue
[cr
];
5000 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
5001 // stat used stored in miscValueB for this aura
5002 AuraList
const& modRatingFromStat
= GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT
);
5003 for(AuraList::const_iterator i
= modRatingFromStat
.begin();i
!= modRatingFromStat
.end(); ++i
)
5004 if ((*i
)->GetMiscValue() & (1<<cr
))
5005 amount
+= int32(GetStat(Stats((*i
)->GetMiscBValue())) * (*i
)->GetModifier()->m_amount
/ 100.0f
);
5008 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
, uint32(amount
));
5010 bool affectStats
= CanModifyStats();
5014 case CR_WEAPON_SKILL
: // Implemented in Unit::RollMeleeOutcomeAgainst
5015 case CR_DEFENSE_SKILL
:
5016 UpdateDefenseBonusesMod();
5019 UpdateDodgePercentage();
5022 UpdateParryPercentage();
5025 UpdateBlockPercentage();
5028 UpdateMeleeHitChances();
5031 UpdateRangedHitChances();
5034 UpdateSpellHitChances();
5039 UpdateCritPercentage(BASE_ATTACK
);
5040 UpdateCritPercentage(OFF_ATTACK
);
5043 case CR_CRIT_RANGED
:
5045 UpdateCritPercentage(RANGED_ATTACK
);
5049 UpdateAllSpellCritChances();
5051 case CR_HIT_TAKEN_MELEE
: // Implemented in Unit::MeleeMissChanceCalc
5052 case CR_HIT_TAKEN_RANGED
:
5054 case CR_HIT_TAKEN_SPELL
: // Implemented in Unit::MagicSpellHitResult
5056 case CR_CRIT_TAKEN_MELEE
: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
5057 case CR_CRIT_TAKEN_RANGED
:
5059 case CR_CRIT_TAKEN_SPELL
: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
5061 case CR_HASTE_MELEE
: // Implemented in Player::ApplyRatingMod
5062 case CR_HASTE_RANGED
:
5063 case CR_HASTE_SPELL
:
5065 case CR_WEAPON_SKILL_MAINHAND
: // Implemented in Unit::RollMeleeOutcomeAgainst
5066 case CR_WEAPON_SKILL_OFFHAND
:
5067 case CR_WEAPON_SKILL_RANGED
:
5072 UpdateExpertise(BASE_ATTACK
);
5073 UpdateExpertise(OFF_ATTACK
);
5076 case CR_ARMOR_PENETRATION
:
5078 UpdateArmorPenetration();
5083 void Player::UpdateAllRatings()
5085 for(int cr
= 0; cr
< MAX_COMBAT_RATING
; ++cr
)
5086 UpdateRating(CombatRating(cr
));
5089 void Player::SetRegularAttackTime()
5091 for(int i
= 0; i
< MAX_ATTACK
; ++i
)
5093 Item
*tmpitem
= GetWeaponForAttack(WeaponAttackType(i
),true,false);
5096 ItemPrototype
const *proto
= tmpitem
->GetProto();
5098 SetAttackTime(WeaponAttackType(i
), proto
->Delay
);
5100 SetAttackTime(WeaponAttackType(i
), BASE_ATTACK_TIME
);
5105 //skill+step, checking for max value
5106 bool Player::UpdateSkill(uint32 skill_id
, uint32 step
)
5111 SkillStatusMap::iterator itr
= mSkillStatus
.find(skill_id
);
5112 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5115 uint32 valueIndex
= PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
);
5116 uint32 data
= GetUInt32Value(valueIndex
);
5117 uint32 value
= SKILL_VALUE(data
);
5118 uint32 max
= SKILL_MAX(data
);
5120 if ((!max
) || (!value
) || (value
>= max
))
5123 if (value
*512 < max
*urand(0,512))
5125 uint32 new_value
= value
+step
;
5129 SetUInt32Value(valueIndex
,MAKE_SKILL_VALUE(new_value
,max
));
5130 if(itr
->second
.uState
!= SKILL_NEW
)
5131 itr
->second
.uState
= SKILL_CHANGED
;
5132 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,skill_id
);
5139 inline int SkillGainChance(uint32 SkillValue
, uint32 GrayLevel
, uint32 GreenLevel
, uint32 YellowLevel
)
5141 if ( SkillValue
>= GrayLevel
)
5142 return sWorld
.getConfig(CONFIG_UINT32_SKILL_CHANCE_GREY
)*10;
5143 if ( SkillValue
>= GreenLevel
)
5144 return sWorld
.getConfig(CONFIG_UINT32_SKILL_CHANCE_GREEN
)*10;
5145 if ( SkillValue
>= YellowLevel
)
5146 return sWorld
.getConfig(CONFIG_UINT32_SKILL_CHANCE_YELLOW
)*10;
5147 return sWorld
.getConfig(CONFIG_UINT32_SKILL_CHANCE_ORANGE
)*10;
5150 bool Player::UpdateCraftSkill(uint32 spellid
)
5152 sLog
.outDebug("UpdateCraftSkill spellid %d", spellid
);
5154 SkillLineAbilityMapBounds bounds
= sSpellMgr
.GetSkillLineAbilityMapBounds(spellid
);
5156 for(SkillLineAbilityMap::const_iterator _spell_idx
= bounds
.first
; _spell_idx
!= bounds
.second
; ++_spell_idx
)
5158 if (_spell_idx
->second
->skillId
)
5160 uint32 SkillValue
= GetPureSkillValue(_spell_idx
->second
->skillId
);
5162 // Alchemy Discoveries here
5163 SpellEntry
const* spellEntry
= sSpellStore
.LookupEntry(spellid
);
5164 if (spellEntry
&& spellEntry
->Mechanic
==MECHANIC_DISCOVERY
)
5166 if (uint32 discoveredSpell
= GetSkillDiscoverySpell(_spell_idx
->second
->skillId
, spellid
, this))
5167 learnSpell(discoveredSpell
,false);
5170 uint32 craft_skill_gain
= sWorld
.getConfig(CONFIG_UINT32_SKILL_GAIN_CRAFTING
);
5172 return UpdateSkillPro(_spell_idx
->second
->skillId
, SkillGainChance(SkillValue
,
5173 _spell_idx
->second
->max_value
,
5174 (_spell_idx
->second
->max_value
+ _spell_idx
->second
->min_value
)/2,
5175 _spell_idx
->second
->min_value
),
5182 bool Player::UpdateGatherSkill(uint32 SkillId
, uint32 SkillValue
, uint32 RedLevel
, uint32 Multiplicator
)
5184 sLog
.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId
, SkillValue
, RedLevel
);
5186 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_UINT32_SKILL_GAIN_GATHERING
);
5188 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
5191 case SKILL_HERBALISM
:
5192 case SKILL_LOCKPICKING
:
5193 case SKILL_JEWELCRAFTING
:
5194 case SKILL_INSCRIPTION
:
5195 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
5196 case SKILL_SKINNING
:
5197 if( sWorld
.getConfig(CONFIG_UINT32_SKILL_CHANCE_SKINNING_STEPS
)==0)
5198 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
5200 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_UINT32_SKILL_CHANCE_SKINNING_STEPS
)), gathering_skill_gain
);
5202 if (sWorld
.getConfig(CONFIG_UINT32_SKILL_CHANCE_MINING_STEPS
)==0)
5203 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
5205 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_UINT32_SKILL_CHANCE_MINING_STEPS
)),gathering_skill_gain
);
5210 bool Player::UpdateFishingSkill()
5212 sLog
.outDebug("UpdateFishingSkill");
5214 uint32 SkillValue
= GetPureSkillValue(SKILL_FISHING
);
5216 int32 chance
= SkillValue
< 75 ? 100 : 2500/(SkillValue
-50);
5218 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_UINT32_SKILL_GAIN_GATHERING
);
5220 return UpdateSkillPro(SKILL_FISHING
,chance
*10,gathering_skill_gain
);
5223 // levels sync. with spell requirement for skill levels to learn
5224 // bonus abilities in sSkillLineAbilityStore
5225 // Used only to avoid scan DBC at each skill grow
5226 static uint32 bonusSkillLevels
[] = {75,150,225,300,375,450};
5228 bool Player::UpdateSkillPro(uint16 SkillId
, int32 Chance
, uint32 step
)
5230 sLog
.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId
, Chance
/10.0);
5234 if(Chance
<= 0) // speedup in 0 chance case
5236 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
5240 SkillStatusMap::iterator itr
= mSkillStatus
.find(SkillId
);
5241 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5244 uint32 valueIndex
= PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
);
5246 uint32 data
= GetUInt32Value(valueIndex
);
5247 uint16 SkillValue
= SKILL_VALUE(data
);
5248 uint16 MaxValue
= SKILL_MAX(data
);
5250 if ( !MaxValue
|| !SkillValue
|| SkillValue
>= MaxValue
)
5253 int32 Roll
= irand(1,1000);
5255 if ( Roll
<= Chance
)
5257 uint32 new_value
= SkillValue
+step
;
5258 if(new_value
> MaxValue
)
5259 new_value
= MaxValue
;
5261 SetUInt32Value(valueIndex
,MAKE_SKILL_VALUE(new_value
,MaxValue
));
5262 if(itr
->second
.uState
!= SKILL_NEW
)
5263 itr
->second
.uState
= SKILL_CHANGED
;
5264 for(uint32
* bsl
= &bonusSkillLevels
[0]; *bsl
; ++bsl
)
5266 if((SkillValue
< *bsl
&& new_value
>= *bsl
))
5268 learnSkillRewardedSpells( SkillId
, new_value
);
5272 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,SkillId
);
5273 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance
/10.0);
5277 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
5281 void Player::UpdateWeaponSkill (WeaponAttackType attType
)
5283 // no skill gain in pvp
5284 Unit
*pVictim
= getVictim();
5285 if(pVictim
&& pVictim
->IsCharmerOrOwnerPlayerOrPlayerItself())
5289 return; // always maximized SKILL_FERAL_COMBAT in fact
5291 if(m_form
== FORM_TREE
)
5292 return; // use weapon but not skill up
5294 uint32 weapon_skill_gain
= sWorld
.getConfig(CONFIG_UINT32_SKILL_GAIN_WEAPON
);
5300 Item
*tmpitem
= GetWeaponForAttack(attType
,true,true);
5303 UpdateSkill(SKILL_UNARMED
,weapon_skill_gain
);
5304 else if(tmpitem
->GetProto()->SubClass
!= ITEM_SUBCLASS_WEAPON_FISHING_POLE
)
5305 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
5311 Item
*tmpitem
= GetWeaponForAttack(attType
,true,true);
5313 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
5317 UpdateAllCritPercentages();
5320 void Player::UpdateCombatSkills(Unit
*pVictim
, WeaponAttackType attType
, bool defence
)
5322 uint32 plevel
= getLevel(); // if defense than pVictim == attacker
5323 uint32 greylevel
= MaNGOS::XP::GetGrayLevel(plevel
);
5324 uint32 moblevel
= pVictim
->getLevelForTarget(this);
5325 if(moblevel
< greylevel
)
5328 if (moblevel
> plevel
+ 5)
5329 moblevel
= plevel
+ 5;
5331 uint32 lvldif
= moblevel
- greylevel
;
5335 uint32 skilldif
= 5 * plevel
- (defence
? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType
));
5339 float chance
= float(3 * lvldif
* skilldif
) / plevel
;
5342 if(getClass() == CLASS_WARRIOR
|| getClass() == CLASS_ROGUE
)
5343 chance
*= 0.1f
* GetStat(STAT_INTELLECT
);
5346 chance
= chance
< 1.0f
? 1.0f
: chance
; //minimum chance to increase skill is 1%
5348 if(roll_chance_f(chance
))
5353 UpdateWeaponSkill(attType
);
5359 void Player::ModifySkillBonus(uint32 skillid
,int32 val
, bool talent
)
5361 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skillid
);
5362 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5365 uint32 bonusIndex
= PLAYER_SKILL_BONUS_INDEX(itr
->second
.pos
);
5367 uint32 bonus_val
= GetUInt32Value(bonusIndex
);
5368 int16 temp_bonus
= SKILL_TEMP_BONUS(bonus_val
);
5369 int16 perm_bonus
= SKILL_PERM_BONUS(bonus_val
);
5371 if(talent
) // permanent bonus stored in high part
5372 SetUInt32Value(bonusIndex
,MAKE_SKILL_BONUS(temp_bonus
,perm_bonus
+val
));
5373 else // temporary/item bonus stored in low part
5374 SetUInt32Value(bonusIndex
,MAKE_SKILL_BONUS(temp_bonus
+val
,perm_bonus
));
5377 void Player::UpdateSkillsForLevel()
5379 uint16 maxconfskill
= sWorld
.GetConfigMaxSkillValue();
5380 uint32 maxSkill
= GetMaxSkillValueForLevel();
5382 bool alwaysMaxSkill
= sWorld
.getConfig(CONFIG_BOOL_ALWAYS_MAX_SKILL_FOR_LEVEL
);
5384 for(SkillStatusMap::iterator itr
= mSkillStatus
.begin(); itr
!= mSkillStatus
.end(); ++itr
)
5386 if(itr
->second
.uState
== SKILL_DELETED
)
5389 uint32 pskill
= itr
->first
;
5391 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(pskill
);
5395 if(GetSkillRangeType(pSkill
,false) != SKILL_RANGE_LEVEL
)
5398 uint32 valueIndex
= PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
);
5399 uint32 data
= GetUInt32Value(valueIndex
);
5400 uint32 max
= SKILL_MAX(data
);
5401 uint32 val
= SKILL_VALUE(data
);
5403 /// update only level dependent max skill values
5406 /// maximize skill always
5409 SetUInt32Value(valueIndex
, MAKE_SKILL_VALUE(maxSkill
,maxSkill
));
5410 if(itr
->second
.uState
!= SKILL_NEW
)
5411 itr
->second
.uState
= SKILL_CHANGED
;
5413 else if(max
!= maxconfskill
) /// update max skill value if current max skill not maximized
5415 SetUInt32Value(valueIndex
, MAKE_SKILL_VALUE(val
,maxSkill
));
5416 if(itr
->second
.uState
!= SKILL_NEW
)
5417 itr
->second
.uState
= SKILL_CHANGED
;
5423 void Player::UpdateSkillsToMaxSkillsForLevel()
5425 for(SkillStatusMap::iterator itr
= mSkillStatus
.begin(); itr
!= mSkillStatus
.end(); ++itr
)
5427 if(itr
->second
.uState
== SKILL_DELETED
)
5430 uint32 pskill
= itr
->first
;
5431 if( IsProfessionOrRidingSkill(pskill
))
5433 uint32 valueIndex
= PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
);
5434 uint32 data
= GetUInt32Value(valueIndex
);
5436 uint32 max
= SKILL_MAX(data
);
5440 SetUInt32Value(valueIndex
,MAKE_SKILL_VALUE(max
,max
));
5441 if(itr
->second
.uState
!= SKILL_NEW
)
5442 itr
->second
.uState
= SKILL_CHANGED
;
5445 if(pskill
== SKILL_DEFENSE
)
5446 UpdateDefenseBonusesMod();
5450 // This functions sets a skill line value (and adds if doesn't exist yet)
5451 // To "remove" a skill line, set it's values to zero
5452 void Player::SetSkill(uint32 id
, uint16 currVal
, uint16 maxVal
)
5457 SkillStatusMap::iterator itr
= mSkillStatus
.find(id
);
5460 if(itr
!= mSkillStatus
.end() && itr
->second
.uState
!= SKILL_DELETED
)
5464 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
),MAKE_SKILL_VALUE(currVal
,maxVal
));
5465 if(itr
->second
.uState
!= SKILL_NEW
)
5466 itr
->second
.uState
= SKILL_CHANGED
;
5467 learnSkillRewardedSpells(id
, currVal
);
5468 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,id
);
5469 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL
,id
);
5473 // clear skill fields
5474 SetUInt32Value(PLAYER_SKILL_INDEX(itr
->second
.pos
),0);
5475 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
),0);
5476 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr
->second
.pos
),0);
5478 // mark as deleted or simply remove from map if not saved yet
5479 if(itr
->second
.uState
!= SKILL_NEW
)
5480 itr
->second
.uState
= SKILL_DELETED
;
5482 mSkillStatus
.erase(itr
);
5484 // remove all spells that related to this skill
5485 for (uint32 j
=0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
5486 if(SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
))
5487 if (pAbility
->skillId
==id
)
5488 removeSpell(sSpellMgr
.GetFirstSpellInChain(pAbility
->spellId
));
5491 else if(currVal
) //add
5493 for (int i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5494 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5496 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
5499 sLog
.outError("Skill not found in SkillLineStore: skill #%u", id
);
5502 // enable unlearn button for primary professions only
5503 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
5504 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
5506 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
5507 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
5508 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,id
);
5509 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL
,id
);
5511 // insert new entry or update if not deleted old entry yet
5512 if(itr
!= mSkillStatus
.end())
5514 itr
->second
.pos
= i
;
5515 itr
->second
.uState
= SKILL_CHANGED
;
5518 mSkillStatus
.insert(SkillStatusMap::value_type(id
, SkillStatusData(i
, SKILL_NEW
)));
5520 // apply skill bonuses
5521 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
5523 // temporary bonuses
5524 AuraList
const& mModSkill
= GetAurasByType(SPELL_AURA_MOD_SKILL
);
5525 for(AuraList::const_iterator j
= mModSkill
.begin(); j
!= mModSkill
.end(); ++j
)
5526 if ((*j
)->GetModifier()->m_miscvalue
== int32(id
))
5527 (*j
)->ApplyModifier(true);
5529 // permanent bonuses
5530 AuraList
const& mModSkillTalent
= GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT
);
5531 for(AuraList::const_iterator j
= mModSkillTalent
.begin(); j
!= mModSkillTalent
.end(); ++j
)
5532 if ((*j
)->GetModifier()->m_miscvalue
== int32(id
))
5533 (*j
)->ApplyModifier(true);
5535 // Learn all spells for skill
5536 learnSkillRewardedSpells(id
, currVal
);
5542 bool Player::HasSkill(uint32 skill
) const
5547 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skill
);
5548 return (itr
!= mSkillStatus
.end() && itr
->second
.uState
!= SKILL_DELETED
);
5551 uint16
Player::GetSkillValue(uint32 skill
) const
5556 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skill
);
5557 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5560 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr
->second
.pos
));
5562 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
))));
5563 result
+= SKILL_TEMP_BONUS(bonus
);
5564 result
+= SKILL_PERM_BONUS(bonus
);
5565 return result
< 0 ? 0 : result
;
5568 uint16
Player::GetMaxSkillValue(uint32 skill
) const
5573 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skill
);
5574 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5577 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr
->second
.pos
));
5579 int32 result
= int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
))));
5580 result
+= SKILL_TEMP_BONUS(bonus
);
5581 result
+= SKILL_PERM_BONUS(bonus
);
5582 return result
< 0 ? 0 : result
;
5585 uint16
Player::GetPureMaxSkillValue(uint32 skill
) const
5590 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skill
);
5591 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5594 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
)));
5597 uint16
Player::GetBaseSkillValue(uint32 skill
) const
5602 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skill
);
5603 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5606 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
))));
5607 result
+= SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr
->second
.pos
)));
5608 return result
< 0 ? 0 : result
;
5611 uint16
Player::GetPureSkillValue(uint32 skill
) const
5616 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skill
);
5617 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5620 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
)));
5623 int16
Player::GetSkillPermBonusValue(uint32 skill
) const
5628 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skill
);
5629 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5632 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr
->second
.pos
)));
5635 int16
Player::GetSkillTempBonusValue(uint32 skill
) const
5640 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skill
);
5641 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5644 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr
->second
.pos
)));
5647 void Player::SendInitialActionButtons() const
5649 sLog
.outDetail( "Initializing Action Buttons for '%u' spec '%u'", GetGUIDLow(), m_activeSpec
);
5651 WorldPacket
data(SMSG_ACTION_BUTTONS
, 1+(MAX_ACTION_BUTTONS
*4));
5652 data
<< uint8(1); // talent spec amount
5653 ActionButtonList
const& currentActionButtonList
= m_actionButtons
[m_activeSpec
];
5654 for(uint8 button
= 0; button
< MAX_ACTION_BUTTONS
; ++button
)
5656 ActionButtonList::const_iterator itr
= currentActionButtonList
.find(button
);
5657 if(itr
!= currentActionButtonList
.end() && itr
->second
.uState
!= ACTIONBUTTON_DELETED
)
5658 data
<< uint32(itr
->second
.packedData
);
5663 GetSession()->SendPacket( &data
);
5664 sLog
.outDetail( "Action Buttons for '%u' spec '%u' Initialized", GetGUIDLow(), m_activeSpec
);
5667 bool Player::IsActionButtonDataValid(uint8 button
, uint32 action
, uint8 type
, Player
* player
, bool msg
)
5669 if(button
>= MAX_ACTION_BUTTONS
)
5674 sLog
.outError( "Action %u not added into button %u for player %s: button must be < %u", action
, button
, player
->GetName(), MAX_ACTION_BUTTONS
);
5676 sLog
.outError( "Table `playercreateinfo_action` have action %u into button %u : button must be < %u", action
, button
, MAX_ACTION_BUTTONS
);
5682 if(action
>= MAX_ACTION_BUTTON_ACTION_VALUE
)
5687 sLog
.outError( "Action %u not added into button %u for player %s: action must be < %u", action
, button
, player
->GetName(), MAX_ACTION_BUTTON_ACTION_VALUE
);
5689 sLog
.outError( "Table `playercreateinfo_action` have action %u into button %u : action must be < %u", action
, button
, MAX_ACTION_BUTTON_ACTION_VALUE
);
5696 case ACTION_BUTTON_SPELL
:
5697 if(!sSpellStore
.LookupEntry(action
))
5702 sLog
.outError( "Spell action %u not added into button %u for player %s: spell not exist", action
, button
, player
->GetName() );
5704 sLog
.outError( "Table `playercreateinfo_action` have spell action %u into button %u: spell not exist", action
, button
);
5709 if(player
&& !player
->HasSpell(action
))
5712 sLog
.outError( "Spell action %u not added into button %u for player %s: player don't known this spell", action
, button
, player
->GetName() );
5716 case ACTION_BUTTON_ITEM
:
5717 if(!ObjectMgr::GetItemPrototype(action
))
5722 sLog
.outError( "Item action %u not added into button %u for player %s: item not exist", action
, button
, player
->GetName() );
5724 sLog
.outError( "Table `playercreateinfo_action` have item action %u into button %u: item not exist", action
, button
);
5730 break; // other cases not checked at this moment
5736 ActionButton
* Player::addActionButton(uint8 spec
, uint8 button
, uint32 action
, uint8 type
)
5738 // check action only for active spec (so not check at copy/load passive spec)
5739 if (spec
== GetActiveSpec() && !IsActionButtonDataValid(button
,action
,type
,this))
5742 // it create new button (NEW state) if need or return existed
5743 ActionButton
& ab
= m_actionButtons
[spec
][button
];
5745 // set data and update to CHANGED if not NEW
5746 ab
.SetActionAndType(action
,ActionButtonType(type
));
5748 sLog
.outDetail("Player '%u' Added Action '%u' (type %u) to Button '%u' for spec %u", GetGUIDLow(), action
, uint32(type
), button
, spec
);
5752 void Player::removeActionButton(uint8 spec
, uint8 button
)
5754 ActionButtonList
& currentActionButtonList
= m_actionButtons
[spec
];
5755 ActionButtonList::iterator buttonItr
= currentActionButtonList
.find(button
);
5756 if (buttonItr
== currentActionButtonList
.end() || buttonItr
->second
.uState
== ACTIONBUTTON_DELETED
)
5759 if (buttonItr
->second
.uState
== ACTIONBUTTON_NEW
)
5760 currentActionButtonList
.erase(buttonItr
); // new and not saved
5762 buttonItr
->second
.uState
= ACTIONBUTTON_DELETED
; // saved, will deleted at next save
5764 sLog
.outDetail("Action Button '%u' Removed from Player '%u' for spec %u", button
, GetGUIDLow(), spec
);
5767 ActionButton
const* Player::GetActionButton(uint8 button
)
5769 ActionButtonList
& currentActionButtonList
= m_actionButtons
[m_activeSpec
];
5770 ActionButtonList::iterator buttonItr
= currentActionButtonList
.find(button
);
5771 if (buttonItr
==currentActionButtonList
.end() || buttonItr
->second
.uState
== ACTIONBUTTON_DELETED
)
5774 return &buttonItr
->second
;
5777 bool Player::SetPosition(float x
, float y
, float z
, float orientation
, bool teleport
)
5779 // prevent crash when a bad coord is sent by the client
5780 if(!MaNGOS::IsValidMapCoord(x
,y
,z
,orientation
))
5782 sLog
.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x
,y
,z
,orientation
,teleport
,GetGUIDLow());
5788 const float old_x
= GetPositionX();
5789 const float old_y
= GetPositionY();
5790 const float old_z
= GetPositionZ();
5791 const float old_r
= GetOrientation();
5793 if( teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
|| old_r
!= orientation
)
5795 if (teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
)
5796 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE
| AURA_INTERRUPT_FLAG_TURNING
);
5798 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING
);
5800 // move and update visible state if need
5801 m
->PlayerRelocation(this, x
, y
, z
, orientation
);
5803 // reread after Map::Relocation
5810 if(GetGroup() && (old_x
!= x
|| old_y
!= y
))
5811 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION
);
5814 // code block for underwater state update
5815 UpdateUnderwaterState(m
, x
, y
, z
);
5817 CheckExploreSystem();
5822 void Player::SaveRecallPosition()
5824 m_recallMap
= GetMapId();
5825 m_recallX
= GetPositionX();
5826 m_recallY
= GetPositionY();
5827 m_recallZ
= GetPositionZ();
5828 m_recallO
= GetOrientation();
5831 void Player::SendMessageToSet(WorldPacket
*data
, bool self
)
5833 Map
* _map
= IsInWorld() ? GetMap() : sMapMgr
.FindMap(GetMapId(), GetInstanceId());
5836 _map
->MessageBroadcast(this, data
, self
);
5840 //if player is not in world and map in not created/already destroyed
5841 //no need to create one, just send packet for itself!
5843 GetSession()->SendPacket(data
);
5846 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
)
5848 Map
* _map
= IsInWorld() ? GetMap() : sMapMgr
.FindMap(GetMapId(), GetInstanceId());
5851 _map
->MessageDistBroadcast(this, data
, dist
, self
);
5856 GetSession()->SendPacket(data
);
5859 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
, bool own_team_only
)
5861 Map
* _map
= IsInWorld() ? GetMap() : sMapMgr
.FindMap(GetMapId(), GetInstanceId());
5864 _map
->MessageDistBroadcast(this, data
, dist
, self
, own_team_only
);
5869 GetSession()->SendPacket(data
);
5872 void Player::SendDirectMessage(WorldPacket
*data
)
5874 GetSession()->SendPacket(data
);
5877 void Player::SendCinematicStart(uint32 CinematicSequenceId
)
5879 WorldPacket
data(SMSG_TRIGGER_CINEMATIC
, 4);
5880 data
<< uint32(CinematicSequenceId
);
5881 SendDirectMessage(&data
);
5884 void Player::SendMovieStart(uint32 MovieId
)
5886 WorldPacket
data(SMSG_TRIGGER_MOVIE
, 4);
5887 data
<< uint32(MovieId
);
5888 SendDirectMessage(&data
);
5891 void Player::CheckExploreSystem()
5899 uint16 areaFlag
= GetBaseMap()->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5900 if(areaFlag
==0xffff)
5902 int offset
= areaFlag
/ 32;
5904 if(offset
>= PLAYER_EXPLORED_ZONES_SIZE
)
5906 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 < %u ).",areaFlag
,GetPositionX(),GetPositionY(),offset
,offset
, PLAYER_EXPLORED_ZONES_SIZE
);
5910 uint32 val
= (uint32
)(1 << (areaFlag
% 32));
5911 uint32 currFields
= GetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
);
5913 if( !(currFields
& val
) )
5915 SetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
, (uint32
)(currFields
| val
));
5917 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA
);
5919 AreaTableEntry
const *p
= GetAreaEntryByAreaFlagAndMap(areaFlag
,GetMapId());
5922 sLog
.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5924 else if(p
->area_level
> 0)
5926 uint32 area
= p
->ID
;
5927 if (getLevel() >= sWorld
.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL
))
5929 SendExplorationExperience(area
,0);
5933 int32 diff
= int32(getLevel()) - p
->area_level
;
5937 XP
= uint32(sObjectMgr
.GetBaseXP(getLevel()+5)*sWorld
.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE
));
5941 int32 exploration_percent
= (100-((diff
-5)*5));
5942 if (exploration_percent
> 100)
5943 exploration_percent
= 100;
5944 else if (exploration_percent
< 0)
5945 exploration_percent
= 0;
5947 XP
= uint32(sObjectMgr
.GetBaseXP(p
->area_level
)*exploration_percent
/100*sWorld
.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE
));
5951 XP
= uint32(sObjectMgr
.GetBaseXP(p
->area_level
)*sWorld
.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE
));
5955 SendExplorationExperience(area
,XP
);
5957 sLog
.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area
);
5962 uint32
Player::TeamForRace(uint8 race
)
5964 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5967 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5971 switch(rEntry
->TeamID
)
5973 case 7: return ALLIANCE
;
5974 case 1: return HORDE
;
5977 sLog
.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race
),rEntry
->TeamID
);
5981 uint32
Player::getFactionForRace(uint8 race
)
5983 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5986 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5990 return rEntry
->FactionID
;
5993 void Player::setFactionForRace(uint8 race
)
5995 m_team
= TeamForRace(race
);
5996 setFaction( getFactionForRace(race
) );
5999 ReputationRank
Player::GetReputationRank(uint32 faction
) const
6001 FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(faction
);
6002 return GetReputationMgr().GetRank(factionEntry
);
6005 //Calculate total reputation percent player gain with quest/creature level
6006 int32
Player::CalculateReputationGain(uint32 creatureOrQuestLevel
, int32 rep
, int32 faction
, bool for_quest
)
6008 float percent
= 100.0f
;
6010 float rate
= for_quest
? sWorld
.getConfig(CONFIG_FLOAT_RATE_REPUTATION_LOWLEVEL_QUEST
) : sWorld
.getConfig(CONFIG_FLOAT_RATE_REPUTATION_LOWLEVEL_KILL
);
6012 if (rate
!= 1.0f
&& creatureOrQuestLevel
<= MaNGOS::XP::GetGrayLevel(getLevel()))
6015 float repMod
= (float)GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN
);
6018 repMod
+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN
, faction
);
6020 percent
+= rep
> 0 ? repMod
: -repMod
;
6022 if (percent
<= 0.0f
)
6025 return int32(sWorld
.getConfig(CONFIG_FLOAT_RATE_REPUTATION_GAIN
)*rep
*percent
/100.0f
);
6028 //Calculates how many reputation points player gains in victim's enemy factions
6029 void Player::RewardReputation(Unit
*pVictim
, float rate
)
6031 if(!pVictim
|| pVictim
->GetTypeId() == TYPEID_PLAYER
)
6034 ReputationOnKillEntry
const* Rep
= sObjectMgr
.GetReputationOnKilEntry(((Creature
*)pVictim
)->GetCreatureInfo()->Entry
);
6039 if(Rep
->repfaction1
&& (!Rep
->team_dependent
|| GetTeam()==ALLIANCE
))
6041 int32 donerep1
= CalculateReputationGain(pVictim
->getLevel(), Rep
->repvalue1
, Rep
->repfaction1
, false);
6042 donerep1
= int32(donerep1
*rate
);
6043 FactionEntry
const *factionEntry1
= sFactionStore
.LookupEntry(Rep
->repfaction1
);
6044 uint32 current_reputation_rank1
= GetReputationMgr().GetRank(factionEntry1
);
6045 if (factionEntry1
&& current_reputation_rank1
<= Rep
->reputation_max_cap1
)
6046 GetReputationMgr().ModifyReputation(factionEntry1
, donerep1
);
6048 // Wiki: Team factions value divided by 2
6049 if (factionEntry1
&& Rep
->is_teamaward1
)
6051 FactionEntry
const *team1_factionEntry
= sFactionStore
.LookupEntry(factionEntry1
->team
);
6052 if(team1_factionEntry
)
6053 GetReputationMgr().ModifyReputation(team1_factionEntry
, donerep1
/ 2);
6057 if(Rep
->repfaction2
&& (!Rep
->team_dependent
|| GetTeam()==HORDE
))
6059 int32 donerep2
= CalculateReputationGain(pVictim
->getLevel(), Rep
->repvalue2
, Rep
->repfaction2
, false);
6060 donerep2
= int32(donerep2
*rate
);
6061 FactionEntry
const *factionEntry2
= sFactionStore
.LookupEntry(Rep
->repfaction2
);
6062 uint32 current_reputation_rank2
= GetReputationMgr().GetRank(factionEntry2
);
6063 if (factionEntry2
&& current_reputation_rank2
<= Rep
->reputation_max_cap2
)
6064 GetReputationMgr().ModifyReputation(factionEntry2
, donerep2
);
6066 // Wiki: Team factions value divided by 2
6067 if (factionEntry2
&& Rep
->is_teamaward2
)
6069 FactionEntry
const *team2_factionEntry
= sFactionStore
.LookupEntry(factionEntry2
->team
);
6070 if(team2_factionEntry
)
6071 GetReputationMgr().ModifyReputation(team2_factionEntry
, donerep2
/ 2);
6076 //Calculate how many reputation points player gain with the quest
6077 void Player::RewardReputation(Quest
const *pQuest
)
6079 // quest reputation reward/loss
6080 for(int i
= 0; i
< QUEST_REPUTATIONS_COUNT
; ++i
)
6082 if (!pQuest
->RewRepFaction
[i
])
6085 // For future, this row should be used as "override". Example quests are 10298 and 10870.
6086 // Typically, no diplomacy mod must apply to the final value (flat). Note the formula must be (finalValue = DBvalue/100)
6087 if (pQuest
->RewRepValue
[i
])
6089 int32 rep
= CalculateReputationGain(GetQuestLevelForPlayer(pQuest
), pQuest
->RewRepValue
[i
], pQuest
->RewRepFaction
[i
], true);
6091 if (FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(pQuest
->RewRepFaction
[i
]))
6092 GetReputationMgr().ModifyReputation(factionEntry
, rep
);
6096 uint32 row
= ((pQuest
->RewRepValueId
[i
] < 0) ? 1 : 0) + 1;
6097 uint32 field
= abs(pQuest
->RewRepValueId
[i
]);
6099 if (const QuestFactionRewardEntry
*pRow
= sQuestFactionRewardStore
.LookupEntry(row
))
6101 int32 repPoints
= pRow
->rewardValue
[field
];
6106 repPoints
= CalculateReputationGain(GetQuestLevelForPlayer(pQuest
), repPoints
, pQuest
->RewRepFaction
[i
], true);
6108 if (const FactionEntry
* factionEntry
= sFactionStore
.LookupEntry(pQuest
->RewRepFaction
[i
]))
6109 GetReputationMgr().ModifyReputation(factionEntry
, repPoints
);
6114 // TODO: implement reputation spillover
6117 void Player::UpdateArenaFields(void)
6119 /* arena calcs go here */
6122 void Player::UpdateHonorFields()
6124 /// called when rewarding honor and at each save
6125 time_t now
= time(NULL
);
6126 time_t today
= (time(NULL
) / DAY
) * DAY
;
6128 if(m_lastHonorUpdateTime
< today
)
6130 time_t yesterday
= today
- DAY
;
6132 uint16 kills_today
= PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS
));
6134 // update yesterday's contribution
6135 if(m_lastHonorUpdateTime
>= yesterday
)
6137 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
));
6139 // this is the first update today, reset today's contribution
6140 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, 0);
6141 SetUInt32Value(PLAYER_FIELD_KILLS
, MAKE_PAIR32(0,kills_today
));
6145 // no honor/kills yesterday or today, reset
6146 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0);
6147 SetUInt32Value(PLAYER_FIELD_KILLS
, 0);
6151 m_lastHonorUpdateTime
= now
;
6154 ///Calculate the amount of honor gained based on the victim
6155 ///and the size of the group for which the honor is divided
6156 ///An exact honor value can also be given (overriding the calcs)
6157 bool Player::RewardHonor(Unit
*uVictim
, uint32 groupsize
, float honor
)
6159 // do not reward honor in arenas, but enable onkill spellproc
6162 if(!uVictim
|| uVictim
== this || uVictim
->GetTypeId() != TYPEID_PLAYER
)
6165 if( GetBGTeam() == ((Player
*)uVictim
)->GetBGTeam() )
6171 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
6172 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE
))
6175 uint64 victim_guid
= 0;
6176 uint32 victim_rank
= 0;
6178 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
6179 UpdateHonorFields();
6183 if(!uVictim
|| uVictim
== this || uVictim
->HasAuraType(SPELL_AURA_NO_PVP_CREDIT
))
6186 victim_guid
= uVictim
->GetGUID();
6188 if( uVictim
->GetTypeId() == TYPEID_PLAYER
)
6190 Player
*pVictim
= (Player
*)uVictim
;
6192 if( GetTeam() == pVictim
->GetTeam() && !sWorld
.IsFFAPvPRealm() )
6195 float f
= 1; //need for total kills (?? need more info)
6197 uint32 k_level
= getLevel();
6198 uint32 v_level
= pVictim
->getLevel();
6201 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6203 // [1..14] Alliance honor titles and player name
6204 // [15..28] Horde honor titles and player name
6205 // [29..38] Other title and player name
6207 uint32 victim_title
= pVictim
->GetUInt32Value(PLAYER_CHOSEN_TITLE
);
6208 // Get Killer titles, CharTitlesEntry::bit_index
6210 // title[1..14] -> rank[5..18]
6211 // title[15..28] -> rank[5..18]
6212 // title[other] -> 0
6213 if (victim_title
== 0)
6214 victim_guid
= 0; // Don't show HK: <rank> message, only log.
6215 else if (victim_title
< 15)
6216 victim_rank
= victim_title
+ 4;
6217 else if (victim_title
< 29)
6218 victim_rank
= victim_title
- 14 + 4;
6220 victim_guid
= 0; // Don't show HK: <rank> message, only log.
6223 k_grey
= MaNGOS::XP::GetGrayLevel(k_level
);
6228 float diff_level
= (k_level
== k_grey
) ? 1 : ((float(v_level
) - float(k_grey
)) / (float(k_level
) - float(k_grey
)));
6230 int32 v_rank
=1; //need more info
6232 honor
= ((f
* diff_level
* (190 + v_rank
*10))/6);
6233 honor
*= ((float)k_level
) / 70.0f
; //factor of dependence on levels of the killer
6235 // count the number of playerkills in one day
6236 ApplyModUInt32Value(PLAYER_FIELD_KILLS
, 1, true);
6237 // and those in a lifetime
6238 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 1, true);
6239 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL
);
6240 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS
, pVictim
->getClass());
6241 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE
, pVictim
->getRace());
6245 Creature
*cVictim
= (Creature
*)uVictim
;
6247 if (!cVictim
->isRacialLeader())
6250 honor
= 100; // ??? need more info
6251 victim_rank
= 19; // HK: Leader
6255 if (uVictim
!= NULL
)
6257 honor
*= sWorld
.getConfig(CONFIG_FLOAT_RATE_HONOR
);
6258 honor
*= (GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HONOR_GAIN
) + 100.0f
)/100.0f
;
6263 honor
*= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6266 // honor - for show honor points in log
6267 // victim_guid - for show victim name in log
6268 // victim_rank [1..4] HK: <dishonored rank>
6269 // victim_rank [5..19] HK: <alliance\horde rank>
6270 // victim_rank [0,20+] HK: <>
6271 WorldPacket
data(SMSG_PVP_CREDIT
,4+8+4);
6272 data
<< (uint32
) honor
;
6273 data
<< (uint64
) victim_guid
;
6274 data
<< (uint32
) victim_rank
;
6276 GetSession()->SendPacket(&data
);
6279 ModifyHonorPoints(int32(honor
));
6281 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, uint32(honor
), true);
6285 void Player::ModifyHonorPoints( int32 value
)
6289 if (GetHonorPoints() > sWorld
.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS
))
6290 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS
) + value
);
6292 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() > uint32(-value
) ? GetHonorPoints() + value
: 0);
6295 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() < sWorld
.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS
) - value
? GetHonorPoints() + value
: sWorld
.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS
));
6298 void Player::ModifyArenaPoints( int32 value
)
6302 if (GetArenaPoints() > sWorld
.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS
))
6303 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS
) + value
);
6305 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() > uint32(-value
) ? GetArenaPoints() + value
: 0);
6308 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() < sWorld
.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS
) - value
? GetArenaPoints() + value
: sWorld
.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS
));
6311 uint32
Player::GetGuildIdFromDB(uint64 guid
)
6313 QueryResult
* result
= CharacterDatabase
.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid
));
6317 uint32 id
= result
->Fetch()[0].GetUInt32();
6322 uint32
Player::GetRankFromDB(uint64 guid
)
6324 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid
) );
6327 uint32 v
= result
->Fetch()[0].GetUInt32();
6335 uint32
Player::GetArenaTeamIdFromDB(uint64 guid
, uint8 type
)
6337 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
);
6341 uint32 id
= (*result
)[0].GetUInt32();
6346 uint32
Player::GetZoneIdFromDB(uint64 guid
)
6348 uint32 guidLow
= GUID_LOPART(guid
);
6349 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow
);
6352 Field
* fields
= result
->Fetch();
6353 uint32 zone
= fields
[0].GetUInt32();
6358 // stored zone is zero, use generic and slow zone detection
6359 result
= CharacterDatabase
.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow
);
6362 fields
= result
->Fetch();
6363 uint32 map
= fields
[0].GetUInt32();
6364 float posx
= fields
[1].GetFloat();
6365 float posy
= fields
[2].GetFloat();
6366 float posz
= fields
[3].GetFloat();
6369 zone
= sMapMgr
.GetZoneId(map
,posx
,posy
,posz
);
6372 CharacterDatabase
.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone
, guidLow
);
6378 uint32
Player::GetLevelFromDB(uint64 guid
)
6380 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT level FROM characters WHERE guid='%u'", GUID_LOPART(guid
) );
6384 Field
* fields
= result
->Fetch();
6385 uint32 level
= fields
[0].GetUInt32();
6391 void Player::UpdateArea(uint32 newArea
)
6393 // FFA_PVP flags are area and not zone id dependent
6394 // so apply them accordingly
6395 m_areaUpdateId
= newArea
;
6397 AreaTableEntry
const* area
= GetAreaEntryByAreaID(newArea
);
6399 if(area
&& (area
->flags
& AREA_FLAG_ARENA
))
6406 // remove ffa flag only if not ffapvp realm
6407 // removal in sanctuaries and capitals is handled in zone update
6408 if(IsFFAPvP() && !sWorld
.IsFFAPvPRealm())
6412 UpdateAreaDependentAuras(newArea
);
6415 void Player::UpdateZone(uint32 newZone
, uint32 newArea
)
6417 AreaTableEntry
const* zone
= GetAreaEntryByAreaID(newZone
);
6421 if(m_zoneUpdateId
!= newZone
)
6423 SendInitWorldStates(newZone
, newArea
); // only if really enters to new zone, not just area change, works strange...
6425 if (sWorld
.getConfig(CONFIG_BOOL_WEATHER
))
6427 if(Weather
*wth
= sWorld
.FindWeather(zone
->ID
))
6428 wth
->SendWeatherUpdateToPlayer(this);
6429 else if(!sWorld
.AddWeather(zone
->ID
))
6431 // send fine weather packet to remove old zone's weather
6432 Weather::SendFineWeatherUpdateToPlayer(this);
6437 m_zoneUpdateId
= newZone
;
6438 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
6440 // zone changed, so area changed as well, update it
6441 UpdateArea(newArea
);
6443 // in PvP, any not controlled zone (except zone->team == 6, default case)
6444 // in PvE, only opposition team capital
6448 pvpInfo
.inHostileArea
= GetTeam() != ALLIANCE
&& (sWorld
.IsPvPRealm() || zone
->flags
& AREA_FLAG_CAPITAL
);
6450 case AREATEAM_HORDE
:
6451 pvpInfo
.inHostileArea
= GetTeam() != HORDE
&& (sWorld
.IsPvPRealm() || zone
->flags
& AREA_FLAG_CAPITAL
);
6454 // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6455 pvpInfo
.inHostileArea
= sWorld
.IsPvPRealm() || InBattleGround();
6457 default: // 6 in fact
6458 pvpInfo
.inHostileArea
= false;
6462 if(pvpInfo
.inHostileArea
) // in hostile area
6464 if(!IsPvP() || pvpInfo
.endTimer
!= 0)
6465 UpdatePvP(true, true);
6467 else // in friendly area
6469 if(IsPvP() && !HasFlag(PLAYER_FLAGS
,PLAYER_FLAGS_IN_PVP
) && pvpInfo
.endTimer
== 0)
6470 pvpInfo
.endTimer
= time(0); // start toggle-off
6473 if(zone
->flags
& AREA_FLAG_SANCTUARY
) // in sanctuary
6475 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_SANCTUARY
);
6476 if(sWorld
.IsFFAPvPRealm())
6481 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_SANCTUARY
);
6484 if(zone
->flags
& AREA_FLAG_CAPITAL
) // in capital city
6485 SetRestType(REST_TYPE_IN_CITY
);
6486 else // anywhere else
6488 if (HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6490 if (GetRestType()==REST_TYPE_IN_TAVERN
) // has been in tavern. Is still in?
6492 AreaTriggerEntry
const* at
= sAreaTriggerStore
.LookupEntry(inn_trigger_id
);
6493 if (!at
|| !IsPointInAreaTriggerZone(at
, GetMapId(), GetPositionX(), GetPositionY(), GetPositionY()))
6494 SetRestType(REST_TYPE_NO
);
6496 else // not in tavern (leave city then)
6497 SetRestType(REST_TYPE_NO
);
6501 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6502 // if player resurrected at teleport this will be applied in resurrect code
6504 DestroyZoneLimitedItem( true, newZone
);
6506 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6507 AutoUnequipOffhandIfNeed();
6509 // recent client version not send leave/join channel packets for built-in local channels
6510 UpdateLocalChannels( newZone
);
6514 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE
);
6516 UpdateZoneDependentAuras(newZone
);
6519 //If players are too far way of duel flag... then player loose the duel
6520 void Player::CheckDuelDistance(time_t currTime
)
6525 uint64 duelFlagGUID
= GetUInt64Value(PLAYER_DUEL_ARBITER
);
6526 GameObject
* obj
= GetMap()->GetGameObject(duelFlagGUID
);
6530 if(duel
->outOfBound
== 0)
6532 if(!IsWithinDistInMap(obj
, 50))
6534 duel
->outOfBound
= currTime
;
6536 WorldPacket
data(SMSG_DUEL_OUTOFBOUNDS
, 0);
6537 GetSession()->SendPacket(&data
);
6542 if(IsWithinDistInMap(obj
, 40))
6544 duel
->outOfBound
= 0;
6546 WorldPacket
data(SMSG_DUEL_INBOUNDS
, 0);
6547 GetSession()->SendPacket(&data
);
6549 else if(currTime
>= (duel
->outOfBound
+10))
6551 DuelComplete(DUEL_FLED
);
6556 void Player::DuelComplete(DuelCompleteType type
)
6558 // duel not requested
6562 WorldPacket
data(SMSG_DUEL_COMPLETE
, (1));
6563 data
<< (uint8
)((type
!= DUEL_INTERUPTED
) ? 1 : 0);
6564 GetSession()->SendPacket(&data
);
6565 duel
->opponent
->GetSession()->SendPacket(&data
);
6567 if(type
!= DUEL_INTERUPTED
)
6569 data
.Initialize(SMSG_DUEL_WINNER
, (1+20)); // we guess size
6570 data
<< (uint8
)((type
==DUEL_WON
) ? 0 : 1); // 0 = just won; 1 = fled
6571 data
<< duel
->opponent
->GetName();
6573 SendMessageToSet(&data
,true);
6576 if (type
== DUEL_WON
)
6578 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL
, 1);
6580 duel
->opponent
->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL
, 1);
6583 //Remove Duel Flag object
6584 GameObject
* obj
= GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER
));
6586 duel
->initiator
->RemoveGameObject(obj
,true);
6589 std::vector
<uint32
> auras2remove
;
6590 AuraMap
const& vAuras
= duel
->opponent
->GetAuras();
6591 for (AuraMap::const_iterator i
= vAuras
.begin(); i
!= vAuras
.end(); ++i
)
6593 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6594 auras2remove
.push_back(i
->second
->GetId());
6597 for(size_t i
=0; i
<auras2remove
.size(); ++i
)
6598 duel
->opponent
->RemoveAurasDueToSpell(auras2remove
[i
]);
6600 auras2remove
.clear();
6601 AuraMap
const& auras
= GetAuras();
6602 for (AuraMap::const_iterator i
= auras
.begin(); i
!= auras
.end(); ++i
)
6604 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == duel
->opponent
->GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6605 auras2remove
.push_back(i
->second
->GetId());
6607 for(size_t i
=0; i
<auras2remove
.size(); ++i
)
6608 RemoveAurasDueToSpell(auras2remove
[i
]);
6610 // cleanup combo points
6611 if(GetComboTarget()==duel
->opponent
->GetGUID())
6613 else if(GetComboTarget()==duel
->opponent
->GetPetGUID())
6616 if(duel
->opponent
->GetComboTarget()==GetGUID())
6617 duel
->opponent
->ClearComboPoints();
6618 else if(duel
->opponent
->GetComboTarget()==GetPetGUID())
6619 duel
->opponent
->ClearComboPoints();
6622 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6623 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6624 duel
->opponent
->SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6625 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6627 delete duel
->opponent
->duel
;
6628 duel
->opponent
->duel
= NULL
;
6633 //---------------------------------------------------------//
6635 void Player::_ApplyItemMods(Item
*item
, uint8 slot
,bool apply
)
6637 if(slot
>= INVENTORY_SLOT_BAG_END
|| !item
)
6640 // not apply/remove mods for broken item
6641 if(item
->IsBroken())
6644 ItemPrototype
const *proto
= item
->GetProto();
6649 sLog
.outDetail("applying mods for item %u ",item
->GetGUIDLow());
6651 uint32 attacktype
= Player::GetAttackBySlot(slot
);
6652 if(attacktype
< MAX_ATTACK
)
6653 _ApplyWeaponDependentAuraMods(item
,WeaponAttackType(attacktype
),apply
);
6655 _ApplyItemBonuses(proto
,slot
,apply
);
6657 if( slot
==EQUIPMENT_SLOT_RANGED
)
6658 _ApplyAmmoBonuses();
6660 ApplyItemEquipSpell(item
,apply
);
6661 ApplyEnchantment(item
, apply
);
6663 if(proto
->Socket
[0].Color
) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6664 CorrectMetaGemEnchants(slot
, apply
);
6666 sLog
.outDebug("_ApplyItemMods complete.");
6669 void Player::_ApplyItemBonuses(ItemPrototype
const *proto
, uint8 slot
, bool apply
, bool only_level_scale
/*= false*/)
6671 if (slot
>= INVENTORY_SLOT_BAG_END
|| !proto
)
6674 ScalingStatDistributionEntry
const *ssd
= proto
->ScalingStatDistribution
? sScalingStatDistributionStore
.LookupEntry(proto
->ScalingStatDistribution
) : NULL
;
6675 if (only_level_scale
&& !ssd
)
6678 // req. check at equip, but allow use for extended range if range limit max level, set proper level
6679 uint32 ssd_level
= getLevel();
6680 if (ssd
&& ssd_level
> ssd
->MaxLevel
)
6681 ssd_level
= ssd
->MaxLevel
;
6683 ScalingStatValuesEntry
const *ssv
= proto
->ScalingStatValue
? sScalingStatValuesStore
.LookupEntry(ssd_level
) : NULL
;
6684 if (only_level_scale
&& !ssv
)
6687 for (uint32 i
= 0; i
< MAX_ITEM_PROTO_STATS
; ++i
)
6689 uint32 statType
= 0;
6691 // If set ScalingStatDistribution need get stats and values from it
6694 if (ssd
->StatMod
[i
] < 0)
6696 statType
= ssd
->StatMod
[i
];
6697 val
= (ssv
->getssdMultiplier(proto
->ScalingStatValue
) * ssd
->Modifier
[i
]) / 10000;
6701 if (i
>= proto
->StatsCount
)
6703 statType
= proto
->ItemStat
[i
].ItemStatType
;
6704 val
= proto
->ItemStat
[i
].ItemStatValue
;
6713 HandleStatModifier(UNIT_MOD_MANA
, BASE_VALUE
, float(val
), apply
);
6715 case ITEM_MOD_HEALTH
: // modify HP
6716 HandleStatModifier(UNIT_MOD_HEALTH
, BASE_VALUE
, float(val
), apply
);
6718 case ITEM_MOD_AGILITY
: // modify agility
6719 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, BASE_VALUE
, float(val
), apply
);
6720 ApplyStatBuffMod(STAT_AGILITY
, float(val
), apply
);
6722 case ITEM_MOD_STRENGTH
: //modify strength
6723 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, BASE_VALUE
, float(val
), apply
);
6724 ApplyStatBuffMod(STAT_STRENGTH
, float(val
), apply
);
6726 case ITEM_MOD_INTELLECT
: //modify intellect
6727 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, BASE_VALUE
, float(val
), apply
);
6728 ApplyStatBuffMod(STAT_INTELLECT
, float(val
), apply
);
6730 case ITEM_MOD_SPIRIT
: //modify spirit
6731 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, BASE_VALUE
, float(val
), apply
);
6732 ApplyStatBuffMod(STAT_SPIRIT
, float(val
), apply
);
6734 case ITEM_MOD_STAMINA
: //modify stamina
6735 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, BASE_VALUE
, float(val
), apply
);
6736 ApplyStatBuffMod(STAT_STAMINA
, float(val
), apply
);
6738 case ITEM_MOD_DEFENSE_SKILL_RATING
:
6739 ApplyRatingMod(CR_DEFENSE_SKILL
, int32(val
), apply
);
6741 case ITEM_MOD_DODGE_RATING
:
6742 ApplyRatingMod(CR_DODGE
, int32(val
), apply
);
6744 case ITEM_MOD_PARRY_RATING
:
6745 ApplyRatingMod(CR_PARRY
, int32(val
), apply
);
6747 case ITEM_MOD_BLOCK_RATING
:
6748 ApplyRatingMod(CR_BLOCK
, int32(val
), apply
);
6750 case ITEM_MOD_HIT_MELEE_RATING
:
6751 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6753 case ITEM_MOD_HIT_RANGED_RATING
:
6754 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6756 case ITEM_MOD_HIT_SPELL_RATING
:
6757 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6759 case ITEM_MOD_CRIT_MELEE_RATING
:
6760 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6762 case ITEM_MOD_CRIT_RANGED_RATING
:
6763 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6765 case ITEM_MOD_CRIT_SPELL_RATING
:
6766 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6768 case ITEM_MOD_HIT_TAKEN_MELEE_RATING
:
6769 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6771 case ITEM_MOD_HIT_TAKEN_RANGED_RATING
:
6772 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6774 case ITEM_MOD_HIT_TAKEN_SPELL_RATING
:
6775 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6777 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING
:
6778 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6780 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING
:
6781 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6783 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING
:
6784 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6786 case ITEM_MOD_HASTE_MELEE_RATING
:
6787 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6789 case ITEM_MOD_HASTE_RANGED_RATING
:
6790 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6792 case ITEM_MOD_HASTE_SPELL_RATING
:
6793 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6795 case ITEM_MOD_HIT_RATING
:
6796 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6797 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6798 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6800 case ITEM_MOD_CRIT_RATING
:
6801 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6802 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6803 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6805 case ITEM_MOD_HIT_TAKEN_RATING
:
6806 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6807 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6808 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6810 case ITEM_MOD_CRIT_TAKEN_RATING
:
6811 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6812 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6813 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6815 case ITEM_MOD_RESILIENCE_RATING
:
6816 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6817 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6818 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6820 case ITEM_MOD_HASTE_RATING
:
6821 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6822 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6823 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6825 case ITEM_MOD_EXPERTISE_RATING
:
6826 ApplyRatingMod(CR_EXPERTISE
, int32(val
), apply
);
6828 case ITEM_MOD_ATTACK_POWER
:
6829 HandleStatModifier(UNIT_MOD_ATTACK_POWER
, TOTAL_VALUE
, float(val
), apply
);
6830 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(val
), apply
);
6832 case ITEM_MOD_RANGED_ATTACK_POWER
:
6833 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(val
), apply
);
6835 case ITEM_MOD_MANA_REGENERATION
:
6836 ApplyManaRegenBonus(int32(val
), apply
);
6838 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
6839 ApplyRatingMod(CR_ARMOR_PENETRATION
, int32(val
), apply
);
6841 case ITEM_MOD_SPELL_POWER
:
6842 ApplySpellPowerBonus(int32(val
), apply
);
6844 // depricated item mods
6845 case ITEM_MOD_FERAL_ATTACK_POWER
:
6846 case ITEM_MOD_SPELL_HEALING_DONE
:
6847 case ITEM_MOD_SPELL_DAMAGE_DONE
:
6852 // Apply Spell Power from ScalingStatValue if set
6855 if (int32 spellbonus
= ssv
->getSpellBonus(proto
->ScalingStatValue
))
6856 ApplySpellPowerBonus(spellbonus
, apply
);
6859 // If set ScalingStatValue armor get it or use item armor
6860 uint32 armor
= proto
->Armor
;
6863 if (uint32 ssvarmor
= ssv
->getArmorMod(proto
->ScalingStatValue
))
6866 // Add armor bonus from ArmorDamageModifier if > 0
6867 if (proto
->ArmorDamageModifier
> 0)
6868 armor
+= uint32(proto
->ArmorDamageModifier
);
6871 HandleStatModifier(UNIT_MOD_ARMOR
, BASE_VALUE
, float(armor
), apply
);
6874 HandleBaseModValue(SHIELD_BLOCK_VALUE
, FLAT_MOD
, float(proto
->Block
), apply
);
6877 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY
, BASE_VALUE
, float(proto
->HolyRes
), apply
);
6880 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE
, BASE_VALUE
, float(proto
->FireRes
), apply
);
6882 if (proto
->NatureRes
)
6883 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE
, BASE_VALUE
, float(proto
->NatureRes
), apply
);
6885 if (proto
->FrostRes
)
6886 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST
, BASE_VALUE
, float(proto
->FrostRes
), apply
);
6888 if (proto
->ShadowRes
)
6889 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW
, BASE_VALUE
, float(proto
->ShadowRes
), apply
);
6891 if (proto
->ArcaneRes
)
6892 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE
, BASE_VALUE
, float(proto
->ArcaneRes
), apply
);
6894 WeaponAttackType attType
= BASE_ATTACK
;
6895 float damage
= 0.0f
;
6897 if( slot
== EQUIPMENT_SLOT_RANGED
&& (
6898 proto
->InventoryType
== INVTYPE_RANGED
|| proto
->InventoryType
== INVTYPE_THROWN
||
6899 proto
->InventoryType
== INVTYPE_RANGEDRIGHT
))
6901 attType
= RANGED_ATTACK
;
6903 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6905 attType
= OFF_ATTACK
;
6908 float minDamage
= proto
->Damage
[0].DamageMin
;
6909 float maxDamage
= proto
->Damage
[0].DamageMax
;
6911 // If set dpsMod in ScalingStatValue use it for min (70% from average), max (130% from average) damage
6914 if ((extraDPS
= ssv
->getDPSMod(proto
->ScalingStatValue
)))
6916 float average
= extraDPS
* proto
->Delay
/ 1000.0f
;
6917 minDamage
= 0.7f
* average
;
6918 maxDamage
= 1.3f
* average
;
6923 damage
= apply
? minDamage
: BASE_MINDAMAGE
;
6924 SetBaseWeaponDamage(attType
, MINDAMAGE
, damage
);
6925 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6930 damage
= apply
? maxDamage
: BASE_MAXDAMAGE
;
6931 SetBaseWeaponDamage(attType
, MAXDAMAGE
, damage
);
6934 // Apply feral bonus from ScalingStatValue if set
6937 if (int32 feral_bonus
= ssv
->getFeralBonus(proto
->ScalingStatValue
))
6938 ApplyFeralAPBonus(feral_bonus
, apply
);
6940 // Druids get feral AP bonus from weapon dps (lso use DPS from ScalingStatValue)
6941 if(getClass() == CLASS_DRUID
)
6943 int32 feral_bonus
= proto
->getFeralBonus(extraDPS
);
6944 if (feral_bonus
> 0)
6945 ApplyFeralAPBonus(feral_bonus
, apply
);
6948 if(!IsUseEquipedWeapon(slot
==EQUIPMENT_SLOT_MAINHAND
))
6953 if(slot
== EQUIPMENT_SLOT_RANGED
)
6954 SetAttackTime(RANGED_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6955 else if(slot
==EQUIPMENT_SLOT_MAINHAND
)
6956 SetAttackTime(BASE_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6957 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6958 SetAttackTime(OFF_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6961 if(CanModifyStats() && (damage
|| proto
->Delay
))
6962 UpdateDamagePhysical(attType
);
6965 void Player::_ApplyWeaponDependentAuraMods(Item
*item
,WeaponAttackType attackType
,bool apply
)
6967 AuraList
const& auraCritList
= GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT
);
6968 for(AuraList::const_iterator itr
= auraCritList
.begin(); itr
!=auraCritList
.end();++itr
)
6969 _ApplyWeaponDependentAuraCritMod(item
,attackType
,*itr
,apply
);
6971 AuraList
const& auraDamageFlatList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE
);
6972 for(AuraList::const_iterator itr
= auraDamageFlatList
.begin(); itr
!=auraDamageFlatList
.end();++itr
)
6973 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6975 AuraList
const& auraDamagePCTList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
);
6976 for(AuraList::const_iterator itr
= auraDamagePCTList
.begin(); itr
!=auraDamagePCTList
.end();++itr
)
6977 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6980 void Player::_ApplyWeaponDependentAuraCritMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6982 // generic not weapon specific case processes in aura code
6983 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6986 BaseModGroup mod
= BASEMOD_END
;
6989 case BASE_ATTACK
: mod
= CRIT_PERCENTAGE
; break;
6990 case OFF_ATTACK
: mod
= OFFHAND_CRIT_PERCENTAGE
;break;
6991 case RANGED_ATTACK
: mod
= RANGED_CRIT_PERCENTAGE
; break;
6995 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6997 HandleBaseModValue(mod
, FLAT_MOD
, float (aura
->GetModifier()->m_amount
), apply
);
7001 void Player::_ApplyWeaponDependentAuraDamageMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
7003 // ignore spell mods for not wands
7004 Modifier
const* modifier
= aura
->GetModifier();
7005 if((modifier
->m_miscvalue
& SPELL_SCHOOL_MASK_NORMAL
)==0 && (getClassMask() & CLASSMASK_WAND_USERS
)==0)
7008 // generic not weapon specific case processes in aura code
7009 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
7012 UnitMods unitMod
= UNIT_MOD_END
;
7015 case BASE_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_MAINHAND
; break;
7016 case OFF_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_OFFHAND
; break;
7017 case RANGED_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_RANGED
; break;
7021 UnitModifierType unitModType
= TOTAL_VALUE
;
7022 switch(modifier
->m_auraname
)
7024 case SPELL_AURA_MOD_DAMAGE_DONE
: unitModType
= TOTAL_VALUE
; break;
7025 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
: unitModType
= TOTAL_PCT
; break;
7029 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
7031 HandleStatModifier(unitMod
, unitModType
, float(modifier
->m_amount
),apply
);
7035 void Player::ApplyItemEquipSpell(Item
*item
, bool apply
, bool form_change
)
7040 ItemPrototype
const *proto
= item
->GetProto();
7044 for (int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
7046 _Spell
const& spellData
= proto
->Spells
[i
];
7049 if(!spellData
.SpellId
)
7052 // wrong triggering type
7053 if(apply
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_EQUIP
)
7056 // check if it is valid spell
7057 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellData
.SpellId
);
7061 ApplyEquipSpell(spellproto
,item
,apply
,form_change
);
7065 void Player::ApplyEquipSpell(SpellEntry
const* spellInfo
, Item
* item
, bool apply
, bool form_change
)
7069 // Cannot be used in this stance/form
7070 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
) != SPELL_CAST_OK
)
7073 if(form_change
) // check aura active state from other form
7076 for (int k
=0; k
< MAX_EFFECT_INDEX
; ++k
)
7078 spellEffectPair spair
= spellEffectPair(spellInfo
->Id
, SpellEffectIndex(k
));
7079 for (AuraMap::const_iterator iter
= m_Auras
.lower_bound(spair
); iter
!= m_Auras
.upper_bound(spair
); ++iter
)
7081 if(!item
|| iter
->second
->GetCastItemGUID() == item
->GetGUID())
7091 if(found
) // and skip re-cast already active aura at form change
7095 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item
? "item" : "itemset"), spellInfo
->Id
);
7097 CastSpell(this,spellInfo
,true,item
);
7101 if(form_change
) // check aura compatibility
7103 // Cannot be used in this stance/form
7104 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
)==SPELL_CAST_OK
)
7105 return; // and remove only not compatible at form change
7109 RemoveAurasDueToItemSpell(item
,spellInfo
->Id
); // un-apply all spells , not only at-equipped
7111 RemoveAurasDueToSpell(spellInfo
->Id
); // un-apply spell (item set case)
7115 void Player::UpdateEquipSpellsAtFormChange()
7117 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
7119 if(m_items
[i
] && !m_items
[i
]->IsBroken())
7121 ApplyItemEquipSpell(m_items
[i
],false,true); // remove spells that not fit to form
7122 ApplyItemEquipSpell(m_items
[i
],true,true); // add spells that fit form but not active
7126 // item set bonuses not dependent from item broken state
7127 for(size_t setindex
= 0; setindex
< ItemSetEff
.size(); ++setindex
)
7129 ItemSetEffect
* eff
= ItemSetEff
[setindex
];
7133 for(uint32 y
=0;y
<8; ++y
)
7135 SpellEntry
const* spellInfo
= eff
->spells
[y
];
7139 ApplyEquipSpell(spellInfo
,NULL
,false,true); // remove spells that not fit to form
7140 ApplyEquipSpell(spellInfo
,NULL
,true,true); // add spells that fit form but not active
7145 void Player::CastItemCombatSpell(Unit
* Target
, WeaponAttackType attType
)
7147 Item
*item
= GetWeaponForAttack(attType
, true, false);
7151 ItemPrototype
const *proto
= item
->GetProto();
7155 if (!Target
|| Target
== this )
7158 for (int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
7160 _Spell
const& spellData
= proto
->Spells
[i
];
7163 if(!spellData
.SpellId
)
7166 // wrong triggering type
7167 if(spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_CHANCE_ON_HIT
)
7170 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
7173 sLog
.outError("WORLD: unknown Item spellid %i", spellData
.SpellId
);
7177 // not allow proc extra attack spell at extra attack
7178 if( m_extraAttacks
&& IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_ADD_EXTRA_ATTACKS
) )
7181 float chance
= (float)spellInfo
->procChance
;
7183 if(spellData
.SpellPPMRate
)
7185 uint32 WeaponSpeed
= proto
->Delay
;
7186 chance
= GetPPMProcChance(WeaponSpeed
, spellData
.SpellPPMRate
);
7188 else if(chance
> 100.0f
)
7190 chance
= GetWeaponProcChance();
7193 if (roll_chance_f(chance
))
7194 CastSpell(Target
, spellInfo
->Id
, true, item
);
7197 // item combat enchantments
7198 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
7200 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
7201 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
7202 if(!pEnchant
) continue;
7203 for (int s
= 0; s
< 3; ++s
)
7205 if (pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
)
7208 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
7211 sLog
.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
7215 // Use first rank to access spell item enchant procs
7216 float ppmRate
= sSpellMgr
.GetItemEnchantProcChance(spellInfo
->Id
);
7218 float chance
= ppmRate
7219 ? GetPPMProcChance(proto
->Delay
, ppmRate
)
7220 : pEnchant
->amount
[s
] != 0 ? float(pEnchant
->amount
[s
]) : GetWeaponProcChance();
7223 ApplySpellMod(spellInfo
->Id
,SPELLMOD_CHANCE_OF_SUCCESS
,chance
);
7224 ApplySpellMod(spellInfo
->Id
,SPELLMOD_FREQUENCY_OF_SUCCESS
,chance
);
7226 if (roll_chance_f(chance
))
7228 if(IsPositiveSpell(pEnchant
->spellid
[s
]))
7229 CastSpell(this, pEnchant
->spellid
[s
], true, item
);
7231 CastSpell(Target
, pEnchant
->spellid
[s
], true, item
);
7237 void Player::CastItemUseSpell(Item
*item
,SpellCastTargets
const& targets
,uint8 cast_count
, uint32 glyphIndex
)
7239 ItemPrototype
const* proto
= item
->GetProto();
7240 // special learning case
7241 if(proto
->Spells
[0].SpellId
==SPELL_ID_GENERIC_LEARN
|| proto
->Spells
[0].SpellId
==SPELL_ID_GENERIC_LEARN_PET
)
7243 uint32 learn_spell_id
= proto
->Spells
[0].SpellId
;
7244 uint32 learning_spell_id
= proto
->Spells
[1].SpellId
;
7246 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(learn_spell_id
);
7249 sLog
.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto
->ItemId
, learn_spell_id
);
7250 SendEquipError(EQUIP_ERR_NONE
, item
);
7254 Spell
*spell
= new Spell(this, spellInfo
, false);
7255 spell
->m_CastItem
= item
;
7256 spell
->m_cast_count
= cast_count
; //set count of casts
7257 spell
->m_currentBasePoints
[0] = learning_spell_id
;
7258 spell
->prepare(&targets
);
7262 // use triggered flag only for items with many spell casts and for not first cast
7265 // item spells casted at use
7266 for(int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
7268 _Spell
const& spellData
= proto
->Spells
[i
];
7271 if(!spellData
.SpellId
)
7274 // wrong triggering type
7275 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_NO_DELAY_USE
)
7278 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
7281 sLog
.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto
->ItemId
, spellData
.SpellId
);
7285 Spell
*spell
= new Spell(this, spellInfo
, (count
> 0));
7286 spell
->m_CastItem
= item
;
7287 spell
->m_cast_count
= cast_count
; // set count of casts
7288 spell
->m_glyphIndex
= glyphIndex
; // glyph index
7289 spell
->prepare(&targets
);
7294 // Item enchantments spells casted at use
7295 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
7297 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
7298 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
7299 if(!pEnchant
) continue;
7300 for (int s
= 0; s
< 3; ++s
)
7302 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL
)
7305 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
7308 sLog
.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
7312 Spell
*spell
= new Spell(this, spellInfo
, (count
> 0));
7313 spell
->m_CastItem
= item
;
7314 spell
->m_cast_count
= cast_count
; // set count of casts
7315 spell
->m_glyphIndex
= glyphIndex
; // glyph index
7316 spell
->prepare(&targets
);
7323 void Player::_RemoveAllItemMods()
7325 sLog
.outDebug("_RemoveAllItemMods start.");
7327 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
7331 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7335 // item set bonuses not dependent from item broken state
7337 RemoveItemsSetItem(this,proto
);
7339 if(m_items
[i
]->IsBroken())
7342 ApplyItemEquipSpell(m_items
[i
],false);
7343 ApplyEnchantment(m_items
[i
], false);
7347 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
7351 if(m_items
[i
]->IsBroken())
7353 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7357 uint32 attacktype
= Player::GetAttackBySlot(i
);
7358 if(attacktype
< MAX_ATTACK
)
7359 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),false);
7361 _ApplyItemBonuses(proto
,i
, false);
7363 if( i
== EQUIPMENT_SLOT_RANGED
)
7364 _ApplyAmmoBonuses();
7368 sLog
.outDebug("_RemoveAllItemMods complete.");
7371 void Player::_ApplyAllItemMods()
7373 sLog
.outDebug("_ApplyAllItemMods start.");
7375 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
7379 if(m_items
[i
]->IsBroken())
7382 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7386 uint32 attacktype
= Player::GetAttackBySlot(i
);
7387 if(attacktype
< MAX_ATTACK
)
7388 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),true);
7390 _ApplyItemBonuses(proto
,i
, true);
7392 if( i
== EQUIPMENT_SLOT_RANGED
)
7393 _ApplyAmmoBonuses();
7397 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
7401 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7405 // item set bonuses not dependent from item broken state
7407 AddItemsSetItem(this,m_items
[i
]);
7409 if(m_items
[i
]->IsBroken())
7412 ApplyItemEquipSpell(m_items
[i
],true);
7413 ApplyEnchantment(m_items
[i
], true);
7417 sLog
.outDebug("_ApplyAllItemMods complete.");
7420 void Player::_ApplyAllLevelScaleItemMods(bool apply
)
7422 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
7426 if(m_items
[i
]->IsBroken())
7429 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7433 _ApplyItemBonuses(proto
,i
, apply
, true);
7438 void Player::_ApplyAmmoBonuses()
7441 uint32 ammo_id
= GetUInt32Value(PLAYER_AMMO_ID
);
7445 float currentAmmoDPS
;
7447 ItemPrototype
const *ammo_proto
= ObjectMgr::GetItemPrototype( ammo_id
);
7448 if( !ammo_proto
|| ammo_proto
->Class
!=ITEM_CLASS_PROJECTILE
|| !CheckAmmoCompatibility(ammo_proto
))
7449 currentAmmoDPS
= 0.0f
;
7451 currentAmmoDPS
= ammo_proto
->Damage
[0].DamageMin
;
7453 if(currentAmmoDPS
== GetAmmoDPS())
7456 m_ammoDPS
= currentAmmoDPS
;
7458 if(CanModifyStats())
7459 UpdateDamagePhysical(RANGED_ATTACK
);
7462 bool Player::CheckAmmoCompatibility(const ItemPrototype
*ammo_proto
) const
7467 // check ranged weapon
7468 Item
*weapon
= GetWeaponForAttack( RANGED_ATTACK
, true, false );
7472 ItemPrototype
const* weapon_proto
= weapon
->GetProto();
7473 if(!weapon_proto
|| weapon_proto
->Class
!=ITEM_CLASS_WEAPON
)
7476 // check ammo ws. weapon compatibility
7477 switch(weapon_proto
->SubClass
)
7479 case ITEM_SUBCLASS_WEAPON_BOW
:
7480 case ITEM_SUBCLASS_WEAPON_CROSSBOW
:
7481 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_ARROW
)
7484 case ITEM_SUBCLASS_WEAPON_GUN
:
7485 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_BULLET
)
7495 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7496 Called by remove insignia spell effect */
7497 void Player::RemovedInsignia(Player
* looterPlr
)
7499 if (!GetBattleGroundId())
7502 // If not released spirit, do it !
7503 if(m_deathTimer
> 0)
7510 Corpse
*corpse
= GetCorpse();
7514 // We have to convert player corpse to bones, not to be able to resurrect there
7515 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7516 Corpse
*bones
= sObjectAccessor
.ConvertCorpseForPlayer(GetGUID(),true);
7520 // Now we must make bones lootable, and send player loot
7521 bones
->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS
, CORPSE_DYNFLAG_LOOTABLE
);
7523 // We store the level of our player in the gold field
7524 // We retrieve this information at Player::SendLoot()
7525 bones
->loot
.gold
= getLevel();
7526 bones
->lootRecipient
= looterPlr
;
7527 looterPlr
->SendLoot(bones
->GetGUID(), LOOT_INSIGNIA
);
7530 void Player::SendLootRelease(ObjectGuid guid
)
7532 WorldPacket
data( SMSG_LOOT_RELEASE_RESPONSE
, (8+1) );
7535 SendDirectMessage( &data
);
7538 void Player::SendLoot(ObjectGuid guid
, LootType loot_type
)
7540 if (uint64 lguid
= GetLootGUID())
7541 m_session
->DoLootRelease(lguid
);
7544 PermissionTypes permission
= ALL_PERMISSION
;
7546 sLog
.outDebug("Player::SendLoot");
7547 switch(guid
.GetHigh())
7549 case HIGHGUID_GAMEOBJECT
:
7551 sLog
.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7552 GameObject
*go
= GetMap()->GetGameObject(guid
);
7554 // not check distance for GO in case owned GO (fishing bobber case, for example)
7555 // And permit out of range GO with no owner in case fishing hole
7556 if (!go
|| (loot_type
!= LOOT_FISHINGHOLE
&& (loot_type
!= LOOT_FISHING
|| go
->GetOwnerGUID() != GetGUID()) && !go
->IsWithinDistInMap(this,INTERACTION_DISTANCE
)))
7558 SendLootRelease(guid
);
7564 if (go
->getLootState() == GO_READY
)
7566 uint32 lootid
= go
->GetGOInfo()->GetLootId();
7567 if ((go
->GetEntry() == BG_AV_OBJECTID_MINE_N
|| go
->GetEntry() == BG_AV_OBJECTID_MINE_S
))
7568 if (BattleGround
*bg
= GetBattleGround())
7569 if (bg
->GetTypeID() == BATTLEGROUND_AV
)
7570 if (!(((BattleGroundAV
*)bg
)->PlayerCanDoMineQuest(go
->GetEntry(), GetTeam())))
7572 SendLootRelease(guid
);
7578 sLog
.outDebug(" if(lootid)");
7580 loot
->FillLoot(lootid
, LootTemplates_Gameobject
, this, false);
7583 if (loot_type
== LOOT_FISHING
)
7584 go
->getFishLoot(loot
,this);
7586 go
->SetLootState(GO_ACTIVATED
);
7592 Item
*item
= GetItemByGuid( guid
);
7596 SendLootRelease(guid
);
7602 if (!item
->m_lootGenerated
)
7604 item
->m_lootGenerated
= true;
7609 case LOOT_DISENCHANTING
:
7610 loot
->FillLoot(item
->GetProto()->DisenchantID
, LootTemplates_Disenchant
, this,true);
7612 case LOOT_PROSPECTING
:
7613 loot
->FillLoot(item
->GetEntry(), LootTemplates_Prospecting
, this,true);
7616 loot
->FillLoot(item
->GetEntry(), LootTemplates_Milling
, this,true);
7619 loot
->FillLoot(item
->GetEntry(), LootTemplates_Item
, this,true);
7620 loot
->generateMoneyLoot(item
->GetProto()->MinMoneyLoot
,item
->GetProto()->MaxMoneyLoot
);
7626 case HIGHGUID_CORPSE
: // remove insignia
7628 Corpse
*bones
= GetMap()->GetCorpse(guid
);
7630 if (!bones
|| !((loot_type
== LOOT_CORPSE
) || (loot_type
== LOOT_INSIGNIA
)) || (bones
->GetType() != CORPSE_BONES
) )
7632 SendLootRelease(guid
);
7636 loot
= &bones
->loot
;
7638 if (!bones
->lootForBody
)
7640 bones
->lootForBody
= true;
7641 uint32 pLevel
= bones
->loot
.gold
;
7642 bones
->loot
.clear();
7643 if (GetBattleGround()->GetTypeID() == BATTLEGROUND_AV
)
7644 loot
->FillLoot(0, LootTemplates_Creature
, this, false);
7645 // It may need a better formula
7646 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7647 bones
->loot
.gold
= (uint32
)( urand(50, 150) * 0.016f
* pow( ((float)pLevel
)/5.76f
, 2.5f
) * sWorld
.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY
) );
7650 if (bones
->lootRecipient
!= this)
7651 permission
= NONE_PERMISSION
;
7656 Creature
*creature
= GetMap()->GetCreature(guid
);
7658 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7659 if (!creature
|| creature
->isAlive()!=(loot_type
== LOOT_PICKPOCKETING
) || !creature
->IsWithinDistInMap(this,INTERACTION_DISTANCE
))
7661 SendLootRelease(guid
);
7665 if (loot_type
== LOOT_PICKPOCKETING
&& IsFriendlyTo(creature
))
7667 SendLootRelease(guid
);
7671 loot
= &creature
->loot
;
7673 if (loot_type
== LOOT_PICKPOCKETING
)
7675 if (!creature
->lootForPickPocketed
)
7677 creature
->lootForPickPocketed
= true;
7680 if (uint32 lootid
= creature
->GetCreatureInfo()->pickpocketLootId
)
7681 loot
->FillLoot(lootid
, LootTemplates_Pickpocketing
, this, false);
7683 // Generate extra money for pick pocket loot
7684 const uint32 a
= urand(0, creature
->getLevel()/2);
7685 const uint32 b
= urand(0, getLevel()/2);
7686 loot
->gold
= uint32(10 * (a
+ b
) * sWorld
.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY
));
7691 // the player whose group may loot the corpse
7692 Player
*recipient
= creature
->GetLootRecipient();
7695 creature
->SetLootRecipient(this);
7699 if (creature
->lootForPickPocketed
)
7701 creature
->lootForPickPocketed
= false;
7705 if (!creature
->lootForBody
)
7707 creature
->lootForBody
= true;
7710 if (uint32 lootid
= creature
->GetCreatureInfo()->lootid
)
7711 loot
->FillLoot(lootid
, LootTemplates_Creature
, recipient
, false);
7713 loot
->generateMoneyLoot(creature
->GetCreatureInfo()->mingold
,creature
->GetCreatureInfo()->maxgold
);
7715 if (Group
* group
= recipient
->GetGroup())
7717 group
->UpdateLooterGuid(creature
,true);
7719 switch (group
->GetLootMethod())
7722 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7723 group
->GroupLoot(recipient
->GetObjectGuid(), loot
, creature
);
7725 case NEED_BEFORE_GREED
:
7726 group
->NeedBeforeGreed(recipient
->GetObjectGuid(), loot
, creature
);
7729 group
->MasterLoot(recipient
->GetObjectGuid(), loot
, creature
);
7737 // possible only if creature->lootForBody && loot->empty() at spell cast check
7738 if (loot_type
== LOOT_SKINNING
)
7741 loot
->FillLoot(creature
->GetCreatureInfo()->SkinLootId
, LootTemplates_Skinning
, this, false);
7743 // set group rights only for loot_type != LOOT_SKINNING
7746 if(Group
* group
= GetGroup())
7748 if (group
== recipient
->GetGroup())
7750 if (group
->GetLootMethod() == FREE_FOR_ALL
)
7751 permission
= ALL_PERMISSION
;
7752 else if (group
->GetLooterGuid() == GetGUID())
7754 if (group
->GetLootMethod() == MASTER_LOOT
)
7755 permission
= MASTER_PERMISSION
;
7757 permission
= ALL_PERMISSION
;
7760 permission
= GROUP_PERMISSION
;
7763 permission
= NONE_PERMISSION
;
7765 else if (recipient
== this)
7766 permission
= ALL_PERMISSION
;
7768 permission
= NONE_PERMISSION
;
7775 sLog
.outError("%s is unsupported for looting.", guid
.GetString().c_str());
7782 // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
7785 case LOOT_INSIGNIA
: loot_type
= LOOT_SKINNING
; break;
7786 case LOOT_FISHINGHOLE
: loot_type
= LOOT_FISHING
; break;
7790 // need know merged fishing/corpse loot type for achievements
7791 loot
->loot_type
= loot_type
;
7793 WorldPacket
data(SMSG_LOOT_RESPONSE
, (9+50)); // we guess size
7796 data
<< uint8(loot_type
);
7797 data
<< LootView(*loot
, this, permission
);
7799 SendDirectMessage(&data
);
7801 // add 'this' player as one of the players that are looting 'loot'
7802 if (permission
!= NONE_PERMISSION
)
7803 loot
->AddLooter(GetGUID());
7805 if (loot_type
== LOOT_CORPSE
&& !guid
.IsItem())
7806 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_LOOTING
);
7809 void Player::SendNotifyLootMoneyRemoved()
7811 WorldPacket
data(SMSG_LOOT_CLEAR_MONEY
, 0);
7812 GetSession()->SendPacket( &data
);
7815 void Player::SendNotifyLootItemRemoved(uint8 lootSlot
)
7817 WorldPacket
data(SMSG_LOOT_REMOVED
, 1);
7818 data
<< uint8(lootSlot
);
7819 GetSession()->SendPacket( &data
);
7822 void Player::SendUpdateWorldState(uint32 Field
, uint32 Value
)
7824 WorldPacket
data(SMSG_UPDATE_WORLD_STATE
, 8);
7827 GetSession()->SendPacket(&data
);
7830 void Player::SendInitWorldStates(uint32 zoneid
, uint32 areaid
)
7832 // data depends on zoneid/mapid...
7833 BattleGround
* bg
= GetBattleGround();
7834 uint16 NumberOfFields
= 0;
7835 uint32 mapid
= GetMapId();
7837 sLog
.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid
, zoneid
);
7839 // may be exist better way to do this...
7862 NumberOfFields
= 41;
7865 NumberOfFields
= 15;
7868 NumberOfFields
= 83;
7871 NumberOfFields
= 16;
7875 NumberOfFields
= 40;
7878 NumberOfFields
= 27;
7881 NumberOfFields
= 39;
7884 NumberOfFields
= 38;
7887 NumberOfFields
= 37;
7892 NumberOfFields
= 11;
7895 NumberOfFields
= 11;
7898 NumberOfFields
= 12;
7902 WorldPacket
data(SMSG_INIT_WORLD_STATES
, (4+4+4+2+(NumberOfFields
*8)));
7903 data
<< uint32(mapid
); // mapid
7904 data
<< uint32(zoneid
); // zone id
7905 data
<< uint32(areaid
); // area id, new 2.1.0
7906 data
<< uint16(NumberOfFields
); // count of uint64 blocks
7907 data
<< uint32(0x8d8) << uint32(0x0); // 1
7908 data
<< uint32(0x8d7) << uint32(0x0); // 2
7909 data
<< uint32(0x8d6) << uint32(0x0); // 3
7910 data
<< uint32(0x8d5) << uint32(0x0); // 4
7911 data
<< uint32(0x8d4) << uint32(0x0); // 5
7912 data
<< uint32(0x8d3) << uint32(0x0); // 6
7913 // 7 1 - Arena season in progress, 0 - end of season
7914 data
<< uint32(0xC77) << uint32(sWorld
.getConfig(CONFIG_BOOL_ARENA_SEASON_IN_PROGRESS
));
7915 // 8 Arena season id
7916 data
<< uint32(0xF3D) << uint32(sWorld
.getConfig(CONFIG_UINT32_ARENA_SEASON_ID
));
7917 if(mapid
== 530) // Outland
7919 data
<< uint32(0x9bf) << uint32(0x0); // 7
7920 data
<< uint32(0x9bd) << uint32(0xF); // 8
7921 data
<< uint32(0x9bb) << uint32(0xF); // 9
7936 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_AV
)
7937 bg
->FillInitialWorldStates(data
);
7940 data
<< uint32(0x7ae) << uint32(0x1); // 7 snowfall n
7941 data
<< uint32(0x532) << uint32(0x1); // 8 frostwolfhut hc
7942 data
<< uint32(0x531) << uint32(0x0); // 9 frostwolfhut ac
7943 data
<< uint32(0x52e) << uint32(0x0); // 10 stormpike firstaid a_a
7944 data
<< uint32(0x571) << uint32(0x0); // 11 east frostwolf tower horde assaulted -unused
7945 data
<< uint32(0x570) << uint32(0x0); // 12 west frostwolf tower horde assaulted - unused
7946 data
<< uint32(0x567) << uint32(0x1); // 13 frostwolfe c
7947 data
<< uint32(0x566) << uint32(0x1); // 14 frostwolfw c
7948 data
<< uint32(0x550) << uint32(0x1); // 15 irondeep (N) ally
7949 data
<< uint32(0x544) << uint32(0x0); // 16 ice grave a_a
7950 data
<< uint32(0x536) << uint32(0x0); // 17 stormpike grave h_c
7951 data
<< uint32(0x535) << uint32(0x1); // 18 stormpike grave a_c
7952 data
<< uint32(0x518) << uint32(0x0); // 19 stoneheart grave a_a
7953 data
<< uint32(0x517) << uint32(0x0); // 20 stoneheart grave h_a
7954 data
<< uint32(0x574) << uint32(0x0); // 21 1396 unk
7955 data
<< uint32(0x573) << uint32(0x0); // 22 iceblood tower horde assaulted -unused
7956 data
<< uint32(0x572) << uint32(0x0); // 23 towerpoint horde assaulted - unused
7957 data
<< uint32(0x56f) << uint32(0x0); // 24 1391 unk
7958 data
<< uint32(0x56e) << uint32(0x0); // 25 iceblood a
7959 data
<< uint32(0x56d) << uint32(0x0); // 26 towerp a
7960 data
<< uint32(0x56c) << uint32(0x0); // 27 frostwolfe a
7961 data
<< uint32(0x56b) << uint32(0x0); // 28 froswolfw a
7962 data
<< uint32(0x56a) << uint32(0x1); // 29 1386 unk
7963 data
<< uint32(0x569) << uint32(0x1); // 30 iceblood c
7964 data
<< uint32(0x568) << uint32(0x1); // 31 towerp c
7965 data
<< uint32(0x565) << uint32(0x0); // 32 stoneh tower a
7966 data
<< uint32(0x564) << uint32(0x0); // 33 icewing tower a
7967 data
<< uint32(0x563) << uint32(0x0); // 34 dunn a
7968 data
<< uint32(0x562) << uint32(0x0); // 35 duns a
7969 data
<< uint32(0x561) << uint32(0x0); // 36 stoneheart bunker alliance assaulted - unused
7970 data
<< uint32(0x560) << uint32(0x0); // 37 icewing bunker alliance assaulted - unused
7971 data
<< uint32(0x55f) << uint32(0x0); // 38 dunbaldar south alliance assaulted - unused
7972 data
<< uint32(0x55e) << uint32(0x0); // 39 dunbaldar north alliance assaulted - unused
7973 data
<< uint32(0x55d) << uint32(0x0); // 40 stone tower d
7974 data
<< uint32(0x3c6) << uint32(0x0); // 41 966 unk
7975 data
<< uint32(0x3c4) << uint32(0x0); // 42 964 unk
7976 data
<< uint32(0x3c2) << uint32(0x0); // 43 962 unk
7977 data
<< uint32(0x516) << uint32(0x1); // 44 stoneheart grave a_c
7978 data
<< uint32(0x515) << uint32(0x0); // 45 stonheart grave h_c
7979 data
<< uint32(0x3b6) << uint32(0x0); // 46 950 unk
7980 data
<< uint32(0x55c) << uint32(0x0); // 47 icewing tower d
7981 data
<< uint32(0x55b) << uint32(0x0); // 48 dunn d
7982 data
<< uint32(0x55a) << uint32(0x0); // 49 duns d
7983 data
<< uint32(0x559) << uint32(0x0); // 50 1369 unk
7984 data
<< uint32(0x558) << uint32(0x0); // 51 iceblood d
7985 data
<< uint32(0x557) << uint32(0x0); // 52 towerp d
7986 data
<< uint32(0x556) << uint32(0x0); // 53 frostwolfe d
7987 data
<< uint32(0x555) << uint32(0x0); // 54 frostwolfw d
7988 data
<< uint32(0x554) << uint32(0x1); // 55 stoneh tower c
7989 data
<< uint32(0x553) << uint32(0x1); // 56 icewing tower c
7990 data
<< uint32(0x552) << uint32(0x1); // 57 dunn c
7991 data
<< uint32(0x551) << uint32(0x1); // 58 duns c
7992 data
<< uint32(0x54f) << uint32(0x0); // 59 irondeep (N) horde
7993 data
<< uint32(0x54e) << uint32(0x0); // 60 irondeep (N) ally
7994 data
<< uint32(0x54d) << uint32(0x1); // 61 mine (S) neutral
7995 data
<< uint32(0x54c) << uint32(0x0); // 62 mine (S) horde
7996 data
<< uint32(0x54b) << uint32(0x0); // 63 mine (S) ally
7997 data
<< uint32(0x545) << uint32(0x0); // 64 iceblood h_a
7998 data
<< uint32(0x543) << uint32(0x1); // 65 iceblod h_c
7999 data
<< uint32(0x542) << uint32(0x0); // 66 iceblood a_c
8000 data
<< uint32(0x540) << uint32(0x0); // 67 snowfall h_a
8001 data
<< uint32(0x53f) << uint32(0x0); // 68 snowfall a_a
8002 data
<< uint32(0x53e) << uint32(0x0); // 69 snowfall h_c
8003 data
<< uint32(0x53d) << uint32(0x0); // 70 snowfall a_c
8004 data
<< uint32(0x53c) << uint32(0x0); // 71 frostwolf g h_a
8005 data
<< uint32(0x53b) << uint32(0x0); // 72 frostwolf g a_a
8006 data
<< uint32(0x53a) << uint32(0x1); // 73 frostwolf g h_c
8007 data
<< uint32(0x539) << uint32(0x0); // 74 frostwolf g a_c
8008 data
<< uint32(0x538) << uint32(0x0); // 75 stormpike grave h_a
8009 data
<< uint32(0x537) << uint32(0x0); // 76 stormpike grave a_a
8010 data
<< uint32(0x534) << uint32(0x0); // 77 frostwolf hut h_a
8011 data
<< uint32(0x533) << uint32(0x0); // 78 frostwolf hut a_a
8012 data
<< uint32(0x530) << uint32(0x0); // 79 stormpike first aid h_a
8013 data
<< uint32(0x52f) << uint32(0x0); // 80 stormpike first aid h_c
8014 data
<< uint32(0x52d) << uint32(0x1); // 81 stormpike first aid a_c
8018 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_WS
)
8019 bg
->FillInitialWorldStates(data
);
8022 data
<< uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
8023 data
<< uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
8024 data
<< uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
8025 data
<< uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
8026 data
<< uint32(0x60b) << uint32(0x2); // 11 1547 unk
8027 data
<< uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
8028 data
<< uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
8029 data
<< uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
8033 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_AB
)
8034 bg
->FillInitialWorldStates(data
);
8037 data
<< uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
8038 data
<< uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
8039 data
<< uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
8040 data
<< uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
8041 data
<< uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
8042 data
<< uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
8043 data
<< uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
8044 data
<< uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
8045 data
<< uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
8046 data
<< uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
8047 data
<< uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
8048 data
<< uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
8049 data
<< uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
8050 data
<< uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
8051 data
<< uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
8052 data
<< uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
8053 data
<< uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
8054 data
<< uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
8055 data
<< uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
8056 data
<< uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
8057 data
<< uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
8058 data
<< uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
8059 data
<< uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
8060 data
<< uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
8061 data
<< uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
8062 data
<< uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
8063 data
<< uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
8064 data
<< uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
8065 data
<< uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
8066 data
<< uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
8067 data
<< uint32(0x745) << uint32(0x2); // 37 1861 unk
8068 data
<< uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
8072 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_EY
)
8073 bg
->FillInitialWorldStates(data
);
8076 data
<< uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
8077 data
<< uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
8078 data
<< uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
8079 data
<< uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
8080 data
<< uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
8081 data
<< uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
8082 data
<< uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
8083 data
<< uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
8084 data
<< uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
8085 data
<< uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
8086 data
<< uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
8087 data
<< uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
8088 data
<< uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
8089 data
<< uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
8090 data
<< uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
8091 data
<< uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
8092 data
<< uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
8093 data
<< uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
8094 data
<< uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
8095 data
<< uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
8096 data
<< uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
8097 data
<< uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
8098 data
<< uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
8099 data
<< uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
8100 data
<< uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
8101 data
<< uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
8102 data
<< uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
8103 data
<< uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
8104 data
<< uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
8105 data
<< uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
8106 data
<< uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
8107 data
<< uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
8108 // and some more ... unknown
8111 case 3483: // Hellfire Peninsula
8112 data
<< uint32(0x9ba) << uint32(0x1); // 10
8113 data
<< uint32(0x9b9) << uint32(0x1); // 11
8114 data
<< uint32(0x9b5) << uint32(0x0); // 12
8115 data
<< uint32(0x9b4) << uint32(0x1); // 13
8116 data
<< uint32(0x9b3) << uint32(0x0); // 14
8117 data
<< uint32(0x9b2) << uint32(0x0); // 15
8118 data
<< uint32(0x9b1) << uint32(0x1); // 16
8119 data
<< uint32(0x9b0) << uint32(0x0); // 17
8120 data
<< uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
8121 data
<< uint32(0x9ac) << uint32(0x0); // 19
8122 data
<< uint32(0x9a8) << uint32(0x0); // 20
8123 data
<< uint32(0x9a7) << uint32(0x0); // 21
8124 data
<< uint32(0x9a6) << uint32(0x1); // 22
8126 case 3519: // Terokkar Forest
8127 data
<< uint32(0xa41) << uint32(0x0); // 10
8128 data
<< uint32(0xa40) << uint32(0x14); // 11
8129 data
<< uint32(0xa3f) << uint32(0x0); // 12
8130 data
<< uint32(0xa3e) << uint32(0x0); // 13
8131 data
<< uint32(0xa3d) << uint32(0x5); // 14
8132 data
<< uint32(0xa3c) << uint32(0x0); // 15
8133 data
<< uint32(0xa87) << uint32(0x0); // 16
8134 data
<< uint32(0xa86) << uint32(0x0); // 17
8135 data
<< uint32(0xa85) << uint32(0x0); // 18
8136 data
<< uint32(0xa84) << uint32(0x0); // 19
8137 data
<< uint32(0xa83) << uint32(0x0); // 20
8138 data
<< uint32(0xa82) << uint32(0x0); // 21
8139 data
<< uint32(0xa81) << uint32(0x0); // 22
8140 data
<< uint32(0xa80) << uint32(0x0); // 23
8141 data
<< uint32(0xa7e) << uint32(0x0); // 24
8142 data
<< uint32(0xa7d) << uint32(0x0); // 25
8143 data
<< uint32(0xa7c) << uint32(0x0); // 26
8144 data
<< uint32(0xa7b) << uint32(0x0); // 27
8145 data
<< uint32(0xa7a) << uint32(0x0); // 28
8146 data
<< uint32(0xa79) << uint32(0x0); // 29
8147 data
<< uint32(0x9d0) << uint32(0x5); // 30
8148 data
<< uint32(0x9ce) << uint32(0x0); // 31
8149 data
<< uint32(0x9cd) << uint32(0x0); // 32
8150 data
<< uint32(0x9cc) << uint32(0x0); // 33
8151 data
<< uint32(0xa88) << uint32(0x0); // 34
8152 data
<< uint32(0xad0) << uint32(0x0); // 35
8153 data
<< uint32(0xacf) << uint32(0x1); // 36
8155 case 3521: // Zangarmarsh
8156 data
<< uint32(0x9e1) << uint32(0x0); // 10
8157 data
<< uint32(0x9e0) << uint32(0x0); // 11
8158 data
<< uint32(0x9df) << uint32(0x0); // 12
8159 data
<< uint32(0xa5d) << uint32(0x1); // 13
8160 data
<< uint32(0xa5c) << uint32(0x0); // 14
8161 data
<< uint32(0xa5b) << uint32(0x1); // 15
8162 data
<< uint32(0xa5a) << uint32(0x0); // 16
8163 data
<< uint32(0xa59) << uint32(0x1); // 17
8164 data
<< uint32(0xa58) << uint32(0x0); // 18
8165 data
<< uint32(0xa57) << uint32(0x0); // 19
8166 data
<< uint32(0xa56) << uint32(0x0); // 20
8167 data
<< uint32(0xa55) << uint32(0x1); // 21
8168 data
<< uint32(0xa54) << uint32(0x0); // 22
8169 data
<< uint32(0x9e7) << uint32(0x0); // 23
8170 data
<< uint32(0x9e6) << uint32(0x0); // 24
8171 data
<< uint32(0x9e5) << uint32(0x0); // 25
8172 data
<< uint32(0xa00) << uint32(0x0); // 26
8173 data
<< uint32(0x9ff) << uint32(0x1); // 27
8174 data
<< uint32(0x9fe) << uint32(0x0); // 28
8175 data
<< uint32(0x9fd) << uint32(0x0); // 29
8176 data
<< uint32(0x9fc) << uint32(0x1); // 30
8177 data
<< uint32(0x9fb) << uint32(0x0); // 31
8178 data
<< uint32(0xa62) << uint32(0x0); // 32
8179 data
<< uint32(0xa61) << uint32(0x1); // 33
8180 data
<< uint32(0xa60) << uint32(0x1); // 34
8181 data
<< uint32(0xa5f) << uint32(0x0); // 35
8183 case 3698: // Nagrand Arena
8184 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_NA
)
8185 bg
->FillInitialWorldStates(data
);
8188 data
<< uint32(0xa0f) << uint32(0x0); // 7
8189 data
<< uint32(0xa10) << uint32(0x0); // 8
8190 data
<< uint32(0xa11) << uint32(0x0); // 9 show
8193 case 3702: // Blade's Edge Arena
8194 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_BE
)
8195 bg
->FillInitialWorldStates(data
);
8198 data
<< uint32(0x9f0) << uint32(0x0); // 7 gold
8199 data
<< uint32(0x9f1) << uint32(0x0); // 8 green
8200 data
<< uint32(0x9f3) << uint32(0x0); // 9 show
8203 case 3968: // Ruins of Lordaeron
8204 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_RL
)
8205 bg
->FillInitialWorldStates(data
);
8208 data
<< uint32(0xbb8) << uint32(0x0); // 7 gold
8209 data
<< uint32(0xbb9) << uint32(0x0); // 8 green
8210 data
<< uint32(0xbba) << uint32(0x0); // 9 show
8213 case 3703: // Shattrath City
8216 data
<< uint32(0x914) << uint32(0x0); // 7
8217 data
<< uint32(0x913) << uint32(0x0); // 8
8218 data
<< uint32(0x912) << uint32(0x0); // 9
8219 data
<< uint32(0x915) << uint32(0x0); // 10
8222 GetSession()->SendPacket(&data
);
8225 uint32
Player::GetXPRestBonus(uint32 xp
)
8227 uint32 rested_bonus
= (uint32
)GetRestBonus(); // xp for each rested bonus
8229 if(rested_bonus
> xp
) // max rested_bonus == xp or (r+x) = 200% xp
8232 SetRestBonus( GetRestBonus() - rested_bonus
);
8234 sLog
.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp
+rested_bonus
,rested_bonus
,GetRestBonus());
8235 return rested_bonus
;
8238 void Player::SetBindPoint(uint64 guid
)
8240 WorldPacket
data(SMSG_BINDER_CONFIRM
, 8);
8241 data
<< uint64(guid
);
8242 GetSession()->SendPacket( &data
);
8245 void Player::SendTalentWipeConfirm(uint64 guid
)
8247 WorldPacket
data(MSG_TALENT_WIPE_CONFIRM
, (8+4));
8248 data
<< uint64(guid
);
8249 data
<< uint32(resetTalentsCost());
8250 GetSession()->SendPacket( &data
);
8253 void Player::SendPetSkillWipeConfirm()
8255 Pet
* pet
= GetPet();
8258 WorldPacket
data(SMSG_PET_UNLEARN_CONFIRM
, (8+4));
8259 data
<< pet
->GetGUID();
8260 data
<< uint32(pet
->resetTalentsCost());
8261 GetSession()->SendPacket( &data
);
8264 /*********************************************************/
8265 /*** STORAGE SYSTEM ***/
8266 /*********************************************************/
8268 void Player::SetVirtualItemSlot( uint8 i
, Item
* item
)
8273 if(!item
->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT
))
8275 uint32 charges
= item
->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
);
8279 item
->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
,charges
-1);
8280 else if(charges
<= 1)
8282 ApplyEnchantment(item
,TEMP_ENCHANTMENT_SLOT
,false);
8283 item
->ClearEnchantment(TEMP_ENCHANTMENT_SLOT
);
8288 void Player::SetSheath( SheathState sheathed
)
8292 case SHEATH_STATE_UNARMED
: // no prepared weapon
8293 SetVirtualItemSlot(0,NULL
);
8294 SetVirtualItemSlot(1,NULL
);
8295 SetVirtualItemSlot(2,NULL
);
8297 case SHEATH_STATE_MELEE
: // prepared melee weapon
8299 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK
,true,true));
8300 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK
,true,true));
8301 SetVirtualItemSlot(2,NULL
);
8303 case SHEATH_STATE_RANGED
: // prepared ranged weapon
8304 SetVirtualItemSlot(0,NULL
);
8305 SetVirtualItemSlot(1,NULL
);
8306 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK
,true,true));
8309 SetVirtualItemSlot(0,NULL
);
8310 SetVirtualItemSlot(1,NULL
);
8311 SetVirtualItemSlot(2,NULL
);
8314 Unit::SetSheath(sheathed
); // this must visualize Sheath changing for other players...
8317 uint8
Player::FindEquipSlot( ItemPrototype
const* proto
, uint32 slot
, bool swap
) const
8319 uint8 pClass
= getClass();
8322 slots
[0] = NULL_SLOT
;
8323 slots
[1] = NULL_SLOT
;
8324 slots
[2] = NULL_SLOT
;
8325 slots
[3] = NULL_SLOT
;
8326 switch( proto
->InventoryType
)
8329 slots
[0] = EQUIPMENT_SLOT_HEAD
;
8332 slots
[0] = EQUIPMENT_SLOT_NECK
;
8334 case INVTYPE_SHOULDERS
:
8335 slots
[0] = EQUIPMENT_SLOT_SHOULDERS
;
8338 slots
[0] = EQUIPMENT_SLOT_BODY
;
8341 slots
[0] = EQUIPMENT_SLOT_CHEST
;
8344 slots
[0] = EQUIPMENT_SLOT_CHEST
;
8347 slots
[0] = EQUIPMENT_SLOT_WAIST
;
8350 slots
[0] = EQUIPMENT_SLOT_LEGS
;
8353 slots
[0] = EQUIPMENT_SLOT_FEET
;
8355 case INVTYPE_WRISTS
:
8356 slots
[0] = EQUIPMENT_SLOT_WRISTS
;
8359 slots
[0] = EQUIPMENT_SLOT_HANDS
;
8361 case INVTYPE_FINGER
:
8362 slots
[0] = EQUIPMENT_SLOT_FINGER1
;
8363 slots
[1] = EQUIPMENT_SLOT_FINGER2
;
8365 case INVTYPE_TRINKET
:
8366 slots
[0] = EQUIPMENT_SLOT_TRINKET1
;
8367 slots
[1] = EQUIPMENT_SLOT_TRINKET2
;
8370 slots
[0] = EQUIPMENT_SLOT_BACK
;
8372 case INVTYPE_WEAPON
:
8374 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8376 // suggest offhand slot only if know dual wielding
8377 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8379 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
8382 case INVTYPE_SHIELD
:
8383 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8385 case INVTYPE_RANGED
:
8386 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8388 case INVTYPE_2HWEAPON
:
8389 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8390 if (CanDualWield() && CanTitanGrip())
8391 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
8393 case INVTYPE_TABARD
:
8394 slots
[0] = EQUIPMENT_SLOT_TABARD
;
8396 case INVTYPE_WEAPONMAINHAND
:
8397 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8399 case INVTYPE_WEAPONOFFHAND
:
8400 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8402 case INVTYPE_HOLDABLE
:
8403 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8405 case INVTYPE_THROWN
:
8406 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8408 case INVTYPE_RANGEDRIGHT
:
8409 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8412 slots
[0] = INVENTORY_SLOT_BAG_START
+ 0;
8413 slots
[1] = INVENTORY_SLOT_BAG_START
+ 1;
8414 slots
[2] = INVENTORY_SLOT_BAG_START
+ 2;
8415 slots
[3] = INVENTORY_SLOT_BAG_START
+ 3;
8419 switch(proto
->SubClass
)
8421 case ITEM_SUBCLASS_ARMOR_LIBRAM
:
8422 if (pClass
== CLASS_PALADIN
)
8423 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8425 case ITEM_SUBCLASS_ARMOR_IDOL
:
8426 if (pClass
== CLASS_DRUID
)
8427 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8429 case ITEM_SUBCLASS_ARMOR_TOTEM
:
8430 if (pClass
== CLASS_SHAMAN
)
8431 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8433 case ITEM_SUBCLASS_ARMOR_MISC
:
8434 if (pClass
== CLASS_WARLOCK
)
8435 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8437 case ITEM_SUBCLASS_ARMOR_SIGIL
:
8438 if (pClass
== CLASS_DEATH_KNIGHT
)
8439 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8448 if( slot
!= NULL_SLOT
)
8450 if( swap
|| !GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
) )
8452 for (int i
= 0; i
< 4; ++i
)
8454 if ( slots
[i
] == slot
)
8461 // search free slot at first
8462 for (int i
= 0; i
< 4; ++i
)
8464 if ( slots
[i
] != NULL_SLOT
&& !GetItemByPos( INVENTORY_SLOT_BAG_0
, slots
[i
] ) )
8466 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8467 if(slots
[i
]!=EQUIPMENT_SLOT_OFFHAND
|| !IsTwoHandUsed())
8472 // if not found free and can swap return first appropriate from used
8473 for (int i
= 0; i
< 4; ++i
)
8475 if ( slots
[i
] != NULL_SLOT
&& swap
)
8484 uint8
Player::CanUnequipItems( uint32 item
, uint32 count
) const
8487 uint32 tempcount
= 0;
8489 uint8 res
= EQUIP_ERR_OK
;
8491 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8493 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8494 if( pItem
&& pItem
->GetEntry() == item
)
8496 uint8 ires
= CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
, false);
8497 if(ires
==EQUIP_ERR_OK
)
8499 tempcount
+= pItem
->GetCount();
8500 if( tempcount
>= count
)
8501 return EQUIP_ERR_OK
;
8507 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8509 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8510 if( pItem
&& pItem
->GetEntry() == item
)
8512 tempcount
+= pItem
->GetCount();
8513 if( tempcount
>= count
)
8514 return EQUIP_ERR_OK
;
8517 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
8519 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8520 if( pItem
&& pItem
->GetEntry() == item
)
8522 tempcount
+= pItem
->GetCount();
8523 if( tempcount
>= count
)
8524 return EQUIP_ERR_OK
;
8528 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8530 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8533 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8535 pItem
= GetItemByPos( i
, j
);
8536 if( pItem
&& pItem
->GetEntry() == item
)
8538 tempcount
+= pItem
->GetCount();
8539 if( tempcount
>= count
)
8540 return EQUIP_ERR_OK
;
8546 // not found req. item count and have unequippable items
8550 uint32
Player::GetItemCount( uint32 item
, bool inBankAlso
, Item
* skipItem
) const
8553 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8555 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8556 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8557 count
+= pItem
->GetCount();
8559 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
8561 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8562 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8563 count
+= pItem
->GetCount();
8565 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8567 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8569 count
+= pBag
->GetItemCount(item
,skipItem
);
8572 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8574 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8576 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8577 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8578 count
+= pItem
->GetGemCountWithID(item
);
8584 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; ++i
)
8586 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8587 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8588 count
+= pItem
->GetCount();
8590 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
8592 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8594 count
+= pBag
->GetItemCount(item
,skipItem
);
8597 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8599 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; ++i
)
8601 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8602 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8603 count
+= pItem
->GetGemCountWithID(item
);
8611 uint32
Player::GetItemCountWithLimitCategory( uint32 limitCategory
) const
8614 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8615 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8616 if (pItem
->GetProto()->ItemLimitCategory
== limitCategory
)
8617 count
+= pItem
->GetCount();
8619 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
8620 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8621 if (pItem
->GetProto()->ItemLimitCategory
== limitCategory
)
8622 count
+= pItem
->GetCount();
8624 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8625 if (Bag
* pBag
= (Bag
*)GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8626 count
+= pBag
->GetItemCountWithLimitCategory(limitCategory
);
8628 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; ++i
)
8629 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8630 if (pItem
->GetProto()->ItemLimitCategory
== limitCategory
)
8631 count
+= pItem
->GetCount();
8633 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
8634 if (Bag
* pBag
= (Bag
*)GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8635 count
+= pBag
->GetItemCountWithLimitCategory(limitCategory
);
8640 Item
* Player::GetItemByEntry( uint32 item
) const
8642 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8643 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8644 if (pItem
->GetEntry() == item
)
8647 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
8648 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8649 if (pItem
->GetEntry() == item
)
8652 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8653 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8654 if (Item
* itemPtr
= pBag
->GetItemByEntry(item
))
8660 Item
* Player::GetItemByLimitedCategory(uint32 limitedCategory
) const
8662 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8663 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8664 if (pItem
->GetProto()->ItemLimitCategory
== limitedCategory
)
8667 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
8668 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8669 if (pItem
->GetProto()->ItemLimitCategory
== limitedCategory
)
8672 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8673 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8674 if (Item
* itemPtr
= pBag
->GetItemByLimitedCategory(limitedCategory
))
8680 Item
* Player::GetItemByGuid(ObjectGuid guid
) const
8682 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8683 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8684 if (pItem
->GetObjectGuid() == guid
)
8687 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
8688 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8689 if (pItem
->GetObjectGuid() == guid
)
8692 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8693 if (Bag
*pBag
= (Bag
*)GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8694 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8695 if (Item
* pItem
= pBag
->GetItemByPos(j
))
8696 if (pItem
->GetObjectGuid() == guid
)
8699 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
8700 if (Bag
*pBag
= (Bag
*)GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8701 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8702 if (Item
* pItem
= pBag
->GetItemByPos(j
))
8703 if (pItem
->GetObjectGuid() == guid
)
8709 Item
* Player::GetItemByPos( uint16 pos
) const
8711 uint8 bag
= pos
>> 8;
8712 uint8 slot
= pos
& 255;
8713 return GetItemByPos( bag
, slot
);
8716 Item
* Player::GetItemByPos( uint8 bag
, uint8 slot
) const
8718 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< BANK_SLOT_BAG_END
|| (slot
>= KEYRING_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)) )
8719 return m_items
[slot
];
8720 else if ((bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8721 || (bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
) )
8723 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8725 return pBag
->GetItemByPos(slot
);
8730 Item
* Player::GetWeaponForAttack(WeaponAttackType attackType
, bool nonbroken
, bool useable
) const
8735 case BASE_ATTACK
: slot
= EQUIPMENT_SLOT_MAINHAND
; break;
8736 case OFF_ATTACK
: slot
= EQUIPMENT_SLOT_OFFHAND
; break;
8737 case RANGED_ATTACK
: slot
= EQUIPMENT_SLOT_RANGED
; break;
8738 default: return NULL
;
8741 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, slot
);
8742 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_WEAPON
)
8745 if (useable
&& !IsUseEquipedWeapon(attackType
==BASE_ATTACK
))
8748 if (nonbroken
&& item
->IsBroken())
8754 Item
* Player::GetShield(bool useable
) const
8756 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
8757 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_ARMOR
)
8763 if( item
->IsBroken())
8769 uint32
Player::GetAttackBySlot( uint8 slot
)
8773 case EQUIPMENT_SLOT_MAINHAND
: return BASE_ATTACK
;
8774 case EQUIPMENT_SLOT_OFFHAND
: return OFF_ATTACK
;
8775 case EQUIPMENT_SLOT_RANGED
: return RANGED_ATTACK
;
8776 default: return MAX_ATTACK
;
8780 bool Player::IsInventoryPos( uint8 bag
, uint8 slot
)
8782 if( bag
== INVENTORY_SLOT_BAG_0
&& slot
== NULL_SLOT
)
8784 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
) )
8786 if( bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8788 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= KEYRING_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
) )
8793 bool Player::IsEquipmentPos( uint8 bag
, uint8 slot
)
8795 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< EQUIPMENT_SLOT_END
) )
8797 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8802 bool Player::IsBankPos( uint8 bag
, uint8 slot
)
8804 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
) )
8806 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8808 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8813 bool Player::IsBagPos( uint16 pos
)
8815 uint8 bag
= pos
>> 8;
8816 uint8 slot
= pos
& 255;
8817 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8819 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8824 bool Player::IsValidPos( uint8 bag
, uint8 slot
, bool explicit_pos
) const
8827 if(bag
== NULL_BAG
&& !explicit_pos
)
8830 if (bag
== INVENTORY_SLOT_BAG_0
)
8832 // any post selected
8833 if (slot
== NULL_SLOT
&& !explicit_pos
)
8837 if (slot
< EQUIPMENT_SLOT_END
)
8841 if (slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
)
8845 if (slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
)
8849 if (slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_END
)
8853 if (slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
)
8857 if (slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
8863 // bag content slots
8864 if (bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8866 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8870 // any post selected
8871 if (slot
== NULL_SLOT
&& !explicit_pos
)
8874 return slot
< pBag
->GetBagSize();
8877 // bank bag content slots
8878 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8880 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8884 // any post selected
8885 if (slot
== NULL_SLOT
&& !explicit_pos
)
8888 return slot
< pBag
->GetBagSize();
8896 bool Player::HasItemCount( uint32 item
, uint32 count
, bool inBankAlso
) const
8898 uint32 tempcount
= 0;
8899 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8901 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8902 if( pItem
&& pItem
->GetEntry() == item
)
8904 tempcount
+= pItem
->GetCount();
8905 if( tempcount
>= count
)
8909 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
8911 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8912 if( pItem
&& pItem
->GetEntry() == item
)
8914 tempcount
+= pItem
->GetCount();
8915 if( tempcount
>= count
)
8919 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8921 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8923 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8925 Item
* pItem
= GetItemByPos( i
, j
);
8926 if( pItem
&& pItem
->GetEntry() == item
)
8928 tempcount
+= pItem
->GetCount();
8929 if( tempcount
>= count
)
8938 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; ++i
)
8940 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8941 if( pItem
&& pItem
->GetEntry() == item
)
8943 tempcount
+= pItem
->GetCount();
8944 if( tempcount
>= count
)
8948 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
8950 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8952 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8954 Item
* pItem
= GetItemByPos( i
, j
);
8955 if( pItem
&& pItem
->GetEntry() == item
)
8957 tempcount
+= pItem
->GetCount();
8958 if( tempcount
>= count
)
8969 bool Player::HasItemOrGemWithIdEquipped( uint32 item
, uint32 count
, uint8 except_slot
) const
8971 uint32 tempcount
= 0;
8972 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
8974 if(i
==int(except_slot
))
8977 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8978 if( pItem
&& pItem
->GetEntry() == item
)
8980 tempcount
+= pItem
->GetCount();
8981 if( tempcount
>= count
)
8986 ItemPrototype
const *pProto
= ObjectMgr::GetItemPrototype(item
);
8987 if (pProto
&& pProto
->GemProperties
)
8989 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
8991 if(i
==int(except_slot
))
8994 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8995 if( pItem
&& pItem
->GetProto()->Socket
[0].Color
)
8997 tempcount
+= pItem
->GetGemCountWithID(item
);
8998 if( tempcount
>= count
)
9007 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory
, uint32 count
, uint8 except_slot
) const
9009 uint32 tempcount
= 0;
9010 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
9012 if(i
==int(except_slot
))
9015 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9019 ItemPrototype
const *pProto
= pItem
->GetProto();
9023 if (pProto
->ItemLimitCategory
== limitCategory
)
9025 tempcount
+= pItem
->GetCount();
9026 if( tempcount
>= count
)
9030 if( pProto
->Socket
[0].Color
)
9032 tempcount
+= pItem
->GetGemCountWithLimitCategory(limitCategory
);
9033 if( tempcount
>= count
)
9041 uint8
Player::_CanTakeMoreSimilarItems(uint32 entry
, uint32 count
, Item
* pItem
, uint32
* no_space_count
) const
9043 ItemPrototype
const *pProto
= ObjectMgr::GetItemPrototype(entry
);
9047 *no_space_count
= count
;
9048 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9052 if(pProto
->MaxCount
> 0)
9054 uint32 curcount
= GetItemCount(pProto
->ItemId
,true,pItem
);
9056 if (curcount
+ count
> uint32(pProto
->MaxCount
))
9059 *no_space_count
= count
+curcount
- pProto
->MaxCount
;
9060 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9064 // check unique-equipped limit
9065 if (pProto
->ItemLimitCategory
)
9067 ItemLimitCategoryEntry
const* limitEntry
= sItemLimitCategoryStore
.LookupEntry(pProto
->ItemLimitCategory
);
9071 *no_space_count
= count
;
9072 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9075 if (limitEntry
->mode
== ITEM_LIMIT_CATEGORY_MODE_HAVE
)
9077 uint32 curcount
= GetItemCountWithLimitCategory(pProto
->ItemLimitCategory
);
9079 if (curcount
+ count
> uint32(limitEntry
->maxCount
))
9082 *no_space_count
= count
+ curcount
- limitEntry
->maxCount
;
9083 return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS
;
9088 return EQUIP_ERR_OK
;
9091 bool Player::HasItemTotemCategory( uint32 TotemCategory
) const
9094 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
9096 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9097 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
9100 for(uint8 i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
9102 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9103 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
9106 for(uint8 i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9108 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
9110 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9112 pItem
= GetItemByPos( i
, j
);
9113 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
9121 uint8
Player::_CanStoreItem_InSpecificSlot( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, ItemPrototype
const *pProto
, uint32
& count
, bool swap
, Item
* pSrcItem
) const
9123 Item
* pItem2
= GetItemByPos( bag
, slot
);
9125 // ignore move item (this slot will be empty at move)
9126 if (pItem2
==pSrcItem
)
9131 // empty specific slot - check item fit to slot
9132 if (!pItem2
|| swap
)
9134 if (bag
== INVENTORY_SLOT_BAG_0
)
9137 if (slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_START
+GetMaxKeyringSize() && !(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
))
9138 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9140 // currencytoken case
9141 if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
&& !(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
))
9142 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9145 if (slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
|| slot
>= PLAYER_SLOT_END
)
9146 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9150 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
9152 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9154 ItemPrototype
const* pBagProto
= pBag
->GetProto();
9156 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9158 if (slot
>= pBagProto
->ContainerSlots
)
9159 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9161 if (!ItemCanGoIntoBag(pProto
,pBagProto
))
9162 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9165 // non empty stack with space
9166 need_space
= pProto
->GetMaxStackSize();
9168 // non empty slot, check item type
9171 // can be merged at least partly
9172 uint8 res
= pItem2
->CanBeMergedPartlyWith(pProto
);
9173 if (res
!= EQUIP_ERR_OK
)
9176 // free stack space or infinity
9177 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
9180 if (need_space
> count
)
9183 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | slot
, need_space
);
9184 if (!newPosition
.isContainedIn(dest
))
9186 dest
.push_back(newPosition
);
9187 count
-= need_space
;
9189 return EQUIP_ERR_OK
;
9192 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
9194 // skip specific bag already processed in first called _CanStoreItem_InBag
9196 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9198 // skip not existed bag or self targeted bag
9199 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
9200 if (!pBag
|| pBag
==pSrcItem
)
9201 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9203 ItemPrototype
const* pBagProto
= pBag
->GetProto();
9205 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9207 // specialized bag mode or non-specilized
9208 if (non_specialized
!= (pBagProto
->Class
== ITEM_CLASS_CONTAINER
&& pBagProto
->SubClass
== ITEM_SUBCLASS_CONTAINER
))
9209 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9211 if (!ItemCanGoIntoBag(pProto
,pBagProto
))
9212 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9214 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9216 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9220 Item
* pItem2
= GetItemByPos( bag
, j
);
9222 // ignore move item (this slot will be empty at move)
9223 if (pItem2
== pSrcItem
)
9226 // if merge skip empty, if !merge skip non-empty
9227 if ((pItem2
!= NULL
) != merge
)
9230 uint32 need_space
= pProto
->GetMaxStackSize();
9234 // can be merged at least partly
9235 uint8 res
= pItem2
->CanBeMergedPartlyWith(pProto
);
9236 if (res
!= EQUIP_ERR_OK
)
9239 // descrease at current stacksize
9240 need_space
-= pItem2
->GetCount();
9243 if (need_space
> count
)
9246 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
9247 if (!newPosition
.isContainedIn(dest
))
9249 dest
.push_back(newPosition
);
9250 count
-= need_space
;
9253 return EQUIP_ERR_OK
;
9256 return EQUIP_ERR_OK
;
9259 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
9261 for(uint32 j
= slot_begin
; j
< slot_end
; ++j
)
9263 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9264 if (INVENTORY_SLOT_BAG_0
==skip_bag
&& j
==skip_slot
)
9267 Item
* pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, j
);
9269 // ignore move item (this slot will be empty at move)
9270 if (pItem2
==pSrcItem
)
9273 // if merge skip empty, if !merge skip non-empty
9274 if ((pItem2
!= NULL
) != merge
)
9277 uint32 need_space
= pProto
->GetMaxStackSize();
9281 // can be merged at least partly
9282 uint8 res
= pItem2
->CanBeMergedPartlyWith(pProto
);
9283 if (res
!= EQUIP_ERR_OK
)
9286 // descrease at current stacksize
9287 need_space
-= pItem2
->GetCount();
9290 if (need_space
> count
)
9293 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
9294 if (!newPosition
.isContainedIn(dest
))
9296 dest
.push_back(newPosition
);
9297 count
-= need_space
;
9300 return EQUIP_ERR_OK
;
9303 return EQUIP_ERR_OK
;
9306 uint8
Player::_CanStoreItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, uint32 entry
, uint32 count
, Item
*pItem
, bool swap
, uint32
* no_space_count
) const
9308 sLog
.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, entry
, count
);
9310 ItemPrototype
const *pProto
= ObjectMgr::GetItemPrototype(entry
);
9314 *no_space_count
= count
;
9315 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
:EQUIP_ERR_ITEM_NOT_FOUND
;
9321 if(pItem
->m_lootGenerated
)
9324 *no_space_count
= count
;
9325 return EQUIP_ERR_ALREADY_LOOTED
;
9328 if (pItem
->IsBindedNotWith(this))
9331 *no_space_count
= count
;
9332 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9336 // check count of items (skip for auto move for same player from bank)
9337 uint32 no_similar_count
= 0; // can't store this amount similar items
9338 uint8 res
= _CanTakeMoreSimilarItems(entry
,count
,pItem
,&no_similar_count
);
9339 if (res
!=EQUIP_ERR_OK
)
9341 if (count
==no_similar_count
)
9344 *no_space_count
= no_similar_count
;
9347 count
-= no_similar_count
;
9351 if (bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
9353 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
9354 if (res
!=EQUIP_ERR_OK
)
9357 *no_space_count
= count
+ no_similar_count
;
9363 if (no_similar_count
==0)
9364 return EQUIP_ERR_OK
;
9367 *no_space_count
= count
+ no_similar_count
;
9368 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9372 // not specific slot or have space for partly store only in specific slot
9375 if (bag
!= NULL_BAG
)
9377 // search stack in bag for merge to
9378 if (pProto
->Stackable
!= 1)
9380 if (bag
== INVENTORY_SLOT_BAG_0
) // inventory
9382 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9383 if (res
!=EQUIP_ERR_OK
)
9386 *no_space_count
= count
+ no_similar_count
;
9392 if (no_similar_count
==0)
9393 return EQUIP_ERR_OK
;
9396 *no_space_count
= count
+ no_similar_count
;
9397 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9400 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9401 if (res
!=EQUIP_ERR_OK
)
9404 *no_space_count
= count
+ no_similar_count
;
9410 if (no_similar_count
==0)
9411 return EQUIP_ERR_OK
;
9414 *no_space_count
= count
+ no_similar_count
;
9415 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9418 else // equipped bag
9420 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
9421 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
9422 if (res
!=EQUIP_ERR_OK
)
9423 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
9425 if (res
!=EQUIP_ERR_OK
)
9428 *no_space_count
= count
+ no_similar_count
;
9434 if (no_similar_count
==0)
9435 return EQUIP_ERR_OK
;
9438 *no_space_count
= count
+ no_similar_count
;
9439 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9444 // search free slot in bag for place to
9445 if(bag
== INVENTORY_SLOT_BAG_0
) // inventory
9447 // search free slot - keyring case
9448 if (pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9450 uint32 keyringSize
= GetMaxKeyringSize();
9451 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9452 if (res
!=EQUIP_ERR_OK
)
9455 *no_space_count
= count
+ no_similar_count
;
9461 if (no_similar_count
==0)
9462 return EQUIP_ERR_OK
;
9465 *no_space_count
= count
+ no_similar_count
;
9466 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9469 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9470 if (res
!=EQUIP_ERR_OK
)
9473 *no_space_count
= count
+ no_similar_count
;
9479 if (no_similar_count
==0)
9480 return EQUIP_ERR_OK
;
9483 *no_space_count
= count
+ no_similar_count
;
9484 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9487 else if (pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
9489 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9490 if (res
!=EQUIP_ERR_OK
)
9493 *no_space_count
= count
+ no_similar_count
;
9499 if (no_similar_count
==0)
9500 return EQUIP_ERR_OK
;
9503 *no_space_count
= count
+ no_similar_count
;
9504 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9508 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9509 if (res
!=EQUIP_ERR_OK
)
9512 *no_space_count
= count
+ no_similar_count
;
9518 if (no_similar_count
==0)
9519 return EQUIP_ERR_OK
;
9522 *no_space_count
= count
+ no_similar_count
;
9523 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9526 else // equipped bag
9528 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
9529 if (res
!=EQUIP_ERR_OK
)
9530 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
9532 if (res
!=EQUIP_ERR_OK
)
9535 *no_space_count
= count
+ no_similar_count
;
9541 if (no_similar_count
==0)
9542 return EQUIP_ERR_OK
;
9545 *no_space_count
= count
+ no_similar_count
;
9546 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9551 // not specific bag or have space for partly store only in specific bag
9553 // search stack for merge to
9554 if (pProto
->Stackable
!= 1)
9556 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9557 if (res
!=EQUIP_ERR_OK
)
9560 *no_space_count
= count
+ no_similar_count
;
9566 if (no_similar_count
==0)
9567 return EQUIP_ERR_OK
;
9570 *no_space_count
= count
+ no_similar_count
;
9571 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9574 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9575 if (res
!=EQUIP_ERR_OK
)
9578 *no_space_count
= count
+ no_similar_count
;
9584 if (no_similar_count
==0)
9585 return EQUIP_ERR_OK
;
9588 *no_space_count
= count
+ no_similar_count
;
9589 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9592 if (pProto
->BagFamily
)
9594 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9596 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
9597 if (res
!=EQUIP_ERR_OK
)
9602 if (no_similar_count
==0)
9603 return EQUIP_ERR_OK
;
9606 *no_space_count
= count
+ no_similar_count
;
9607 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9612 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9614 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
9615 if (res
!=EQUIP_ERR_OK
)
9620 if (no_similar_count
==0)
9621 return EQUIP_ERR_OK
;
9624 *no_space_count
= count
+ no_similar_count
;
9625 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9630 // search free slot - special bag case
9631 if (pProto
->BagFamily
)
9633 if (pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9635 uint32 keyringSize
= GetMaxKeyringSize();
9636 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9637 if (res
!=EQUIP_ERR_OK
)
9640 *no_space_count
= count
+ no_similar_count
;
9646 if (no_similar_count
==0)
9647 return EQUIP_ERR_OK
;
9650 *no_space_count
= count
+ no_similar_count
;
9651 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9654 else if (pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
9656 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9657 if (res
!=EQUIP_ERR_OK
)
9660 *no_space_count
= count
+ no_similar_count
;
9666 if (no_similar_count
==0)
9667 return EQUIP_ERR_OK
;
9670 *no_space_count
= count
+ no_similar_count
;
9671 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9675 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9677 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
9678 if (res
!=EQUIP_ERR_OK
)
9683 if (no_similar_count
==0)
9684 return EQUIP_ERR_OK
;
9687 *no_space_count
= count
+ no_similar_count
;
9688 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9694 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9695 if (res
!=EQUIP_ERR_OK
)
9698 *no_space_count
= count
+ no_similar_count
;
9704 if (no_similar_count
==0)
9705 return EQUIP_ERR_OK
;
9708 *no_space_count
= count
+ no_similar_count
;
9709 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9712 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9714 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
9715 if (res
!=EQUIP_ERR_OK
)
9720 if (no_similar_count
==0)
9721 return EQUIP_ERR_OK
;
9724 *no_space_count
= count
+ no_similar_count
;
9725 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9730 *no_space_count
= count
+ no_similar_count
;
9732 return EQUIP_ERR_INVENTORY_FULL
;
9735 //////////////////////////////////////////////////////////////////////////
9736 uint8
Player::CanStoreItems( Item
**pItems
,int count
) const
9741 int inv_slot_items
[INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
];
9742 int inv_bags
[INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
][MAX_BAG_SIZE
];
9743 int inv_keys
[KEYRING_SLOT_END
-KEYRING_SLOT_START
];
9744 int inv_tokens
[CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
];
9746 memset(inv_slot_items
,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
));
9747 memset(inv_bags
,0,sizeof(int)*(INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
)*MAX_BAG_SIZE
);
9748 memset(inv_keys
,0,sizeof(int)*(KEYRING_SLOT_END
-KEYRING_SLOT_START
));
9749 memset(inv_tokens
,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
));
9751 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
9753 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9755 if (pItem2
&& !pItem2
->IsInTrade())
9757 inv_slot_items
[i
-INVENTORY_SLOT_ITEM_START
] = pItem2
->GetCount();
9761 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; ++i
)
9763 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9765 if (pItem2
&& !pItem2
->IsInTrade())
9767 inv_keys
[i
-KEYRING_SLOT_START
] = pItem2
->GetCount();
9771 for(int i
= CURRENCYTOKEN_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
9773 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9775 if (pItem2
&& !pItem2
->IsInTrade())
9777 inv_tokens
[i
-CURRENCYTOKEN_SLOT_START
] = pItem2
->GetCount();
9781 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9783 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
9785 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9787 pItem2
= GetItemByPos( i
, j
);
9788 if (pItem2
&& !pItem2
->IsInTrade())
9790 inv_bags
[i
-INVENTORY_SLOT_BAG_START
][j
] = pItem2
->GetCount();
9796 // check free space for all items
9797 for (int k
= 0; k
< count
; ++k
)
9799 Item
*pItem
= pItems
[k
];
9802 if (!pItem
) continue;
9804 sLog
.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k
+1, pItem
->GetEntry(), pItem
->GetCount());
9805 ItemPrototype
const *pProto
= pItem
->GetProto();
9809 return EQUIP_ERR_ITEM_NOT_FOUND
;
9812 if(pItem
->m_lootGenerated
)
9813 return EQUIP_ERR_ALREADY_LOOTED
;
9816 if(pItem
->IsBindedNotWith(this))
9817 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9820 ItemPrototype
const *pBagProto
;
9822 // item is 'one item only'
9823 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9824 if(res
!= EQUIP_ERR_OK
)
9827 // search stack for merge to
9828 if( pProto
->Stackable
!= 1 )
9830 bool b_found
= false;
9832 for(int t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_END
; ++t
)
9834 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9835 if( pItem2
&& pItem2
->CanBeMergedPartlyWith(pProto
) == EQUIP_ERR_OK
&& inv_keys
[t
-KEYRING_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9837 inv_keys
[t
-KEYRING_SLOT_START
] += pItem
->GetCount();
9842 if (b_found
) continue;
9844 for(int t
= CURRENCYTOKEN_SLOT_START
; t
< CURRENCYTOKEN_SLOT_END
; ++t
)
9846 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9847 if( pItem2
&& pItem2
->CanBeMergedPartlyWith(pProto
) == EQUIP_ERR_OK
&& inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9849 inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] += pItem
->GetCount();
9854 if (b_found
) continue;
9856 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; ++t
)
9858 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9859 if( pItem2
&& pItem2
->CanBeMergedPartlyWith(pProto
) == EQUIP_ERR_OK
&& inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9861 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] += pItem
->GetCount();
9866 if (b_found
) continue;
9868 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; ++t
)
9870 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9873 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9875 pItem2
= GetItemByPos( t
, j
);
9876 if( pItem2
&& pItem2
->CanBeMergedPartlyWith(pProto
) == EQUIP_ERR_OK
&& inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9878 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] += pItem
->GetCount();
9885 if (b_found
) continue;
9889 if( pProto
->BagFamily
)
9891 bool b_found
= false;
9892 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9894 uint32 keyringSize
= GetMaxKeyringSize();
9895 for(uint32 t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_START
+keyringSize
; ++t
)
9897 if( inv_keys
[t
-KEYRING_SLOT_START
] == 0 )
9899 inv_keys
[t
-KEYRING_SLOT_START
] = 1;
9906 if (b_found
) continue;
9908 if(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
9910 for(uint32 t
= CURRENCYTOKEN_SLOT_START
; t
< CURRENCYTOKEN_SLOT_END
; ++t
)
9912 if( inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] == 0 )
9914 inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] = 1;
9921 if (b_found
) continue;
9923 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; ++t
)
9925 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9928 pBagProto
= pBag
->GetProto();
9930 // not plain container check
9931 if( pBagProto
&& (pBagProto
->Class
!= ITEM_CLASS_CONTAINER
|| pBagProto
->SubClass
!= ITEM_SUBCLASS_CONTAINER
) &&
9932 ItemCanGoIntoBag(pProto
,pBagProto
) )
9934 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9936 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9938 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9946 if (b_found
) continue;
9950 bool b_found
= false;
9951 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; ++t
)
9953 if( inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] == 0 )
9955 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] = 1;
9960 if (b_found
) continue;
9962 // search free slot in bags
9963 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; ++t
)
9965 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9968 pBagProto
= pBag
->GetProto();
9970 // special bag already checked
9971 if( pBagProto
&& (pBagProto
->Class
!= ITEM_CLASS_CONTAINER
|| pBagProto
->SubClass
!= ITEM_SUBCLASS_CONTAINER
))
9974 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9976 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9978 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9986 // no free slot found?
9988 return EQUIP_ERR_INVENTORY_FULL
;
9991 return EQUIP_ERR_OK
;
9994 //////////////////////////////////////////////////////////////////////////
9995 uint8
Player::CanEquipNewItem( uint8 slot
, uint16
&dest
, uint32 item
, bool swap
) const
9998 Item
*pItem
= Item::CreateItem( item
, 1, this );
10001 uint8 result
= CanEquipItem(slot
, dest
, pItem
, swap
);
10006 return EQUIP_ERR_ITEM_NOT_FOUND
;
10009 uint8
Player::CanEquipItem( uint8 slot
, uint16
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
10014 sLog
.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot
, pItem
->GetEntry(), pItem
->GetCount());
10015 ItemPrototype
const *pProto
= pItem
->GetProto();
10019 if(pItem
->m_lootGenerated
)
10020 return EQUIP_ERR_ALREADY_LOOTED
;
10022 if(pItem
->IsBindedNotWith(this))
10023 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
10025 // check count of items (skip for auto move for same player from bank)
10026 uint8 res
= CanTakeMoreSimilarItems(pItem
);
10027 if(res
!= EQUIP_ERR_OK
)
10030 // check this only in game
10033 // May be here should be more stronger checks; STUNNED checked
10034 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
10035 if (hasUnitState(UNIT_STAT_STUNNED
))
10036 return EQUIP_ERR_YOU_ARE_STUNNED
;
10038 // do not allow equipping gear except weapons, offhands, projectiles, relics in
10040 // - in-progress arenas
10041 if( !pProto
->CanChangeEquipStateInCombat() )
10044 return EQUIP_ERR_NOT_IN_COMBAT
;
10046 if(BattleGround
* bg
= GetBattleGround())
10047 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
10048 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
10051 if(isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
!= 0)
10052 return EQUIP_ERR_CANT_DO_RIGHT_NOW
; // maybe exist better err
10054 if(IsNonMeleeSpellCasted(false))
10055 return EQUIP_ERR_CANT_DO_RIGHT_NOW
;
10058 ScalingStatDistributionEntry
const *ssd
= pProto
->ScalingStatDistribution
? sScalingStatDistributionStore
.LookupEntry(pProto
->ScalingStatDistribution
) : 0;
10059 // 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)
10060 if (ssd
&& ssd
->MaxLevel
< DEFAULT_MAX_LEVEL
&& ssd
->MaxLevel
< getLevel())
10061 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
10063 uint8 eslot
= FindEquipSlot( pProto
, slot
, swap
);
10064 if (eslot
== NULL_SLOT
)
10065 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
10067 uint8 msg
= CanUseItem(pItem
, not_loading
);
10068 if (msg
!= EQUIP_ERR_OK
)
10070 if (!swap
&& GetItemByPos(INVENTORY_SLOT_BAG_0
, eslot
))
10071 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE
;
10073 // if swap ignore item (equipped also)
10074 if (uint8 res2
= CanEquipUniqueItem(pItem
, swap
? eslot
: NULL_SLOT
))
10077 // check unique-equipped special item classes
10078 if (pProto
->Class
== ITEM_CLASS_QUIVER
)
10080 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
10082 if (Item
* pBag
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
10086 if (ItemPrototype
const* pBagProto
= pBag
->GetProto())
10088 if (pBagProto
->Class
==pProto
->Class
&& (!swap
|| pBag
->GetSlot() != eslot
))
10089 return (pBagProto
->SubClass
== ITEM_SUBCLASS_AMMO_POUCH
)
10090 ? EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
10091 : EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER
;
10098 uint32 type
= pProto
->InventoryType
;
10100 if (eslot
== EQUIPMENT_SLOT_OFFHAND
)
10102 if (type
== INVTYPE_WEAPON
|| type
== INVTYPE_WEAPONOFFHAND
)
10104 if (!CanDualWield())
10105 return EQUIP_ERR_CANT_DUAL_WIELD
;
10107 else if (type
== INVTYPE_2HWEAPON
)
10109 if (!CanDualWield() || !CanTitanGrip())
10110 return EQUIP_ERR_CANT_DUAL_WIELD
;
10113 if (IsTwoHandUsed())
10114 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED
;
10117 // equip two-hand weapon case (with possible unequip 2 items)
10118 if (type
== INVTYPE_2HWEAPON
)
10120 if (eslot
== EQUIPMENT_SLOT_OFFHAND
)
10122 if (!CanTitanGrip())
10123 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
10125 else if (eslot
!= EQUIPMENT_SLOT_MAINHAND
)
10126 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
10128 if (!CanTitanGrip())
10130 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
10131 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
10132 ItemPosCountVec off_dest
;
10133 if (offItem
&& (!not_loading
||
10134 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0
) << 8 | EQUIPMENT_SLOT_OFFHAND
,false) != EQUIP_ERR_OK
||
10135 CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false ) != EQUIP_ERR_OK
))
10136 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_INVENTORY_FULL
;
10139 dest
= ((INVENTORY_SLOT_BAG_0
<< 8) | eslot
);
10140 return EQUIP_ERR_OK
;
10144 return !swap
? EQUIP_ERR_ITEM_NOT_FOUND
: EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
;
10147 uint8
Player::CanUnequipItem( uint16 pos
, bool swap
) const
10149 // Applied only to equipped items and bank bags
10150 if(!IsEquipmentPos(pos
) && !IsBagPos(pos
))
10151 return EQUIP_ERR_OK
;
10153 Item
* pItem
= GetItemByPos(pos
);
10155 // Applied only to existed equipped item
10157 return EQUIP_ERR_OK
;
10159 sLog
.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos
, pItem
->GetEntry(), pItem
->GetCount());
10161 ItemPrototype
const *pProto
= pItem
->GetProto();
10163 return EQUIP_ERR_ITEM_NOT_FOUND
;
10166 if(pItem
->m_lootGenerated
)
10167 return EQUIP_ERR_ALREADY_LOOTED
;
10169 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
10171 // - in-progress arenas
10172 if( !pProto
->CanChangeEquipStateInCombat() )
10175 return EQUIP_ERR_NOT_IN_COMBAT
;
10177 if(BattleGround
* bg
= GetBattleGround())
10178 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
10179 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
10182 if(!swap
&& pItem
->IsBag() && !((Bag
*)pItem
)->IsEmpty())
10183 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS
;
10185 return EQUIP_ERR_OK
;
10188 uint8
Player::CanBankItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
10191 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
10193 uint32 count
= pItem
->GetCount();
10195 sLog
.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), pItem
->GetCount());
10196 ItemPrototype
const *pProto
= pItem
->GetProto();
10198 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
10201 if(pItem
->m_lootGenerated
)
10202 return EQUIP_ERR_ALREADY_LOOTED
;
10204 if (pItem
->IsBindedNotWith(this))
10205 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
10207 // check count of items (skip for auto move for same player from bank)
10208 uint8 res
= CanTakeMoreSimilarItems(pItem
);
10209 if (res
!= EQUIP_ERR_OK
)
10212 // in specific slot
10213 if (bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
10215 if (slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
10217 if (!pItem
->IsBag())
10218 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
;
10220 if (slot
- BANK_SLOT_BAG_START
>= GetBankBagSlotCount())
10221 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT
;
10223 if (uint8 cantuse
= CanUseItem( pItem
, not_loading
) != EQUIP_ERR_OK
)
10227 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
10228 if (res
!=EQUIP_ERR_OK
)
10232 return EQUIP_ERR_OK
;
10235 // not specific slot or have space for partly store only in specific slot
10238 if( bag
!= NULL_BAG
)
10240 if( pProto
->InventoryType
== INVTYPE_BAG
)
10242 Bag
*pBag
= (Bag
*)pItem
;
10243 if( pBag
&& !pBag
->IsEmpty() )
10244 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
;
10247 // search stack in bag for merge to
10248 if( pProto
->Stackable
!= 1 )
10250 if( bag
== INVENTORY_SLOT_BAG_0
)
10252 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
10253 if(res
!=EQUIP_ERR_OK
)
10257 return EQUIP_ERR_OK
;
10261 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
10262 if(res
!=EQUIP_ERR_OK
)
10263 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
10265 if(res
!=EQUIP_ERR_OK
)
10269 return EQUIP_ERR_OK
;
10273 // search free slot in bag
10274 if( bag
== INVENTORY_SLOT_BAG_0
)
10276 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
10277 if(res
!=EQUIP_ERR_OK
)
10281 return EQUIP_ERR_OK
;
10285 res
= _CanStoreItem_InBag(bag
, dest
, pProto
, count
, false, false, pItem
, NULL_BAG
, slot
);
10286 if(res
!= EQUIP_ERR_OK
)
10287 res
= _CanStoreItem_InBag(bag
, dest
, pProto
, count
, false, true, pItem
, NULL_BAG
, slot
);
10289 if(res
!= EQUIP_ERR_OK
)
10293 return EQUIP_ERR_OK
;
10297 // not specific bag or have space for partly store only in specific bag
10299 // search stack for merge to
10300 if( pProto
->Stackable
!= 1 )
10303 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
10304 if(res
!= EQUIP_ERR_OK
)
10308 return EQUIP_ERR_OK
;
10311 if( pProto
->BagFamily
)
10313 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
10315 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
10316 if(res
!=EQUIP_ERR_OK
)
10320 return EQUIP_ERR_OK
;
10324 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
10326 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
10327 if(res
!=EQUIP_ERR_OK
)
10331 return EQUIP_ERR_OK
;
10335 // search free place in special bag
10336 if( pProto
->BagFamily
)
10338 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
10340 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
10341 if(res
!=EQUIP_ERR_OK
)
10345 return EQUIP_ERR_OK
;
10349 // search free space
10350 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
10351 if(res
!=EQUIP_ERR_OK
)
10355 return EQUIP_ERR_OK
;
10357 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
10359 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
10360 if(res
!=EQUIP_ERR_OK
)
10364 return EQUIP_ERR_OK
;
10366 return EQUIP_ERR_BANK_FULL
;
10369 uint8
Player::CanUseItem( Item
*pItem
, bool not_loading
) const
10373 sLog
.outDebug( "STORAGE: CanUseItem item = %u", pItem
->GetEntry());
10375 if (!isAlive() && not_loading
)
10376 return EQUIP_ERR_YOU_ARE_DEAD
;
10379 // return EQUIP_ERR_YOU_ARE_STUNNED;
10381 ItemPrototype
const *pProto
= pItem
->GetProto();
10384 if (pItem
->IsBindedNotWith(this))
10385 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
10387 if ((pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0)
10388 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
10390 if (uint32 item_use_skill
= pItem
->GetSkill())
10392 if (GetSkillValue(item_use_skill
) == 0)
10394 // armor items with scaling stats can downgrade armor skill reqs if related class can learn armor use at some level
10395 if (pProto
->Class
!= ITEM_CLASS_ARMOR
)
10396 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10398 ScalingStatDistributionEntry
const *ssd
= pProto
->ScalingStatDistribution
? sScalingStatDistributionStore
.LookupEntry(pProto
->ScalingStatDistribution
) : NULL
;
10400 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10402 bool allowScaleSkill
= false;
10403 for (uint32 i
= 0; i
< sSkillLineAbilityStore
.GetNumRows(); ++i
)
10405 SkillLineAbilityEntry
const *skillInfo
= sSkillLineAbilityStore
.LookupEntry(i
);
10409 if (skillInfo
->skillId
!= item_use_skill
)
10413 if (skillInfo
->classmask
&& (skillInfo
->classmask
& getClassMask()) == 0)
10416 if (skillInfo
->racemask
&& (skillInfo
->racemask
& getRaceMask()) == 0)
10419 allowScaleSkill
= true;
10423 if (!allowScaleSkill
)
10424 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10428 if (pProto
->RequiredSkill
!= 0)
10430 if (GetSkillValue( pProto
->RequiredSkill
) == 0)
10431 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10433 if (GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10434 return EQUIP_ERR_CANT_EQUIP_SKILL
;
10437 if (pProto
->RequiredSpell
!= 0 && !HasSpell(pProto
->RequiredSpell
))
10438 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10440 if (pProto
->RequiredReputationFaction
&& uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
10441 return EQUIP_ERR_CANT_EQUIP_REPUTATION
;
10443 if (getLevel() < pProto
->RequiredLevel
)
10444 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
10446 return EQUIP_ERR_OK
;
10449 return EQUIP_ERR_ITEM_NOT_FOUND
;
10452 bool Player::CanUseItem( ItemPrototype
const *pProto
)
10454 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10458 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
10460 if( pProto
->RequiredSkill
!= 0 )
10462 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
10464 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10467 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
10469 if( getLevel() < pProto
->RequiredLevel
)
10476 uint8
Player::CanUseAmmo( uint32 item
) const
10478 sLog
.outDebug( "STORAGE: CanUseAmmo item = %u", item
);
10480 return EQUIP_ERR_YOU_ARE_DEAD
;
10481 //if( isStunned() )
10482 // return EQUIP_ERR_YOU_ARE_STUNNED;
10483 ItemPrototype
const *pProto
= ObjectMgr::GetItemPrototype( item
);
10486 if( pProto
->InventoryType
!= INVTYPE_AMMO
)
10487 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE
;
10488 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
10489 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
10490 if( pProto
->RequiredSkill
!= 0 )
10492 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
10493 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10494 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10495 return EQUIP_ERR_CANT_EQUIP_SKILL
;
10497 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
10498 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10499 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
10500 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10502 if( getLevel() < pProto
->RequiredLevel
)
10503 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
10505 // Requires No Ammo
10506 if(GetDummyAura(46699))
10507 return EQUIP_ERR_BAG_FULL6
;
10509 return EQUIP_ERR_OK
;
10511 return EQUIP_ERR_ITEM_NOT_FOUND
;
10514 void Player::SetAmmo( uint32 item
)
10520 if( GetUInt32Value(PLAYER_AMMO_ID
) == item
)
10526 uint8 msg
= CanUseAmmo( item
);
10527 if (msg
!= EQUIP_ERR_OK
)
10529 SendEquipError(msg
, NULL
, NULL
, item
);
10534 SetUInt32Value(PLAYER_AMMO_ID
, item
);
10536 _ApplyAmmoBonuses();
10539 void Player::RemoveAmmo()
10541 SetUInt32Value(PLAYER_AMMO_ID
, 0);
10545 if (CanModifyStats())
10546 UpdateDamagePhysical(RANGED_ATTACK
);
10549 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10550 Item
* Player::StoreNewItem( ItemPosCountVec
const& dest
, uint32 item
, bool update
,int32 randomPropertyId
)
10553 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); ++itr
)
10554 count
+= itr
->count
;
10556 Item
*pItem
= Item::CreateItem( item
, count
, this );
10559 ItemAddedQuestCheck( item
, count
);
10560 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM
, item
, count
);
10561 if(randomPropertyId
)
10562 pItem
->SetItemRandomProperties(randomPropertyId
);
10563 pItem
= StoreItem( dest
, pItem
, update
);
10568 Item
* Player::StoreItem( ItemPosCountVec
const& dest
, Item
* pItem
, bool update
)
10573 Item
* lastItem
= pItem
;
10574 uint32 entry
= pItem
->GetEntry();
10575 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); )
10577 uint16 pos
= itr
->pos
;
10578 uint32 count
= itr
->count
;
10582 if(itr
== dest
.end())
10584 lastItem
= _StoreItem(pos
,pItem
,count
,false,update
);
10588 lastItem
= _StoreItem(pos
,pItem
,count
,true,update
);
10590 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM
, entry
);
10594 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10595 Item
* Player::_StoreItem( uint16 pos
, Item
*pItem
, uint32 count
, bool clone
, bool update
)
10600 uint8 bag
= pos
>> 8;
10601 uint8 slot
= pos
& 255;
10603 sLog
.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), count
);
10605 Item
*pItem2
= GetItemByPos( bag
, slot
);
10610 pItem
= pItem
->CloneItem(count
, this);
10612 pItem
->SetCount(count
);
10617 if (pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10618 pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10619 (pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
)))
10620 pItem
->SetBinding( true );
10622 if (bag
== INVENTORY_SLOT_BAG_0
)
10624 m_items
[slot
] = pItem
;
10625 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2), pItem
->GetGUID() );
10626 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10627 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10629 pItem
->SetSlot( slot
);
10630 pItem
->SetContainer( NULL
);
10632 // need update known currency
10633 if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)
10634 UpdateKnownCurrencies(pItem
->GetEntry(), true);
10636 if (IsInWorld() && update
)
10638 pItem
->AddToWorld();
10639 pItem
->SendCreateUpdateToPlayer( this );
10642 pItem
->SetState(ITEM_CHANGED
, this);
10644 else if (Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
))
10646 pBag
->StoreItem( slot
, pItem
, update
);
10647 if( IsInWorld() && update
)
10649 pItem
->AddToWorld();
10650 pItem
->SendCreateUpdateToPlayer( this );
10652 pItem
->SetState(ITEM_CHANGED
, this);
10653 pBag
->SetState(ITEM_CHANGED
, this);
10656 AddEnchantmentDurations(pItem
);
10657 AddItemDurations(pItem
);
10663 if (pItem2
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10664 pItem2
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10665 (pItem2
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
)))
10666 pItem2
->SetBinding( true );
10668 pItem2
->SetCount( pItem2
->GetCount() + count
);
10669 if (IsInWorld() && update
)
10670 pItem2
->SendCreateUpdateToPlayer( this );
10674 // delete item (it not in any slot currently)
10675 if (IsInWorld() && update
)
10677 pItem
->RemoveFromWorld();
10678 pItem
->DestroyForPlayer( this );
10681 RemoveEnchantmentDurations(pItem
);
10682 RemoveItemDurations(pItem
);
10684 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10685 pItem
->SetState(ITEM_REMOVED
, this);
10688 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10689 AddEnchantmentDurations(pItem2
);
10691 pItem2
->SetState(ITEM_CHANGED
, this);
10697 Item
* Player::EquipNewItem( uint16 pos
, uint32 item
, bool update
)
10699 if (Item
*pItem
= Item::CreateItem( item
, 1, this ))
10701 ItemAddedQuestCheck( item
, 1 );
10702 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM
, item
, 1);
10703 return EquipItem( pos
, pItem
, update
);
10709 Item
* Player::EquipItem( uint16 pos
, Item
*pItem
, bool update
)
10711 AddEnchantmentDurations(pItem
);
10712 AddItemDurations(pItem
);
10714 uint8 bag
= pos
>> 8;
10715 uint8 slot
= pos
& 255;
10717 Item
*pItem2
= GetItemByPos( bag
, slot
);
10721 VisualizeItem( slot
, pItem
);
10725 ItemPrototype
const *pProto
= pItem
->GetProto();
10727 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10728 if(pProto
&& pProto
->ItemSet
)
10729 AddItemsSetItem(this, pItem
);
10731 _ApplyItemMods(pItem
, slot
, true);
10733 if(pProto
&& isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
== 0)
10735 uint32 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s
;
10737 if (getClass() == CLASS_ROGUE
)
10738 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s
;
10740 SpellEntry
const* spellProto
= sSpellStore
.LookupEntry(cooldownSpell
);
10743 sLog
.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell
);
10746 m_weaponChangeTimer
= spellProto
->StartRecoveryTime
;
10748 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+4);
10749 data
<< uint64(GetGUID());
10751 data
<< uint32(cooldownSpell
);
10753 GetSession()->SendPacket(&data
);
10758 if( IsInWorld() && update
)
10760 pItem
->AddToWorld();
10761 pItem
->SendCreateUpdateToPlayer( this );
10764 ApplyEquipCooldown(pItem
);
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();
10779 pItem2
->SetCount( pItem2
->GetCount() + pItem
->GetCount() );
10780 if( IsInWorld() && update
)
10781 pItem2
->SendCreateUpdateToPlayer( this );
10783 // delete item (it not in any slot currently)
10784 //pItem->DeleteFromDB();
10785 if( IsInWorld() && update
)
10787 pItem
->RemoveFromWorld();
10788 pItem
->DestroyForPlayer( this );
10791 RemoveEnchantmentDurations(pItem
);
10792 RemoveItemDurations(pItem
);
10794 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10795 pItem
->SetState(ITEM_REMOVED
, this);
10796 pItem2
->SetState(ITEM_CHANGED
, this);
10798 ApplyEquipCooldown(pItem2
);
10803 // only for full equip instead adding to stack
10804 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM
, pItem
->GetEntry());
10805 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM
, slot
+1);
10810 void Player::QuickEquipItem( uint16 pos
, Item
*pItem
)
10814 AddEnchantmentDurations(pItem
);
10815 AddItemDurations(pItem
);
10817 uint8 slot
= pos
& 255;
10818 VisualizeItem( slot
, pItem
);
10822 pItem
->AddToWorld();
10823 pItem
->SendCreateUpdateToPlayer( this );
10826 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM
, pItem
->GetEntry());
10827 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM
, slot
+1);
10831 void Player::SetVisibleItemSlot(uint8 slot
, Item
*pItem
)
10835 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID
+ (slot
* 2), pItem
->GetEntry());
10836 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT
+ (slot
* 2), 0, pItem
->GetEnchantmentId(PERM_ENCHANTMENT_SLOT
));
10837 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT
+ (slot
* 2), 1, pItem
->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT
));
10841 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID
+ (slot
* 2), 0);
10842 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT
+ (slot
* 2), 0);
10846 void Player::VisualizeItem( uint8 slot
, Item
*pItem
)
10851 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10852 if( pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
|| pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
|| pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
)
10853 pItem
->SetBinding( true );
10855 sLog
.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot
, pItem
->GetEntry());
10857 m_items
[slot
] = pItem
;
10858 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2), pItem
->GetGUID() );
10859 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10860 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10861 pItem
->SetSlot( slot
);
10862 pItem
->SetContainer( NULL
);
10864 if( slot
< EQUIPMENT_SLOT_END
)
10865 SetVisibleItemSlot(slot
, pItem
);
10867 pItem
->SetState(ITEM_CHANGED
, this);
10870 void Player::RemoveItem( uint8 bag
, uint8 slot
, bool update
)
10872 // note: removeitem does not actually change the item
10873 // it only takes the item out of storage temporarily
10874 // note2: if removeitem is to be used for delinking
10875 // the item must be removed from the player's updatequeue
10877 Item
*pItem
= GetItemByPos( bag
, slot
);
10880 sLog
.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10882 RemoveEnchantmentDurations(pItem
);
10883 RemoveItemDurations(pItem
);
10885 if( bag
== INVENTORY_SLOT_BAG_0
)
10887 if ( slot
< INVENTORY_SLOT_BAG_END
)
10889 ItemPrototype
const *pProto
= pItem
->GetProto();
10890 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10892 if(pProto
&& pProto
->ItemSet
)
10893 RemoveItemsSetItem(this, pProto
);
10895 _ApplyItemMods(pItem
, slot
, false);
10897 // remove item dependent auras and casts (only weapon and armor slots)
10898 if(slot
< EQUIPMENT_SLOT_END
)
10900 RemoveItemDependentAurasAndCasts(pItem
);
10902 // remove held enchantments, update expertise
10903 if ( slot
== EQUIPMENT_SLOT_MAINHAND
)
10905 if (pItem
->GetItemSuffixFactor())
10907 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3
);
10908 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4
);
10912 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0
);
10913 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1
);
10916 UpdateExpertise(BASE_ATTACK
);
10917 UpdateArmorPenetration();
10919 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10921 UpdateExpertise(OFF_ATTACK
);
10922 UpdateArmorPenetration();
10926 // need update known currency
10927 else if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)
10928 UpdateKnownCurrencies(pItem
->GetEntry(), false);
10930 m_items
[slot
] = NULL
;
10931 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2), 0);
10933 if ( slot
< EQUIPMENT_SLOT_END
)
10934 SetVisibleItemSlot(slot
, NULL
);
10938 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
10940 pBag
->RemoveItem(slot
, update
);
10942 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10943 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10944 pItem
->SetSlot( NULL_SLOT
);
10945 if( IsInWorld() && update
)
10946 pItem
->SendCreateUpdateToPlayer( this );
10950 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10951 void Player::MoveItemFromInventory(uint8 bag
, uint8 slot
, bool update
)
10953 if(Item
* it
= GetItemByPos(bag
,slot
))
10955 ItemRemovedQuestCheck(it
->GetEntry(), it
->GetCount());
10956 RemoveItem(bag
, slot
, update
);
10957 it
->RemoveFromUpdateQueueOf(this);
10958 if(it
->IsInWorld())
10960 it
->RemoveFromWorld();
10961 it
->DestroyForPlayer( this );
10966 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10967 void Player::MoveItemToInventory(ItemPosCountVec
const& dest
, Item
* pItem
, bool update
, bool in_characterInventoryDB
)
10969 // update quest counters
10970 ItemAddedQuestCheck(pItem
->GetEntry(), pItem
->GetCount());
10971 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM
, pItem
->GetEntry(), pItem
->GetCount());
10974 Item
* pLastItem
= StoreItem(dest
, pItem
, update
);
10976 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10977 if(pLastItem
== pItem
)
10979 // update owner for last item (this can be original item with wrong owner
10980 if(pLastItem
->GetOwnerGUID() != GetGUID())
10981 pLastItem
->SetOwnerGUID(GetGUID());
10983 // if this original item then it need create record in inventory
10984 // in case trade we already have item in other player inventory
10985 pLastItem
->SetState(in_characterInventoryDB
? ITEM_CHANGED
: ITEM_NEW
, this);
10989 void Player::DestroyItem( uint8 bag
, uint8 slot
, bool update
)
10991 Item
*pItem
= GetItemByPos( bag
, slot
);
10994 sLog
.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10996 // start from destroy contained items (only equipped bag can have its)
10997 if (pItem
->IsBag() && pItem
->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10999 for (int i
= 0; i
< MAX_BAG_SIZE
; ++i
)
11000 DestroyItem(slot
, i
, update
);
11003 if(pItem
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_WRAPPED
))
11004 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem
->GetGUIDLow());
11006 RemoveEnchantmentDurations(pItem
);
11007 RemoveItemDurations(pItem
);
11009 ItemRemovedQuestCheck( pItem
->GetEntry(), pItem
->GetCount() );
11011 if( bag
== INVENTORY_SLOT_BAG_0
)
11013 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2), 0);
11015 // equipment and equipped bags can have applied bonuses
11016 if ( slot
< INVENTORY_SLOT_BAG_END
)
11018 ItemPrototype
const *pProto
= pItem
->GetProto();
11020 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
11021 if(pProto
&& pProto
->ItemSet
)
11022 RemoveItemsSetItem(this, pProto
);
11024 _ApplyItemMods(pItem
, slot
, false);
11027 if ( slot
< EQUIPMENT_SLOT_END
)
11029 // remove item dependent auras and casts (only weapon and armor slots)
11030 RemoveItemDependentAurasAndCasts(pItem
);
11032 // update expertise
11033 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
11035 UpdateExpertise(BASE_ATTACK
);
11036 UpdateArmorPenetration();
11038 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
11040 UpdateExpertise(OFF_ATTACK
);
11041 UpdateArmorPenetration();
11044 // equipment visual show
11045 SetVisibleItemSlot(slot
, NULL
);
11047 // need update known currency
11048 else if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)
11049 UpdateKnownCurrencies(pItem
->GetEntry(), false);
11051 m_items
[slot
] = NULL
;
11053 else if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
))
11054 pBag
->RemoveItem(slot
, update
);
11056 if( IsInWorld() && update
)
11058 pItem
->RemoveFromWorld();
11059 pItem
->DestroyForPlayer(this);
11062 //pItem->SetOwnerGUID(0);
11063 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
11064 pItem
->SetSlot( NULL_SLOT
);
11065 pItem
->SetState(ITEM_REMOVED
, this);
11069 void Player::DestroyItemCount( uint32 item
, uint32 count
, bool update
, bool unequip_check
)
11071 sLog
.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item
, count
);
11072 uint32 remcount
= 0;
11075 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
11077 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11079 if (pItem
->GetEntry() == item
)
11081 if (pItem
->GetCount() + remcount
<= count
)
11083 // all items in inventory can unequipped
11084 remcount
+= pItem
->GetCount();
11085 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11087 if (remcount
>= count
)
11092 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
11093 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
11094 if (IsInWorld() & update
)
11095 pItem
->SendCreateUpdateToPlayer( this );
11096 pItem
->SetState(ITEM_CHANGED
, this);
11103 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
11105 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11107 if (pItem
->GetEntry() == item
)
11109 if (pItem
->GetCount() + remcount
<= count
)
11111 // all keys can be unequipped
11112 remcount
+= pItem
->GetCount();
11113 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11115 if (remcount
>= count
)
11120 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
11121 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
11122 if (IsInWorld() & update
)
11123 pItem
->SendCreateUpdateToPlayer( this );
11124 pItem
->SetState(ITEM_CHANGED
, this);
11131 // in inventory bags
11132 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
11134 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11136 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
11138 if(Item
* pItem
= pBag
->GetItemByPos(j
))
11140 if (pItem
->GetEntry() == item
)
11142 // all items in bags can be unequipped
11143 if (pItem
->GetCount() + remcount
<= count
)
11145 remcount
+= pItem
->GetCount();
11146 DestroyItem( i
, j
, update
);
11148 if (remcount
>= count
)
11153 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
11154 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
11155 if (IsInWorld() && update
)
11156 pItem
->SendCreateUpdateToPlayer( this );
11157 pItem
->SetState(ITEM_CHANGED
, this);
11166 // in equipment and bag list
11167 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
11169 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11171 if (pItem
&& pItem
->GetEntry() == item
)
11173 if (pItem
->GetCount() + remcount
<= count
)
11175 if (!unequip_check
|| CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
, false) == EQUIP_ERR_OK
)
11177 remcount
+= pItem
->GetCount();
11178 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11180 if (remcount
>= count
)
11186 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
11187 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
11188 if (IsInWorld() & update
)
11189 pItem
->SendCreateUpdateToPlayer( this );
11190 pItem
->SetState(ITEM_CHANGED
, this);
11198 void Player::DestroyZoneLimitedItem( bool update
, uint32 new_zone
)
11200 sLog
.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone
);
11203 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
11204 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11205 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone
))
11206 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11208 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
11209 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11210 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone
))
11211 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11213 // in inventory bags
11214 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
11215 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11216 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
11217 if (Item
* pItem
= pBag
->GetItemByPos(j
))
11218 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone
))
11219 DestroyItem(i
, j
, update
);
11221 // in equipment and bag list
11222 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
11223 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11224 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone
))
11225 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11228 void Player::DestroyConjuredItems( bool update
)
11230 // used when entering arena
11231 // destroys all conjured items
11232 sLog
.outDebug( "STORAGE: DestroyConjuredItems" );
11235 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
11236 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11237 if (pItem
->IsConjuredConsumable())
11238 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11240 // in inventory bags
11241 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
11242 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11243 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
11244 if (Item
* pItem
= pBag
->GetItemByPos(j
))
11245 if (pItem
->IsConjuredConsumable())
11246 DestroyItem( i
, j
, update
);
11248 // in equipment and bag list
11249 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
11250 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11251 if (pItem
->IsConjuredConsumable())
11252 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11255 void Player::DestroyItemCount( Item
* pItem
, uint32
&count
, bool update
)
11260 sLog
.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem
->GetGUIDLow(),pItem
->GetEntry(), count
);
11262 if( pItem
->GetCount() <= count
)
11264 count
-= pItem
->GetCount();
11266 DestroyItem( pItem
->GetBagSlot(),pItem
->GetSlot(), update
);
11270 ItemRemovedQuestCheck( pItem
->GetEntry(), count
);
11271 pItem
->SetCount( pItem
->GetCount() - count
);
11273 if( IsInWorld() & update
)
11274 pItem
->SendCreateUpdateToPlayer( this );
11275 pItem
->SetState(ITEM_CHANGED
, this);
11279 void Player::SplitItem( uint16 src
, uint16 dst
, uint32 count
)
11281 uint8 srcbag
= src
>> 8;
11282 uint8 srcslot
= src
& 255;
11284 uint8 dstbag
= dst
>> 8;
11285 uint8 dstslot
= dst
& 255;
11287 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
11290 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
11294 if(pSrcItem
->m_lootGenerated
) // prevent split looting item (item
11296 //best error message found for attempting to split while looting
11297 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
11301 // not let split all items (can be only at cheating)
11302 if(pSrcItem
->GetCount() == count
)
11304 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
11308 // not let split more existed items (can be only at cheating)
11309 if(pSrcItem
->GetCount() < count
)
11311 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT
, pSrcItem
, NULL
);
11315 sLog
.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag
, dstslot
, pSrcItem
->GetEntry(), count
);
11316 Item
*pNewItem
= pSrcItem
->CloneItem( count
, this );
11319 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
11323 if( IsInventoryPos( dst
) )
11325 // change item amount before check (for unique max count check)
11326 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11328 ItemPosCountVec dest
;
11329 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pNewItem
, false );
11330 if( msg
!= EQUIP_ERR_OK
)
11333 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11334 SendEquipError( msg
, pSrcItem
, NULL
);
11339 pSrcItem
->SendCreateUpdateToPlayer( this );
11340 pSrcItem
->SetState(ITEM_CHANGED
, this);
11341 StoreItem( dest
, pNewItem
, true);
11343 else if( IsBankPos ( dst
) )
11345 // change item amount before check (for unique max count check)
11346 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11348 ItemPosCountVec dest
;
11349 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pNewItem
, false );
11350 if( msg
!= EQUIP_ERR_OK
)
11353 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11354 SendEquipError( msg
, pSrcItem
, NULL
);
11359 pSrcItem
->SendCreateUpdateToPlayer( this );
11360 pSrcItem
->SetState(ITEM_CHANGED
, this);
11361 BankItem( dest
, pNewItem
, true);
11363 else if( IsEquipmentPos ( dst
) )
11365 // change item amount before check (for unique max count check), provide space for splitted items
11366 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11369 uint8 msg
= CanEquipItem( dstslot
, dest
, pNewItem
, false );
11370 if( msg
!= EQUIP_ERR_OK
)
11373 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11374 SendEquipError( msg
, pSrcItem
, NULL
);
11379 pSrcItem
->SendCreateUpdateToPlayer( this );
11380 pSrcItem
->SetState(ITEM_CHANGED
, this);
11381 EquipItem( dest
, pNewItem
, true);
11382 AutoUnequipOffhandIfNeed();
11386 void Player::SwapItem( uint16 src
, uint16 dst
)
11388 uint8 srcbag
= src
>> 8;
11389 uint8 srcslot
= src
& 255;
11391 uint8 dstbag
= dst
>> 8;
11392 uint8 dstslot
= dst
& 255;
11394 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
11395 Item
*pDstItem
= GetItemByPos( dstbag
, dstslot
);
11400 sLog
.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag
, dstslot
, pSrcItem
->GetEntry());
11404 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD
, pSrcItem
, pDstItem
);
11410 // check unequip potability for equipped items and bank bags
11411 if (IsEquipmentPos(src
) || IsBagPos(src
))
11413 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11414 uint8 msg
= CanUnequipItem( src
, !IsBagPos ( src
) || IsBagPos ( dst
) || (pDstItem
&& pDstItem
->IsBag() && ((Bag
*)pDstItem
)->IsEmpty()));
11415 if (msg
!= EQUIP_ERR_OK
)
11417 SendEquipError( msg
, pSrcItem
, pDstItem
);
11422 // prevent put equipped/bank bag in self
11423 if (IsBagPos(src
) && srcslot
== dstbag
)
11425 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
11429 // prevent put equipped/bank bag in self
11430 if (IsBagPos(dst
) && dstslot
== srcbag
)
11432 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pDstItem
, pSrcItem
);
11440 // check unequip potability for equipped items and bank bags
11441 if(IsEquipmentPos ( dst
) || IsBagPos ( dst
))
11443 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11444 uint8 msg
= CanUnequipItem( dst
, !IsBagPos ( dst
) || IsBagPos ( src
) || (pSrcItem
->IsBag() && ((Bag
*)pSrcItem
)->IsEmpty()));
11445 if(msg
!= EQUIP_ERR_OK
)
11447 SendEquipError( msg
, pSrcItem
, pDstItem
);
11453 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
11454 // or swap empty bag with another empty or not empty bag (with items exchange)
11459 if( IsInventoryPos( dst
) )
11461 ItemPosCountVec dest
;
11462 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pSrcItem
, false );
11463 if( msg
!= EQUIP_ERR_OK
)
11465 SendEquipError( msg
, pSrcItem
, NULL
);
11469 RemoveItem(srcbag
, srcslot
, true);
11470 StoreItem( dest
, pSrcItem
, true);
11472 else if( IsBankPos ( dst
) )
11474 ItemPosCountVec dest
;
11475 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pSrcItem
, false);
11476 if( msg
!= EQUIP_ERR_OK
)
11478 SendEquipError( msg
, pSrcItem
, NULL
);
11482 RemoveItem(srcbag
, srcslot
, true);
11483 BankItem( dest
, pSrcItem
, true);
11485 else if( IsEquipmentPos ( dst
) )
11488 uint8 msg
= CanEquipItem( dstslot
, dest
, pSrcItem
, false );
11489 if( msg
!= EQUIP_ERR_OK
)
11491 SendEquipError( msg
, pSrcItem
, NULL
);
11495 RemoveItem(srcbag
, srcslot
, true);
11496 EquipItem(dest
, pSrcItem
, true);
11497 AutoUnequipOffhandIfNeed();
11503 // attempt merge to / fill target item
11504 if(!pSrcItem
->IsBag() && !pDstItem
->IsBag())
11507 ItemPosCountVec sDest
;
11509 if( IsInventoryPos( dst
) )
11510 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
11511 else if( IsBankPos ( dst
) )
11512 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
11513 else if( IsEquipmentPos ( dst
) )
11514 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, false );
11518 // can be merge/fill
11519 if(msg
== EQUIP_ERR_OK
)
11521 if( pSrcItem
->GetCount() + pDstItem
->GetCount() <= pSrcItem
->GetProto()->GetMaxStackSize())
11523 RemoveItem(srcbag
, srcslot
, true);
11525 if( IsInventoryPos( dst
) )
11526 StoreItem( sDest
, pSrcItem
, true);
11527 else if( IsBankPos ( dst
) )
11528 BankItem( sDest
, pSrcItem
, true);
11529 else if( IsEquipmentPos ( dst
) )
11531 EquipItem( eDest
, pSrcItem
, true);
11532 AutoUnequipOffhandIfNeed();
11537 pSrcItem
->SetCount( pSrcItem
->GetCount() + pDstItem
->GetCount() - pSrcItem
->GetProto()->GetMaxStackSize());
11538 pDstItem
->SetCount( pSrcItem
->GetProto()->GetMaxStackSize());
11539 pSrcItem
->SetState(ITEM_CHANGED
, this);
11540 pDstItem
->SetState(ITEM_CHANGED
, this);
11543 pSrcItem
->SendCreateUpdateToPlayer( this );
11544 pDstItem
->SendCreateUpdateToPlayer( this );
11551 // impossible merge/fill, do real swap
11554 // check src->dest move possibility
11555 ItemPosCountVec sDest
;
11557 if( IsInventoryPos( dst
) )
11558 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
11559 else if( IsBankPos( dst
) )
11560 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
11561 else if( IsEquipmentPos( dst
) )
11563 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, true );
11564 if( msg
== EQUIP_ERR_OK
)
11565 msg
= CanUnequipItem( eDest
, true );
11568 if( msg
!= EQUIP_ERR_OK
)
11570 SendEquipError( msg
, pSrcItem
, pDstItem
);
11574 // check dest->src move possibility
11575 ItemPosCountVec sDest2
;
11577 if( IsInventoryPos( src
) )
11578 msg
= CanStoreItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11579 else if( IsBankPos( src
) )
11580 msg
= CanBankItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11581 else if( IsEquipmentPos( src
) )
11583 msg
= CanEquipItem( srcslot
, eDest2
, pDstItem
, true);
11584 if( msg
== EQUIP_ERR_OK
)
11585 msg
= CanUnequipItem( eDest2
, true);
11588 if( msg
!= EQUIP_ERR_OK
)
11590 SendEquipError( msg
, pDstItem
, pSrcItem
);
11594 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11595 if(pSrcItem
->IsBag() && pDstItem
->IsBag())
11597 Bag
* emptyBag
= NULL
;
11598 Bag
* fullBag
= NULL
;
11599 if(((Bag
*)pSrcItem
)->IsEmpty() && !IsBagPos(src
))
11601 emptyBag
= (Bag
*)pSrcItem
;
11602 fullBag
= (Bag
*)pDstItem
;
11604 else if(((Bag
*)pDstItem
)->IsEmpty() && !IsBagPos(dst
))
11606 emptyBag
= (Bag
*)pDstItem
;
11607 fullBag
= (Bag
*)pSrcItem
;
11610 // bag swap (with items exchange) case
11611 if(emptyBag
&& fullBag
)
11613 ItemPrototype
const* emotyProto
= emptyBag
->GetProto();
11617 for(uint32 i
=0; i
< fullBag
->GetBagSize(); ++i
)
11619 Item
*bagItem
= fullBag
->GetItemByPos(i
);
11623 ItemPrototype
const* bagItemProto
= bagItem
->GetProto();
11624 if (!bagItemProto
|| !ItemCanGoIntoBag(bagItemProto
, emotyProto
))
11626 // one from items not go to empty target bag
11627 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
11635 if (count
> emptyBag
->GetBagSize())
11637 // too small targeted bag
11638 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
, pSrcItem
, pDstItem
);
11643 count
= 0; // will pos in new bag
11644 for(uint32 i
= 0; i
< fullBag
->GetBagSize(); ++i
)
11646 Item
*bagItem
= fullBag
->GetItemByPos(i
);
11650 fullBag
->RemoveItem(i
, true);
11651 emptyBag
->StoreItem(count
, bagItem
, true);
11652 bagItem
->SetState(ITEM_CHANGED
, this);
11659 // now do moves, remove...
11660 RemoveItem(dstbag
, dstslot
, false);
11661 RemoveItem(srcbag
, srcslot
, false);
11664 if (IsInventoryPos(dst
))
11665 StoreItem(sDest
, pSrcItem
, true);
11666 else if (IsBankPos(dst
))
11667 BankItem(sDest
, pSrcItem
, true);
11668 else if (IsEquipmentPos(dst
))
11669 EquipItem(eDest
, pSrcItem
, true);
11672 if (IsInventoryPos(src
))
11673 StoreItem(sDest2
, pDstItem
, true);
11674 else if (IsBankPos(src
))
11675 BankItem(sDest2
, pDstItem
, true);
11676 else if (IsEquipmentPos(src
))
11677 EquipItem(eDest2
, pDstItem
, true);
11679 AutoUnequipOffhandIfNeed();
11682 void Player::AddItemToBuyBackSlot( Item
*pItem
)
11686 uint32 slot
= m_currentBuybackSlot
;
11687 // if current back slot non-empty search oldest or free
11690 uint32 oldest_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
);
11691 uint32 oldest_slot
= BUYBACK_SLOT_START
;
11693 for(uint32 i
= BUYBACK_SLOT_START
+1; i
< BUYBACK_SLOT_END
; ++i
)
11702 uint32 i_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ i
- BUYBACK_SLOT_START
);
11704 if (oldest_time
> i_time
)
11706 oldest_time
= i_time
;
11712 slot
= oldest_slot
;
11715 RemoveItemFromBuyBackSlot( slot
, true );
11716 sLog
.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem
->GetEntry(), slot
);
11718 m_items
[slot
] = pItem
;
11719 time_t base
= time(NULL
);
11720 uint32 etime
= uint32(base
- m_logintime
+ (30 * 3600));
11721 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11723 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ (eslot
* 2), pItem
->GetGUID() );
11724 if (ItemPrototype
const *pProto
= pItem
->GetProto())
11725 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, pProto
->SellPrice
* pItem
->GetCount() );
11727 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11728 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, (uint32
)etime
);
11730 // move to next (for non filled list is move most optimized choice)
11731 if (m_currentBuybackSlot
< BUYBACK_SLOT_END
- 1)
11732 ++m_currentBuybackSlot
;
11736 Item
* Player::GetItemFromBuyBackSlot( uint32 slot
)
11738 sLog
.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot
);
11739 if (slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11740 return m_items
[slot
];
11744 void Player::RemoveItemFromBuyBackSlot( uint32 slot
, bool del
)
11746 sLog
.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot
);
11747 if (slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11749 Item
*pItem
= m_items
[slot
];
11752 pItem
->RemoveFromWorld();
11753 if(del
) pItem
->SetState(ITEM_REMOVED
, this);
11756 m_items
[slot
] = NULL
;
11758 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11759 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ (eslot
* 2), 0 );
11760 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11761 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, 0 );
11763 // if current backslot is filled set to now free slot
11764 if (m_items
[m_currentBuybackSlot
])
11765 m_currentBuybackSlot
= slot
;
11769 void Player::SendEquipError( uint8 msg
, Item
* pItem
, Item
*pItem2
, uint32 itemid
/*= 0*/ )
11771 sLog
.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg
);
11772 WorldPacket
data(SMSG_INVENTORY_CHANGE_FAILURE
, 1+8+8+1);
11773 data
<< uint8(msg
);
11775 if (msg
!= EQUIP_ERR_OK
)
11777 data
<< uint64(pItem
? pItem
->GetGUID() : 0);
11778 data
<< uint64(pItem2
? pItem2
->GetGUID() : 0);
11779 data
<< uint8(0); // bag type subclass, used with EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM and EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG2
11783 case EQUIP_ERR_CANT_EQUIP_LEVEL_I
:
11784 case EQUIP_ERR_PURCHASE_LEVEL_TOO_LOW
:
11786 ItemPrototype
const* proto
= pItem
? pItem
->GetProto() : sObjectMgr
.GetItemPrototype(itemid
);
11787 data
<< uint32(proto
? proto
->RequiredLevel
: 0);
11790 case EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM
: // no idea about this one...
11797 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS
:
11798 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_SOCKETED_EXCEEDED_IS
:
11799 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS
:
11801 ItemPrototype
const* proto
= pItem
? pItem
->GetProto() : sObjectMgr
.GetItemPrototype(itemid
);
11802 data
<< uint32(proto
? proto
->ItemLimitCategory
: 0);
11809 GetSession()->SendPacket(&data
);
11812 void Player::SendBuyError( uint8 msg
, Creature
* pCreature
, uint32 item
, uint32 param
)
11814 sLog
.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11815 WorldPacket
data( SMSG_BUY_FAILED
, (8+4+4+1) );
11816 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11817 data
<< uint32(item
);
11819 data
<< uint32(param
);
11820 data
<< uint8(msg
);
11821 GetSession()->SendPacket(&data
);
11824 void Player::SendSellError( uint8 msg
, Creature
* pCreature
, uint64 guid
, uint32 param
)
11826 sLog
.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11827 WorldPacket
data( SMSG_SELL_ITEM
,(8+8+(param
?4:0)+1)); // last check 2.0.10
11828 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11829 data
<< uint64(guid
);
11831 data
<< uint32(param
);
11832 data
<< uint8(msg
);
11833 GetSession()->SendPacket(&data
);
11836 void Player::ClearTrade()
11839 acceptTrade
= false;
11840 for(int i
= 0; i
< TRADE_SLOT_COUNT
; ++i
)
11841 tradeItems
[i
] = NULL_SLOT
;
11844 void Player::TradeCancel(bool sendback
)
11848 // send yellow "Trade canceled" message to both traders
11852 ws
->SendCancelTrade();
11853 ws
= pTrader
->GetSession();
11854 if (!ws
->PlayerLogout())
11855 ws
->SendCancelTrade();
11859 pTrader
->ClearTrade();
11860 // prevent loss of reference
11861 pTrader
->pTrader
= NULL
;
11866 void Player::UpdateItemDuration(uint32 time
, bool realtimeonly
)
11868 if (m_itemDuration
.empty())
11871 sLog
.outDebug("Player::UpdateItemDuration(%u,%u)", time
, realtimeonly
);
11873 for(ItemDurationList::const_iterator itr
= m_itemDuration
.begin(); itr
!= m_itemDuration
.end(); )
11876 ++itr
; // current element can be erased in UpdateDuration
11878 if ((realtimeonly
&& (item
->GetProto()->ExtraFlags
& ITEM_EXTRA_REAL_TIME_DURATION
)) || !realtimeonly
)
11879 item
->UpdateDuration(this,time
);
11883 void Player::UpdateEnchantTime(uint32 time
)
11885 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11889 if (!itr
->item
->GetEnchantmentId(itr
->slot
))
11891 next
= m_enchantDuration
.erase(itr
);
11893 else if (itr
->leftduration
<= time
)
11895 ApplyEnchantment(itr
->item
, itr
->slot
, false, false);
11896 itr
->item
->ClearEnchantment(itr
->slot
);
11897 next
= m_enchantDuration
.erase(itr
);
11899 else if (itr
->leftduration
> time
)
11901 itr
->leftduration
-= time
;
11907 void Player::AddEnchantmentDurations(Item
*item
)
11909 for(int x
= 0; x
< MAX_ENCHANTMENT_SLOT
; ++x
)
11911 if (!item
->GetEnchantmentId(EnchantmentSlot(x
)))
11914 uint32 duration
= item
->GetEnchantmentDuration(EnchantmentSlot(x
));
11916 AddEnchantmentDuration(item
, EnchantmentSlot(x
), duration
);
11920 void Player::RemoveEnchantmentDurations(Item
*item
)
11922 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(); itr
!= m_enchantDuration
.end();)
11924 if (itr
->item
== item
)
11926 // save duration in item
11927 item
->SetEnchantmentDuration(EnchantmentSlot(itr
->slot
), itr
->leftduration
);
11928 itr
= m_enchantDuration
.erase(itr
);
11935 void Player::RemoveAllEnchantments(EnchantmentSlot slot
)
11937 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11938 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(), next
; itr
!= m_enchantDuration
.end(); itr
= next
)
11941 if (itr
->slot
== slot
)
11943 if (itr
->item
&& itr
->item
->GetEnchantmentId(slot
))
11945 // remove from stats
11946 ApplyEnchantment(itr
->item
, slot
, false, false);
11948 itr
->item
->ClearEnchantment(slot
);
11950 // remove from update list
11951 next
= m_enchantDuration
.erase(itr
);
11957 // remove enchants from inventory items
11958 // NOTE: no need to remove these from stats, since these aren't equipped
11960 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
11961 if (Item
* pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
11962 if (pItem
->GetEnchantmentId(slot
))
11963 pItem
->ClearEnchantment(slot
);
11965 // in inventory bags
11966 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
11967 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11968 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
11969 if (Item
* pItem
= pBag
->GetItemByPos(j
))
11970 if (pItem
->GetEnchantmentId(slot
))
11971 pItem
->ClearEnchantment(slot
);
11974 // duration == 0 will remove item enchant
11975 void Player::AddEnchantmentDuration(Item
*item
,EnchantmentSlot slot
,uint32 duration
)
11980 if (slot
>= MAX_ENCHANTMENT_SLOT
)
11983 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(); itr
!= m_enchantDuration
.end(); ++itr
)
11985 if (itr
->item
== item
&& itr
->slot
== slot
)
11987 itr
->item
->SetEnchantmentDuration(itr
->slot
, itr
->leftduration
);
11988 m_enchantDuration
.erase(itr
);
11992 if (item
&& duration
> 0 )
11994 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item
->GetGUID(), slot
, uint32(duration
/1000));
11995 m_enchantDuration
.push_back(EnchantDuration(item
, slot
, duration
));
11999 void Player::ApplyEnchantment(Item
*item
,bool apply
)
12001 for(uint32 slot
= 0; slot
< MAX_ENCHANTMENT_SLOT
; ++slot
)
12002 ApplyEnchantment(item
, EnchantmentSlot(slot
), apply
);
12005 void Player::ApplyEnchantment(Item
*item
, EnchantmentSlot slot
, bool apply
, bool apply_dur
, bool ignore_condition
)
12010 if (!item
->IsEquipped())
12013 if (slot
>= MAX_ENCHANTMENT_SLOT
)
12016 uint32 enchant_id
= item
->GetEnchantmentId(slot
);
12020 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
12024 if (!ignore_condition
&& pEnchant
->EnchantmentCondition
&& !((Player
*)this)->EnchantmentFitsRequirements(pEnchant
->EnchantmentCondition
, -1))
12027 if (!item
->IsBroken())
12029 for (int s
= 0; s
< 3; ++s
)
12031 uint32 enchant_display_type
= pEnchant
->type
[s
];
12032 uint32 enchant_amount
= pEnchant
->amount
[s
];
12033 uint32 enchant_spell_id
= pEnchant
->spellid
[s
];
12035 switch(enchant_display_type
)
12037 case ITEM_ENCHANTMENT_TYPE_NONE
:
12039 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
:
12040 // processed in Player::CastItemCombatSpell
12042 case ITEM_ENCHANTMENT_TYPE_DAMAGE
:
12043 if (item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
12044 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12045 else if (item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
12046 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12047 else if (item
->GetSlot() == EQUIPMENT_SLOT_RANGED
)
12048 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12050 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL
:
12051 if (enchant_spell_id
)
12055 int32 basepoints
= 0;
12056 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
12057 if (item
->GetItemRandomPropertyId())
12059 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
12062 // Search enchant_amount
12063 for (int k
= 0; k
< 3; ++k
)
12065 if(item_rand
->enchant_id
[k
] == enchant_id
)
12067 basepoints
= int32((item_rand
->prefix
[k
] * item
->GetItemSuffixFactor()) / 10000 );
12073 // Cast custom spell vs all equal basepoints getted from enchant_amount
12075 CastCustomSpell(this, enchant_spell_id
, &basepoints
, &basepoints
, &basepoints
, true, item
);
12077 CastSpell(this, enchant_spell_id
, true, item
);
12080 RemoveAurasDueToItemSpell(item
, enchant_spell_id
);
12083 case ITEM_ENCHANTMENT_TYPE_RESISTANCE
:
12084 if (!enchant_amount
)
12086 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
12089 for (int k
= 0; k
< 3; ++k
)
12091 if(item_rand
->enchant_id
[k
] == enchant_id
)
12093 enchant_amount
= uint32((item_rand
->prefix
[k
] * item
->GetItemSuffixFactor()) / 10000 );
12100 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START
+ enchant_spell_id
), TOTAL_VALUE
, float(enchant_amount
), apply
);
12102 case ITEM_ENCHANTMENT_TYPE_STAT
:
12104 if (!enchant_amount
)
12106 ItemRandomSuffixEntry
const *item_rand_suffix
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
12107 if(item_rand_suffix
)
12109 for (int k
= 0; k
< 3; ++k
)
12111 if(item_rand_suffix
->enchant_id
[k
] == enchant_id
)
12113 enchant_amount
= uint32((item_rand_suffix
->prefix
[k
] * item
->GetItemSuffixFactor()) / 10000 );
12120 sLog
.outDebug("Adding %u to stat nb %u",enchant_amount
,enchant_spell_id
);
12121 switch (enchant_spell_id
)
12123 case ITEM_MOD_MANA
:
12124 sLog
.outDebug("+ %u MANA",enchant_amount
);
12125 HandleStatModifier(UNIT_MOD_MANA
, BASE_VALUE
, float(enchant_amount
), apply
);
12127 case ITEM_MOD_HEALTH
:
12128 sLog
.outDebug("+ %u HEALTH",enchant_amount
);
12129 HandleStatModifier(UNIT_MOD_HEALTH
, BASE_VALUE
, float(enchant_amount
), apply
);
12131 case ITEM_MOD_AGILITY
:
12132 sLog
.outDebug("+ %u AGILITY",enchant_amount
);
12133 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12134 ApplyStatBuffMod(STAT_AGILITY
, float(enchant_amount
), apply
);
12136 case ITEM_MOD_STRENGTH
:
12137 sLog
.outDebug("+ %u STRENGTH",enchant_amount
);
12138 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12139 ApplyStatBuffMod(STAT_STRENGTH
, float(enchant_amount
), apply
);
12141 case ITEM_MOD_INTELLECT
:
12142 sLog
.outDebug("+ %u INTELLECT",enchant_amount
);
12143 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12144 ApplyStatBuffMod(STAT_INTELLECT
, float(enchant_amount
), apply
);
12146 case ITEM_MOD_SPIRIT
:
12147 sLog
.outDebug("+ %u SPIRIT",enchant_amount
);
12148 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12149 ApplyStatBuffMod(STAT_SPIRIT
, float(enchant_amount
), apply
);
12151 case ITEM_MOD_STAMINA
:
12152 sLog
.outDebug("+ %u STAMINA",enchant_amount
);
12153 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12154 ApplyStatBuffMod(STAT_STAMINA
, float(enchant_amount
), apply
);
12156 case ITEM_MOD_DEFENSE_SKILL_RATING
:
12157 ((Player
*)this)->ApplyRatingMod(CR_DEFENSE_SKILL
, enchant_amount
, apply
);
12158 sLog
.outDebug("+ %u DEFENCE", enchant_amount
);
12160 case ITEM_MOD_DODGE_RATING
:
12161 ((Player
*)this)->ApplyRatingMod(CR_DODGE
, enchant_amount
, apply
);
12162 sLog
.outDebug("+ %u DODGE", enchant_amount
);
12164 case ITEM_MOD_PARRY_RATING
:
12165 ((Player
*)this)->ApplyRatingMod(CR_PARRY
, enchant_amount
, apply
);
12166 sLog
.outDebug("+ %u PARRY", enchant_amount
);
12168 case ITEM_MOD_BLOCK_RATING
:
12169 ((Player
*)this)->ApplyRatingMod(CR_BLOCK
, enchant_amount
, apply
);
12170 sLog
.outDebug("+ %u SHIELD_BLOCK", enchant_amount
);
12172 case ITEM_MOD_HIT_MELEE_RATING
:
12173 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
12174 sLog
.outDebug("+ %u MELEE_HIT", enchant_amount
);
12176 case ITEM_MOD_HIT_RANGED_RATING
:
12177 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
12178 sLog
.outDebug("+ %u RANGED_HIT", enchant_amount
);
12180 case ITEM_MOD_HIT_SPELL_RATING
:
12181 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
12182 sLog
.outDebug("+ %u SPELL_HIT", enchant_amount
);
12184 case ITEM_MOD_CRIT_MELEE_RATING
:
12185 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
12186 sLog
.outDebug("+ %u MELEE_CRIT", enchant_amount
);
12188 case ITEM_MOD_CRIT_RANGED_RATING
:
12189 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
12190 sLog
.outDebug("+ %u RANGED_CRIT", enchant_amount
);
12192 case ITEM_MOD_CRIT_SPELL_RATING
:
12193 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
12194 sLog
.outDebug("+ %u SPELL_CRIT", enchant_amount
);
12196 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
12198 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
12199 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12201 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
12202 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12204 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
12205 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12207 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
12208 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12210 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
12211 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12213 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
12214 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12216 // case ITEM_MOD_HASTE_MELEE_RATING:
12217 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12219 // case ITEM_MOD_HASTE_RANGED_RATING:
12220 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12222 case ITEM_MOD_HASTE_SPELL_RATING
:
12223 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
12225 case ITEM_MOD_HIT_RATING
:
12226 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
12227 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
12228 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
12229 sLog
.outDebug("+ %u HIT", enchant_amount
);
12231 case ITEM_MOD_CRIT_RATING
:
12232 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
12233 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
12234 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
12235 sLog
.outDebug("+ %u CRITICAL", enchant_amount
);
12237 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
12238 // case ITEM_MOD_HIT_TAKEN_RATING:
12239 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12240 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12241 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12243 // case ITEM_MOD_CRIT_TAKEN_RATING:
12244 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12245 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12246 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12248 case ITEM_MOD_RESILIENCE_RATING
:
12249 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, enchant_amount
, apply
);
12250 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, enchant_amount
, apply
);
12251 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, enchant_amount
, apply
);
12252 sLog
.outDebug("+ %u RESILIENCE", enchant_amount
);
12254 case ITEM_MOD_HASTE_RATING
:
12255 ((Player
*)this)->ApplyRatingMod(CR_HASTE_MELEE
, enchant_amount
, apply
);
12256 ((Player
*)this)->ApplyRatingMod(CR_HASTE_RANGED
, enchant_amount
, apply
);
12257 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
12258 sLog
.outDebug("+ %u HASTE", enchant_amount
);
12260 case ITEM_MOD_EXPERTISE_RATING
:
12261 ((Player
*)this)->ApplyRatingMod(CR_EXPERTISE
, enchant_amount
, apply
);
12262 sLog
.outDebug("+ %u EXPERTISE", enchant_amount
);
12264 case ITEM_MOD_ATTACK_POWER
:
12265 HandleStatModifier(UNIT_MOD_ATTACK_POWER
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12266 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12267 sLog
.outDebug("+ %u ATTACK_POWER", enchant_amount
);
12269 case ITEM_MOD_RANGED_ATTACK_POWER
:
12270 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12271 sLog
.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount
);
12273 case ITEM_MOD_MANA_REGENERATION
:
12274 ((Player
*)this)->ApplyManaRegenBonus(enchant_amount
, apply
);
12275 sLog
.outDebug("+ %u MANA_REGENERATION", enchant_amount
);
12277 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
12278 ((Player
*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION
, enchant_amount
, apply
);
12279 sLog
.outDebug("+ %u ARMOR PENETRATION", enchant_amount
);
12281 case ITEM_MOD_SPELL_POWER
:
12282 ((Player
*)this)->ApplySpellPowerBonus(enchant_amount
, apply
);
12283 sLog
.outDebug("+ %u SPELL_POWER", enchant_amount
);
12285 case ITEM_MOD_FERAL_ATTACK_POWER
:
12286 case ITEM_MOD_SPELL_HEALING_DONE
: // deprecated
12287 case ITEM_MOD_SPELL_DAMAGE_DONE
: // deprecated
12293 case ITEM_ENCHANTMENT_TYPE_TOTEM
: // Shaman Rockbiter Weapon
12295 if(getClass() == CLASS_SHAMAN
)
12297 float addValue
= 0.0f
;
12298 if(item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
12300 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/ 1000.0f
);
12301 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, addValue
, apply
);
12303 else if(item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
12305 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/ 1000.0f
);
12306 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, addValue
, apply
);
12311 case ITEM_ENCHANTMENT_TYPE_USE_SPELL
:
12312 // processed in Player::CastItemUseSpell
12314 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET
:
12318 sLog
.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id
, enchant_display_type
);
12320 } /*switch(enchant_display_type)*/
12324 // visualize enchantment at player and equipped items
12325 if(slot
== PERM_ENCHANTMENT_SLOT
)
12326 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT
+ (item
->GetSlot() * 2), 0, apply
? item
->GetEnchantmentId(slot
) : 0);
12328 if(slot
== TEMP_ENCHANTMENT_SLOT
)
12329 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT
+ (item
->GetSlot() * 2), 1, apply
? item
->GetEnchantmentId(slot
) : 0);
12337 uint32 duration
= item
->GetEnchantmentDuration(slot
);
12339 AddEnchantmentDuration(item
, slot
, duration
);
12343 // duration == 0 will remove EnchantDuration
12344 AddEnchantmentDuration(item
, slot
, 0);
12349 void Player::SendEnchantmentDurations()
12351 for(EnchantDurationList::const_iterator itr
= m_enchantDuration
.begin(); itr
!= m_enchantDuration
.end(); ++itr
)
12353 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr
->item
->GetGUID(), itr
->slot
, uint32(itr
->leftduration
) / 1000);
12357 void Player::SendItemDurations()
12359 for(ItemDurationList::const_iterator itr
= m_itemDuration
.begin(); itr
!= m_itemDuration
.end(); ++itr
)
12361 (*itr
)->SendTimeUpdate(this);
12365 void Player::SendNewItem(Item
*item
, uint32 count
, bool received
, bool created
, bool broadcast
)
12367 if(!item
) // prevent crash
12370 // last check 2.0.10
12371 WorldPacket
data( SMSG_ITEM_PUSH_RESULT
, (8+4+4+4+1+4+4+4+4+4) );
12372 data
<< uint64(GetGUID()); // player GUID
12373 data
<< uint32(received
); // 0=looted, 1=from npc
12374 data
<< uint32(created
); // 0=received, 1=created
12375 data
<< uint32(1); // always 0x01 (probably meant to be count of listed items)
12376 data
<< uint8(item
->GetBagSlot()); // bagslot
12377 // item slot, but when added to stack: 0xFFFFFFFF
12378 data
<< uint32((item
->GetCount() == count
) ? item
->GetSlot() : -1);
12379 data
<< uint32(item
->GetEntry()); // item id
12380 data
<< uint32(item
->GetItemSuffixFactor()); // SuffixFactor
12381 data
<< uint32(item
->GetItemRandomPropertyId()); // random item property id
12382 data
<< uint32(count
); // count of items
12383 data
<< uint32(GetItemCount(item
->GetEntry())); // count of items in inventory
12385 if (broadcast
&& GetGroup())
12386 GetGroup()->BroadcastPacket(&data
, true);
12388 GetSession()->SendPacket(&data
);
12391 /*********************************************************/
12392 /*** GOSSIP SYSTEM ***/
12393 /*********************************************************/
12395 void Player::PrepareGossipMenu(WorldObject
*pSource
, uint32 menuId
)
12397 PlayerMenu
* pMenu
= PlayerTalkClass
;
12398 pMenu
->ClearMenus();
12400 pMenu
->GetGossipMenu().SetMenuId(menuId
);
12402 GossipMenuItemsMapBounds pMenuItemBounds
= sObjectMgr
.GetGossipMenuItemsMapBounds(menuId
);
12404 // if default menuId and no menu options exist for this, use options from default options
12405 if (pMenuItemBounds
.first
== pMenuItemBounds
.second
&& menuId
== GetDefaultGossipMenuForSource(pSource
))
12406 pMenuItemBounds
= sObjectMgr
.GetGossipMenuItemsMapBounds(0);
12408 for(GossipMenuItemsMap::const_iterator itr
= pMenuItemBounds
.first
; itr
!= pMenuItemBounds
.second
; ++itr
)
12410 bool bCanTalk
= true;
12412 if (itr
->second
.cond_1
&& !sObjectMgr
.IsPlayerMeetToCondition(this, itr
->second
.cond_1
))
12415 if (itr
->second
.cond_2
&& !sObjectMgr
.IsPlayerMeetToCondition(this, itr
->second
.cond_2
))
12418 if (itr
->second
.cond_3
&& !sObjectMgr
.IsPlayerMeetToCondition(this, itr
->second
.cond_3
))
12421 if (pSource
->GetTypeId() == TYPEID_UNIT
)
12423 Creature
*pCreature
= (Creature
*)pSource
;
12425 uint32 npcflags
= pCreature
->GetUInt32Value(UNIT_NPC_FLAGS
);
12427 if (!(itr
->second
.npc_option_npcflag
& npcflags
))
12430 switch(itr
->second
.option_id
)
12432 case GOSSIP_OPTION_QUESTGIVER
:
12433 PrepareQuestMenu(pSource
->GetGUID());
12436 case GOSSIP_OPTION_ARMORER
:
12437 bCanTalk
= false; // added in special mode
12439 case GOSSIP_OPTION_SPIRITHEALER
:
12443 case GOSSIP_OPTION_VENDOR
:
12445 VendorItemData
const* vItems
= pCreature
->GetVendorItems();
12446 if (!vItems
|| vItems
->Empty())
12448 sLog
.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.", pCreature
->GetGUIDLow(), pCreature
->GetEntry());
12453 case GOSSIP_OPTION_TRAINER
:
12454 if (!pCreature
->isCanTrainingOf(this, false))
12457 case GOSSIP_OPTION_UNLEARNTALENTS
:
12458 if (!pCreature
->isCanTrainingAndResetTalentsOf(this))
12461 case GOSSIP_OPTION_UNLEARNPETSKILLS
:
12462 if (!GetPet() || GetPet()->getPetType() != HUNTER_PET
|| GetPet()->m_spells
.size() <= 1 || pCreature
->GetCreatureInfo()->trainer_type
!= TRAINER_TYPE_PETS
|| pCreature
->GetCreatureInfo()->trainer_class
!= CLASS_HUNTER
)
12465 case GOSSIP_OPTION_TAXIVENDOR
:
12466 if (GetSession()->SendLearnNewTaxiNode(pCreature
))
12469 case GOSSIP_OPTION_BATTLEFIELD
:
12470 if (!pCreature
->isCanInteractWithBattleMaster(this, false))
12473 case GOSSIP_OPTION_STABLEPET
:
12474 if (getClass() != CLASS_HUNTER
)
12477 case GOSSIP_OPTION_GOSSIP
:
12478 case GOSSIP_OPTION_SPIRITGUIDE
:
12479 case GOSSIP_OPTION_INNKEEPER
:
12480 case GOSSIP_OPTION_BANKER
:
12481 case GOSSIP_OPTION_PETITIONER
:
12482 case GOSSIP_OPTION_TABARDDESIGNER
:
12483 case GOSSIP_OPTION_AUCTIONEER
:
12484 break; // no checks
12486 sLog
.outErrorDb("Creature entry %u have unknown gossip option %u for menu %u", pCreature
->GetEntry(), itr
->second
.option_id
, itr
->second
.menu_id
);
12491 else if (pSource
->GetTypeId() == TYPEID_GAMEOBJECT
)
12493 GameObject
*pGo
= (GameObject
*)pSource
;
12495 switch(itr
->second
.option_id
)
12497 case GOSSIP_OPTION_QUESTGIVER
:
12498 if (pGo
->GetGoType() == GAMEOBJECT_TYPE_QUESTGIVER
)
12499 PrepareQuestMenu(pSource
->GetGUID());
12502 case GOSSIP_OPTION_GOSSIP
:
12503 if (pGo
->GetGoType() != GAMEOBJECT_TYPE_QUESTGIVER
&& pGo
->GetGoType() != GAMEOBJECT_TYPE_GOOBER
)
12514 std::string strOptionText
= itr
->second
.option_text
;
12515 std::string strBoxText
= itr
->second
.box_text
;
12517 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
12521 uint32 idxEntry
= MAKE_PAIR32(menuId
, itr
->second
.id
);
12523 if (GossipMenuItemsLocale
const *no
= sObjectMgr
.GetGossipMenuItemsLocale(idxEntry
))
12525 if (no
->OptionText
.size() > (size_t)loc_idx
&& !no
->OptionText
[loc_idx
].empty())
12526 strOptionText
= no
->OptionText
[loc_idx
];
12528 if (no
->BoxText
.size() > (size_t)loc_idx
&& !no
->BoxText
[loc_idx
].empty())
12529 strBoxText
= no
->BoxText
[loc_idx
];
12533 pMenu
->GetGossipMenu().AddMenuItem(itr
->second
.option_icon
, strOptionText
, 0, itr
->second
.option_id
, strBoxText
, itr
->second
.box_money
, itr
->second
.box_coded
);
12534 pMenu
->GetGossipMenu().AddGossipMenuItemData(itr
->second
.action_menu_id
, itr
->second
.action_poi_id
, itr
->second
.action_script_id
);
12538 // some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
12539 /*if (pMenu->Empty())
12541 if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
12543 // output error message if need
12544 pCreature->isCanTrainingOf(this, true);
12547 if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
12549 // output error message if need
12550 pCreature->isCanInteractWithBattleMaster(this, true);
12555 void Player::SendPreparedGossip(WorldObject
*pSource
)
12560 if (pSource
->GetTypeId() == TYPEID_UNIT
)
12562 // in case no gossip flag and quest menu not empty, open quest menu (client expect gossip menu with this flag)
12563 if (!((Creature
*)pSource
)->HasFlag(UNIT_NPC_FLAGS
,UNIT_NPC_FLAG_GOSSIP
) && !PlayerTalkClass
->GetQuestMenu().Empty())
12565 SendPreparedQuest(pSource
->GetGUID());
12569 else if (pSource
->GetTypeId() == TYPEID_GAMEOBJECT
)
12571 // probably need to find a better way here
12572 if (!PlayerTalkClass
->GetGossipMenu().GetMenuId() && !PlayerTalkClass
->GetQuestMenu().Empty())
12574 SendPreparedQuest(pSource
->GetGUID());
12579 // in case non empty gossip menu (that not included quests list size) show it
12580 // (quest entries from quest menu will be included in list)
12582 uint32 textId
= GetGossipTextId(pSource
);
12584 if (uint32 menuId
= PlayerTalkClass
->GetGossipMenu().GetMenuId())
12585 textId
= GetGossipTextId(menuId
);
12587 PlayerTalkClass
->SendGossipMenu(textId
, pSource
->GetGUID());
12590 void Player::OnGossipSelect(WorldObject
* pSource
, uint32 gossipListId
, uint32 menuId
)
12592 GossipMenu
& gossipmenu
= PlayerTalkClass
->GetGossipMenu();
12594 if (gossipListId
>= gossipmenu
.MenuItemCount())
12597 // if not same, then something funky is going on
12598 if (menuId
!= gossipmenu
.GetMenuId())
12601 uint32 gossipOptionId
= gossipmenu
.GetItem(gossipListId
).m_gOptionId
;
12602 uint64 guid
= pSource
->GetGUID();
12604 if (pSource
->GetTypeId() == TYPEID_GAMEOBJECT
)
12606 if (gossipOptionId
> GOSSIP_OPTION_QUESTGIVER
)
12608 sLog
.outError("Player guid %u request invalid gossip option for GameObject entry %u", GetGUIDLow(), pSource
->GetEntry());
12613 GossipMenuItemData pMenuData
= gossipmenu
.GetItemData(gossipListId
);
12615 switch(gossipOptionId
)
12617 case GOSSIP_OPTION_GOSSIP
:
12619 if (pMenuData
.m_gAction_poi
)
12620 PlayerTalkClass
->SendPointOfInterest(pMenuData
.m_gAction_poi
);
12622 if (pMenuData
.m_gAction_menu
)
12624 PrepareGossipMenu(pSource
, pMenuData
.m_gAction_menu
);
12625 SendPreparedGossip(pSource
);
12628 if (pMenuData
.m_gAction_script
)
12630 if (pSource
->GetTypeId() == TYPEID_GAMEOBJECT
)
12631 GetMap()->ScriptsStart(sGossipScripts
, pMenuData
.m_gAction_script
, this, pSource
);
12632 else if (pSource
->GetTypeId() == TYPEID_UNIT
)
12633 GetMap()->ScriptsStart(sGossipScripts
, pMenuData
.m_gAction_script
, pSource
, this);
12638 case GOSSIP_OPTION_SPIRITHEALER
:
12640 ((Creature
*)pSource
)->CastSpell(((Creature
*)pSource
),17251,true,NULL
,NULL
,GetGUID());
12642 case GOSSIP_OPTION_QUESTGIVER
:
12643 PrepareQuestMenu(guid
);
12644 SendPreparedQuest(guid
);
12646 case GOSSIP_OPTION_VENDOR
:
12647 case GOSSIP_OPTION_ARMORER
:
12648 GetSession()->SendListInventory(guid
);
12650 case GOSSIP_OPTION_STABLEPET
:
12651 GetSession()->SendStablePet(guid
);
12653 case GOSSIP_OPTION_TRAINER
:
12654 GetSession()->SendTrainerList(guid
);
12656 case GOSSIP_OPTION_UNLEARNTALENTS
:
12657 PlayerTalkClass
->CloseGossip();
12658 SendTalentWipeConfirm(guid
);
12660 case GOSSIP_OPTION_UNLEARNPETSKILLS
:
12661 PlayerTalkClass
->CloseGossip();
12662 SendPetSkillWipeConfirm();
12664 case GOSSIP_OPTION_TAXIVENDOR
:
12665 GetSession()->SendTaxiMenu(((Creature
*)pSource
));
12667 case GOSSIP_OPTION_INNKEEPER
:
12668 PlayerTalkClass
->CloseGossip();
12669 SetBindPoint(guid
);
12671 case GOSSIP_OPTION_BANKER
:
12672 GetSession()->SendShowBank(guid
);
12674 case GOSSIP_OPTION_PETITIONER
:
12675 PlayerTalkClass
->CloseGossip();
12676 GetSession()->SendPetitionShowList(guid
);
12678 case GOSSIP_OPTION_TABARDDESIGNER
:
12679 PlayerTalkClass
->CloseGossip();
12680 GetSession()->SendTabardVendorActivate(guid
);
12682 case GOSSIP_OPTION_AUCTIONEER
:
12683 GetSession()->SendAuctionHello(guid
, ((Creature
*)pSource
));
12685 case GOSSIP_OPTION_SPIRITGUIDE
:
12686 PrepareGossipMenu(pSource
);
12687 SendPreparedGossip(pSource
);
12689 case GOSSIP_OPTION_BATTLEFIELD
:
12691 BattleGroundTypeId bgTypeId
= sBattleGroundMgr
.GetBattleMasterBG(pSource
->GetEntry());
12693 if (bgTypeId
== BATTLEGROUND_TYPE_NONE
)
12695 sLog
.outError("a user (guid %u) requested battlegroundlist from a npc who is no battlemaster", GetGUIDLow());
12699 GetSession()->SendBattlegGroundList(guid
, bgTypeId
);
12705 uint32
Player::GetGossipTextId(WorldObject
*pSource
)
12707 if (!pSource
|| pSource
->GetTypeId() != TYPEID_UNIT
|| !((Creature
*)pSource
)->GetDBTableGUIDLow())
12708 return DEFAULT_GOSSIP_MESSAGE
;
12710 if (uint32 pos
= sObjectMgr
.GetNpcGossip(((Creature
*)pSource
)->GetDBTableGUIDLow()))
12713 return DEFAULT_GOSSIP_MESSAGE
;
12716 uint32
Player::GetGossipTextId(uint32 menuId
)
12718 uint32 textId
= DEFAULT_GOSSIP_MESSAGE
;
12723 GossipMenusMapBounds pMenuBounds
= sObjectMgr
.GetGossipMenusMapBounds(menuId
);
12725 for(GossipMenusMap::const_iterator itr
= pMenuBounds
.first
; itr
!= pMenuBounds
.second
; ++itr
)
12727 if (sObjectMgr
.IsPlayerMeetToCondition(this, itr
->second
.cond_1
) && sObjectMgr
.IsPlayerMeetToCondition(this, itr
->second
.cond_2
))
12728 textId
= itr
->second
.text_id
;
12734 uint32
Player::GetDefaultGossipMenuForSource(WorldObject
*pSource
)
12736 if (pSource
->GetTypeId() == TYPEID_UNIT
)
12737 return ((Creature
*)pSource
)->GetCreatureInfo()->GossipMenuId
;
12738 else if (pSource
->GetTypeId() == TYPEID_GAMEOBJECT
)
12739 return((GameObject
*)pSource
)->GetGOInfo()->GetGossipMenuId();
12744 /*********************************************************/
12745 /*** QUEST SYSTEM ***/
12746 /*********************************************************/
12748 void Player::PrepareQuestMenu( uint64 guid
)
12751 QuestRelations
* pObjectQR
;
12752 QuestRelations
* pObjectQIR
;
12754 // pets also can have quests
12755 if (Creature
*pCreature
= GetMap()->GetCreatureOrPetOrVehicle(guid
))
12757 pObject
= (Object
*)pCreature
;
12758 pObjectQR
= &sObjectMgr
.mCreatureQuestRelations
;
12759 pObjectQIR
= &sObjectMgr
.mCreatureQuestInvolvedRelations
;
12763 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12764 //only for quests which cast teleport spells on player
12765 Map
* _map
= IsInWorld() ? GetMap() : sMapMgr
.FindMap(GetMapId(), GetInstanceId());
12767 GameObject
*pGameObject
= _map
->GetGameObject(guid
);
12770 pObject
= (Object
*)pGameObject
;
12771 pObjectQR
= &sObjectMgr
.mGOQuestRelations
;
12772 pObjectQIR
= &sObjectMgr
.mGOQuestInvolvedRelations
;
12778 QuestMenu
&qm
= PlayerTalkClass
->GetQuestMenu();
12781 for(QuestRelations::const_iterator i
= pObjectQIR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQIR
->upper_bound(pObject
->GetEntry()); ++i
)
12783 uint32 quest_id
= i
->second
;
12784 QuestStatus status
= GetQuestStatus( quest_id
);
12785 if ( status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus( quest_id
) )
12786 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_UNK2
);
12787 else if ( status
== QUEST_STATUS_INCOMPLETE
)
12788 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_UNK2
);
12789 else if (status
== QUEST_STATUS_AVAILABLE
)
12790 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_CHAT
);
12793 for(QuestRelations::const_iterator i
= pObjectQR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++i
)
12795 uint32 quest_id
= i
->second
;
12796 Quest
const* pQuest
= sObjectMgr
.GetQuestTemplate(quest_id
);
12797 if(!pQuest
) continue;
12799 QuestStatus status
= GetQuestStatus( quest_id
);
12801 if (pQuest
->IsAutoComplete() && CanTakeQuest(pQuest
, false))
12802 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_UNK2
);
12803 else if ( status
== QUEST_STATUS_NONE
&& CanTakeQuest( pQuest
, false ) )
12804 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_CHAT
);
12808 void Player::SendPreparedQuest(uint64 guid
)
12810 QuestMenu
& questMenu
= PlayerTalkClass
->GetQuestMenu();
12812 if (questMenu
.Empty())
12815 QuestMenuItem
const& qmi0
= questMenu
.GetItem(0);
12817 uint32 status
= qmi0
.m_qIcon
;
12819 // single element case
12820 if (questMenu
.MenuItemCount() == 1)
12822 // Auto open -- maybe also should verify there is no greeting
12823 uint32 quest_id
= qmi0
.m_qId
;
12824 Quest
const* pQuest
= sObjectMgr
.GetQuestTemplate(quest_id
);
12828 if (status
== DIALOG_STATUS_UNK2
&& !GetQuestRewardStatus(quest_id
))
12829 PlayerTalkClass
->SendQuestGiverRequestItems(pQuest
, guid
, CanRewardQuest(pQuest
, false), true);
12830 else if (status
== DIALOG_STATUS_UNK2
)
12831 PlayerTalkClass
->SendQuestGiverRequestItems(pQuest
, guid
, CanRewardQuest(pQuest
, false), true);
12832 // Send completable on repeatable and autoCompletable quest if player don't have quest
12833 // TODO: verify if check for !pQuest->IsDaily() is really correct (possibly not)
12834 else if (pQuest
->IsAutoComplete() && pQuest
->IsRepeatable() && !pQuest
->IsDaily())
12835 PlayerTalkClass
->SendQuestGiverRequestItems(pQuest
, guid
, CanCompleteRepeatableQuest(pQuest
), true);
12837 PlayerTalkClass
->SendQuestGiverQuestDetails(pQuest
, guid
, true);
12840 // multiply entries
12846 std::string title
= "";
12848 // need pet case for some quests
12849 if (Creature
*pCreature
= GetMap()->GetCreatureOrPetOrVehicle(guid
))
12851 uint32 textid
= GetGossipTextId(pCreature
);
12853 GossipText
const* gossiptext
= sObjectMgr
.GetGossipText(textid
);
12856 qe
._Delay
= 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12857 qe
._Emote
= 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12862 qe
= gossiptext
->Options
[0].Emotes
[0];
12864 if(!gossiptext
->Options
[0].Text_0
.empty())
12866 title
= gossiptext
->Options
[0].Text_0
;
12868 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
12871 NpcTextLocale
const *nl
= sObjectMgr
.GetNpcTextLocale(textid
);
12874 if ((int32
)nl
->Text_0
[0].size() > loc_idx
&& !nl
->Text_0
[0][loc_idx
].empty())
12875 title
= nl
->Text_0
[0][loc_idx
];
12881 title
= gossiptext
->Options
[0].Text_1
;
12883 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
12886 NpcTextLocale
const *nl
= sObjectMgr
.GetNpcTextLocale(textid
);
12889 if ((int32
)nl
->Text_1
[0].size() > loc_idx
&& !nl
->Text_1
[0][loc_idx
].empty())
12890 title
= nl
->Text_1
[0][loc_idx
];
12896 PlayerTalkClass
->SendQuestGiverQuestList(qe
, title
, guid
);
12900 bool Player::IsActiveQuest( uint32 quest_id
) const
12902 QuestStatusMap::const_iterator itr
= mQuestStatus
.find(quest_id
);
12904 return itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
;
12907 Quest
const * Player::GetNextQuest( uint64 guid
, Quest
const *pQuest
)
12910 QuestRelations
* pObjectQR
;
12911 QuestRelations
* pObjectQIR
;
12913 if (Creature
*pCreature
= GetMap()->GetCreatureOrPetOrVehicle(guid
))
12915 pObject
= (Object
*)pCreature
;
12916 pObjectQR
= &sObjectMgr
.mCreatureQuestRelations
;
12917 pObjectQIR
= &sObjectMgr
.mCreatureQuestInvolvedRelations
;
12921 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12922 //only for quests which cast teleport spells on player
12923 Map
* _map
= IsInWorld() ? GetMap() : sMapMgr
.FindMap(GetMapId(), GetInstanceId());
12925 GameObject
*pGameObject
= _map
->GetGameObject(guid
);
12928 pObject
= (Object
*)pGameObject
;
12929 pObjectQR
= &sObjectMgr
.mGOQuestRelations
;
12930 pObjectQIR
= &sObjectMgr
.mGOQuestInvolvedRelations
;
12936 uint32 nextQuestID
= pQuest
->GetNextQuestInChain();
12937 for(QuestRelations::const_iterator itr
= pObjectQR
->lower_bound(pObject
->GetEntry()); itr
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++itr
)
12939 if (itr
->second
== nextQuestID
)
12940 return sObjectMgr
.GetQuestTemplate(nextQuestID
);
12946 bool Player::CanSeeStartQuest( Quest
const *pQuest
)
12948 if( SatisfyQuestRace( pQuest
, false ) && SatisfyQuestSkillOrClass( pQuest
, false ) &&
12949 SatisfyQuestExclusiveGroup( pQuest
, false ) && SatisfyQuestReputation( pQuest
, false ) &&
12950 SatisfyQuestPreviousQuest( pQuest
, false ) && SatisfyQuestNextChain( pQuest
, false ) &&
12951 SatisfyQuestPrevChain( pQuest
, false ) && SatisfyQuestDay( pQuest
, false ) )
12953 return getLevel() + sWorld
.getConfig(CONFIG_UINT32_QUEST_HIGH_LEVEL_HIDE_DIFF
) >= pQuest
->GetMinLevel();
12959 bool Player::CanTakeQuest( Quest
const *pQuest
, bool msg
)
12961 return SatisfyQuestStatus( pQuest
, msg
) && SatisfyQuestExclusiveGroup( pQuest
, msg
)
12962 && SatisfyQuestRace( pQuest
, msg
) && SatisfyQuestLevel( pQuest
, msg
)
12963 && SatisfyQuestSkillOrClass( pQuest
, msg
) && SatisfyQuestReputation( pQuest
, msg
)
12964 && SatisfyQuestPreviousQuest( pQuest
, msg
) && SatisfyQuestTimed( pQuest
, msg
)
12965 && SatisfyQuestNextChain( pQuest
, msg
) && SatisfyQuestPrevChain( pQuest
, msg
)
12966 && SatisfyQuestDay( pQuest
, msg
);
12969 bool Player::CanAddQuest( Quest
const *pQuest
, bool msg
)
12971 if( !SatisfyQuestLog( msg
) )
12974 uint32 srcitem
= pQuest
->GetSrcItemId();
12977 uint32 count
= pQuest
->GetSrcItemCount();
12978 ItemPosCountVec dest
;
12979 uint8 msg2
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
12981 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12982 if( msg2
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
12984 else if( msg2
!= EQUIP_ERR_OK
)
12986 SendEquipError(msg2
, NULL
, NULL
, srcitem
);
12993 bool Player::CanCompleteQuest( uint32 quest_id
)
12997 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12998 if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
12999 return false; // not allow re-complete quest
13001 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(quest_id
);
13006 // auto complete quest
13007 if (qInfo
->IsAutoComplete() && CanTakeQuest(qInfo
, false))
13010 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13013 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13015 for(int i
= 0; i
< QUEST_ITEM_OBJECTIVES_COUNT
; ++i
)
13017 if( qInfo
->ReqItemCount
[i
] != 0 && q_status
.m_itemcount
[i
] < qInfo
->ReqItemCount
[i
] )
13022 if ( qInfo
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
13024 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
13026 if( qInfo
->ReqCreatureOrGOId
[i
] == 0 )
13029 if( qInfo
->ReqCreatureOrGOCount
[i
] != 0 && q_status
.m_creatureOrGOcount
[i
] < qInfo
->ReqCreatureOrGOCount
[i
] )
13034 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT
) && !q_status
.m_explored
)
13037 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && q_status
.m_timer
== 0 )
13040 if ( qInfo
->GetRewOrReqMoney() < 0 )
13042 if ( GetMoney() < uint32(-qInfo
->GetRewOrReqMoney()) )
13046 uint32 repFacId
= qInfo
->GetRepObjectiveFaction();
13047 if ( repFacId
&& GetReputationMgr().GetReputation(repFacId
) < qInfo
->GetRepObjectiveValue() )
13056 bool Player::CanCompleteRepeatableQuest( Quest
const *pQuest
)
13058 // Solve problem that player don't have the quest and try complete it.
13059 // if repeatable she must be able to complete event if player don't have it.
13060 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
13061 if( !CanTakeQuest(pQuest
, false) )
13064 if (pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13065 for(int i
= 0; i
< QUEST_ITEM_OBJECTIVES_COUNT
; ++i
)
13066 if( pQuest
->ReqItemId
[i
] && pQuest
->ReqItemCount
[i
] && !HasItemCount(pQuest
->ReqItemId
[i
], pQuest
->ReqItemCount
[i
]) )
13069 if( !CanRewardQuest(pQuest
, false) )
13075 bool Player::CanRewardQuest( Quest
const *pQuest
, bool msg
)
13077 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
13078 if(!pQuest
->IsAutoComplete() && GetQuestStatus(pQuest
->GetQuestId()) != QUEST_STATUS_COMPLETE
)
13081 // daily quest can't be rewarded (25 daily quest already completed)
13082 if(!SatisfyQuestDay(pQuest
,true))
13085 // rewarded and not repeatable quest (only cheating case, then ignore without message)
13086 if(GetQuestRewardStatus(pQuest
->GetQuestId()))
13089 // prevent receive reward with quest items in bank
13090 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13092 for(int i
= 0; i
< QUEST_ITEM_OBJECTIVES_COUNT
; ++i
)
13094 if( pQuest
->ReqItemCount
[i
] != 0 &&
13095 GetItemCount(pQuest
->ReqItemId
[i
]) < pQuest
->ReqItemCount
[i
] )
13098 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, NULL
, NULL
, pQuest
->ReqItemId
[i
]);
13104 // prevent receive reward with low money and GetRewOrReqMoney() < 0
13105 if(pQuest
->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest
->GetRewOrReqMoney()) )
13111 bool Player::CanRewardQuest( Quest
const *pQuest
, uint32 reward
, bool msg
)
13113 // prevent receive reward with quest items in bank or for not completed quest
13114 if(!CanRewardQuest(pQuest
,msg
))
13117 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
13119 if( pQuest
->RewChoiceItemId
[reward
] )
13121 ItemPosCountVec dest
;
13122 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] );
13123 if( res
!= EQUIP_ERR_OK
)
13125 SendEquipError( res
, NULL
, NULL
, pQuest
->RewChoiceItemId
[reward
] );
13131 if ( pQuest
->GetRewItemsCount() > 0 )
13133 for (uint32 i
= 0; i
< pQuest
->GetRewItemsCount(); ++i
)
13135 if( pQuest
->RewItemId
[i
] )
13137 ItemPosCountVec dest
;
13138 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] );
13139 if( res
!= EQUIP_ERR_OK
)
13141 SendEquipError( res
, NULL
, NULL
);
13151 void Player::SendPetTameFailure(PetTameFailureReason reason
)
13153 WorldPacket
data(SMSG_PET_TAME_FAILURE
, 1);
13154 data
<< uint8(reason
);
13155 GetSession()->SendPacket(&data
);
13158 void Player::AddQuest( Quest
const *pQuest
, Object
*questGiver
)
13160 uint16 log_slot
= FindQuestSlot( 0 );
13161 ASSERT(log_slot
< MAX_QUEST_LOG_SIZE
);
13163 uint32 quest_id
= pQuest
->GetQuestId();
13165 // if not exist then created with set uState==NEW and rewarded=false
13166 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
13168 // check for repeatable quests status reset
13169 questStatusData
.m_status
= QUEST_STATUS_INCOMPLETE
;
13170 questStatusData
.m_explored
= false;
13172 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13174 for(int i
= 0; i
< QUEST_ITEM_OBJECTIVES_COUNT
; ++i
)
13175 questStatusData
.m_itemcount
[i
] = 0;
13178 if ( pQuest
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
13180 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
13181 questStatusData
.m_creatureOrGOcount
[i
] = 0;
13184 GiveQuestSourceItem( pQuest
);
13185 AdjustQuestReqItemCount( pQuest
, questStatusData
);
13187 if( pQuest
->GetRepObjectiveFaction() )
13188 if(FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(pQuest
->GetRepObjectiveFaction()))
13189 GetReputationMgr().SetVisible(factionEntry
);
13192 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
13194 uint32 limittime
= pQuest
->GetLimitTime();
13196 // shared timed quest
13197 if(questGiver
&& questGiver
->GetTypeId()==TYPEID_PLAYER
)
13198 limittime
= ((Player
*)questGiver
)->getQuestStatusMap()[quest_id
].m_timer
/ IN_MILLISECONDS
;
13200 AddTimedQuest( quest_id
);
13201 questStatusData
.m_timer
= limittime
* IN_MILLISECONDS
;
13202 qtime
= static_cast<uint32
>(time(NULL
)) + limittime
;
13205 questStatusData
.m_timer
= 0;
13207 SetQuestSlot(log_slot
, quest_id
, qtime
);
13209 if (questStatusData
.uState
!= QUEST_NEW
)
13210 questStatusData
.uState
= QUEST_CHANGED
;
13212 //starting initial quest script
13213 if(questGiver
&& pQuest
->GetQuestStartScript()!=0)
13214 GetMap()->ScriptsStart(sQuestStartScripts
, pQuest
->GetQuestStartScript(), questGiver
, this);
13216 // Some spells applied at quest activation
13217 SpellAreaForQuestMapBounds saBounds
= sSpellMgr
.GetSpellAreaForQuestMapBounds(quest_id
,true);
13218 if(saBounds
.first
!= saBounds
.second
)
13221 GetZoneAndAreaId(zone
,area
);
13223 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
13224 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,zone
,area
))
13225 if (!HasAura(itr
->second
->spellId
, EFFECT_INDEX_0
) )
13226 CastSpell(this,itr
->second
->spellId
,true);
13229 UpdateForQuestWorldObjects();
13232 void Player::CompleteQuest( uint32 quest_id
)
13236 SetQuestStatus( quest_id
, QUEST_STATUS_COMPLETE
);
13238 uint16 log_slot
= FindQuestSlot( quest_id
);
13239 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13240 SetQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
13242 if(Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(quest_id
))
13244 if( qInfo
->HasFlag(QUEST_FLAGS_AUTO_REWARDED
) )
13245 RewardQuest(qInfo
,0,this,false);
13247 SendQuestComplete( quest_id
);
13252 void Player::IncompleteQuest( uint32 quest_id
)
13256 SetQuestStatus( quest_id
, QUEST_STATUS_INCOMPLETE
);
13258 uint16 log_slot
= FindQuestSlot( quest_id
);
13259 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13260 RemoveQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
13264 void Player::RewardQuest( Quest
const *pQuest
, uint32 reward
, Object
* questGiver
, bool announce
)
13266 //this THING should be here to protect code from quest, which cast on player far teleport as a reward
13267 //should work fine, cause far teleport will be executed in Player::Update()
13268 SetCanDelayTeleport(true);
13270 uint32 quest_id
= pQuest
->GetQuestId();
13272 for (int i
= 0; i
< QUEST_ITEM_OBJECTIVES_COUNT
; ++i
)
13274 if (pQuest
->ReqItemId
[i
])
13275 DestroyItemCount( pQuest
->ReqItemId
[i
], pQuest
->ReqItemCount
[i
], true);
13278 RemoveTimedQuest(quest_id
);
13280 if (BattleGround
* bg
= GetBattleGround())
13281 if (bg
->GetTypeID() == BATTLEGROUND_AV
)
13282 ((BattleGroundAV
*)bg
)->HandleQuestComplete(pQuest
->GetQuestId(), this);
13284 if (pQuest
->GetRewChoiceItemsCount() > 0)
13286 if (uint32 itemId
= pQuest
->RewChoiceItemId
[reward
])
13288 ItemPosCountVec dest
;
13289 if (CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, itemId
, pQuest
->RewChoiceItemCount
[reward
] ) == EQUIP_ERR_OK
)
13291 Item
* item
= StoreNewItem( dest
, itemId
, true, Item::GenerateItemRandomPropertyId(itemId
));
13292 SendNewItem(item
, pQuest
->RewChoiceItemCount
[reward
], true, false);
13297 if (pQuest
->GetRewItemsCount() > 0)
13299 for (uint32 i
=0; i
< pQuest
->GetRewItemsCount(); ++i
)
13301 if (uint32 itemId
= pQuest
->RewItemId
[i
])
13303 ItemPosCountVec dest
;
13304 if (CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, itemId
, pQuest
->RewItemCount
[i
] ) == EQUIP_ERR_OK
)
13306 Item
* item
= StoreNewItem( dest
, itemId
, true, Item::GenerateItemRandomPropertyId(itemId
));
13307 SendNewItem(item
, pQuest
->RewItemCount
[i
], true, false);
13313 RewardReputation( pQuest
);
13315 uint16 log_slot
= FindQuestSlot( quest_id
);
13316 if (log_slot
< MAX_QUEST_LOG_SIZE
)
13317 SetQuestSlot(log_slot
,0);
13319 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
13321 // Not give XP in case already completed once repeatable quest
13322 uint32 XP
= q_status
.m_rewarded
? 0 : uint32(pQuest
->XPValue( this )*sWorld
.getConfig(CONFIG_FLOAT_RATE_XP_QUEST
));
13324 if (getLevel() < sWorld
.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL
))
13325 GiveXP( XP
, NULL
);
13328 uint32 money
= uint32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY
));
13329 ModifyMoney( money
);
13330 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD
, money
);
13333 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
13334 if (pQuest
->GetRewOrReqMoney())
13336 ModifyMoney( pQuest
->GetRewOrReqMoney() );
13338 if (pQuest
->GetRewOrReqMoney() > 0)
13339 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD
, pQuest
->GetRewOrReqMoney());
13343 if (pQuest
->GetRewHonorAddition())
13344 RewardHonor(NULL
, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorAddition()));
13347 if (pQuest
->GetCharTitleId())
13349 if (CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
13350 SetTitle(titleEntry
);
13353 if (pQuest
->GetBonusTalents())
13355 m_questRewardTalentCount
+=pQuest
->GetBonusTalents();
13356 InitTalentForLevel();
13359 // Send reward mail
13360 if (uint32 mail_template_id
= pQuest
->GetRewMailTemplateId())
13361 MailDraft(mail_template_id
).SendMailTo(this, questGiver
, MAIL_CHECK_MASK_NONE
, pQuest
->GetRewMailDelaySecs());
13363 if (pQuest
->IsDaily())
13365 SetDailyQuestStatus(quest_id
);
13366 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST
, 1);
13369 if (!pQuest
->IsRepeatable())
13370 SetQuestStatus(quest_id
, QUEST_STATUS_COMPLETE
);
13372 SetQuestStatus(quest_id
, QUEST_STATUS_NONE
);
13374 q_status
.m_rewarded
= true;
13375 if (q_status
.uState
!= QUEST_NEW
)
13376 q_status
.uState
= QUEST_CHANGED
;
13379 SendQuestReward( pQuest
, XP
, questGiver
);
13381 // cast spells after mark quest complete (some spells have quest completed state reqyurements in spell_area data)
13382 if (pQuest
->GetRewSpellCast() > 0)
13383 CastSpell( this, pQuest
->GetRewSpellCast(), true);
13384 else if ( pQuest
->GetRewSpell() > 0)
13385 CastSpell( this, pQuest
->GetRewSpell(), true);
13387 if (pQuest
->GetZoneOrSort() > 0)
13388 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE
, pQuest
->GetZoneOrSort());
13389 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT
);
13390 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST
, pQuest
->GetQuestId());
13395 // remove auras from spells with quest reward state limitations
13396 SpellAreaForQuestMapBounds saEndBounds
= sSpellMgr
.GetSpellAreaForQuestEndMapBounds(quest_id
);
13397 if(saEndBounds
.first
!= saEndBounds
.second
)
13399 GetZoneAndAreaId(zone
,area
);
13401 for(SpellAreaForAreaMap::const_iterator itr
= saEndBounds
.first
; itr
!= saEndBounds
.second
; ++itr
)
13402 if(!itr
->second
->IsFitToRequirements(this,zone
,area
))
13403 RemoveAurasDueToSpell(itr
->second
->spellId
);
13406 // Some spells applied at quest reward
13407 SpellAreaForQuestMapBounds saBounds
= sSpellMgr
.GetSpellAreaForQuestMapBounds(quest_id
,false);
13408 if(saBounds
.first
!= saBounds
.second
)
13411 GetZoneAndAreaId(zone
,area
);
13413 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
13414 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,zone
,area
))
13415 if (!HasAura(itr
->second
->spellId
, EFFECT_INDEX_0
))
13416 CastSpell(this,itr
->second
->spellId
,true);
13419 //lets remove flag for delayed teleports
13420 SetCanDelayTeleport(false);
13423 void Player::FailQuest(uint32 questId
)
13425 if (Quest
const* pQuest
= sObjectMgr
.GetQuestTemplate(questId
))
13427 SetQuestStatus(questId
, QUEST_STATUS_FAILED
);
13429 uint16 log_slot
= FindQuestSlot(questId
);
13431 if (log_slot
< MAX_QUEST_LOG_SIZE
)
13433 SetQuestSlotTimer(log_slot
, 1);
13434 SetQuestSlotState(log_slot
, QUEST_STATE_FAIL
);
13437 if (pQuest
->HasFlag(QUEST_MANGOS_FLAGS_TIMED
))
13439 QuestStatusData
& q_status
= mQuestStatus
[questId
];
13441 RemoveTimedQuest(questId
);
13442 q_status
.m_timer
= 0;
13444 SendQuestTimerFailed(questId
);
13447 SendQuestFailed(questId
);
13451 bool Player::SatisfyQuestSkillOrClass( Quest
const* qInfo
, bool msg
)
13453 int32 zoneOrSort
= qInfo
->GetZoneOrSort();
13454 int32 skillOrClass
= qInfo
->GetSkillOrClass();
13456 // skip zone zoneOrSort and 0 case skillOrClass
13457 if( zoneOrSort
>= 0 && skillOrClass
== 0 )
13460 int32 questSort
= -zoneOrSort
;
13461 uint8 reqSortClass
= ClassByQuestSort(questSort
);
13463 // check class sort cases in zoneOrSort
13464 if( reqSortClass
!= 0 && getClass() != reqSortClass
)
13467 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13472 if( skillOrClass
< 0 )
13474 uint8 reqClass
= -int32(skillOrClass
);
13475 if(getClass() != reqClass
)
13478 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13483 else if( skillOrClass
> 0 )
13485 uint32 reqSkill
= skillOrClass
;
13486 if( GetSkillValue( reqSkill
) < qInfo
->GetRequiredSkillValue() )
13489 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13497 bool Player::SatisfyQuestLevel( Quest
const* qInfo
, bool msg
)
13499 if( getLevel() < qInfo
->GetMinLevel() )
13502 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13508 bool Player::SatisfyQuestLog( bool msg
)
13511 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE
)
13516 WorldPacket
data( SMSG_QUESTLOG_FULL
, 0 );
13517 GetSession()->SendPacket( &data
);
13518 sLog
.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
13523 bool Player::SatisfyQuestPreviousQuest( Quest
const* qInfo
, bool msg
)
13525 // No previous quest (might be first quest in a series)
13526 if( qInfo
->prevQuests
.empty())
13529 for(Quest::PrevQuests::const_iterator iter
= qInfo
->prevQuests
.begin(); iter
!= qInfo
->prevQuests
.end(); ++iter
)
13531 uint32 prevId
= abs(*iter
);
13533 QuestStatusMap::const_iterator i_prevstatus
= mQuestStatus
.find( prevId
);
13534 Quest
const* qPrevInfo
= sObjectMgr
.GetQuestTemplate(prevId
);
13536 if( qPrevInfo
&& i_prevstatus
!= mQuestStatus
.end() )
13538 // If any of the positive previous quests completed, return true
13539 if( *iter
> 0 && i_prevstatus
->second
.m_rewarded
)
13541 // skip one-from-all exclusive group
13542 if(qPrevInfo
->GetExclusiveGroup() >= 0)
13545 // each-from-all exclusive group ( < 0)
13546 // can be start if only all quests in prev quest exclusive group completed and rewarded
13547 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2
= sObjectMgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
13548 ObjectMgr::ExclusiveQuestGroups::const_iterator end
= sObjectMgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
13550 ASSERT(iter2
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
13552 for(; iter2
!= end
; ++iter2
)
13554 uint32 exclude_Id
= iter2
->second
;
13556 // skip checked quest id, only state of other quests in group is interesting
13557 if(exclude_Id
== prevId
)
13560 QuestStatusMap::const_iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
13562 // alternative quest from group also must be completed and rewarded(reported)
13563 if( i_exstatus
== mQuestStatus
.end() || !i_exstatus
->second
.m_rewarded
)
13566 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13572 // If any of the negative previous quests active, return true
13573 if( *iter
< 0 && (i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
13574 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
))))
13576 // skip one-from-all exclusive group
13577 if(qPrevInfo
->GetExclusiveGroup() >= 0)
13580 // each-from-all exclusive group ( < 0)
13581 // can be start if only all quests in prev quest exclusive group active
13582 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2
= sObjectMgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
13583 ObjectMgr::ExclusiveQuestGroups::const_iterator end
= sObjectMgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
13585 ASSERT(iter2
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
13587 for(; iter2
!= end
; ++iter2
)
13589 uint32 exclude_Id
= iter2
->second
;
13591 // skip checked quest id, only state of other quests in group is interesting
13592 if(exclude_Id
== prevId
)
13595 QuestStatusMap::const_iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
13597 // alternative quest from group also must be active
13598 if( i_exstatus
== mQuestStatus
.end() ||
13599 i_exstatus
->second
.m_status
!= QUEST_STATUS_INCOMPLETE
&&
13600 (i_prevstatus
->second
.m_status
!= QUEST_STATUS_COMPLETE
|| GetQuestRewardStatus(prevId
)) )
13603 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13612 // Has only positive prev. quests in non-rewarded state
13613 // and negative prev. quests in non-active state
13615 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13620 bool Player::SatisfyQuestRace( Quest
const* qInfo
, bool msg
)
13622 uint32 reqraces
= qInfo
->GetRequiredRaces();
13623 if ( reqraces
== 0 )
13625 if( (reqraces
& getRaceMask()) == 0 )
13628 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE
);
13634 bool Player::SatisfyQuestReputation( Quest
const* qInfo
, bool msg
)
13636 uint32 fIdMin
= qInfo
->GetRequiredMinRepFaction(); //Min required rep
13637 if(fIdMin
&& GetReputationMgr().GetReputation(fIdMin
) < qInfo
->GetRequiredMinRepValue())
13640 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13644 uint32 fIdMax
= qInfo
->GetRequiredMaxRepFaction(); //Max required rep
13645 if(fIdMax
&& GetReputationMgr().GetReputation(fIdMax
) >= qInfo
->GetRequiredMaxRepValue())
13648 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13655 bool Player::SatisfyQuestStatus( Quest
const* qInfo
, bool msg
)
13657 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( qInfo
->GetQuestId() );
13658 if ( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
)
13661 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON
);
13667 bool Player::SatisfyQuestTimed(Quest
const* qInfo
, bool msg
)
13669 if (!m_timedquests
.empty() && qInfo
->HasFlag(QUEST_MANGOS_FLAGS_TIMED
))
13672 SendCanTakeQuestResponse(INVALIDREASON_QUEST_ONLY_ONE_TIMED
);
13679 bool Player::SatisfyQuestExclusiveGroup( Quest
const* qInfo
, bool msg
)
13681 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
13682 if(qInfo
->GetExclusiveGroup() <= 0)
13685 ObjectMgr::ExclusiveQuestGroups::const_iterator iter
= sObjectMgr
.mExclusiveQuestGroups
.lower_bound(qInfo
->GetExclusiveGroup());
13686 ObjectMgr::ExclusiveQuestGroups::const_iterator end
= sObjectMgr
.mExclusiveQuestGroups
.upper_bound(qInfo
->GetExclusiveGroup());
13688 ASSERT(iter
!=end
); // always must be found if qInfo->ExclusiveGroup != 0
13690 for(; iter
!= end
; ++iter
)
13692 uint32 exclude_Id
= iter
->second
;
13694 // skip checked quest id, only state of other quests in group is interesting
13695 if(exclude_Id
== qInfo
->GetQuestId())
13698 // not allow have daily quest if daily quest from exclusive group already recently completed
13699 Quest
const* Nquest
= sObjectMgr
.GetQuestTemplate(exclude_Id
);
13700 if( !SatisfyQuestDay(Nquest
, false) )
13703 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13707 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
13709 // alternative quest already started or completed
13710 if( i_exstatus
!= mQuestStatus
.end()
13711 && (i_exstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
|| i_exstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
13714 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13721 bool Player::SatisfyQuestNextChain( Quest
const* qInfo
, bool msg
)
13723 if(!qInfo
->GetNextQuestInChain())
13726 // next quest in chain already started or completed
13727 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( qInfo
->GetNextQuestInChain() );
13728 if( itr
!= mQuestStatus
.end()
13729 && (itr
->second
.m_status
== QUEST_STATUS_COMPLETE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
13732 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13736 // check for all quests further up the chain
13737 // only necessary if there are quest chains with more than one quest that can be skipped
13738 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
13742 bool Player::SatisfyQuestPrevChain( Quest
const* qInfo
, bool msg
)
13744 // No previous quest in chain
13745 if( qInfo
->prevChainQuests
.empty())
13748 for(Quest::PrevChainQuests::const_iterator iter
= qInfo
->prevChainQuests
.begin(); iter
!= qInfo
->prevChainQuests
.end(); ++iter
)
13750 uint32 prevId
= *iter
;
13752 QuestStatusMap::const_iterator i_prevstatus
= mQuestStatus
.find( prevId
);
13754 if( i_prevstatus
!= mQuestStatus
.end() )
13756 // If any of the previous quests in chain active, return false
13757 if( i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
13758 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
)))
13761 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13766 // check for all quests further down the chain
13767 // only necessary if there are quest chains with more than one quest that can be skipped
13768 //if( !SatisfyQuestPrevChain( prevId, msg ) )
13772 // No previous quest in chain active
13776 bool Player::SatisfyQuestDay( Quest
const* qInfo
, bool msg
)
13778 if(!qInfo
->IsDaily())
13781 bool have_slot
= false;
13782 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
13784 uint32 id
= GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
);
13785 if(qInfo
->GetQuestId()==id
)
13795 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING
);
13802 bool Player::GiveQuestSourceItem( Quest
const *pQuest
)
13804 uint32 srcitem
= pQuest
->GetSrcItemId();
13807 uint32 count
= pQuest
->GetSrcItemCount();
13811 ItemPosCountVec dest
;
13812 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
13813 if( msg
== EQUIP_ERR_OK
)
13815 Item
* item
= StoreNewItem(dest
, srcitem
, true);
13816 SendNewItem(item
, count
, true, false);
13819 // player already have max amount required item, just report success
13820 else if( msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
13823 SendEquipError( msg
, NULL
, NULL
, srcitem
);
13830 bool Player::TakeQuestSourceItem( uint32 quest_id
, bool msg
)
13832 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(quest_id
);
13835 uint32 srcitem
= qInfo
->GetSrcItemId();
13838 uint32 count
= qInfo
->GetSrcItemCount();
13842 // exist one case when destroy source quest item not possible:
13843 // non un-equippable item (equipped non-empty bag, for example)
13844 uint8 res
= CanUnequipItems(srcitem
,count
);
13845 if(res
!= EQUIP_ERR_OK
)
13848 SendEquipError( res
, NULL
, NULL
, srcitem
);
13852 DestroyItemCount(srcitem
, count
, true, true);
13858 bool Player::GetQuestRewardStatus( uint32 quest_id
) const
13860 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(quest_id
);
13863 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13864 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13865 if( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
13866 && !qInfo
->IsRepeatable() )
13867 return itr
->second
.m_rewarded
;
13874 QuestStatus
Player::GetQuestStatus( uint32 quest_id
) const
13878 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13879 if( itr
!= mQuestStatus
.end() )
13880 return itr
->second
.m_status
;
13882 return QUEST_STATUS_NONE
;
13885 bool Player::CanShareQuest(uint32 quest_id
) const
13887 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(quest_id
);
13888 if( qInfo
&& qInfo
->HasFlag(QUEST_FLAGS_SHARABLE
) )
13890 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13891 if( itr
!= mQuestStatus
.end() )
13892 return itr
->second
.m_status
== QUEST_STATUS_NONE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
;
13897 void Player::SetQuestStatus(uint32 quest_id
, QuestStatus status
)
13899 if (sObjectMgr
.GetQuestTemplate(quest_id
))
13901 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
13903 q_status
.m_status
= status
;
13905 if (q_status
.uState
!= QUEST_NEW
)
13906 q_status
.uState
= QUEST_CHANGED
;
13909 UpdateForQuestWorldObjects();
13912 // not used in MaNGOS, but used in scripting code
13913 uint32
Player::GetReqKillOrCastCurrentCount(uint32 quest_id
, int32 entry
)
13915 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(quest_id
);
13919 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13920 if ( qInfo
->ReqCreatureOrGOId
[j
] == entry
)
13921 return mQuestStatus
[quest_id
].m_creatureOrGOcount
[j
];
13926 void Player::AdjustQuestReqItemCount( Quest
const* pQuest
, QuestStatusData
& questStatusData
)
13928 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13930 for(int i
= 0; i
< QUEST_ITEM_OBJECTIVES_COUNT
; ++i
)
13932 uint32 reqitemcount
= pQuest
->ReqItemCount
[i
];
13933 if( reqitemcount
!= 0 )
13935 uint32 curitemcount
= GetItemCount(pQuest
->ReqItemId
[i
], true);
13937 questStatusData
.m_itemcount
[i
] = std::min(curitemcount
, reqitemcount
);
13938 if (questStatusData
.uState
!= QUEST_NEW
) questStatusData
.uState
= QUEST_CHANGED
;
13944 uint16
Player::FindQuestSlot( uint32 quest_id
) const
13946 for ( uint16 i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13947 if ( GetQuestSlotQuestId(i
) == quest_id
)
13950 return MAX_QUEST_LOG_SIZE
;
13953 void Player::AreaExploredOrEventHappens( uint32 questId
)
13957 uint16 log_slot
= FindQuestSlot( questId
);
13958 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13960 QuestStatusData
& q_status
= mQuestStatus
[questId
];
13962 if(!q_status
.m_explored
)
13964 q_status
.m_explored
= true;
13965 if (q_status
.uState
!= QUEST_NEW
)
13966 q_status
.uState
= QUEST_CHANGED
;
13969 if( CanCompleteQuest( questId
) )
13970 CompleteQuest( questId
);
13974 //not used in mangosd, function for external script library
13975 void Player::GroupEventHappens( uint32 questId
, WorldObject
const* pEventObject
)
13977 if( Group
*pGroup
= GetGroup() )
13979 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
13981 Player
*pGroupGuy
= itr
->getSource();
13983 // for any leave or dead (with not released body) group member at appropriate distance
13984 if( pGroupGuy
&& pGroupGuy
->IsAtGroupRewardDistance(pEventObject
) && !pGroupGuy
->HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
13985 pGroupGuy
->AreaExploredOrEventHappens(questId
);
13989 AreaExploredOrEventHappens(questId
);
13992 void Player::ItemAddedQuestCheck( uint32 entry
, uint32 count
)
13994 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13996 uint32 questid
= GetQuestSlotQuestId(i
);
13997 if ( questid
== 0 )
14000 QuestStatusData
& q_status
= mQuestStatus
[questid
];
14002 if ( q_status
.m_status
!= QUEST_STATUS_INCOMPLETE
)
14005 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(questid
);
14006 if( !qInfo
|| !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
14009 for (int j
= 0; j
< QUEST_ITEM_OBJECTIVES_COUNT
; ++j
)
14011 uint32 reqitem
= qInfo
->ReqItemId
[j
];
14012 if ( reqitem
== entry
)
14014 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
14015 uint32 curitemcount
= q_status
.m_itemcount
[j
];
14016 if ( curitemcount
< reqitemcount
)
14018 uint32 additemcount
= ( curitemcount
+ count
<= reqitemcount
? count
: reqitemcount
- curitemcount
);
14019 q_status
.m_itemcount
[j
] += additemcount
;
14020 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
14022 SendQuestUpdateAddItem( qInfo
, j
, additemcount
);
14024 if ( CanCompleteQuest( questid
) )
14025 CompleteQuest( questid
);
14030 UpdateForQuestWorldObjects();
14033 void Player::ItemRemovedQuestCheck( uint32 entry
, uint32 count
)
14035 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14037 uint32 questid
= GetQuestSlotQuestId(i
);
14040 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(questid
);
14043 if( !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
14046 for (int j
= 0; j
< QUEST_ITEM_OBJECTIVES_COUNT
; ++j
)
14048 uint32 reqitem
= qInfo
->ReqItemId
[j
];
14049 if ( reqitem
== entry
)
14051 QuestStatusData
& q_status
= mQuestStatus
[questid
];
14053 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
14054 uint32 curitemcount
;
14055 if( q_status
.m_status
!= QUEST_STATUS_COMPLETE
)
14056 curitemcount
= q_status
.m_itemcount
[j
];
14058 curitemcount
= GetItemCount(entry
, true);
14059 if ( curitemcount
< reqitemcount
+ count
)
14061 uint32 remitemcount
= ( curitemcount
<= reqitemcount
? count
: count
+ reqitemcount
- curitemcount
);
14062 q_status
.m_itemcount
[j
] = curitemcount
- remitemcount
;
14063 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
14065 IncompleteQuest( questid
);
14071 UpdateForQuestWorldObjects();
14074 void Player::KilledMonster( CreatureInfo
const* cInfo
, ObjectGuid guid
)
14077 KilledMonsterCredit(cInfo
->Entry
, guid
);
14079 for(int i
= 0; i
< MAX_KILL_CREDIT
; ++i
)
14080 if(cInfo
->KillCredit
[i
])
14081 KilledMonsterCredit(cInfo
->KillCredit
[i
], guid
);
14084 void Player::KilledMonsterCredit( uint32 entry
, ObjectGuid guid
)
14086 uint32 addkillcount
= 1;
14087 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE
, entry
, addkillcount
);
14088 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14090 uint32 questid
= GetQuestSlotQuestId(i
);
14094 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(questid
);
14097 // just if !ingroup || !noraidgroup || raidgroup
14098 QuestStatusData
& q_status
= mQuestStatus
[questid
];
14099 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
&& (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo
->GetType() == QUEST_TYPE_RAID
))
14101 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
14103 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
14105 // skip GO activate objective or none
14106 if(qInfo
->ReqCreatureOrGOId
[j
] <=0)
14109 // skip Cast at creature objective
14110 if(qInfo
->ReqSpell
[j
] !=0 )
14113 uint32 reqkill
= qInfo
->ReqCreatureOrGOId
[j
];
14115 if ( reqkill
== entry
)
14117 uint32 reqkillcount
= qInfo
->ReqCreatureOrGOCount
[j
];
14118 uint32 curkillcount
= q_status
.m_creatureOrGOcount
[j
];
14119 if ( curkillcount
< reqkillcount
)
14121 q_status
.m_creatureOrGOcount
[j
] = curkillcount
+ addkillcount
;
14122 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
14124 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curkillcount
, addkillcount
);
14126 if ( CanCompleteQuest( questid
) )
14127 CompleteQuest( questid
);
14129 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
14138 void Player::CastedCreatureOrGO( uint32 entry
, ObjectGuid guid
, uint32 spell_id
)
14140 bool isCreature
= guid
.IsCreature();
14142 uint32 addCastCount
= 1;
14143 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14145 uint32 questid
= GetQuestSlotQuestId(i
);
14149 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(questid
);
14153 QuestStatusData
& q_status
= mQuestStatus
[questid
];
14155 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
14157 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
14159 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
14161 // skip kill creature objective (0) or wrong spell casts
14162 if(qInfo
->ReqSpell
[j
] != spell_id
)
14165 uint32 reqTarget
= 0;
14169 // creature activate objectives
14170 if(qInfo
->ReqCreatureOrGOId
[j
] > 0)
14171 // checked at quest_template loading
14172 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
14176 // GO activate objective
14177 if(qInfo
->ReqCreatureOrGOId
[j
] < 0)
14178 // checked at quest_template loading
14179 reqTarget
= - qInfo
->ReqCreatureOrGOId
[j
];
14182 // other not this creature/GO related objectives
14183 if( reqTarget
!= entry
)
14186 uint32 reqCastCount
= qInfo
->ReqCreatureOrGOCount
[j
];
14187 uint32 curCastCount
= q_status
.m_creatureOrGOcount
[j
];
14188 if ( curCastCount
< reqCastCount
)
14190 q_status
.m_creatureOrGOcount
[j
] = curCastCount
+ addCastCount
;
14191 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
14193 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curCastCount
, addCastCount
);
14196 if ( CanCompleteQuest( questid
) )
14197 CompleteQuest( questid
);
14199 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
14207 void Player::TalkedToCreature( uint32 entry
, ObjectGuid guid
)
14209 uint32 addTalkCount
= 1;
14210 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14212 uint32 questid
= GetQuestSlotQuestId(i
);
14216 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(questid
);
14220 QuestStatusData
& q_status
= mQuestStatus
[questid
];
14222 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
14224 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
14226 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
14228 // skip spell casts and Gameobject objectives
14229 if(qInfo
->ReqSpell
[j
] > 0 || qInfo
->ReqCreatureOrGOId
[j
] < 0)
14232 uint32 reqTarget
= 0;
14234 if(qInfo
->ReqCreatureOrGOId
[j
] > 0) // creature activate objectives
14235 // checked at quest_template loading
14236 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
14240 if ( reqTarget
== entry
)
14242 uint32 reqTalkCount
= qInfo
->ReqCreatureOrGOCount
[j
];
14243 uint32 curTalkCount
= q_status
.m_creatureOrGOcount
[j
];
14244 if ( curTalkCount
< reqTalkCount
)
14246 q_status
.m_creatureOrGOcount
[j
] = curTalkCount
+ addTalkCount
;
14247 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
14249 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curTalkCount
, addTalkCount
);
14251 if ( CanCompleteQuest( questid
) )
14252 CompleteQuest( questid
);
14254 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
14263 void Player::MoneyChanged( uint32 count
)
14265 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14267 uint32 questid
= GetQuestSlotQuestId(i
);
14271 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(questid
);
14272 if( qInfo
&& qInfo
->GetRewOrReqMoney() < 0 )
14274 QuestStatusData
& q_status
= mQuestStatus
[questid
];
14276 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
14278 if(int32(count
) >= -qInfo
->GetRewOrReqMoney())
14280 if ( CanCompleteQuest( questid
) )
14281 CompleteQuest( questid
);
14284 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
14286 if(int32(count
) < -qInfo
->GetRewOrReqMoney())
14287 IncompleteQuest( questid
);
14293 void Player::ReputationChanged(FactionEntry
const* factionEntry
)
14295 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14297 if(uint32 questid
= GetQuestSlotQuestId(i
))
14299 if(Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(questid
))
14301 if(qInfo
->GetRepObjectiveFaction() == factionEntry
->ID
)
14303 QuestStatusData
& q_status
= mQuestStatus
[questid
];
14304 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
14306 if(GetReputationMgr().GetReputation(factionEntry
) >= qInfo
->GetRepObjectiveValue())
14307 if ( CanCompleteQuest( questid
) )
14308 CompleteQuest( questid
);
14310 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
14312 if(GetReputationMgr().GetReputation(factionEntry
) < qInfo
->GetRepObjectiveValue())
14313 IncompleteQuest( questid
);
14321 bool Player::HasQuestForItem( uint32 itemid
) const
14323 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14325 uint32 questid
= GetQuestSlotQuestId(i
);
14326 if ( questid
== 0 )
14329 QuestStatusMap::const_iterator qs_itr
= mQuestStatus
.find(questid
);
14330 if(qs_itr
== mQuestStatus
.end())
14333 QuestStatusData
const& q_status
= qs_itr
->second
;
14335 if (q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
14337 Quest
const* qinfo
= sObjectMgr
.GetQuestTemplate(questid
);
14341 // hide quest if player is in raid-group and quest is no raid quest
14342 if (GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
14343 && !InBattleGround())
14346 // There should be no mixed ReqItem/ReqSource drop
14347 // This part for ReqItem drop
14348 for (int j
= 0; j
< QUEST_ITEM_OBJECTIVES_COUNT
; ++j
)
14350 if(itemid
== qinfo
->ReqItemId
[j
] && q_status
.m_itemcount
[j
] < qinfo
->ReqItemCount
[j
] )
14353 // This part - for ReqSource
14354 for (int j
= 0; j
< QUEST_SOURCE_ITEM_IDS_COUNT
; ++j
)
14356 // examined item is a source item
14357 if (qinfo
->ReqSourceId
[j
] == itemid
)
14359 ItemPrototype
const *pProto
= ObjectMgr::GetItemPrototype(itemid
);
14362 if (pProto
->MaxCount
&& (int32
)GetItemCount(itemid
,true) < pProto
->MaxCount
)
14365 // allows custom amount drop when not 0
14366 if (qinfo
->ReqSourceCount
[j
])
14368 if (GetItemCount(itemid
,true) < qinfo
->ReqSourceCount
[j
])
14370 } else if ((int32
)GetItemCount(itemid
,true) < pProto
->Stackable
)
14379 void Player::SendQuestComplete( uint32 quest_id
)
14383 WorldPacket
data( SMSG_QUESTUPDATE_COMPLETE
, 4 );
14384 data
<< uint32(quest_id
);
14385 GetSession()->SendPacket( &data
);
14386 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id
);
14390 void Player::SendQuestReward( Quest
const *pQuest
, uint32 XP
, Object
* questGiver
)
14392 uint32 questid
= pQuest
->GetQuestId();
14393 sLog
.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid
);
14394 WorldPacket
data( SMSG_QUESTGIVER_QUEST_COMPLETE
, (4+4+4+4+4) );
14395 data
<< uint32(questid
);
14397 if ( getLevel() < sWorld
.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL
) )
14399 data
<< uint32(XP
);
14400 data
<< uint32(pQuest
->GetRewOrReqMoney());
14405 data
<< uint32(pQuest
->GetRewOrReqMoney() + int32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY
)));
14408 data
<< uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorAddition()));
14409 data
<< uint32(pQuest
->GetBonusTalents()); // bonus talents
14411 GetSession()->SendPacket( &data
);
14413 if (pQuest
->GetQuestCompleteScript() != 0)
14414 GetMap()->ScriptsStart(sQuestEndScripts
, pQuest
->GetQuestCompleteScript(), questGiver
, this);
14417 void Player::SendQuestFailed( uint32 quest_id
)
14421 WorldPacket
data( SMSG_QUESTGIVER_QUEST_FAILED
, 4+4 );
14422 data
<< uint32(quest_id
);
14423 data
<< uint32(0); // failed reason (4 for inventory is full)
14424 GetSession()->SendPacket( &data
);
14425 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
14429 void Player::SendQuestTimerFailed( uint32 quest_id
)
14433 WorldPacket
data( SMSG_QUESTUPDATE_FAILEDTIMER
, 4 );
14434 data
<< uint32(quest_id
);
14435 GetSession()->SendPacket( &data
);
14436 sLog
.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
14440 void Player::SendCanTakeQuestResponse( uint32 msg
)
14442 WorldPacket
data( SMSG_QUESTGIVER_QUEST_INVALID
, 4 );
14443 data
<< uint32(msg
);
14444 GetSession()->SendPacket( &data
);
14445 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
14448 void Player::SendQuestConfirmAccept(const Quest
* pQuest
, Player
* pReceiver
)
14452 std::string strTitle
= pQuest
->GetTitle();
14454 int loc_idx
= pReceiver
->GetSession()->GetSessionDbLocaleIndex();
14458 if (const QuestLocale
* pLocale
= sObjectMgr
.GetQuestLocale(pQuest
->GetQuestId()))
14460 if ((int32
)pLocale
->Title
.size() > loc_idx
&& !pLocale
->Title
[loc_idx
].empty())
14461 strTitle
= pLocale
->Title
[loc_idx
];
14465 WorldPacket
data(SMSG_QUEST_CONFIRM_ACCEPT
, (4 + strTitle
.size() + 8));
14466 data
<< uint32(pQuest
->GetQuestId());
14468 data
<< uint64(GetGUID());
14469 pReceiver
->GetSession()->SendPacket(&data
);
14471 sLog
.outDebug("WORLD: Sent SMSG_QUEST_CONFIRM_ACCEPT");
14475 void Player::SendPushToPartyResponse( Player
*pPlayer
, uint32 msg
)
14479 WorldPacket
data( MSG_QUEST_PUSH_RESULT
, (8+1) );
14480 data
<< uint64(pPlayer
->GetGUID());
14481 data
<< uint8(msg
); // valid values: 0-8
14482 GetSession()->SendPacket( &data
);
14483 sLog
.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
14487 void Player::SendQuestUpdateAddItem( Quest
const* /*pQuest*/, uint32
/*item_idx*/, uint32
/*count*/ )
14489 WorldPacket
data( SMSG_QUESTUPDATE_ADD_ITEM
, 0 );
14490 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
14491 //data << pQuest->ReqItemId[item_idx];
14493 GetSession()->SendPacket( &data
);
14496 void Player::SendQuestUpdateAddCreatureOrGo( Quest
const* pQuest
, ObjectGuid guid
, uint32 creatureOrGO_idx
, uint32 old_count
, uint32 add_count
)
14498 ASSERT(old_count
+ add_count
< 65536 && "mob/GO count store in 16 bits 2^16 = 65536 (0..65536)");
14500 int32 entry
= pQuest
->ReqCreatureOrGOId
[ creatureOrGO_idx
];
14502 // client expected gameobject template id in form (id|0x80000000)
14503 entry
= (-entry
) | 0x80000000;
14505 WorldPacket
data( SMSG_QUESTUPDATE_ADD_KILL
, (4*4+8) );
14506 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
14507 data
<< uint32(pQuest
->GetQuestId());
14508 data
<< uint32(entry
);
14509 data
<< uint32(old_count
+ add_count
);
14510 data
<< uint32(pQuest
->ReqCreatureOrGOCount
[ creatureOrGO_idx
]);
14512 GetSession()->SendPacket(&data
);
14514 uint16 log_slot
= FindQuestSlot( pQuest
->GetQuestId() );
14515 if( log_slot
< MAX_QUEST_LOG_SIZE
)
14516 SetQuestSlotCounter(log_slot
,creatureOrGO_idx
,GetQuestSlotCounter(log_slot
,creatureOrGO_idx
)+add_count
);
14519 /*********************************************************/
14520 /*** LOAD SYSTEM ***/
14521 /*********************************************************/
14523 void Player::_LoadDeclinedNames(QueryResult
* result
)
14529 delete m_declinedname
;
14531 m_declinedname
= new DeclinedName
;
14532 Field
*fields
= result
->Fetch();
14533 for(int i
= 0; i
< MAX_DECLINED_NAME_CASES
; ++i
)
14534 m_declinedname
->name
[i
] = fields
[i
].GetCppString();
14539 void Player::_LoadArenaTeamInfo(QueryResult
*result
)
14541 // arenateamid, played_week, played_season, personal_rating
14542 memset((void*)&m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
], 0, sizeof(uint32
) * MAX_ARENA_SLOT
* ARENA_TEAM_END
);
14548 Field
*fields
= result
->Fetch();
14550 uint32 arenateamid
= fields
[0].GetUInt32();
14551 uint32 played_week
= fields
[1].GetUInt32();
14552 uint32 played_season
= fields
[2].GetUInt32();
14553 uint32 wons_season
= fields
[3].GetUInt32();
14554 uint32 personal_rating
= fields
[4].GetUInt32();
14556 ArenaTeam
* aTeam
= sObjectMgr
.GetArenaTeamById(arenateamid
);
14559 sLog
.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u", arenateamid
);
14562 uint8 arenaSlot
= aTeam
->GetSlot();
14564 SetArenaTeamInfoField(arenaSlot
, ARENA_TEAM_ID
, arenateamid
);
14565 SetArenaTeamInfoField(arenaSlot
, ARENA_TEAM_TYPE
, aTeam
->GetType());
14566 SetArenaTeamInfoField(arenaSlot
, ARENA_TEAM_MEMBER
, (aTeam
->GetCaptain() == GetGUID()) ? 0 : 1);
14567 SetArenaTeamInfoField(arenaSlot
, ARENA_TEAM_GAMES_WEEK
, played_week
);
14568 SetArenaTeamInfoField(arenaSlot
, ARENA_TEAM_GAMES_SEASON
, played_season
);
14569 SetArenaTeamInfoField(arenaSlot
, ARENA_TEAM_WINS_SEASON
, wons_season
);
14570 SetArenaTeamInfoField(arenaSlot
, ARENA_TEAM_PERSONAL_RATING
, personal_rating
);
14572 } while (result
->NextRow());
14576 void Player::_LoadEquipmentSets(QueryResult
*result
)
14578 // 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));
14585 Field
*fields
= result
->Fetch();
14587 EquipmentSet eqSet
;
14589 eqSet
.Guid
= fields
[0].GetUInt64();
14590 uint32 index
= fields
[1].GetUInt32();
14591 eqSet
.Name
= fields
[2].GetCppString();
14592 eqSet
.IconName
= fields
[3].GetCppString();
14593 eqSet
.state
= EQUIPMENT_SET_UNCHANGED
;
14595 for(uint32 i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
14596 eqSet
.Items
[i
] = fields
[4+i
].GetUInt32();
14598 m_EquipmentSets
[index
] = eqSet
;
14602 if(count
>= MAX_EQUIPMENT_SET_INDEX
) // client limit
14604 } while (result
->NextRow());
14608 void Player::_LoadBGData(QueryResult
* result
)
14613 // Expecting only one row
14614 Field
*fields
= result
->Fetch();
14615 /* bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
14616 m_bgData
.bgInstanceID
= fields
[0].GetUInt32();
14617 m_bgData
.bgTeam
= fields
[1].GetUInt32();
14618 m_bgData
.joinPos
= WorldLocation(fields
[6].GetUInt32(), // Map
14619 fields
[2].GetFloat(), // X
14620 fields
[3].GetFloat(), // Y
14621 fields
[4].GetFloat(), // Z
14622 fields
[5].GetFloat()); // Orientation
14623 m_bgData
.taxiPath
[0] = fields
[7].GetUInt32();
14624 m_bgData
.taxiPath
[1] = fields
[8].GetUInt32();
14625 m_bgData
.mountSpell
= fields
[9].GetUInt32();
14630 bool Player::LoadPositionFromDB(uint32
& mapid
, float& x
,float& y
,float& z
,float& o
, bool& in_flight
, uint64 guid
)
14632 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid
));
14636 Field
*fields
= result
->Fetch();
14638 x
= fields
[0].GetFloat();
14639 y
= fields
[1].GetFloat();
14640 z
= fields
[2].GetFloat();
14641 o
= fields
[3].GetFloat();
14642 mapid
= fields
[4].GetUInt32();
14643 in_flight
= !fields
[5].GetCppString().empty();
14649 void Player::_LoadIntoDataField(const char* data
, uint32 startOffset
, uint32 count
)
14654 Tokens tokens
= StrSplit(data
, " ");
14656 if(tokens
.size() != count
)
14659 Tokens::iterator iter
;
14661 for (iter
= tokens
.begin(), index
= 0; index
< count
; ++iter
, ++index
)
14663 m_uint32Values
[startOffset
+ index
] = atol((*iter
).c_str());
14667 bool Player::LoadFromDB( uint32 guid
, SqlQueryHolder
*holder
)
14669 // 0 1 2 3 4 5 6 7 8 9 10 11
14670 //SELECT guid, account, name, race, class, gender, level, xp, money, playerBytes, playerBytes2, playerFlags,"
14671 // 12 13 14 15 16 17 18 19 20 21 22 23 24
14672 //"position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost,"
14673 // 25 26 27 28 29 30 31 32 33 34 35 36 37 38
14674 //"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,"
14675 // 39 40 41 42 43 44 45 46 47 48 49
14676 //"arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk,"
14677 // 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
14678 //"health, power1, power2, power3, power4, power5, power6, power7, specCount, activeSpec, exploredZones, equipmentCache, ammoId, knownTitles, actionBars FROM characters WHERE guid = '%u'", GUID_LOPART(m_guid));
14679 QueryResult
*result
= holder
->GetResult(PLAYER_LOGIN_QUERY_LOADFROM
);
14683 sLog
.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid
);
14687 Field
*fields
= result
->Fetch();
14689 uint32 dbAccountId
= fields
[1].GetUInt32();
14691 // check if the character's account in the db and the logged in account match.
14692 // player should be able to load/delete character only with correct account!
14693 if( dbAccountId
!= GetSession()->GetAccountId() )
14695 sLog
.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid
,GetSession()->GetAccountId(),dbAccountId
);
14700 Object::_Create( guid
, 0, HIGHGUID_PLAYER
);
14702 m_name
= fields
[2].GetCppString();
14704 // check name limitations
14705 if (ObjectMgr::CheckPlayerName(m_name
) != CHAR_NAME_SUCCESS
||
14706 (GetSession()->GetSecurity() == SEC_PLAYER
&& sObjectMgr
.IsReservedName(m_name
)))
14709 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME
),guid
);
14713 // overwrite possible wrong/corrupted guid
14714 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
14716 // overwrite some data fields
14718 bytes0
|= fields
[3].GetUInt8(); // race
14719 bytes0
|= fields
[4].GetUInt8() << 8; // class
14720 bytes0
|= fields
[5].GetUInt8() << 16; // gender
14721 SetUInt32Value(UNIT_FIELD_BYTES_0
, bytes0
);
14723 SetUInt32Value(UNIT_FIELD_LEVEL
, fields
[6].GetUInt8());
14724 SetUInt32Value(PLAYER_XP
, fields
[7].GetUInt32());
14726 _LoadIntoDataField(fields
[60].GetString(), PLAYER_EXPLORED_ZONES_1
, PLAYER_EXPLORED_ZONES_SIZE
);
14727 _LoadIntoDataField(fields
[63].GetString(), PLAYER__FIELD_KNOWN_TITLES
, KNOWN_TITLES_SIZE
*2);
14729 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, DEFAULT_WORLD_OBJECT_SIZE
);
14730 SetFloatValue(UNIT_FIELD_COMBATREACH
, 1.5f
);
14731 SetFloatValue(UNIT_FIELD_HOVERHEIGHT
, 1.0f
);
14733 uint32 money
= fields
[8].GetUInt32();
14734 if(money
> MAX_MONEY_AMOUNT
)
14735 money
= MAX_MONEY_AMOUNT
;
14738 SetUInt32Value(PLAYER_BYTES
, fields
[9].GetUInt32());
14739 SetUInt32Value(PLAYER_BYTES_2
, fields
[10].GetUInt32());
14740 SetUInt32Value(PLAYER_BYTES_3
, (fields
[49].GetUInt16() & 0xFFFE) | fields
[5].GetUInt8());
14741 SetUInt32Value(PLAYER_FLAGS
, fields
[11].GetUInt32());
14742 SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX
, fields
[48].GetInt32());
14744 SetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES
, fields
[47].GetUInt64());
14746 SetUInt32Value(PLAYER_AMMO_ID
, fields
[62].GetUInt32());
14747 SetByteValue(PLAYER_FIELD_BYTES
, 2, fields
[64].GetUInt8());
14752 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
14753 for(uint8 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
14755 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2), 0 );
14756 SetVisibleItemSlot(slot
, NULL
);
14760 delete m_items
[slot
];
14761 m_items
[slot
] = NULL
;
14765 sLog
.outDebug("Load Basic value of player %s is: ", m_name
.c_str());
14768 //Need to call it to initialize m_team (m_team can be calculated from race)
14769 //Other way is to saves m_team into characters table.
14770 setFactionForRace(getRace());
14773 // load home bind and check in same time class/race pair, it used later for restore broken positions
14774 if(!_LoadHomeBind(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND
)))
14780 InitPrimaryProfessions(); // to max set before any spell loaded
14782 // init saved position, and fix it later if problematic
14783 uint32 transGUID
= fields
[30].GetUInt32();
14784 Relocate(fields
[12].GetFloat(),fields
[13].GetFloat(),fields
[14].GetFloat(),fields
[16].GetFloat());
14785 SetLocationMapId(fields
[15].GetUInt32());
14787 uint32 difficulty
= fields
[38].GetUInt32();
14788 if(difficulty
>= MAX_DUNGEON_DIFFICULTY
)
14789 difficulty
= DUNGEON_DIFFICULTY_NORMAL
;
14790 SetDungeonDifficulty(Difficulty(difficulty
)); // may be changed in _LoadGroup
14792 _LoadGroup(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP
));
14794 _LoadArenaTeamInfo(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO
));
14796 uint32 arena_currency
= fields
[39].GetUInt32();
14797 if (arena_currency
> sWorld
.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS
))
14798 arena_currency
= sWorld
.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS
);
14800 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, arena_currency
);
14802 // check arena teams integrity
14803 for(uint32 arena_slot
= 0; arena_slot
< MAX_ARENA_SLOT
; ++arena_slot
)
14805 uint32 arena_team_id
= GetArenaTeamId(arena_slot
);
14809 if(ArenaTeam
* at
= sObjectMgr
.GetArenaTeamById(arena_team_id
))
14810 if(at
->HaveMember(GetGUID()))
14813 // arena team not exist or not member, cleanup fields
14814 for(int j
= 0; j
< ARENA_TEAM_END
; ++j
)
14815 SetArenaTeamInfoField(arena_slot
, ArenaTeamInfoType(j
), 0);
14818 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, fields
[40].GetUInt32());
14819 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, fields
[41].GetUInt32());
14820 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, fields
[42].GetUInt32());
14821 SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, fields
[43].GetUInt32());
14822 SetUInt16Value(PLAYER_FIELD_KILLS
, 0, fields
[44].GetUInt16());
14823 SetUInt16Value(PLAYER_FIELD_KILLS
, 1, fields
[45].GetUInt16());
14825 _LoadBoundInstances(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES
));
14827 if(!IsPositionValid())
14829 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());
14830 RelocateToHomebind();
14834 m_movementInfo
.SetTransportData(0, 0.0f
, 0.0f
, 0.0f
, 0.0f
, 0, -1);
14837 _LoadBGData(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADBGDATA
));
14839 if(m_bgData
.bgInstanceID
) //saved in BattleGround
14841 BattleGround
*currentBg
= sBattleGroundMgr
.GetBattleGround(m_bgData
.bgInstanceID
, BATTLEGROUND_TYPE_NONE
);
14843 bool player_at_bg
= currentBg
&& currentBg
->IsPlayerInBattleGround(GetGUID());
14845 if(player_at_bg
&& currentBg
->GetStatus() != STATUS_WAIT_LEAVE
)
14847 BattleGroundQueueTypeId bgQueueTypeId
= BattleGroundMgr::BGQueueTypeId(currentBg
->GetTypeID(), currentBg
->GetArenaType());
14848 AddBattleGroundQueueId(bgQueueTypeId
);
14850 m_bgData
.bgTypeID
= currentBg
->GetTypeID();
14852 //join player to battleground group
14853 currentBg
->EventPlayerLoggedIn(this, GetGUID());
14854 currentBg
->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), m_bgData
.bgTeam
);
14856 SetInviteForBattleGroundQueueType(bgQueueTypeId
,currentBg
->GetInstanceID());
14862 currentBg
->RemovePlayerAtLeave(GetGUID(), false, true);
14864 // move to bg enter point
14865 const WorldLocation
& _loc
= GetBattleGroundEntryPoint();
14866 SetLocationMapId(_loc
.mapid
);
14867 Relocate(_loc
.coord_x
, _loc
.coord_y
, _loc
.coord_z
, _loc
.orientation
);
14869 // We are not in BG anymore
14870 m_bgData
.bgInstanceID
= 0;
14875 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(GetMapId());
14876 // if server restart after player save in BG or area
14877 // player can have current coordinates in to BG/Arena map, fix this
14878 if(!mapEntry
|| mapEntry
->IsBattleGroundOrArena())
14880 const WorldLocation
& _loc
= GetBattleGroundEntryPoint();
14881 SetLocationMapId(_loc
.mapid
);
14882 Relocate(_loc
.coord_x
, _loc
.coord_y
, _loc
.coord_z
, _loc
.orientation
);
14886 if (transGUID
!= 0)
14888 m_movementInfo
.SetTransportData(transGUID
, fields
[26].GetFloat(), fields
[27].GetFloat(), fields
[28].GetFloat(), fields
[29].GetFloat(), 0, -1);
14890 if( !MaNGOS::IsValidMapCoord(
14891 GetPositionX() + m_movementInfo
.GetTransportPos()->x
, GetPositionY() + m_movementInfo
.GetTransportPos()->y
,
14892 GetPositionZ() + m_movementInfo
.GetTransportPos()->z
, GetOrientation() + m_movementInfo
.GetTransportPos()->o
) ||
14893 // transport size limited
14894 m_movementInfo
.GetTransportPos()->x
> 50 || m_movementInfo
.GetTransportPos()->y
> 50 || m_movementInfo
.GetTransportPos()->z
> 50 )
14896 sLog
.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
14897 guid
, GetPositionX() + m_movementInfo
.GetTransportPos()->x
, GetPositionY() + m_movementInfo
.GetTransportPos()->y
,
14898 GetPositionZ() + m_movementInfo
.GetTransportPos()->z
, GetOrientation() + m_movementInfo
.GetTransportPos()->o
);
14900 RelocateToHomebind();
14902 m_movementInfo
.SetTransportData(0, 0.0f
, 0.0f
, 0.0f
, 0.0f
, 0, -1);
14908 if (transGUID
!= 0)
14910 for (MapManager::TransportSet::const_iterator iter
= sMapMgr
.m_Transports
.begin(); iter
!= sMapMgr
.m_Transports
.end(); ++iter
)
14912 if( (*iter
)->GetGUIDLow() == transGUID
)
14914 MapEntry
const* transMapEntry
= sMapStore
.LookupEntry((*iter
)->GetMapId());
14915 // client without expansion support
14916 if(GetSession()->Expansion() < transMapEntry
->Expansion())
14918 sLog
.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter
)->GetMapId());
14922 m_transport
= *iter
;
14923 m_transport
->AddPassenger(this);
14924 SetLocationMapId(m_transport
->GetMapId());
14931 sLog
.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
14934 RelocateToHomebind();
14936 m_movementInfo
.SetTransportData(0, 0.0f
, 0.0f
, 0.0f
, 0.0f
, 0, -1);
14941 else // not transport case
14943 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(GetMapId());
14944 // client without expansion support
14945 if(GetSession()->Expansion() < mapEntry
->Expansion())
14947 sLog
.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
14948 RelocateToHomebind();
14952 // NOW player must have valid map
14953 // load the player's map here if it's not already loaded
14954 SetMap(sMapMgr
.CreateMap(GetMapId(), this));
14956 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14957 if(GetInstanceId() && !sInstanceSaveMgr
.GetInstanceSave(GetInstanceId()))
14959 AreaTrigger
const* at
= sObjectMgr
.GetMapEntranceTrigger(GetMapId());
14961 Relocate(at
->target_X
, at
->target_Y
, at
->target_Z
, at
->target_Orientation
);
14963 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());
14966 SaveRecallPosition();
14968 time_t now
= time(NULL
);
14969 time_t logoutTime
= time_t(fields
[22].GetUInt64());
14971 // since last logout (in seconds)
14972 uint32 time_diff
= uint32(now
- logoutTime
);
14974 // set value, including drunk invisibility detection
14975 // calculate sobering. after 15 minutes logged out, the player will be sober again
14977 if(time_diff
> 15*MINUTE
)
14980 soberFactor
= 1-time_diff
/(15.0f
*MINUTE
);
14981 uint16 newDrunkenValue
= uint16(soberFactor
*(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFE));
14982 SetDrunkValue(newDrunkenValue
);
14984 m_cinematic
= fields
[18].GetUInt32();
14985 m_Played_time
[PLAYED_TIME_TOTAL
]= fields
[19].GetUInt32();
14986 m_Played_time
[PLAYED_TIME_LEVEL
]= fields
[20].GetUInt32();
14988 m_resetTalentsCost
= fields
[24].GetUInt32();
14989 m_resetTalentsTime
= time_t(fields
[25].GetUInt64());
14991 // reserve some flags
14992 uint32 old_safe_flags
= GetUInt32Value(PLAYER_FLAGS
) & ( PLAYER_FLAGS_HIDE_CLOAK
| PLAYER_FLAGS_HIDE_HELM
);
14994 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
) )
14995 SetUInt32Value(PLAYER_FLAGS
, 0 | old_safe_flags
);
14997 m_taxi
.LoadTaxiMask( fields
[17].GetString() ); // must be before InitTaxiNodesForLevel
14999 uint32 extraflags
= fields
[31].GetUInt32();
15001 m_stableSlots
= fields
[32].GetUInt32();
15002 if(m_stableSlots
> MAX_PET_STABLES
)
15004 sLog
.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES
,uint32(m_stableSlots
));
15005 m_stableSlots
= MAX_PET_STABLES
;
15008 m_atLoginFlags
= fields
[33].GetUInt32();
15011 // Update Honor kills data
15012 m_lastHonorUpdateTime
= logoutTime
;
15013 UpdateHonorFields();
15015 m_deathExpireTime
= (time_t)fields
[36].GetUInt64();
15016 if(m_deathExpireTime
> now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
)
15017 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
-1;
15019 std::string taxi_nodes
= fields
[37].GetCppString();
15021 // clear channel spell data (if saved at channel spell casting)
15022 SetChannelObjectGUID(0);
15023 SetUInt32Value(UNIT_CHANNEL_SPELL
,0);
15025 // clear charm/summon related fields
15029 SetChannelObjectGUID(0);
15034 // reset some aura modifiers before aura apply
15035 SetFarSightGUID(0);
15036 SetUInt32Value(PLAYER_TRACK_CREATURES
, 0 );
15037 SetUInt32Value(PLAYER_TRACK_RESOURCES
, 0 );
15039 // cleanup aura list explicitly before skill load wher some spells can be applied
15042 // make sure the unit is considered out of combat for proper loading
15045 // make sure the unit is considered not in duel for proper loading
15046 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
15047 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
15049 // reset stats before loading any modifiers
15050 InitStatsForLevel();
15051 InitGlyphsForLevel();
15052 InitTaxiNodesForLevel();
15055 // rest bonus can only be calculated after InitStatsForLevel()
15056 m_rest_bonus
= fields
[21].GetFloat();
15060 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
15061 float bubble0
= 0.031f
;
15062 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
15063 float bubble1
= 0.125f
;
15064 float bubble
= fields
[23].GetUInt32() > 0
15065 ? bubble1
*sWorld
.getConfig(CONFIG_FLOAT_RATE_REST_OFFLINE_IN_TAVERN_OR_CITY
)
15066 : bubble0
*sWorld
.getConfig(CONFIG_FLOAT_RATE_REST_OFFLINE_IN_WILDERNESS
);
15068 SetRestBonus(GetRestBonus()+ time_diff
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
15071 // load skills after InitStatsForLevel because it triggering aura apply also
15072 _LoadSkills(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSKILLS
));
15074 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
15077 _LoadMails(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILS
));
15078 _LoadMailedItems(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILEDITEMS
));
15079 UpdateNextMailTimeAndUnreads();
15081 m_specsCount
= fields
[58].GetUInt8();
15082 m_activeSpec
= fields
[59].GetUInt8();
15084 _LoadGlyphs(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADGLYPHS
));
15086 _LoadAuras(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS
), time_diff
);
15089 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
15090 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
15091 m_deathState
= DEAD
;
15093 _LoadSpells(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS
));
15095 // after spell load, learn rewarded spell if need also
15096 _LoadQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS
));
15097 _LoadDailyQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS
));
15099 // after spell and quest load
15100 InitTalentForLevel();
15101 learnDefaultSpells();
15103 // must be before inventory (some items required reputation check)
15104 m_reputationMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION
));
15106 _LoadInventory(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY
), time_diff
);
15108 // update items with duration and realtime
15109 UpdateItemDuration(time_diff
, true);
15111 _LoadActions(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS
));
15113 m_social
= sSocialMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST
), GetGUIDLow());
15115 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
15116 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
15117 uint32 curTitle
= fields
[46].GetUInt32();
15118 if (curTitle
&& !HasTitle(curTitle
))
15121 SetUInt32Value(PLAYER_CHOSEN_TITLE
, curTitle
);
15123 // Not finish taxi flight path
15124 if(m_bgData
.HasTaxiPath())
15126 m_taxi
.ClearTaxiDestinations();
15127 for (int i
= 0; i
< 2; ++i
)
15128 m_taxi
.AddTaxiDestination(m_bgData
.taxiPath
[i
]);
15130 else if(!m_taxi
.LoadTaxiDestinationsFromString(taxi_nodes
,GetTeam()))
15132 // problems with taxi path loading
15133 TaxiNodesEntry
const* nodeEntry
= NULL
;
15134 if(uint32 node_id
= m_taxi
.GetTaxiSource())
15135 nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
15137 if(!nodeEntry
) // don't know taxi start node, to homebind
15139 sLog
.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
15140 RelocateToHomebind();
15142 else // have start node, to it
15144 sLog
.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
15145 SetLocationMapId(nodeEntry
->map_id
);
15146 Relocate(nodeEntry
->x
, nodeEntry
->y
, nodeEntry
->z
,0.0f
);
15149 //we can be relocated from taxi and still have an outdated Map pointer!
15150 //so we need to get a new Map pointer!
15151 SetMap(sMapMgr
.CreateMap(GetMapId(), this));
15152 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
15154 m_taxi
.ClearTaxiDestinations();
15157 if(uint32 node_id
= m_taxi
.GetTaxiSource())
15159 // save source node as recall coord to prevent recall and fall from sky
15160 TaxiNodesEntry
const* nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
15161 ASSERT(nodeEntry
); // checked in m_taxi.LoadTaxiDestinationsFromString
15162 m_recallMap
= nodeEntry
->map_id
;
15163 m_recallX
= nodeEntry
->x
;
15164 m_recallY
= nodeEntry
->y
;
15165 m_recallZ
= nodeEntry
->z
;
15167 // flight will started later
15170 // has to be called after last Relocate() in Player::LoadFromDB
15171 SetFallInformation(0, GetPositionZ());
15173 _LoadSpellCooldowns(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS
));
15175 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
15176 // Do now before stats re-calculation cleanup for ghost state unexpected auras
15178 RemoveAllAurasOnDeath();
15180 //apply all stat bonuses from items and auras
15181 SetCanModifyStats(true);
15184 // restore remembered power/health values (but not more max values)
15185 uint32 savedhealth
= fields
[50].GetUInt32();
15186 SetHealth(savedhealth
> GetMaxHealth() ? GetMaxHealth() : savedhealth
);
15187 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
15189 uint32 savedpower
= fields
[51+i
].GetUInt32();
15190 SetPower(Powers(i
),savedpower
> GetMaxPower(Powers(i
)) ? GetMaxPower(Powers(i
)) : savedpower
);
15193 sLog
.outDebug("The value of player %s after load item and aura is: ", m_name
.c_str());
15200 if(GetSession()->GetSecurity() > SEC_PLAYER
)
15202 switch(sWorld
.getConfig(CONFIG_UINT32_GM_LOGIN_STATE
))
15205 case 0: break; // disable
15206 case 1: SetGameMaster(true); break; // enable
15207 case 2: // save state
15208 if(extraflags
& PLAYER_EXTRA_GM_ON
)
15209 SetGameMaster(true);
15213 switch(sWorld
.getConfig(CONFIG_UINT32_GM_VISIBLE_STATE
))
15216 case 0: SetGMVisible(false); break; // invisible
15217 case 1: break; // visible
15218 case 2: // save state
15219 if(extraflags
& PLAYER_EXTRA_GM_INVISIBLE
)
15220 SetGMVisible(false);
15224 switch(sWorld
.getConfig(CONFIG_UINT32_GM_ACCEPT_TICKETS
))
15227 case 0: break; // disable
15228 case 1: SetAcceptTicket(true); break; // enable
15229 case 2: // save state
15230 if(extraflags
& PLAYER_EXTRA_GM_ACCEPT_TICKETS
)
15231 SetAcceptTicket(true);
15235 switch(sWorld
.getConfig(CONFIG_UINT32_GM_CHAT
))
15238 case 0: break; // disable
15239 case 1: SetGMChat(true); break; // enable
15240 case 2: // save state
15241 if(extraflags
& PLAYER_EXTRA_GM_CHAT
)
15246 switch(sWorld
.getConfig(CONFIG_UINT32_GM_WISPERING_TO
))
15249 case 0: break; // disable
15250 case 1: SetAcceptWhispers(true); break; // enable
15251 case 2: // save state
15252 if(extraflags
& PLAYER_EXTRA_ACCEPT_WHISPERS
)
15253 SetAcceptWhispers(true);
15258 _LoadDeclinedNames(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES
));
15260 m_achievementMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS
), holder
->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS
));
15261 m_achievementMgr
.CheckAllAchievementCriteria();
15263 _LoadEquipmentSets(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS
));
15268 bool Player::isAllowedToLoot(Creature
* creature
)
15270 if(Player
* recipient
= creature
->GetLootRecipient())
15272 if (recipient
== this)
15274 if( Group
* otherGroup
= recipient
->GetGroup())
15276 Group
* thisGroup
= GetGroup();
15279 return thisGroup
== otherGroup
;
15284 // prevent other players from looting if the recipient got disconnected
15285 return !creature
->hasLootRecipient();
15288 void Player::_LoadActions(QueryResult
*result
)
15290 for(int i
= 0; i
< MAX_TALENT_SPEC_COUNT
; ++i
)
15291 m_actionButtons
[i
].clear();
15293 //QueryResult *result = CharacterDatabase.PQuery("SELECT spec, button,action,type FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
15299 Field
*fields
= result
->Fetch();
15301 uint8 spec
= fields
[0].GetUInt8();
15302 uint8 button
= fields
[1].GetUInt8();
15303 uint32 action
= fields
[2].GetUInt32();
15304 uint8 type
= fields
[3].GetUInt8();
15306 if(ActionButton
* ab
= addActionButton(spec
, button
, action
, type
))
15307 ab
->uState
= ACTIONBUTTON_UNCHANGED
;
15310 sLog
.outError( " ...at loading, and will deleted in DB also");
15312 // Will deleted in DB at next save (it can create data until save but marked as deleted)
15313 m_actionButtons
[spec
][button
].uState
= ACTIONBUTTON_DELETED
;
15316 while( result
->NextRow() );
15322 void Player::_LoadAuras(QueryResult
*result
, uint32 timediff
)
15324 //RemoveAllAuras(); -- some spells casted before aura load, for example in LoadSkills, aura list explcitly cleaned early
15326 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15332 Field
*fields
= result
->Fetch();
15333 uint64 caster_guid
= fields
[0].GetUInt64();
15334 uint32 spellid
= fields
[1].GetUInt32();
15335 SpellEffectIndex effindex
= SpellEffectIndex(fields
[2].GetUInt32());
15336 uint32 stackcount
= fields
[3].GetUInt32();
15337 int32 damage
= fields
[4].GetInt32();
15338 int32 maxduration
= fields
[5].GetInt32();
15339 int32 remaintime
= fields
[6].GetInt32();
15340 int32 remaincharges
= fields
[7].GetInt32();
15342 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellid
);
15345 sLog
.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid
,effindex
);
15349 if (effindex
>= MAX_EFFECT_INDEX
)
15351 sLog
.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid
,effindex
);
15355 // negative effects should continue counting down after logout
15356 if (remaintime
!= -1 && !IsPositiveEffect(spellid
, effindex
))
15358 if (remaintime
/IN_MILLISECONDS
<= int32(timediff
))
15361 remaintime
-= timediff
*IN_MILLISECONDS
;
15364 // prevent wrong values of remaincharges
15365 if (spellproto
->procCharges
)
15367 if (remaincharges
<= 0 || remaincharges
> (int32
)spellproto
->procCharges
)
15368 remaincharges
= spellproto
->procCharges
;
15374 for(uint32 i
= 0; i
< stackcount
; ++i
)
15376 Aura
* aura
= CreateAura(spellproto
, effindex
, NULL
, this, NULL
);
15378 damage
= aura
->GetModifier()->m_amount
;
15380 // reset stolen single target auras
15381 if (caster_guid
!= GetGUID() && aura
->IsSingleTarget())
15382 aura
->SetIsSingleTarget(false);
15384 aura
->SetLoadedState(caster_guid
,damage
,maxduration
,remaintime
,remaincharges
);
15386 sLog
.outDetail("Added aura spellid %u, effect %u", spellproto
->Id
, effindex
);
15389 while( result
->NextRow() );
15394 if(getClass() == CLASS_WARRIOR
&& !HasAuraType(SPELL_AURA_MOD_SHAPESHIFT
))
15395 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
15398 void Player::_LoadGlyphs(QueryResult
*result
)
15404 // "SELECT spec, slot, glyph FROM character_glyphs WHERE guid='%u'"
15408 Field
*fields
= result
->Fetch();
15409 uint8 spec
= fields
[0].GetUInt8();
15410 uint8 slot
= fields
[1].GetUInt8();
15411 uint32 glyph
= fields
[2].GetUInt32();
15413 GlyphPropertiesEntry
const *gp
= sGlyphPropertiesStore
.LookupEntry(glyph
);
15416 sLog
.outError("Player %s has not existing glyph entry %u on index %u, spec %u", m_name
.c_str(), glyph
, slot
, spec
);
15420 GlyphSlotEntry
const *gs
= sGlyphSlotStore
.LookupEntry(GetGlyphSlot(slot
));
15423 sLog
.outError("Player %s has not existing glyph slot entry %u on index %u, spec %u", m_name
.c_str(), GetGlyphSlot(slot
), slot
, spec
);
15427 if(gp
->TypeFlags
!= gs
->TypeFlags
)
15429 sLog
.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name
.c_str(), gp
->TypeFlags
, gs
->TypeFlags
);
15433 m_glyphs
[spec
][slot
].id
= glyph
;
15435 } while( result
->NextRow() );
15442 void Player::LoadCorpse()
15446 sObjectAccessor
.ConvertCorpseForPlayer(GetGUID());
15450 if(Corpse
*corpse
= GetCorpse())
15452 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, corpse
&& !sMapStore
.LookupEntry(corpse
->GetMapId())->Instanceable() );
15456 //Prevent Dead Player login without corpse
15457 ResurrectPlayer(0.5f
);
15462 void Player::_LoadInventory(QueryResult
*result
, uint32 timediff
)
15464 //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());
15465 std::map
<uint64
, Bag
*> bagMap
; // fast guid lookup for bags
15466 //NOTE: the "order by `bag`" is important because it makes sure
15467 //the bagMap is filled before items in the bags are loaded
15468 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
15469 //expected to be equipped before offhand items (TODO: fixme)
15471 uint32 zone
= GetZoneId();
15475 std::list
<Item
*> problematicItems
;
15477 // prevent items from being added to the queue when stored
15478 m_itemUpdateQueueBlocked
= true;
15481 Field
*fields
= result
->Fetch();
15482 uint32 bag_guid
= fields
[1].GetUInt32();
15483 uint8 slot
= fields
[2].GetUInt8();
15484 uint32 item_guid
= fields
[3].GetUInt32();
15485 uint32 item_id
= fields
[4].GetUInt32();
15487 ItemPrototype
const * proto
= ObjectMgr::GetItemPrototype(item_id
);
15491 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
15492 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid
);
15493 sLog
.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id
);
15497 Item
*item
= NewItemOrBag(proto
);
15499 if(!item
->LoadFromDB(item_guid
, GetGUID(), result
))
15501 sLog
.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id
);
15502 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
15503 item
->FSetState(ITEM_REMOVED
);
15504 item
->SaveToDB(); // it also deletes item object !
15508 // not allow have in alive state item limited to another map/zone
15509 if(isAlive() && item
->IsLimitedToAnotherMapOrZone(GetMapId(),zone
) )
15511 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
15512 item
->FSetState(ITEM_REMOVED
);
15513 item
->SaveToDB(); // it also deletes item object !
15517 // "Conjured items disappear if you are logged out for more than 15 minutes"
15518 if (timediff
> 15*MINUTE
&& item
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_CONJURED
))
15520 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
15521 item
->FSetState(ITEM_REMOVED
);
15522 item
->SaveToDB(); // it also deletes item object !
15526 bool success
= true;
15528 // the item/bag is not in a bag
15531 item
->SetContainer( NULL
);
15532 item
->SetSlot(slot
);
15534 if( IsInventoryPos( INVENTORY_SLOT_BAG_0
, slot
) )
15536 ItemPosCountVec dest
;
15537 if( CanStoreItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false ) == EQUIP_ERR_OK
)
15538 item
= StoreItem(dest
, item
, true);
15542 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0
, slot
) )
15545 if( CanEquipItem( slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
15546 QuickEquipItem(dest
, item
);
15550 else if( IsBankPos( INVENTORY_SLOT_BAG_0
, slot
) )
15552 ItemPosCountVec dest
;
15553 if( CanBankItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
15554 item
= BankItem(dest
, item
, true);
15561 // store bags that may contain items in them
15562 if(item
->IsBag() && IsBagPos(item
->GetPos()))
15563 bagMap
[item_guid
] = (Bag
*)item
;
15566 // the item/bag in a bag
15569 item
->SetSlot(NULL_SLOT
);
15570 // the item is in a bag, find the bag
15571 std::map
<uint64
, Bag
*>::const_iterator itr
= bagMap
.find(bag_guid
);
15572 if(itr
!= bagMap
.end() && slot
< itr
->second
->GetBagSize())
15574 ItemPosCountVec dest
;
15575 if( CanStoreItem( itr
->second
->GetSlot(), slot
, dest
, item
, false ) == EQUIP_ERR_OK
)
15576 item
= StoreItem(dest
, item
, true);
15584 // item's state may have changed after stored
15587 item
->SetState(ITEM_UNCHANGED
, this);
15589 // recharged mana gem
15590 if (timediff
> 15*MINUTE
&& proto
->ItemLimitCategory
==ITEM_LIMIT_CATEGORY_MANA_GEM
)
15591 item
->RestoreCharges();
15595 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
);
15596 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
15597 problematicItems
.push_back(item
);
15599 } while (result
->NextRow());
15602 m_itemUpdateQueueBlocked
= false;
15604 // send by mail problematic items
15605 while(!problematicItems
.empty())
15607 std::string subject
= GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM
);
15610 MailDraft
draft(subject
);
15612 for(int i
= 0; !problematicItems
.empty() && i
< MAX_MAIL_ITEMS
; ++i
)
15614 Item
* item
= problematicItems
.front();
15615 problematicItems
.pop_front();
15617 draft
.AddItem(item
);
15620 draft
.SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM
));
15624 _ApplyAllItemMods();
15627 // load mailed item which should receive current player
15628 void Player::_LoadMailedItems(QueryResult
*result
)
15630 // data needs to be at first place for Item::LoadFromDB
15632 // "SELECT data, mail_id, item_guid, item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE receiver = '%u'", GUID_LOPART(m_guid)
15638 Field
*fields
= result
->Fetch();
15639 uint32 mail_id
= fields
[1].GetUInt32();
15640 uint32 item_guid_low
= fields
[2].GetUInt32();
15641 uint32 item_template
= fields
[3].GetUInt32();
15643 Mail
* mail
= GetMail(mail_id
);
15646 mail
->AddItem(item_guid_low
, item_template
);
15648 ItemPrototype
const *proto
= ObjectMgr::GetItemPrototype(item_template
);
15652 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
);
15653 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
15654 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low
);
15658 Item
*item
= NewItemOrBag(proto
);
15660 if(!item
->LoadFromDB(item_guid_low
, 0, result
))
15662 sLog
.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail
->messageID
, item_guid_low
);
15663 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
15664 item
->FSetState(ITEM_REMOVED
);
15665 item
->SaveToDB(); // it also deletes item object !
15670 } while (result
->NextRow());
15675 void Player::_LoadMails(QueryResult
*result
)
15678 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13
15679 //"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()
15685 Field
*fields
= result
->Fetch();
15686 Mail
*m
= new Mail
;
15687 m
->messageID
= fields
[0].GetUInt32();
15688 m
->messageType
= fields
[1].GetUInt8();
15689 m
->sender
= fields
[2].GetUInt32();
15690 m
->receiver
= fields
[3].GetUInt32();
15691 m
->subject
= fields
[4].GetCppString();
15692 m
->itemTextId
= fields
[5].GetUInt32();
15693 bool has_items
= fields
[6].GetBool();
15694 m
->expire_time
= (time_t)fields
[7].GetUInt64();
15695 m
->deliver_time
= (time_t)fields
[8].GetUInt64();
15696 m
->money
= fields
[9].GetUInt32();
15697 m
->COD
= fields
[10].GetUInt32();
15698 m
->checked
= fields
[11].GetUInt32();
15699 m
->stationery
= fields
[12].GetUInt8();
15700 m
->mailTemplateId
= fields
[13].GetInt16();
15702 if(m
->mailTemplateId
&& !sMailTemplateStore
.LookupEntry(m
->mailTemplateId
))
15704 sLog
.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m
->messageID
, m
->mailTemplateId
);
15705 m
->mailTemplateId
= 0;
15708 m
->state
= MAIL_STATE_UNCHANGED
;
15710 m_mail
.push_back(m
);
15711 } while( result
->NextRow() );
15715 void Player::LoadPet()
15717 //fixme: the pet should still be loaded if the player is not in world
15718 // just not added to the map
15721 Pet
*pet
= new Pet
;
15722 if(!pet
->LoadPetFromDB(this,0,0,true))
15727 void Player::_LoadQuestStatus(QueryResult
*result
)
15729 mQuestStatus
.clear();
15733 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
15734 //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());
15740 Field
*fields
= result
->Fetch();
15742 uint32 quest_id
= fields
[0].GetUInt32();
15743 // used to be new, no delete?
15744 Quest
const* pQuest
= sObjectMgr
.GetQuestTemplate(quest_id
);
15748 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
15750 uint32 qstatus
= fields
[1].GetUInt32();
15751 if(qstatus
< MAX_QUEST_STATUS
)
15752 questStatusData
.m_status
= QuestStatus(qstatus
);
15755 questStatusData
.m_status
= QUEST_STATUS_NONE
;
15756 sLog
.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id
,qstatus
);
15759 questStatusData
.m_rewarded
= ( fields
[2].GetUInt8() > 0 );
15760 questStatusData
.m_explored
= ( fields
[3].GetUInt8() > 0 );
15762 time_t quest_time
= time_t(fields
[4].GetUInt64());
15764 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && !GetQuestRewardStatus(quest_id
) && questStatusData
.m_status
!= QUEST_STATUS_NONE
)
15766 AddTimedQuest( quest_id
);
15768 if (quest_time
<= sWorld
.GetGameTime())
15769 questStatusData
.m_timer
= 1;
15771 questStatusData
.m_timer
= uint32(quest_time
- sWorld
.GetGameTime()) * IN_MILLISECONDS
;
15776 questStatusData
.m_creatureOrGOcount
[0] = fields
[5].GetUInt32();
15777 questStatusData
.m_creatureOrGOcount
[1] = fields
[6].GetUInt32();
15778 questStatusData
.m_creatureOrGOcount
[2] = fields
[7].GetUInt32();
15779 questStatusData
.m_creatureOrGOcount
[3] = fields
[8].GetUInt32();
15780 questStatusData
.m_itemcount
[0] = fields
[9].GetUInt32();
15781 questStatusData
.m_itemcount
[1] = fields
[10].GetUInt32();
15782 questStatusData
.m_itemcount
[2] = fields
[11].GetUInt32();
15783 questStatusData
.m_itemcount
[3] = fields
[12].GetUInt32();
15785 questStatusData
.uState
= QUEST_UNCHANGED
;
15787 // add to quest log
15788 if (slot
< MAX_QUEST_LOG_SIZE
&&
15789 ((questStatusData
.m_status
== QUEST_STATUS_INCOMPLETE
||
15790 questStatusData
.m_status
== QUEST_STATUS_COMPLETE
||
15791 questStatusData
.m_status
== QUEST_STATUS_FAILED
) &&
15792 (!questStatusData
.m_rewarded
|| pQuest
->IsRepeatable())))
15794 SetQuestSlot(slot
, quest_id
, uint32(quest_time
));
15796 if (questStatusData
.m_status
== QUEST_STATUS_COMPLETE
)
15797 SetQuestSlotState(slot
, QUEST_STATE_COMPLETE
);
15799 if (questStatusData
.m_status
== QUEST_STATUS_FAILED
)
15800 SetQuestSlotState(slot
, QUEST_STATE_FAIL
);
15802 for(uint8 idx
= 0; idx
< QUEST_OBJECTIVES_COUNT
; ++idx
)
15803 if(questStatusData
.m_creatureOrGOcount
[idx
])
15804 SetQuestSlotCounter(slot
, idx
, questStatusData
.m_creatureOrGOcount
[idx
]);
15809 if(questStatusData
.m_rewarded
)
15811 // learn rewarded spell if unknown
15812 learnQuestRewardedSpells(pQuest
);
15814 // set rewarded title if any
15815 if(pQuest
->GetCharTitleId())
15817 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
15818 SetTitle(titleEntry
);
15821 if(pQuest
->GetBonusTalents())
15822 m_questRewardTalentCount
+= pQuest
->GetBonusTalents();
15825 sLog
.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData
.m_status
, quest_id
, GetGUIDLow());
15828 while( result
->NextRow() );
15833 // clear quest log tail
15834 for ( uint16 i
= slot
; i
< MAX_QUEST_LOG_SIZE
; ++i
)
15835 SetQuestSlot(i
, 0);
15838 void Player::_LoadDailyQuestStatus(QueryResult
*result
)
15840 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
15841 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
15843 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
15847 uint32 quest_daily_idx
= 0;
15851 if(quest_daily_idx
>= PLAYER_MAX_DAILY_QUESTS
) // max amount with exist data in query
15853 sLog
.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15857 Field
*fields
= result
->Fetch();
15859 uint32 quest_id
= fields
[0].GetUInt32();
15861 // save _any_ from daily quest times (it must be after last reset anyway)
15862 m_lastDailyQuestTime
= (time_t)fields
[1].GetUInt64();
15864 Quest
const* pQuest
= sObjectMgr
.GetQuestTemplate(quest_id
);
15868 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
15871 sLog
.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id
, GetGUIDLow());
15873 while( result
->NextRow() );
15878 m_DailyQuestChanged
= false;
15881 void Player::_LoadSpells(QueryResult
*result
)
15883 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
15889 Field
*fields
= result
->Fetch();
15891 uint32 spell_id
= fields
[0].GetUInt32();
15893 addSpell(spell_id
, fields
[1].GetBool(), false, false, fields
[2].GetBool());
15895 while( result
->NextRow() );
15901 void Player::_LoadGroup(QueryResult
*result
)
15903 //QueryResult *result = CharacterDatabase.PQuery("SELECT groupId FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
15906 uint32 groupId
= (*result
)[0].GetUInt32();
15909 if (Group
* group
= sObjectMgr
.GetGroupById(groupId
))
15911 uint8 subgroup
= group
->GetMemberGroup(GetGUID());
15912 SetGroup(group
, subgroup
);
15913 if (getLevel() >= LEVELREQUIREMENT_HEROIC
)
15915 // the group leader may change the instance difficulty while the player is offline
15916 SetDungeonDifficulty(group
->GetDungeonDifficulty());
15917 SetRaidDifficulty(group
->GetRaidDifficulty());
15923 void Player::_LoadBoundInstances(QueryResult
*result
)
15925 for(uint8 i
= 0; i
< MAX_DIFFICULTY
; ++i
)
15926 m_boundInstances
[i
].clear();
15928 Group
*group
= GetGroup();
15930 //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));
15935 Field
*fields
= result
->Fetch();
15936 bool perm
= fields
[1].GetBool();
15937 uint32 mapId
= fields
[2].GetUInt32();
15938 uint32 instanceId
= fields
[0].GetUInt32();
15939 uint8 difficulty
= fields
[3].GetUInt8();
15941 time_t resetTime
= (time_t)fields
[4].GetUInt64();
15942 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15943 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15944 // and in that case it is not used
15946 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(mapId
);
15947 if(!mapEntry
|| !mapEntry
->IsDungeon())
15949 sLog
.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId
);
15950 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
15954 if(difficulty
>= MAX_DIFFICULTY
)
15956 sLog
.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty
, mapId
);
15957 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
15961 MapDifficulty
const* mapDiff
= GetMapDifficultyData(mapId
,Difficulty(difficulty
));
15964 sLog
.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty
, mapId
);
15965 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
15971 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
);
15972 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
15976 // since non permanent binds are always solo bind, they can always be reset
15977 InstanceSave
*save
= sInstanceSaveMgr
.AddInstanceSave(mapId
, instanceId
, Difficulty(difficulty
), resetTime
, !perm
, true);
15978 if(save
) BindToInstance(save
, perm
, true);
15979 } while(result
->NextRow());
15984 InstancePlayerBind
* Player::GetBoundInstance(uint32 mapid
, Difficulty difficulty
)
15986 // some instances only have one difficulty
15987 MapDifficulty
const* mapDiff
= GetMapDifficultyData(mapid
,difficulty
);
15991 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
15992 if(itr
!= m_boundInstances
[difficulty
].end())
15993 return &itr
->second
;
15998 void Player::UnbindInstance(uint32 mapid
, Difficulty difficulty
, bool unload
)
16000 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
16001 UnbindInstance(itr
, difficulty
, unload
);
16004 void Player::UnbindInstance(BoundInstancesMap::iterator
&itr
, Difficulty difficulty
, bool unload
)
16006 if(itr
!= m_boundInstances
[difficulty
].end())
16008 if(!unload
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr
->second
.save
->GetInstanceId());
16009 itr
->second
.save
->RemovePlayer(this); // save can become invalid
16010 m_boundInstances
[difficulty
].erase(itr
++);
16014 InstancePlayerBind
* Player::BindToInstance(InstanceSave
*save
, bool permanent
, bool load
)
16018 InstancePlayerBind
& bind
= m_boundInstances
[save
->GetDifficulty()][save
->GetMapId()];
16021 // update the save when the group kills a boss
16022 if(permanent
!= bind
.perm
|| save
!= bind
.save
)
16023 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());
16026 if(!load
) CharacterDatabase
.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save
->GetInstanceId(), permanent
);
16028 if(bind
.save
!= save
)
16030 if(bind
.save
) bind
.save
->RemovePlayer(this);
16031 save
->AddPlayer(this);
16034 if(permanent
) save
->SetCanReset(false);
16037 bind
.perm
= permanent
;
16038 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());
16045 void Player::SendRaidInfo()
16047 uint32 counter
= 0;
16049 WorldPacket
data(SMSG_RAID_INSTANCE_INFO
, 4);
16051 size_t p_counter
= data
.wpos();
16052 data
<< uint32(counter
); // placeholder
16054 time_t now
= time(NULL
);
16056 for(int i
= 0; i
< MAX_DIFFICULTY
; ++i
)
16058 for (BoundInstancesMap::const_iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
16060 if(itr
->second
.perm
)
16062 InstanceSave
*save
= itr
->second
.save
;
16063 data
<< uint32(save
->GetMapId()); // map id
16064 data
<< uint32(save
->GetDifficulty()); // difficulty
16065 data
<< uint64(save
->GetInstanceId()); // instance id
16066 data
<< uint8(1); // expired = 0
16067 data
<< uint8(0); // extended = 1
16068 data
<< uint32(save
->GetResetTime() - now
); // reset time
16073 data
.put
<uint32
>(p_counter
, counter
);
16074 GetSession()->SendPacket(&data
);
16078 - called on every successful teleportation to a map
16080 void Player::SendSavedInstances()
16082 bool hasBeenSaved
= false;
16085 for(uint8 i
= 0; i
< MAX_DIFFICULTY
; ++i
)
16087 for (BoundInstancesMap::const_iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
16089 if(itr
->second
.perm
) // only permanent binds are sent
16091 hasBeenSaved
= true;
16097 //Send opcode 811. true or false means, whether you have current raid/heroic instances
16098 data
.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP
);
16099 data
<< uint32(hasBeenSaved
);
16100 GetSession()->SendPacket(&data
);
16105 for(uint8 i
= 0; i
< MAX_DIFFICULTY
; ++i
)
16107 for (BoundInstancesMap::const_iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
16109 if(itr
->second
.perm
)
16111 data
.Initialize(SMSG_UPDATE_LAST_INSTANCE
);
16112 data
<< uint32(itr
->second
.save
->GetMapId());
16113 GetSession()->SendPacket(&data
);
16119 /// convert the player's binds to the group
16120 void Player::ConvertInstancesToGroup(Player
*player
, Group
*group
, uint64 player_guid
)
16122 bool has_binds
= false;
16123 bool has_solo
= false;
16125 if(player
) { player_guid
= player
->GetGUID(); if(!group
) group
= player
->GetGroup(); }
16126 ASSERT(player_guid
);
16128 // copy all binds to the group, when changing leader it's assumed the character
16129 // will not have any solo binds
16133 for(uint8 i
= 0; i
< MAX_DIFFICULTY
; ++i
)
16135 for (BoundInstancesMap::iterator itr
= player
->m_boundInstances
[i
].begin(); itr
!= player
->m_boundInstances
[i
].end();)
16138 if(group
) group
->BindToInstance(itr
->second
.save
, itr
->second
.perm
, true);
16139 // permanent binds are not removed
16140 if(!itr
->second
.perm
)
16142 // increments itr in call
16143 player
->UnbindInstance(itr
, Difficulty(i
), true);
16152 // if the player's not online we don't know what binds it has
16153 if(!player
|| !group
|| has_binds
)
16154 CharacterDatabase
.PExecute("INSERT INTO group_instance SELECT guid, instance, permanent FROM character_instance WHERE guid = '%u'", GUID_LOPART(player_guid
));
16156 // the following should not get executed when changing leaders
16157 if(!player
|| has_solo
)
16158 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid
));
16161 bool Player::_LoadHomeBind(QueryResult
*result
)
16163 PlayerInfo
const *info
= sObjectMgr
.GetPlayerInfo(getRace(), getClass());
16166 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
16171 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
16174 Field
*fields
= result
->Fetch();
16175 m_homebindMapId
= fields
[0].GetUInt32();
16176 m_homebindAreaId
= fields
[1].GetUInt16();
16177 m_homebindX
= fields
[2].GetFloat();
16178 m_homebindY
= fields
[3].GetFloat();
16179 m_homebindZ
= fields
[4].GetFloat();
16182 MapEntry
const* bindMapEntry
= sMapStore
.LookupEntry(m_homebindMapId
);
16184 // accept saved data only for valid position (and non instanceable), and accessable
16185 if( MapManager::IsValidMapCoord(m_homebindMapId
,m_homebindX
,m_homebindY
,m_homebindZ
) &&
16186 !bindMapEntry
->Instanceable() && GetSession()->Expansion() >= bindMapEntry
->Expansion())
16191 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
16196 m_homebindMapId
= info
->mapId
;
16197 m_homebindAreaId
= info
->areaId
;
16198 m_homebindX
= info
->positionX
;
16199 m_homebindY
= info
->positionY
;
16200 m_homebindZ
= info
->positionZ
;
16202 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_homebindAreaId
, m_homebindX
, m_homebindY
, m_homebindZ
);
16205 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
16206 m_homebindMapId
, m_homebindAreaId
, m_homebindX
, m_homebindY
, m_homebindZ
);
16211 /*********************************************************/
16212 /*** SAVE SYSTEM ***/
16213 /*********************************************************/
16215 void Player::SaveToDB()
16217 // we should assure this: ASSERT((m_nextSave != sWorld.getConfig(CONFIG_UINT32_INTERVAL_SAVE)));
16218 // delay auto save at any saves (manual, in code, or autosave)
16219 m_nextSave
= sWorld
.getConfig(CONFIG_UINT32_INTERVAL_SAVE
);
16221 //lets allow only players in world to be saved
16222 if(IsBeingTeleportedFar())
16224 ScheduleDelayedOperation(DELAYED_SAVE_PLAYER
);
16228 // first save/honor gain after midnight will also update the player's honor fields
16229 UpdateHonorFields();
16231 sLog
.outDebug("The value of player %s at save: ", m_name
.c_str());
16234 CharacterDatabase
.BeginTransaction();
16236 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
16238 std::string sql_name
= m_name
;
16239 CharacterDatabase
.escape_string(sql_name
);
16241 std::ostringstream ss
;
16242 ss
<< "INSERT INTO characters (guid,account,name,race,class,gender,level,xp,money,playerBytes,playerBytes2,playerFlags,"
16243 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, "
16244 "taximask, online, cinematic, "
16245 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
16246 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
16247 "death_expire_time, taxi_path, arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, "
16248 "todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk, health, power1, power2, power3, "
16249 "power4, power5, power6, power7, specCount, activeSpec, exploredZones, equipmentCache, ammoId, knownTitles, actionBars) VALUES ("
16250 << GetGUIDLow() << ", "
16251 << GetSession()->GetAccountId() << ", '"
16252 << sql_name
<< "', "
16253 << (uint32
)getRace() << ", "
16254 << (uint32
)getClass() << ", "
16255 << (uint32
)getGender() << ", "
16256 << getLevel() << ", "
16257 << GetUInt32Value(PLAYER_XP
) << ", "
16258 << GetMoney() << ", "
16259 << GetUInt32Value(PLAYER_BYTES
) << ", "
16260 << GetUInt32Value(PLAYER_BYTES_2
) << ", "
16261 << GetUInt32Value(PLAYER_FLAGS
) << ", ";
16263 if(!IsBeingTeleported())
16265 ss
<< GetMapId() << ", "
16266 << (uint32
)GetDungeonDifficulty() << ", "
16267 << finiteAlways(GetPositionX()) << ", "
16268 << finiteAlways(GetPositionY()) << ", "
16269 << finiteAlways(GetPositionZ()) << ", "
16270 << finiteAlways(GetOrientation()) << ", ";
16274 ss
<< GetTeleportDest().mapid
<< ", "
16275 << (uint32
)GetDungeonDifficulty() << ", "
16276 << finiteAlways(GetTeleportDest().coord_x
) << ", "
16277 << finiteAlways(GetTeleportDest().coord_y
) << ", "
16278 << finiteAlways(GetTeleportDest().coord_z
) << ", "
16279 << finiteAlways(GetTeleportDest().orientation
) << ", ";
16282 ss
<< m_taxi
<< ", "; // string with TaxiMaskSize numbers
16284 ss
<< (IsInWorld() ? 1 : 0) << ", ";
16286 ss
<< m_cinematic
<< ", ";
16288 ss
<< m_Played_time
[PLAYED_TIME_TOTAL
] << ", ";
16289 ss
<< m_Played_time
[PLAYED_TIME_LEVEL
] << ", ";
16291 ss
<< finiteAlways(m_rest_bonus
) << ", ";
16292 ss
<< (uint64
)time(NULL
) << ", ";
16293 ss
<< (HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
) ? 1 : 0) << ", ";
16294 //save, far from tavern/city
16295 //save, but in tavern/city
16296 ss
<< m_resetTalentsCost
<< ", ";
16297 ss
<< (uint64
)m_resetTalentsTime
<< ", ";
16299 ss
<< finiteAlways(m_movementInfo
.GetTransportPos()->x
) << ", ";
16300 ss
<< finiteAlways(m_movementInfo
.GetTransportPos()->y
) << ", ";
16301 ss
<< finiteAlways(m_movementInfo
.GetTransportPos()->z
) << ", ";
16302 ss
<< finiteAlways(m_movementInfo
.GetTransportPos()->o
) << ", ";
16304 ss
<< m_transport
->GetGUIDLow();
16309 ss
<< m_ExtraFlags
<< ", ";
16311 ss
<< uint32(m_stableSlots
) << ", "; // to prevent save uint8 as char
16313 ss
<< uint32(m_atLoginFlags
) << ", ";
16315 ss
<< GetZoneId() << ", ";
16317 ss
<< (uint64
)m_deathExpireTime
<< ", '";
16319 ss
<< m_taxi
.SaveTaxiDestinationsToString() << "', ";
16321 ss
<< GetArenaPoints() << ", ";
16323 ss
<< GetHonorPoints() << ", ";
16325 ss
<< GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
) << ", ";
16327 ss
<< GetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
) << ", ";
16329 ss
<< GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
) << ", ";
16331 ss
<< GetUInt16Value(PLAYER_FIELD_KILLS
, 0) << ", ";
16333 ss
<< GetUInt16Value(PLAYER_FIELD_KILLS
, 1) << ", ";
16335 ss
<< GetUInt32Value(PLAYER_CHOSEN_TITLE
) << ", ";
16337 ss
<< GetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES
) << ", ";
16339 // FIXME: at this moment send to DB as unsigned, including unit32(-1)
16340 ss
<< GetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX
) << ", ";
16342 ss
<< (uint16
)(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFE) << ", ";
16346 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
16347 ss
<< "," << GetPower(Powers(i
));
16350 ss
<< uint32(m_specsCount
) << ", ";
16351 ss
<< uint32(m_activeSpec
) << ", '";
16352 for(uint32 i
= 0; i
< PLAYER_EXPLORED_ZONES_SIZE
; ++i
)
16354 ss
<< GetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ i
) << " ";
16358 for(uint32 i
= 0; i
< EQUIPMENT_SLOT_END
* 2; ++i
)
16360 ss
<< GetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID
+ i
) << " ";
16364 ss
<< GetUInt32Value(PLAYER_AMMO_ID
) << ", '";
16365 for(uint32 i
= 0; i
< KNOWN_TITLES_SIZE
*2; ++i
)
16367 ss
<< GetUInt32Value(PLAYER__FIELD_KNOWN_TITLES
+ i
) << " ";
16370 ss
<< uint32(GetByteValue(PLAYER_FIELD_BYTES
, 2));
16373 CharacterDatabase
.Execute( ss
.str().c_str() );
16375 if(m_mailsUpdated
) //save mails only when needed
16380 _SaveQuestStatus();
16381 _SaveDailyQuestStatus();
16383 _SaveSpellCooldowns();
16387 m_achievementMgr
.SaveToDB();
16388 m_reputationMgr
.SaveToDB();
16389 _SaveEquipmentSets();
16390 GetSession()->SaveTutorialsData(); // changed only while character in game
16393 CharacterDatabase
.CommitTransaction();
16395 // save pet (hunter pet level and experience and all type pets health/mana).
16396 if(Pet
* pet
= GetPet())
16397 pet
->SavePetToDB(PET_SAVE_AS_CURRENT
);
16400 // fast save function for item/money cheating preventing - save only inventory and money state
16401 void Player::SaveInventoryAndGoldToDB()
16407 void Player::SaveGoldToDB()
16409 CharacterDatabase
.PExecute("UPDATE characters SET money = '%u' WHERE guid = '%u'", GetMoney(), GetGUIDLow());
16412 void Player::_SaveActions()
16414 for(int i
= 0; i
< MAX_TALENT_SPEC_COUNT
; ++i
)
16416 for(ActionButtonList::iterator itr
= m_actionButtons
[i
].begin(); itr
!= m_actionButtons
[i
].end(); )
16418 switch (itr
->second
.uState
)
16420 case ACTIONBUTTON_NEW
:
16421 CharacterDatabase
.PExecute("INSERT INTO character_action (guid,spec, button,action,type) VALUES ('%u', '%u', '%u', '%u', '%u')",
16422 GetGUIDLow(), i
, (uint32
)itr
->first
, (uint32
)itr
->second
.GetAction(), (uint32
)itr
->second
.GetType() );
16423 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
16426 case ACTIONBUTTON_CHANGED
:
16427 CharacterDatabase
.PExecute("UPDATE character_action SET action = '%u', type = '%u' WHERE guid= '%u' AND button= '%u' AND spec = '%u'",
16428 (uint32
)itr
->second
.GetAction(), (uint32
)itr
->second
.GetType(), GetGUIDLow(), (uint32
)itr
->first
, i
);
16429 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
16432 case ACTIONBUTTON_DELETED
:
16433 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u' AND button = '%u' AND spec = '%u'", GetGUIDLow(), (uint32
)itr
->first
, i
);
16434 m_actionButtons
[i
].erase(itr
++);
16444 void Player::_SaveAuras()
16446 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
16448 AuraMap
const& auras
= GetAuras();
16453 spellEffectPair lastEffectPair
= auras
.begin()->first
;
16454 uint32 stackCounter
= 1;
16456 /* copied following sql-code partly from achievementmgr */
16457 bool first_round
= true;
16458 std::ostringstream ss
;
16459 for(AuraMap::const_iterator itr
= auras
.begin(); ; ++itr
)
16461 if(itr
== auras
.end() || lastEffectPair
!= itr
->first
)
16463 AuraMap::const_iterator itr2
= itr
;
16464 // save previous spellEffectPair to db
16467 //skip all auras from spells that are passive
16468 //do not save single target auras (unless they were cast by the player)
16469 if (!itr2
->second
->IsPassive() && (itr2
->second
->GetCasterGUID() == GetGUID() || !itr2
->second
->IsSingleTarget()))
16473 ss
<< "INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges)VALUES ";
16474 first_round
= false;
16476 // next new/changed record prefix
16480 ss
<< "("<< GetGUIDLow() << "," << itr2
->second
->GetCasterGUID() << ","
16481 << (uint32
)itr2
->second
->GetId() << "," << (uint32
)itr2
->second
->GetEffIndex() << ","
16482 << stackCounter
<< "," << itr2
->second
->GetModifier()->m_amount
<< ","
16483 <<int(itr2
->second
->GetAuraMaxDuration()) << "," << int(itr2
->second
->GetAuraDuration()) << ","
16484 << int(itr2
->second
->GetAuraCharges()) << ")";
16487 if(itr
== auras
.end())
16491 if (lastEffectPair
== itr
->first
)
16495 lastEffectPair
= itr
->first
;
16500 // if something changed execute
16502 CharacterDatabase
.Execute( ss
.str().c_str() );
16505 void Player::_SaveGlyphs()
16508 for (uint8 spec
= 0; spec
< m_specsCount
; ++spec
)
16510 for (uint8 slot
= 0; slot
< MAX_GLYPH_SLOT_INDEX
; ++slot
)
16512 switch(m_glyphs
[spec
][slot
].uState
)
16515 CharacterDatabase
.PExecute("INSERT INTO character_glyphs (guid, spec, slot, glyph) VALUES ('%u', '%u', '%u', '%u')", GetGUIDLow(), spec
, slot
, m_glyphs
[spec
][slot
].GetId());
16517 case GLYPH_CHANGED
:
16518 CharacterDatabase
.PExecute("UPDATE character_glyphs SET glyph = '%u' WHERE guid='%u' AND spec = '%u' AND slot = '%u'", m_glyphs
[spec
][slot
].GetId(), GetGUIDLow(), spec
, slot
);
16520 case GLYPH_DELETED
:
16521 CharacterDatabase
.PExecute("DELETE FROM character_glyphs WHERE guid='%u' AND spec = '%u' AND slot = '%u'",GetGUIDLow(), spec
, slot
);
16523 case GLYPH_UNCHANGED
:
16526 m_glyphs
[spec
][slot
].uState
= GLYPH_UNCHANGED
;
16531 void Player::_SaveInventory()
16533 // force items in buyback slots to new state
16534 // and remove those that aren't already
16535 for (uint8 i
= BUYBACK_SLOT_START
; i
< BUYBACK_SLOT_END
; ++i
)
16537 Item
*item
= m_items
[i
];
16538 if (!item
|| item
->GetState() == ITEM_NEW
) continue;
16539 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
16540 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item
->GetGUIDLow());
16541 m_items
[i
]->FSetState(ITEM_NEW
);
16544 // update enchantment durations
16545 for(EnchantDurationList::const_iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
16547 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
16551 if (m_itemUpdateQueue
.empty()) return;
16553 // do not save if the update queue is corrupt
16554 bool error
= false;
16555 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); ++i
)
16557 Item
*item
= m_itemUpdateQueue
[i
];
16558 if(!item
|| item
->GetState() == ITEM_REMOVED
) continue;
16559 Item
*test
= GetItemByPos( item
->GetBagSlot(), item
->GetSlot());
16563 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());
16566 else if (test
!= item
)
16568 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());
16575 sLog
.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
16576 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED
);
16580 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); ++i
)
16582 Item
*item
= m_itemUpdateQueue
[i
];
16583 if(!item
) continue;
16585 Bag
*container
= item
->GetContainer();
16586 uint32 bag_guid
= container
? container
->GetGUIDLow() : 0;
16588 switch(item
->GetState())
16591 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());
16594 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());
16597 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
16599 case ITEM_UNCHANGED
:
16603 item
->SaveToDB(); // item have unchanged inventory record and can be save standalone
16605 m_itemUpdateQueue
.clear();
16608 void Player::_SaveMail()
16610 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
16613 if (m
->state
== MAIL_STATE_CHANGED
)
16615 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'",
16616 m
->itemTextId
, m
->HasItems() ? 1 : 0, (uint64
)m
->expire_time
, (uint64
)m
->deliver_time
, m
->money
, m
->COD
, m
->checked
, m
->messageID
);
16617 if(m
->removedItems
.size())
16619 for(std::vector
<uint32
>::const_iterator itr2
= m
->removedItems
.begin(); itr2
!= m
->removedItems
.end(); ++itr2
)
16620 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2
);
16621 m
->removedItems
.clear();
16623 m
->state
= MAIL_STATE_UNCHANGED
;
16625 else if (m
->state
== MAIL_STATE_DELETED
)
16628 for(std::vector
<MailItemInfo
>::const_iterator itr2
= m
->items
.begin(); itr2
!= m
->items
.end(); ++itr2
)
16629 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2
->item_guid
);
16631 CharacterDatabase
.PExecute("DELETE FROM item_text WHERE id = '%u'", m
->itemTextId
);
16632 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", m
->messageID
);
16633 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m
->messageID
);
16637 //deallocate deleted mails...
16638 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); )
16640 if ((*itr
)->state
== MAIL_STATE_DELETED
)
16645 itr
= m_mail
.begin();
16651 m_mailsUpdated
= false;
16654 void Player::_SaveQuestStatus()
16656 // we don't need transactions here.
16657 for( QuestStatusMap::iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
16659 switch (i
->second
.uState
)
16662 CharacterDatabase
.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
16663 "VALUES ('%u', '%u', '%u', '%u', '%u', '" UI64FMTD
"', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
16664 GetGUIDLow(), i
->first
, i
->second
.m_status
, i
->second
.m_rewarded
, i
->second
.m_explored
, uint64(i
->second
.m_timer
/ IN_MILLISECONDS
+ 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]);
16666 case QUEST_CHANGED
:
16667 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' ",
16668 i
->second
.m_status
, i
->second
.m_rewarded
, i
->second
.m_explored
, uint64(i
->second
.m_timer
/ IN_MILLISECONDS
+ 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
);
16670 case QUEST_UNCHANGED
:
16673 i
->second
.uState
= QUEST_UNCHANGED
;
16677 void Player::_SaveDailyQuestStatus()
16679 if(!m_DailyQuestChanged
)
16682 m_DailyQuestChanged
= false;
16684 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
16686 // we don't need transactions here.
16687 CharacterDatabase
.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
16688 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
16689 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
16690 CharacterDatabase
.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" UI64FMTD
"')",
16691 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
),uint64(m_lastDailyQuestTime
));
16695 void Player::_SaveSkills()
16697 // we don't need transactions here.
16698 for( SkillStatusMap::iterator itr
= mSkillStatus
.begin(); itr
!= mSkillStatus
.end(); )
16700 if(itr
->second
.uState
== SKILL_UNCHANGED
)
16706 if(itr
->second
.uState
== SKILL_DELETED
)
16708 CharacterDatabase
.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), itr
->first
);
16709 mSkillStatus
.erase(itr
++);
16713 uint32 valueData
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
));
16714 uint16 value
= SKILL_VALUE(valueData
);
16715 uint16 max
= SKILL_MAX(valueData
);
16717 switch (itr
->second
.uState
)
16720 CharacterDatabase
.PExecute("INSERT INTO character_skills (guid, skill, value, max) VALUES ('%u', '%u', '%u', '%u')",
16721 GetGUIDLow(), itr
->first
, value
, max
);
16723 case SKILL_CHANGED
:
16724 CharacterDatabase
.PExecute("UPDATE character_skills SET value = '%u',max = '%u'WHERE guid = '%u' AND skill = '%u' ",
16725 value
, max
, GetGUIDLow(), itr
->first
);
16728 itr
->second
.uState
= SKILL_UNCHANGED
;
16734 void Player::_SaveSpells()
16736 for (PlayerSpellMap::iterator itr
= m_spells
.begin(), next
= m_spells
.begin(); itr
!= m_spells
.end();)
16738 if (itr
->second
.state
== PLAYERSPELL_REMOVED
|| itr
->second
.state
== PLAYERSPELL_CHANGED
)
16739 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr
->first
);
16741 // add only changed/new not dependent spells
16742 if (!itr
->second
.dependent
&& (itr
->second
.state
== PLAYERSPELL_NEW
|| itr
->second
.state
== PLAYERSPELL_CHANGED
))
16743 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);
16745 if (itr
->second
.state
== PLAYERSPELL_REMOVED
)
16746 m_spells
.erase(itr
++);
16749 itr
->second
.state
= PLAYERSPELL_UNCHANGED
;
16756 void Player::outDebugValues() const
16758 if(!sLog
.IsOutDebug()) // optimize disabled debug output
16761 sLog
.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA
));
16762 sLog
.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY
), GetStat(STAT_STRENGTH
));
16763 sLog
.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT
), GetStat(STAT_SPIRIT
));
16764 sLog
.outDebug("STAMINA is: \t\t%f",GetStat(STAT_STAMINA
));
16765 sLog
.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE
));
16766 sLog
.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY
), GetResistance(SPELL_SCHOOL_FIRE
));
16767 sLog
.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE
), GetResistance(SPELL_SCHOOL_FROST
));
16768 sLog
.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW
), GetResistance(SPELL_SCHOOL_ARCANE
));
16769 sLog
.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE
), GetFloatValue(UNIT_FIELD_MAXDAMAGE
));
16770 sLog
.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
));
16771 sLog
.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
));
16772 sLog
.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK
), GetAttackTime(RANGED_ATTACK
));
16775 /*********************************************************/
16776 /*** FLOOD FILTER SYSTEM ***/
16777 /*********************************************************/
16779 void Player::UpdateSpeakTime()
16781 // ignore chat spam protection for GMs in any mode
16782 if(GetSession()->GetSecurity() > SEC_PLAYER
)
16785 time_t current
= time (NULL
);
16786 if(m_speakTime
> current
)
16788 uint32 max_count
= sWorld
.getConfig(CONFIG_UINT32_CHATFLOOD_MESSAGE_COUNT
);
16793 if(m_speakCount
>= max_count
)
16795 // prevent overwrite mute time, if message send just before mutes set, for example.
16796 time_t new_mute
= current
+ sWorld
.getConfig(CONFIG_UINT32_CHATFLOOD_MUTE_TIME
);
16797 if(GetSession()->m_muteTime
< new_mute
)
16798 GetSession()->m_muteTime
= new_mute
;
16806 m_speakTime
= current
+ sWorld
.getConfig(CONFIG_UINT32_CHATFLOOD_MESSAGE_DELAY
);
16809 bool Player::CanSpeak() const
16811 return GetSession()->m_muteTime
<= time (NULL
);
16814 /*********************************************************/
16815 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
16816 /*********************************************************/
16818 void Player::SendAttackSwingNotInRange()
16820 WorldPacket
data(SMSG_ATTACKSWING_NOTINRANGE
, 0);
16821 GetSession()->SendPacket( &data
);
16824 void Player::SavePositionInDB(uint32 mapid
, float x
,float y
,float z
,float o
,uint32 zone
,uint64 guid
)
16826 std::ostringstream ss
;
16827 ss
<< "UPDATE characters SET position_x='"<<x
<<"',position_y='"<<y
16828 << "',position_z='"<<z
<<"',orientation='"<<o
<<"',map='"<<mapid
16829 << "',zone='"<<zone
<<"',trans_x='0',trans_y='0',trans_z='0',"
16830 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
16831 sLog
.outDebug("%s", ss
.str().c_str());
16832 CharacterDatabase
.Execute(ss
.str().c_str());
16835 void Player::SetUInt32ValueInArray(Tokens
& tokens
,uint16 index
, uint32 value
)
16838 snprintf(buf
,11,"%u",value
);
16840 if(index
>= tokens
.size())
16843 tokens
[index
] = buf
;
16846 void Player::Customize(uint64 guid
, uint8 gender
, uint8 skin
, uint8 face
, uint8 hairStyle
, uint8 hairColor
, uint8 facialHair
)
16849 QueryResult
* result
= CharacterDatabase
.PQuery("SELECT playerBytes2 FROM characters WHERE guid = '%u'", GUID_LOPART(guid
));
16853 Field
* fields
= result
->Fetch();
16855 uint32 player_bytes2
= fields
[0].GetUInt32();
16856 player_bytes2
&= ~0xFF;
16857 player_bytes2
|= facialHair
;
16859 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
));
16864 void Player::SendAttackSwingDeadTarget()
16866 WorldPacket
data(SMSG_ATTACKSWING_DEADTARGET
, 0);
16867 GetSession()->SendPacket( &data
);
16870 void Player::SendAttackSwingCantAttack()
16872 WorldPacket
data(SMSG_ATTACKSWING_CANT_ATTACK
, 0);
16873 GetSession()->SendPacket( &data
);
16876 void Player::SendAttackSwingCancelAttack()
16878 WorldPacket
data(SMSG_CANCEL_COMBAT
, 0);
16879 GetSession()->SendPacket( &data
);
16882 void Player::SendAttackSwingBadFacingAttack()
16884 WorldPacket
data(SMSG_ATTACKSWING_BADFACING
, 0);
16885 GetSession()->SendPacket( &data
);
16888 void Player::SendAutoRepeatCancel(Unit
*target
)
16890 WorldPacket
data(SMSG_CANCEL_AUTO_REPEAT
, target
->GetPackGUID().size());
16891 data
<< target
->GetPackGUID(); // may be it's target guid
16892 GetSession()->SendPacket( &data
);
16895 void Player::SendExplorationExperience(uint32 Area
, uint32 Experience
)
16897 WorldPacket
data( SMSG_EXPLORATION_EXPERIENCE
, 8 );
16898 data
<< uint32(Area
);
16899 data
<< uint32(Experience
);
16900 GetSession()->SendPacket(&data
);
16903 void Player::SendDungeonDifficulty(bool IsInGroup
)
16905 uint8 val
= 0x00000001;
16906 WorldPacket
data(MSG_SET_DUNGEON_DIFFICULTY
, 12);
16907 data
<< uint32(GetDungeonDifficulty());
16908 data
<< uint32(val
);
16909 data
<< uint32(IsInGroup
);
16910 GetSession()->SendPacket(&data
);
16913 void Player::SendRaidDifficulty(bool IsInGroup
)
16915 uint8 val
= 0x00000001;
16916 WorldPacket
data(MSG_SET_RAID_DIFFICULTY
, 12);
16917 data
<< uint32(GetRaidDifficulty());
16918 data
<< uint32(val
);
16919 data
<< uint32(IsInGroup
);
16920 GetSession()->SendPacket(&data
);
16923 void Player::SendResetFailedNotify(uint32 mapid
)
16925 WorldPacket
data(SMSG_RESET_FAILED_NOTIFY
, 4);
16926 data
<< uint32(mapid
);
16927 GetSession()->SendPacket(&data
);
16930 /// Reset all solo instances and optionally send a message on success for each
16931 void Player::ResetInstances(uint8 method
, bool isRaid
)
16933 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
16935 // we assume that when the difficulty changes, all instances that can be reset will be
16936 Difficulty diff
= GetDifficulty(isRaid
);
16938 for (BoundInstancesMap::iterator itr
= m_boundInstances
[diff
].begin(); itr
!= m_boundInstances
[diff
].end();)
16940 InstanceSave
*p
= itr
->second
.save
;
16941 const MapEntry
*entry
= sMapStore
.LookupEntry(itr
->first
);
16942 if(!entry
|| entry
->IsRaid() != isRaid
|| !p
->CanReset())
16948 if(method
== INSTANCE_RESET_ALL
)
16950 // the "reset all instances" method can only reset normal maps
16951 if(entry
->map_type
== MAP_RAID
|| diff
== DUNGEON_DIFFICULTY_HEROIC
)
16958 // if the map is loaded, reset it
16959 Map
*map
= sMapMgr
.FindMap(p
->GetMapId(), p
->GetInstanceId());
16960 if(map
&& map
->IsDungeon())
16961 ((InstanceMap
*)map
)->Reset(method
);
16963 // since this is a solo instance there should not be any players inside
16964 if(method
== INSTANCE_RESET_ALL
|| method
== INSTANCE_RESET_CHANGE_DIFFICULTY
)
16965 SendResetInstanceSuccess(p
->GetMapId());
16968 m_boundInstances
[diff
].erase(itr
++);
16970 // the following should remove the instance save from the manager and delete it as well
16971 p
->RemovePlayer(this);
16975 void Player::SendResetInstanceSuccess(uint32 MapId
)
16977 WorldPacket
data(SMSG_INSTANCE_RESET
, 4);
16978 data
<< uint32(MapId
);
16979 GetSession()->SendPacket(&data
);
16982 void Player::SendResetInstanceFailed(uint32 reason
, uint32 MapId
)
16984 // TODO: find what other fail reasons there are besides players in the instance
16985 WorldPacket
data(SMSG_INSTANCE_RESET_FAILED
, 4);
16986 data
<< uint32(reason
);
16987 data
<< uint32(MapId
);
16988 GetSession()->SendPacket(&data
);
16991 /*********************************************************/
16992 /*** Update timers ***/
16993 /*********************************************************/
16995 ///checks the 15 afk reports per 5 minutes limit
16996 void Player::UpdateAfkReport(time_t currTime
)
16998 if(m_bgData
.bgAfkReportedTimer
<= currTime
)
17000 m_bgData
.bgAfkReportedCount
= 0;
17001 m_bgData
.bgAfkReportedTimer
= currTime
+5*MINUTE
;
17005 void Player::UpdateContestedPvP(uint32 diff
)
17007 if(!m_contestedPvPTimer
||isInCombat())
17009 if(m_contestedPvPTimer
<= diff
)
17011 ResetContestedPvP();
17014 m_contestedPvPTimer
-= diff
;
17017 void Player::UpdatePvPFlag(time_t currTime
)
17021 if(pvpInfo
.endTimer
== 0 || currTime
< (pvpInfo
.endTimer
+ 300))
17027 void Player::UpdateDuelFlag(time_t currTime
)
17029 if(!duel
|| duel
->startTimer
== 0 ||currTime
< duel
->startTimer
+ 3)
17032 SetUInt32Value(PLAYER_DUEL_TEAM
, 1);
17033 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 2);
17035 duel
->startTimer
= 0;
17036 duel
->startTime
= currTime
;
17037 duel
->opponent
->duel
->startTimer
= 0;
17038 duel
->opponent
->duel
->startTime
= currTime
;
17041 void Player::RemovePet(Pet
* pet
, PetSaveMode mode
, bool returnreagent
)
17046 if (!pet
|| pet
->GetOwnerGUID() != GetGUID())
17049 // not save secondary permanent pet as current
17050 if (pet
&& m_temporaryUnsummonedPetNumber
&& m_temporaryUnsummonedPetNumber
!= pet
->GetCharmInfo()->GetPetNumber() && mode
== PET_SAVE_AS_CURRENT
)
17051 mode
= PET_SAVE_NOT_IN_SLOT
;
17053 if (returnreagent
&& pet
&& mode
!= PET_SAVE_AS_CURRENT
)
17055 //returning of reagents only for players, so best done here
17056 uint32 spellId
= pet
? pet
->GetUInt32Value(UNIT_CREATED_BY_SPELL
) : m_oldpetspell
;
17057 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellId
);
17061 for(uint32 i
= 0; i
< 7; ++i
)
17063 if(spellInfo
->Reagent
[i
] > 0)
17065 ItemPosCountVec dest
; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
17066 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, spellInfo
->Reagent
[i
], spellInfo
->ReagentCount
[i
] );
17067 if( msg
== EQUIP_ERR_OK
)
17069 Item
* item
= StoreNewItem( dest
, spellInfo
->Reagent
[i
], true);
17071 SendNewItem(item
,spellInfo
->ReagentCount
[i
],true,false);
17078 // only if current pet in slot
17079 switch(pet
->getPetType())
17085 RemoveGuardian(pet
);
17088 if (GetPetGUID() == pet
->GetGUID())
17095 pet
->SavePetToDB(mode
);
17097 pet
->AddObjectToRemoveList();
17098 pet
->m_removed
= true;
17100 if (pet
->isControlled())
17102 RemovePetActionBar();
17105 SetGroupUpdateFlag(GROUP_UPDATE_PET
);
17109 void Player::RemoveMiniPet()
17111 if (Pet
* pet
= GetMiniPet())
17113 pet
->Remove(PET_SAVE_AS_DELETED
);
17118 Pet
* Player::GetMiniPet()
17123 return GetMap()->GetPet(m_miniPet
);
17126 void Player::BuildPlayerChat(WorldPacket
*data
, uint8 msgtype
, const std::string
& text
, uint32 language
) const
17128 *data
<< (uint8
)msgtype
;
17129 *data
<< (uint32
)language
;
17130 *data
<< (uint64
)GetGUID();
17131 *data
<< (uint32
)language
; //language 2.1.0 ?
17132 *data
<< (uint64
)GetGUID();
17133 *data
<< (uint32
)(text
.length()+1);
17135 *data
<< (uint8
)chatTag();
17138 void Player::Say(const std::string
& text
, const uint32 language
)
17140 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
17141 BuildPlayerChat(&data
, CHAT_MSG_SAY
, text
, language
);
17142 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_FLOAT_LISTEN_RANGE_SAY
),true);
17145 void Player::Yell(const std::string
& text
, const uint32 language
)
17147 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
17148 BuildPlayerChat(&data
, CHAT_MSG_YELL
, text
, language
);
17149 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_FLOAT_LISTEN_RANGE_YELL
),true);
17152 void Player::TextEmote(const std::string
& text
)
17154 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
17155 BuildPlayerChat(&data
, CHAT_MSG_EMOTE
, text
, LANG_UNIVERSAL
);
17156 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_FLOAT_LISTEN_RANGE_TEXTEMOTE
),true, !sWorld
.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_CHAT
) );
17159 void Player::Whisper(const std::string
& text
, uint32 language
,uint64 receiver
)
17161 if (language
!= LANG_ADDON
) // if not addon data
17162 language
= LANG_UNIVERSAL
; // whispers should always be readable
17164 Player
*rPlayer
= sObjectMgr
.GetPlayer(receiver
);
17166 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
17167 if(!rPlayer
->isDND() || isGameMaster())
17169 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
17170 BuildPlayerChat(&data
, CHAT_MSG_WHISPER
, text
, language
);
17171 rPlayer
->GetSession()->SendPacket(&data
);
17173 // not send confirmation for addon messages
17174 if (language
!= LANG_ADDON
)
17176 data
.Initialize(SMSG_MESSAGECHAT
, 200);
17177 rPlayer
->BuildPlayerChat(&data
, CHAT_MSG_WHISPER_INFORM
, text
, language
);
17178 GetSession()->SendPacket(&data
);
17183 // announce to player that player he is whispering to is dnd and cannot receive his message
17184 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND
, rPlayer
->GetName(), rPlayer
->dndMsg
.c_str());
17187 if(!isAcceptWhispers())
17189 SetAcceptWhispers(true);
17190 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON
);
17193 // announce to player that player he is whispering to is afk
17194 if(rPlayer
->isAFK())
17195 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK
, rPlayer
->GetName(), rPlayer
->afkMsg
.c_str());
17197 // if player whisper someone, auto turn of dnd to be able to receive an answer
17198 if(isDND() && !rPlayer
->isGameMaster())
17202 void Player::PetSpellInitialize()
17204 Pet
* pet
= GetPet();
17209 sLog
.outDebug("Pet Spells Groups");
17211 CharmInfo
*charmInfo
= pet
->GetCharmInfo();
17213 WorldPacket
data(SMSG_PET_SPELLS
, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX
+1+1);
17214 data
<< uint64(pet
->GetGUID());
17215 data
<< uint16(pet
->GetCreatureInfo()->family
); // creature family (required for pet talents)
17217 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState()) << uint16(0);
17220 charmInfo
->BuildActionBar(&data
);
17222 size_t spellsCountPos
= data
.wpos();
17226 data
<< uint8(addlist
); // placeholder
17228 if (pet
->IsPermanentPetFor(this))
17231 for (PetSpellMap::const_iterator itr
= pet
->m_spells
.begin(); itr
!= pet
->m_spells
.end(); ++itr
)
17233 if(itr
->second
.state
== PETSPELL_REMOVED
)
17236 data
<< uint32(MAKE_UNIT_ACTION_BUTTON(itr
->first
,itr
->second
.active
));
17241 data
.put
<uint8
>(spellsCountPos
, addlist
);
17243 uint8 cooldownsCount
= pet
->m_CreatureSpellCooldowns
.size() + pet
->m_CreatureCategoryCooldowns
.size();
17244 data
<< uint8(cooldownsCount
);
17246 time_t curTime
= time(NULL
);
17248 for(CreatureSpellCooldowns::const_iterator itr
= pet
->m_CreatureSpellCooldowns
.begin(); itr
!= pet
->m_CreatureSpellCooldowns
.end(); ++itr
)
17250 time_t cooldown
= (itr
->second
> curTime
) ? (itr
->second
- curTime
) * IN_MILLISECONDS
: 0;
17252 data
<< uint32(itr
->first
); // spellid
17253 data
<< uint16(0); // spell category?
17254 data
<< uint32(cooldown
); // cooldown
17255 data
<< uint32(0); // category cooldown
17258 for(CreatureSpellCooldowns::const_iterator itr
= pet
->m_CreatureCategoryCooldowns
.begin(); itr
!= pet
->m_CreatureCategoryCooldowns
.end(); ++itr
)
17260 time_t cooldown
= (itr
->second
> curTime
) ? (itr
->second
- curTime
) * IN_MILLISECONDS
: 0;
17262 data
<< uint32(itr
->first
); // spellid
17263 data
<< uint16(0); // spell category?
17264 data
<< uint32(0); // cooldown
17265 data
<< uint32(cooldown
); // category cooldown
17268 GetSession()->SendPacket(&data
);
17271 void Player::SendPetGUIDs()
17276 // Later this function might get modified for multiple guids
17277 WorldPacket
data(SMSG_PET_GUIDS
, 12);
17278 data
<< uint32(1); // count
17279 data
<< uint64(GetPetGUID());
17280 GetSession()->SendPacket(&data
);
17283 void Player::PossessSpellInitialize()
17285 Unit
* charm
= GetCharm();
17290 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
17294 sLog
.outError("Player::PossessSpellInitialize(): charm (GUID: %u TypeId: %u) has no charminfo!", charm
->GetGUIDLow(),charm
->GetTypeId());
17298 WorldPacket
data(SMSG_PET_SPELLS
, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX
+1+1);
17299 data
<< uint64(charm
->GetGUID());
17304 charmInfo
->BuildActionBar(&data
);
17306 data
<< uint8(0); // spells count
17307 data
<< uint8(0); // cooldowns count
17309 GetSession()->SendPacket(&data
);
17312 void Player::CharmSpellInitialize()
17314 Unit
* charm
= GetCharm();
17319 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
17322 sLog
.outError("Player::CharmSpellInitialize(): the player's charm (GUID: %u TypeId: %u) has no charminfo!", charm
->GetGUIDLow(),charm
->GetTypeId());
17328 if(charm
->GetTypeId() != TYPEID_PLAYER
)
17330 CreatureInfo
const *cinfo
= ((Creature
*)charm
)->GetCreatureInfo();
17332 if(cinfo
&& cinfo
->type
== CREATURE_TYPE_DEMON
&& getClass() == CLASS_WARLOCK
)
17334 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
17336 if(charmInfo
->GetCharmSpell(i
)->GetAction())
17342 WorldPacket
data(SMSG_PET_SPELLS
, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX
+1+4*addlist
+1);
17343 data
<< uint64(charm
->GetGUID());
17347 if(charm
->GetTypeId() != TYPEID_PLAYER
)
17348 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState()) << uint16(0);
17350 data
<< uint8(0) << uint8(0) << uint16(0);
17352 charmInfo
->BuildActionBar(&data
);
17354 data
<< uint8(addlist
);
17358 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
17360 CharmSpellEntry
*cspell
= charmInfo
->GetCharmSpell(i
);
17361 if(cspell
->GetAction())
17362 data
<< uint32(cspell
->packedData
);
17366 data
<< uint8(0); // cooldowns count
17368 GetSession()->SendPacket(&data
);
17371 void Player::RemovePetActionBar()
17373 WorldPacket
data(SMSG_PET_SPELLS
, 8);
17375 SendDirectMessage(&data
);
17378 bool Player::IsAffectedBySpellmod(SpellEntry
const *spellInfo
, SpellModifier
*mod
, Spell
const* spell
)
17380 if (!mod
|| !spellInfo
)
17383 if(mod
->charges
== -1 && mod
->lastAffected
) // marked as expired but locked until spell casting finish
17385 // prevent apply to any spell except spell that trigger expire
17388 if(mod
->lastAffected
!= spell
)
17391 else if(mod
->lastAffected
!= FindCurrentSpellBySpellId(spellInfo
->Id
))
17395 return mod
->isAffectedOnSpell(spellInfo
);
17398 void Player::AddSpellMod(SpellModifier
* mod
, bool apply
)
17400 uint16 Opcode
= (mod
->type
== SPELLMOD_FLAT
) ? SMSG_SET_FLAT_SPELL_MODIFIER
: SMSG_SET_PCT_SPELL_MODIFIER
;
17402 for(int eff
= 0; eff
< 96; ++eff
)
17408 _mask
= uint64(1) << (eff
- 0);
17410 _mask2
= uint32(1) << (eff
- 64);
17412 if ( mod
->mask
& _mask
|| mod
->mask2
& _mask2
)
17415 for (SpellModList::const_iterator itr
= m_spellMods
[mod
->op
].begin(); itr
!= m_spellMods
[mod
->op
].end(); ++itr
)
17417 if ((*itr
)->type
== mod
->type
&& ((*itr
)->mask
& _mask
|| (*itr
)->mask2
& _mask2
))
17418 val
+= (*itr
)->value
;
17420 val
+= apply
? mod
->value
: -(mod
->value
);
17421 WorldPacket
data(Opcode
, (1+1+4));
17422 data
<< uint8(eff
);
17423 data
<< uint8(mod
->op
);
17424 data
<< int32(val
);
17425 SendDirectMessage(&data
);
17430 m_spellMods
[mod
->op
].push_back(mod
);
17433 if (mod
->charges
== -1)
17434 --m_SpellModRemoveCount
;
17435 m_spellMods
[mod
->op
].remove(mod
);
17440 void Player::RemoveSpellMods(Spell
const* spell
)
17442 if(!spell
|| (m_SpellModRemoveCount
== 0))
17445 for(int i
=0;i
<MAX_SPELLMOD
;++i
)
17447 for (SpellModList::const_iterator itr
= m_spellMods
[i
].begin(); itr
!= m_spellMods
[i
].end();)
17449 SpellModifier
*mod
= *itr
;
17452 if (mod
&& mod
->charges
== -1 && (mod
->lastAffected
== spell
|| mod
->lastAffected
==NULL
))
17454 RemoveAurasDueToSpell(mod
->spellId
);
17455 if (m_spellMods
[i
].empty())
17458 itr
= m_spellMods
[i
].begin();
17464 // send Proficiency
17465 void Player::SendProficiency(uint8 pr1
, uint32 pr2
)
17467 WorldPacket
data(SMSG_SET_PROFICIENCY
, 8);
17468 data
<< uint8(pr1
) << uint32(pr2
);
17469 GetSession()->SendPacket (&data
);
17472 void Player::RemovePetitionsAndSigns(uint64 guid
, uint32 type
)
17474 QueryResult
*result
= NULL
;
17476 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
17478 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
17481 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.
17482 { // and SendPetitionQueryOpcode reads data from the DB
17483 Field
*fields
= result
->Fetch();
17484 uint64 ownerguid
= MAKE_NEW_GUID(fields
[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
17485 uint64 petitionguid
= MAKE_NEW_GUID(fields
[1].GetUInt32(), 0, HIGHGUID_ITEM
);
17487 // send update if charter owner in game
17488 Player
* owner
= sObjectMgr
.GetPlayer(ownerguid
);
17490 owner
->GetSession()->SendPetitionQueryOpcode(petitionguid
);
17492 } while ( result
->NextRow() );
17497 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
17499 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
17502 CharacterDatabase
.BeginTransaction();
17505 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid
));
17506 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid
));
17510 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
17511 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
17513 CharacterDatabase
.CommitTransaction();
17516 void Player::LeaveAllArenaTeams(uint64 guid
)
17518 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
));
17524 Field
*fields
= result
->Fetch();
17525 uint32 at_id
= fields
[0].GetUInt32();
17528 ArenaTeam
* at
= sObjectMgr
.GetArenaTeamById(at_id
);
17530 at
->DelMember(guid
);
17532 } while (result
->NextRow());
17537 void Player::SetRestBonus (float rest_bonus_new
)
17539 // Prevent resting on max level
17540 if(getLevel() >= sWorld
.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL
))
17541 rest_bonus_new
= 0;
17543 if(rest_bonus_new
< 0)
17544 rest_bonus_new
= 0;
17546 float rest_bonus_max
= (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)*1.5f
/2.0f
;
17548 if(rest_bonus_new
> rest_bonus_max
)
17549 m_rest_bonus
= rest_bonus_max
;
17551 m_rest_bonus
= rest_bonus_new
;
17553 // update data for client
17554 if(m_rest_bonus
>10)
17555 SetByteValue(PLAYER_BYTES_2
, 3, 0x01); // Set Reststate = Rested
17556 else if(m_rest_bonus
<=1)
17557 SetByteValue(PLAYER_BYTES_2
, 3, 0x02); // Set Reststate = Normal
17560 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE
, uint32(m_rest_bonus
));
17563 void Player::HandleStealthedUnitsDetection()
17565 std::list
<Unit
*> stealthedUnits
;
17567 CellPair
p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
17569 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
17570 cell
.SetNoCreate();
17572 MaNGOS::AnyStealthedCheck u_check
;
17573 MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
> searcher(this,stealthedUnits
, u_check
);
17575 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, WorldTypeMapContainer
> world_unit_searcher(searcher
);
17576 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, GridTypeMapContainer
> grid_unit_searcher(searcher
);
17578 cell
.Visit(p
, world_unit_searcher
, *GetMap(), *this, MAX_PLAYER_STEALTH_DETECT_RANGE
);
17579 cell
.Visit(p
, grid_unit_searcher
, *GetMap(), *this, MAX_PLAYER_STEALTH_DETECT_RANGE
);
17581 WorldObject
const* viewPoint
= GetViewPoint();
17583 for (std::list
<Unit
*>::const_iterator i
= stealthedUnits
.begin(); i
!= stealthedUnits
.end(); ++i
)
17588 bool hasAtClient
= HaveAtClient((*i
));
17589 bool hasDetected
= (*i
)->isVisibleForOrDetect(this, viewPoint
, true);
17595 ObjectGuid i_guid
= (*i
)->GetGUID();
17596 (*i
)->SendCreateUpdateToPlayer(this);
17597 m_clientGUIDs
.insert(i_guid
);
17599 #ifdef MANGOS_DEBUG
17600 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17601 sLog
.outDebug("%s is detected in stealth by player %u. Distance = %f",i_guid
.GetString().c_str(),GetGUIDLow(),GetDistance(*i
));
17604 // target aura duration for caster show only if target exist at caster client
17605 // send data at target visibility change (adding to client)
17606 if((*i
)!=this && (*i
)->isType(TYPEMASK_UNIT
))
17607 SendAurasForTarget(*i
);
17614 (*i
)->DestroyForPlayer(this);
17615 m_clientGUIDs
.erase((*i
)->GetGUID());
17621 bool Player::ActivateTaxiPathTo(std::vector
<uint32
> const& nodes
, Creature
* npc
/*= NULL*/, uint32 spellid
/*= 0*/)
17623 if(nodes
.size() < 2)
17626 // 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
17627 if(GetSession()->isLogingOut() || isInCombat())
17629 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17630 data
<< uint32(ERR_TAXIPLAYERBUSY
);
17631 GetSession()->SendPacket(&data
);
17635 if(HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_DISABLE_MOVE
))
17641 // not let cheating with start flight mounted
17644 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17645 data
<< uint32(ERR_TAXIPLAYERALREADYMOUNTED
);
17646 GetSession()->SendPacket(&data
);
17650 if( m_ShapeShiftFormSpellId
&& m_form
!= FORM_BATTLESTANCE
&& m_form
!= FORM_BERSERKERSTANCE
&& m_form
!= FORM_DEFENSIVESTANCE
&& m_form
!= FORM_SHADOW
)
17652 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17653 data
<< uint32(ERR_TAXIPLAYERSHAPESHIFTED
);
17654 GetSession()->SendPacket(&data
);
17658 // 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
17659 if(IsNonMeleeSpellCasted(false))
17661 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17662 data
<< uint32(ERR_TAXIPLAYERBUSY
);
17663 GetSession()->SendPacket(&data
);
17667 // cast case or scripted call case
17670 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED
);
17672 if( m_ShapeShiftFormSpellId
&& m_form
!= FORM_BATTLESTANCE
&& m_form
!= FORM_BERSERKERSTANCE
&& m_form
!= FORM_DEFENSIVESTANCE
&& m_form
!= FORM_SHADOW
)
17673 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId
);
17675 if (Spell
* spell
= GetCurrentSpell(CURRENT_GENERIC_SPELL
))
17676 if (spell
->m_spellInfo
->Id
!= spellid
)
17677 InterruptSpell(CURRENT_GENERIC_SPELL
,false);
17679 InterruptSpell(CURRENT_AUTOREPEAT_SPELL
,false);
17681 if (Spell
* spell
= GetCurrentSpell(CURRENT_CHANNELED_SPELL
))
17682 if (spell
->m_spellInfo
->Id
!= spellid
)
17683 InterruptSpell(CURRENT_CHANNELED_SPELL
,true);
17686 uint32 sourcenode
= nodes
[0];
17688 // starting node too far away (cheat?)
17689 TaxiNodesEntry
const* node
= sTaxiNodesStore
.LookupEntry(sourcenode
);
17692 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17693 data
<< uint32(ERR_TAXINOSUCHPATH
);
17694 GetSession()->SendPacket(&data
);
17698 // check node starting pos data set case if provided
17699 if (node
->x
!= 0.0f
|| node
->y
!= 0.0f
|| node
->z
!= 0.0f
)
17701 if (node
->map_id
!= GetMapId() ||
17702 (node
->x
- GetPositionX())*(node
->x
- GetPositionX())+
17703 (node
->y
- GetPositionY())*(node
->y
- GetPositionY())+
17704 (node
->z
- GetPositionZ())*(node
->z
- GetPositionZ()) >
17705 (2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
))
17707 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17708 data
<< uint32(ERR_TAXITOOFARAWAY
);
17709 GetSession()->SendPacket(&data
);
17713 // node must have pos if taxi master case (npc != NULL)
17716 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17717 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
17718 GetSession()->SendPacket(&data
);
17722 // Prepare to flight start now
17724 // stop combat at start taxi flight if any
17727 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
17730 // clean not finished taxi path if any
17731 m_taxi
.ClearTaxiDestinations();
17733 // 0 element current node
17734 m_taxi
.AddTaxiDestination(sourcenode
);
17736 // fill destinations path tail
17737 uint32 sourcepath
= 0;
17738 uint32 totalcost
= 0;
17740 uint32 prevnode
= sourcenode
;
17741 uint32 lastnode
= 0;
17743 for(uint32 i
= 1; i
< nodes
.size(); ++i
)
17747 lastnode
= nodes
[i
];
17748 sObjectMgr
.GetTaxiPath(prevnode
, lastnode
, path
, cost
);
17752 m_taxi
.ClearTaxiDestinations();
17758 if(prevnode
== sourcenode
)
17761 m_taxi
.AddTaxiDestination(lastnode
);
17763 prevnode
= lastnode
;
17766 // get mount model (in case non taximaster (npc==NULL) allow more wide lookup)
17767 uint32 mount_display_id
= sObjectMgr
.GetTaxiMountDisplayId(sourcenode
, GetTeam(), npc
== NULL
);
17769 // in spell case allow 0 model
17770 if ((mount_display_id
== 0 && spellid
== 0) || sourcepath
== 0)
17772 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17773 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
17774 GetSession()->SendPacket(&data
);
17775 m_taxi
.ClearTaxiDestinations();
17779 uint32 money
= GetMoney();
17782 totalcost
= (uint32
)ceil(totalcost
*GetReputationPriceDiscount(npc
));
17784 if(money
< totalcost
)
17786 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17787 data
<< uint32(ERR_TAXINOTENOUGHMONEY
);
17788 GetSession()->SendPacket(&data
);
17789 m_taxi
.ClearTaxiDestinations();
17793 //Checks and preparations done, DO FLIGHT
17794 ModifyMoney(-(int32
)totalcost
);
17795 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING
, totalcost
);
17796 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN
, 1);
17798 // prevent stealth flight
17799 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH
);
17801 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17802 data
<< uint32(ERR_TAXIOK
);
17803 GetSession()->SendPacket(&data
);
17805 sLog
.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
17807 GetSession()->SendDoFlight(mount_display_id
, sourcepath
);
17812 bool Player::ActivateTaxiPathTo( uint32 taxi_path_id
, uint32 spellid
/*= 0*/ )
17814 TaxiPathEntry
const* entry
= sTaxiPathStore
.LookupEntry(taxi_path_id
);
17818 std::vector
<uint32
> nodes
;
17821 nodes
[0] = entry
->from
;
17822 nodes
[1] = entry
->to
;
17824 return ActivateTaxiPathTo(nodes
,NULL
,spellid
);
17827 void Player::ContinueTaxiFlight()
17829 uint32 sourceNode
= m_taxi
.GetTaxiSource();
17833 sLog
.outDebug( "WORLD: Restart character %u taxi flight", GetGUIDLow() );
17835 uint32 mountDisplayId
= sObjectMgr
.GetTaxiMountDisplayId(sourceNode
, GetTeam(),true);
17836 uint32 path
= m_taxi
.GetCurrentTaxiPath();
17838 // search appropriate start path node
17839 uint32 startNode
= 0;
17841 TaxiPathNodeList
const& nodeList
= sTaxiPathNodesByPath
[path
];
17843 float distPrev
= MAP_SIZE
*MAP_SIZE
;
17845 (nodeList
[0].x
-GetPositionX())*(nodeList
[0].x
-GetPositionX())+
17846 (nodeList
[0].y
-GetPositionY())*(nodeList
[0].y
-GetPositionY())+
17847 (nodeList
[0].z
-GetPositionZ())*(nodeList
[0].z
-GetPositionZ());
17849 for(uint32 i
= 1; i
< nodeList
.size(); ++i
)
17851 TaxiPathNode
const& node
= nodeList
[i
];
17852 TaxiPathNode
const& prevNode
= nodeList
[i
-1];
17854 // skip nodes at another map
17855 if(node
.mapid
!= GetMapId())
17858 distPrev
= distNext
;
17861 (node
.x
-GetPositionX())*(node
.x
-GetPositionX())+
17862 (node
.y
-GetPositionY())*(node
.y
-GetPositionY())+
17863 (node
.z
-GetPositionZ())*(node
.z
-GetPositionZ());
17866 (node
.x
-prevNode
.x
)*(node
.x
-prevNode
.x
)+
17867 (node
.y
-prevNode
.y
)*(node
.y
-prevNode
.y
)+
17868 (node
.z
-prevNode
.z
)*(node
.z
-prevNode
.z
);
17870 if(distNext
+ distPrev
< distNodes
)
17877 GetSession()->SendDoFlight(mountDisplayId
, path
, startNode
);
17880 void Player::ProhibitSpellSchool(SpellSchoolMask idSchoolMask
, uint32 unTimeMs
)
17882 // last check 2.0.10
17883 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+m_spells
.size()*8);
17884 data
<< uint64(GetGUID());
17885 data
<< uint8(0x0); // flags (0x1, 0x2)
17886 time_t curTime
= time(NULL
);
17887 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
17889 if (itr
->second
.state
== PLAYERSPELL_REMOVED
)
17891 uint32 unSpellId
= itr
->first
;
17892 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(unSpellId
);
17899 // Not send cooldown for this spells
17900 if (spellInfo
->Attributes
& SPELL_ATTR_DISABLED_WHILE_ACTIVE
)
17903 if((idSchoolMask
& GetSpellSchoolMask(spellInfo
)) && GetSpellCooldownDelay(unSpellId
) < unTimeMs
)
17905 data
<< uint32(unSpellId
);
17906 data
<< uint32(unTimeMs
); // in m.secs
17907 AddSpellCooldown(unSpellId
, 0, curTime
+ unTimeMs
/IN_MILLISECONDS
);
17910 GetSession()->SendPacket(&data
);
17913 void Player::InitDataForForm(bool reapplyMods
)
17915 SpellShapeshiftEntry
const* ssEntry
= sSpellShapeshiftStore
.LookupEntry(m_form
);
17916 if(ssEntry
&& ssEntry
->attackSpeed
)
17918 SetAttackTime(BASE_ATTACK
,ssEntry
->attackSpeed
);
17919 SetAttackTime(OFF_ATTACK
,ssEntry
->attackSpeed
);
17920 SetAttackTime(RANGED_ATTACK
, BASE_ATTACK_TIME
);
17923 SetRegularAttackTime();
17929 if(getPowerType()!=POWER_ENERGY
)
17930 setPowerType(POWER_ENERGY
);
17934 case FORM_DIREBEAR
:
17936 if(getPowerType()!=POWER_RAGE
)
17937 setPowerType(POWER_RAGE
);
17940 default: // 0, for example
17942 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(getClass());
17943 if(cEntry
&& cEntry
->powerType
< MAX_POWERS
&& uint32(getPowerType()) != cEntry
->powerType
)
17944 setPowerType(Powers(cEntry
->powerType
));
17949 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
17951 UpdateEquipSpellsAtFormChange();
17953 UpdateAttackPowerAndDamage();
17954 UpdateAttackPowerAndDamage(true);
17957 void Player::InitDisplayIds()
17959 PlayerInfo
const *info
= sObjectMgr
.GetPlayerInfo(getRace(), getClass());
17962 sLog
.outError("Player %u has incorrect race/class pair. Can't init display ids.", GetGUIDLow());
17966 uint8 gender
= getGender();
17969 case GENDER_FEMALE
:
17970 SetDisplayId(info
->displayId_f
);
17971 SetNativeDisplayId(info
->displayId_f
);
17974 SetDisplayId(info
->displayId_m
);
17975 SetNativeDisplayId(info
->displayId_m
);
17978 sLog
.outError("Invalid gender %u for player",gender
);
17983 // Return true is the bought item has a max count to force refresh of window by caller
17984 bool Player::BuyItemFromVendor(uint64 vendorguid
, uint32 item
, uint8 count
, uint8 bag
, uint8 slot
)
17986 // cheating attempt
17987 if (count
< 1) count
= 1;
17992 ItemPrototype
const *pProto
= ObjectMgr::GetItemPrototype( item
);
17995 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, NULL
, item
, 0);
17999 Creature
*pCreature
= GetNPCIfCanInteractWith(vendorguid
,UNIT_NPC_FLAG_VENDOR
);
18002 sLog
.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid
)) );
18003 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR
, NULL
, item
, 0);
18007 VendorItemData
const* vItems
= pCreature
->GetVendorItems();
18008 if(!vItems
|| vItems
->Empty())
18010 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
18014 size_t vendor_slot
= vItems
->FindItemSlot(item
);
18015 if (vendor_slot
>= vItems
->GetItemCount())
18017 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
18021 VendorItem
const* crItem
= vItems
->m_items
[vendor_slot
];
18023 // check current item amount if it limited
18024 if (crItem
->maxcount
!= 0)
18026 if (pCreature
->GetVendorItemCurrentCount(crItem
) < pProto
->BuyCount
* count
)
18028 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD
, pCreature
, item
, 0);
18033 if (uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
18035 SendBuyError( BUY_ERR_REPUTATION_REQUIRE
, pCreature
, item
, 0);
18039 if (crItem
->ExtendedCost
)
18041 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
18044 sLog
.outError("Item %u have wrong ExtendedCost field value %u", pProto
->ItemId
, crItem
->ExtendedCost
);
18048 // honor points price
18049 if (GetHonorPoints() < (iece
->reqhonorpoints
* count
))
18051 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS
, NULL
, NULL
);
18055 // arena points price
18056 if (GetArenaPoints() < (iece
->reqarenapoints
* count
))
18058 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS
, NULL
, NULL
);
18063 for (uint8 i
= 0; i
< 5; ++i
)
18065 if(iece
->reqitem
[i
] && !HasItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
)))
18067 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS
, NULL
, NULL
);
18072 // check for personal arena rating requirement
18073 if( GetMaxPersonalArenaRatingRequirement(iece
->reqarenaslot
) < iece
->reqpersonalarenarating
)
18075 // probably not the proper equip err
18076 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK
,NULL
,NULL
);
18081 uint32 price
= pProto
->BuyPrice
* count
;
18083 // reputation discount
18084 price
= uint32(floor(price
* GetReputationPriceDiscount(pCreature
)));
18086 if (GetMoney() < price
)
18088 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, pCreature
, item
, 0);
18092 if ((bag
== NULL_BAG
&& slot
== NULL_SLOT
) || IsInventoryPos(bag
, slot
))
18094 ItemPosCountVec dest
;
18095 uint8 msg
= CanStoreNewItem( bag
, slot
, dest
, item
, pProto
->BuyCount
* count
);
18096 if (msg
!= EQUIP_ERR_OK
)
18098 SendEquipError( msg
, NULL
, NULL
, item
);
18102 ModifyMoney( -(int32
)price
);
18103 if (crItem
->ExtendedCost
) // case for new honor system
18105 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
18106 if (iece
->reqhonorpoints
)
18107 ModifyHonorPoints( - int32(iece
->reqhonorpoints
* count
));
18108 if (iece
->reqarenapoints
)
18109 ModifyArenaPoints( - int32(iece
->reqarenapoints
* count
));
18110 for (uint8 i
= 0; i
< 5; ++i
)
18112 if (iece
->reqitem
[i
])
18113 DestroyItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
), true);
18117 if (Item
*it
= StoreNewItem( dest
, item
, true ))
18119 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
18121 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
18122 data
<< uint64(pCreature
->GetGUID());
18123 data
<< uint32(vendor_slot
+1); // numbered from 1 at client
18124 data
<< uint32(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
18125 data
<< uint32(count
);
18126 GetSession()->SendPacket(&data
);
18128 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
18131 else if (IsEquipmentPos(bag
, slot
))
18133 if (pProto
->BuyCount
* count
!= 1)
18135 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
, NULL
, NULL
);
18140 uint8 msg
= CanEquipNewItem( slot
, dest
, item
, false );
18141 if (msg
!= EQUIP_ERR_OK
)
18143 SendEquipError( msg
, NULL
, NULL
, item
);
18147 ModifyMoney( -(int32
)price
);
18148 if (crItem
->ExtendedCost
) // case for new honor system
18150 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
18151 if (iece
->reqhonorpoints
)
18152 ModifyHonorPoints( - int32(iece
->reqhonorpoints
));
18153 if (iece
->reqarenapoints
)
18154 ModifyArenaPoints( - int32(iece
->reqarenapoints
));
18155 for (uint8 i
= 0; i
< 5; ++i
)
18157 if(iece
->reqitem
[i
])
18158 DestroyItemCount(iece
->reqitem
[i
], iece
->reqitemcount
[i
], true);
18162 if (Item
*it
= EquipNewItem( dest
, item
, true ))
18164 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
18166 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
18167 data
<< uint64(pCreature
->GetGUID());
18168 data
<< uint32(vendor_slot
+ 1); // numbered from 1 at client
18169 data
<< uint32(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
18170 data
<< uint32(count
);
18171 GetSession()->SendPacket(&data
);
18173 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
18175 AutoUnequipOffhandIfNeed();
18180 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
, NULL
, NULL
);
18184 return crItem
->maxcount
!= 0;
18187 uint32
Player::GetMaxPersonalArenaRatingRequirement(uint32 minarenaslot
)
18189 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
18190 // the personal rating of the arena team must match the required limit as well
18191 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
18192 uint32 max_personal_rating
= 0;
18193 for(int i
= minarenaslot
; i
< MAX_ARENA_SLOT
; ++i
)
18195 if(ArenaTeam
* at
= sObjectMgr
.GetArenaTeamById(GetArenaTeamId(i
)))
18197 uint32 p_rating
= GetArenaPersonalRating(i
);
18198 uint32 t_rating
= at
->GetRating();
18199 p_rating
= p_rating
< t_rating
? p_rating
: t_rating
;
18200 if(max_personal_rating
< p_rating
)
18201 max_personal_rating
= p_rating
;
18204 return max_personal_rating
;
18207 void Player::UpdateHomebindTime(uint32 time
)
18209 // GMs never get homebind timer online
18210 if (m_InstanceValid
|| isGameMaster())
18212 if(m_HomebindTimer
) // instance valid, but timer not reset
18215 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
18217 data
<< uint32(ERR_RAID_GROUP_NONE
); // error used only when timer = 0
18218 GetSession()->SendPacket(&data
);
18220 // instance is valid, reset homebind timer
18221 m_HomebindTimer
= 0;
18223 else if (m_HomebindTimer
> 0)
18225 if (time
>= m_HomebindTimer
)
18227 // teleport to nearest graveyard
18228 RepopAtGraveyard();
18231 m_HomebindTimer
-= time
;
18235 // instance is invalid, start homebind timer
18236 m_HomebindTimer
= 60000;
18237 // send message to player
18238 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
18239 data
<< uint32(m_HomebindTimer
);
18240 data
<< uint32(ERR_RAID_GROUP_NONE
); // error used only when timer = 0
18241 GetSession()->SendPacket(&data
);
18242 sLog
.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
18246 void Player::UpdatePvP(bool state
, bool ovrride
)
18248 if(!state
|| ovrride
)
18251 pvpInfo
.endTimer
= 0;
18255 if(pvpInfo
.endTimer
!= 0)
18256 pvpInfo
.endTimer
= time(NULL
);
18262 void Player::AddSpellAndCategoryCooldowns(SpellEntry
const* spellInfo
, uint32 itemId
, Spell
* spell
, bool infinityCooldown
)
18264 // init cooldown values
18269 // some special item spells without correct cooldown in SpellInfo
18270 // cooldown information stored in item prototype
18271 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
18275 if(ItemPrototype
const* proto
= ObjectMgr::GetItemPrototype(itemId
))
18277 for(int idx
= 0; idx
< 5; ++idx
)
18279 if(proto
->Spells
[idx
].SpellId
== spellInfo
->Id
)
18281 cat
= proto
->Spells
[idx
].SpellCategory
;
18282 rec
= proto
->Spells
[idx
].SpellCooldown
;
18283 catrec
= proto
->Spells
[idx
].SpellCategoryCooldown
;
18290 // if no cooldown found above then base at DBC data
18291 if(rec
< 0 && catrec
< 0)
18293 cat
= spellInfo
->Category
;
18294 rec
= spellInfo
->RecoveryTime
;
18295 catrec
= spellInfo
->CategoryRecoveryTime
;
18298 time_t curTime
= time(NULL
);
18303 // overwrite time for selected category
18304 if(infinityCooldown
)
18306 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
18307 // but not allow ignore until reset or re-login
18308 catrecTime
= catrec
> 0 ? curTime
+infinityCooldownDelay
: 0;
18309 recTime
= rec
> 0 ? curTime
+infinityCooldownDelay
: catrecTime
;
18313 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
18314 // prevent 0 cooldowns set by another way
18315 if (rec
<= 0 && catrec
<= 0 && (cat
== 76 || IsAutoRepeatRangedSpell(spellInfo
) && spellInfo
->Id
!= SPELL_ID_AUTOSHOT
))
18316 rec
= GetAttackTime(RANGED_ATTACK
);
18318 // Now we have cooldown data (if found any), time to apply mods
18320 ApplySpellMod(spellInfo
->Id
, SPELLMOD_COOLDOWN
, rec
, spell
);
18323 ApplySpellMod(spellInfo
->Id
, SPELLMOD_COOLDOWN
, catrec
, spell
);
18325 // replace negative cooldowns by 0
18326 if (rec
< 0) rec
= 0;
18327 if (catrec
< 0) catrec
= 0;
18329 // no cooldown after applying spell mods
18330 if( rec
== 0 && catrec
== 0)
18333 catrecTime
= catrec
? curTime
+catrec
/IN_MILLISECONDS
: 0;
18334 recTime
= rec
? curTime
+rec
/IN_MILLISECONDS
: catrecTime
;
18337 // self spell cooldown
18339 AddSpellCooldown(spellInfo
->Id
, itemId
, recTime
);
18342 if (cat
&& catrec
> 0)
18344 SpellCategoryStore::const_iterator i_scstore
= sSpellCategoryStore
.find(cat
);
18345 if(i_scstore
!= sSpellCategoryStore
.end())
18347 for(SpellCategorySet::const_iterator i_scset
= i_scstore
->second
.begin(); i_scset
!= i_scstore
->second
.end(); ++i_scset
)
18349 if(*i_scset
== spellInfo
->Id
) // skip main spell, already handled above
18352 AddSpellCooldown(*i_scset
, itemId
, catrecTime
);
18358 void Player::AddSpellCooldown(uint32 spellid
, uint32 itemid
, time_t end_time
)
18362 sc
.itemid
= itemid
;
18363 m_spellCooldowns
[spellid
] = sc
;
18366 void Player::SendCooldownEvent(SpellEntry
const *spellInfo
, uint32 itemId
, Spell
* spell
)
18368 // start cooldowns at server side, if any
18369 AddSpellAndCategoryCooldowns(spellInfo
, itemId
, spell
);
18371 // Send activate cooldown timer (possible 0) at client side
18372 WorldPacket
data(SMSG_COOLDOWN_EVENT
, (4+8));
18373 data
<< uint32(spellInfo
->Id
);
18374 data
<< uint64(GetGUID());
18375 SendDirectMessage(&data
);
18378 void Player::UpdatePotionCooldown(Spell
* spell
)
18380 // no potion used i combat or still in combat
18381 if(!m_lastPotionId
|| isInCombat())
18384 // Call not from spell cast, send cooldown event for item spells if no in combat
18387 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
18388 if(ItemPrototype
const* proto
= ObjectMgr::GetItemPrototype(m_lastPotionId
))
18389 for(int idx
= 0; idx
< 5; ++idx
)
18390 if(proto
->Spells
[idx
].SpellId
&& proto
->Spells
[idx
].SpellTrigger
== ITEM_SPELLTRIGGER_ON_USE
)
18391 if(SpellEntry
const* spellInfo
= sSpellStore
.LookupEntry(proto
->Spells
[idx
].SpellId
))
18392 SendCooldownEvent(spellInfo
,m_lastPotionId
);
18394 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
18396 SendCooldownEvent(spell
->m_spellInfo
,m_lastPotionId
,spell
);
18398 m_lastPotionId
= 0;
18401 //slot to be excluded while counting
18402 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition
, int8 slot
)
18404 if(!enchantmentcondition
)
18407 SpellItemEnchantmentConditionEntry
const *Condition
= sSpellItemEnchantmentConditionStore
.LookupEntry(enchantmentcondition
);
18412 uint8 curcount
[4] = {0, 0, 0, 0};
18414 //counting current equipped gem colors
18415 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
18419 Item
*pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
18420 if(pItem2
&& pItem2
->GetProto()->Socket
[0].Color
)
18422 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
18424 uint32 enchant_id
= pItem2
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
18428 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
18432 uint32 gemid
= enchantEntry
->GemID
;
18436 ItemPrototype
const* gemProto
= sItemStorage
.LookupEntry
<ItemPrototype
>(gemid
);
18440 GemPropertiesEntry
const* gemProperty
= sGemPropertiesStore
.LookupEntry(gemProto
->GemProperties
);
18444 uint8 GemColor
= gemProperty
->color
;
18446 for(uint8 b
= 0, tmpcolormask
= 1; b
< 4; b
++, tmpcolormask
<<= 1)
18448 if(tmpcolormask
& GemColor
)
18455 bool activate
= true;
18457 for(int i
= 0; i
< 5; ++i
)
18459 if(!Condition
->Color
[i
])
18462 uint32 _cur_gem
= curcount
[Condition
->Color
[i
] - 1];
18464 // if have <CompareColor> use them as count, else use <value> from Condition
18465 uint32 _cmp_gem
= Condition
->CompareColor
[i
] ? curcount
[Condition
->CompareColor
[i
] - 1]: Condition
->Value
[i
];
18467 switch(Condition
->Comparator
[i
])
18469 case 2: // requires less <color> than (<value> || <comparecolor>) gems
18470 activate
&= (_cur_gem
< _cmp_gem
) ? true : false;
18472 case 3: // requires more <color> than (<value> || <comparecolor>) gems
18473 activate
&= (_cur_gem
> _cmp_gem
) ? true : false;
18475 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
18476 activate
&= (_cur_gem
>= _cmp_gem
) ? true : false;
18481 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");
18486 void Player::CorrectMetaGemEnchants(uint8 exceptslot
, bool apply
)
18488 //cycle all equipped items
18489 for(uint32 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
18491 //enchants for the slot being socketed are handled by Player::ApplyItemMods
18492 if(slot
== exceptslot
)
18495 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
18497 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
)
18500 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
18502 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
18506 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
18510 uint32 condition
= enchantEntry
->EnchantmentCondition
;
18513 //was enchant active with/without item?
18514 bool wasactive
= EnchantmentFitsRequirements(condition
, apply
? exceptslot
: -1);
18515 //should it now be?
18516 if(wasactive
!= EnchantmentFitsRequirements(condition
, apply
? -1 : exceptslot
))
18518 // ignore item gem conditions
18519 //if state changed, (dis)apply enchant
18520 ApplyEnchantment(pItem
, EnchantmentSlot(enchant_slot
), !wasactive
, true, true);
18527 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
18528 void Player::ToggleMetaGemsActive(uint8 exceptslot
, bool apply
)
18530 //cycle all equipped items
18531 for(int slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
18533 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
18534 if(slot
== exceptslot
)
18537 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
18539 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
) //if item has no sockets or no item is equipped go to next item
18542 //cycle all (gem)enchants
18543 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
18545 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
18546 if(!enchant_id
) //if no enchant go to next enchant(slot)
18549 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
18553 //only metagems to be (de)activated, so only enchants with condition
18554 uint32 condition
= enchantEntry
->EnchantmentCondition
;
18556 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
), apply
);
18561 void Player::SetBattleGroundEntryPoint()
18564 if (!m_taxi
.empty())
18566 m_bgData
.mountSpell
= 0;
18567 m_bgData
.taxiPath
[0] = m_taxi
.GetTaxiSource();
18568 m_bgData
.taxiPath
[1] = m_taxi
.GetTaxiDestination();
18570 // On taxi we don't need check for dungeon
18571 m_bgData
.joinPos
= WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
18576 m_bgData
.ClearTaxiPath();
18578 // Mount spell id storing
18581 AuraList
const& auras
= GetAurasByType(SPELL_AURA_MOUNTED
);
18582 if (!auras
.empty())
18583 m_bgData
.mountSpell
= (*auras
.begin())->GetId();
18586 m_bgData
.mountSpell
= 0;
18588 // If map is dungeon find linked graveyard
18589 if(GetMap()->IsDungeon())
18591 if (const WorldSafeLocsEntry
* entry
= sObjectMgr
.GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam()))
18593 m_bgData
.joinPos
= WorldLocation(entry
->map_id
, entry
->x
, entry
->y
, entry
->z
, 0.0f
);
18597 sLog
.outError("SetBattleGroundEntryPoint: Dungeon map %u has no linked graveyard, setting home location as entry point.", GetMapId());
18599 // If new entry point is not BG or arena set it
18600 else if (!GetMap()->IsBattleGroundOrArena())
18602 m_bgData
.joinPos
= WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
18607 // In error cases use homebind position
18608 m_bgData
.joinPos
= WorldLocation(m_homebindMapId
, m_homebindX
, m_homebindY
, m_homebindZ
, 0.0f
);
18611 void Player::LeaveBattleground(bool teleportToEntryPoint
)
18613 if(BattleGround
*bg
= GetBattleGround())
18615 bg
->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint
, true);
18617 // call after remove to be sure that player resurrected for correct cast
18618 if( bg
->isBattleGround() && !isGameMaster() && sWorld
.getConfig(CONFIG_BOOL_BATTLEGROUND_CAST_DESERTER
) )
18620 if( bg
->GetStatus() == STATUS_IN_PROGRESS
|| bg
->GetStatus() == STATUS_WAIT_JOIN
)
18622 //lets check if player was teleported from BG and schedule delayed Deserter spell cast
18623 if(IsBeingTeleportedFar())
18625 ScheduleDelayedOperation(DELAYED_SPELL_CAST_DESERTER
);
18629 CastSpell(this, 26013, true); // Deserter
18635 bool Player::CanJoinToBattleground() const
18637 // check Deserter debuff
18638 if(GetDummyAura(26013))
18644 bool Player::CanReportAfkDueToLimit()
18646 // a player can complain about 15 people per 5 minutes
18647 if(m_bgData
.bgAfkReportedCount
++ >= 15)
18653 ///This player has been blamed to be inactive in a battleground
18654 void Player::ReportedAfkBy(Player
* reporter
)
18656 BattleGround
*bg
= GetBattleGround();
18657 if(!bg
|| bg
!= reporter
->GetBattleGround() || GetTeam() != reporter
->GetTeam())
18660 // check if player has 'Idle' or 'Inactive' debuff
18661 if(m_bgData
.bgAfkReporter
.find(reporter
->GetGUIDLow()) == m_bgData
.bgAfkReporter
.end() && !HasAura(43680, EFFECT_INDEX_0
) && !HasAura(43681, EFFECT_INDEX_0
) && reporter
->CanReportAfkDueToLimit())
18663 m_bgData
.bgAfkReporter
.insert(reporter
->GetGUIDLow());
18664 // 3 players have to complain to apply debuff
18665 if(m_bgData
.bgAfkReporter
.size() >= 3)
18667 // cast 'Idle' spell
18668 CastSpell(this, 43680, true);
18669 m_bgData
.bgAfkReporter
.clear();
18674 WorldObject
const* Player::GetViewPoint() const
18676 if(uint64 far_sight
= GetFarSight())
18678 WorldObject
const* viewPoint
= GetMap()->GetWorldObject(far_sight
);
18679 return viewPoint
? viewPoint
: this; // always expected not NULL
18685 bool Player::IsVisibleInGridForPlayer( Player
* pl
) const
18687 // gamemaster in GM mode see all, including ghosts
18688 if(pl
->isGameMaster() && GetSession()->GetSecurity() <= pl
->GetSession()->GetSecurity())
18691 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
18692 if (InBattleGround())
18694 if (!(isAlive() || m_deathTimer
> 0) && !IsFriendlyTo(pl
) )
18699 // Live player see live player or dead player with not realized corpse
18700 if(pl
->isAlive() || pl
->m_deathTimer
> 0)
18702 return isAlive() || m_deathTimer
> 0;
18705 // Ghost see other friendly ghosts, that's for sure
18706 if(!(isAlive() || m_deathTimer
> 0) && IsFriendlyTo(pl
))
18709 // Dead player see live players near own corpse
18712 Corpse
*corpse
= pl
->GetCorpse();
18715 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
18716 if(corpse
->IsWithinDistInMap(this,(20+25)*sWorld
.getConfig(CONFIG_FLOAT_RATE_CREATURE_AGGRO
)))
18721 // and not see any other
18725 bool Player::IsVisibleGloballyFor( Player
* u
) const
18730 // Always can see self
18734 // Visible units, always are visible for all players
18735 if (GetVisibility() == VISIBILITY_ON
)
18738 // GMs are visible for higher gms (or players are visible for gms)
18739 if (u
->GetSession()->GetSecurity() > SEC_PLAYER
)
18740 return GetSession()->GetSecurity() <= u
->GetSession()->GetSecurity();
18742 // non faction visibility non-breakable for non-GMs
18743 if (GetVisibility() == VISIBILITY_OFF
)
18746 // non-gm stealth/invisibility not hide from global player lists
18751 inline void BeforeVisibilityDestroy(T
* /*t*/, Player
* /*p*/)
18756 inline void BeforeVisibilityDestroy
<Creature
>(Creature
* t
, Player
* p
)
18758 if (p
->GetPetGUID()==t
->GetGUID() && ((Creature
*)t
)->isPet())
18759 ((Pet
*)t
)->Remove(PET_SAVE_NOT_IN_SLOT
, true);
18762 void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, WorldObject
* target
)
18764 if(HaveAtClient(target
))
18766 if(!target
->isVisibleForInState(this, viewPoint
, true))
18768 if (target
->GetTypeId()==TYPEID_UNIT
)
18769 BeforeVisibilityDestroy
<Creature
>((Creature
*)target
,this);
18771 ObjectGuid t_guid
= target
->GetGUID();
18773 target
->DestroyForPlayer(this);
18774 m_clientGUIDs
.erase(t_guid
);
18776 #ifdef MANGOS_DEBUG
18777 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
18778 sLog
.outDebug("%s out of range for player %u. Distance = %f",t_guid
.GetString().c_str(),GetGUIDLow(),GetDistance(target
));
18784 if(target
->isVisibleForInState(this, viewPoint
, false))
18786 target
->SendCreateUpdateToPlayer(this);
18787 if(target
->GetTypeId()!=TYPEID_GAMEOBJECT
||!((GameObject
*)target
)->IsTransport())
18788 m_clientGUIDs
.insert(target
->GetGUID());
18790 #ifdef MANGOS_DEBUG
18791 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
18792 sLog
.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
18795 // target aura duration for caster show only if target exist at caster client
18796 // send data at target visibility change (adding to client)
18797 if(target
!=this && target
->isType(TYPEMASK_UNIT
))
18798 SendAurasForTarget((Unit
*)target
);
18800 if(target
->GetTypeId()==TYPEID_UNIT
&& ((Creature
*)target
)->isAlive())
18801 ((Creature
*)target
)->SendMonsterMoveWithSpeedToCurrentDestination(this);
18807 inline void UpdateVisibilityOf_helper(ObjectGuidSet
& s64
, T
* target
)
18809 s64
.insert(target
->GetGUID());
18813 inline void UpdateVisibilityOf_helper(ObjectGuidSet
& s64
, GameObject
* target
)
18815 if(!target
->IsTransport())
18816 s64
.insert(target
->GetGUID());
18820 void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, T
* target
, UpdateData
& data
, UpdateDataMapType
& /*data_updates*/, std::set
<WorldObject
*>& visibleNow
)
18822 if(HaveAtClient(target
))
18824 if(!target
->isVisibleForInState(this,viewPoint
,true))
18826 BeforeVisibilityDestroy
<T
>(target
,this);
18828 ObjectGuid t_guid
= target
->GetGUID();
18830 target
->BuildOutOfRangeUpdateBlock(&data
);
18831 m_clientGUIDs
.erase(t_guid
);
18833 #ifdef MANGOS_DEBUG
18834 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
18835 sLog
.outDebug("%s is out of range for player %u. Distance = %f",t_guid
.GetString().c_str(),GetGUIDLow(),GetDistance(target
));
18841 if(target
->isVisibleForInState(this,viewPoint
,false))
18843 visibleNow
.insert(target
);
18844 target
->BuildCreateUpdateBlockForPlayer(&data
, this);
18845 UpdateVisibilityOf_helper(m_clientGUIDs
,target
);
18847 #ifdef MANGOS_DEBUG
18848 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
18849 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
));
18855 template void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, Player
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
18856 template void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, Creature
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
18857 template void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, Corpse
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
18858 template void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, GameObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
18859 template void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, DynamicObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
18861 void Player::InitPrimaryProfessions()
18863 SetFreePrimaryProfessions(sWorld
.getConfig(CONFIG_UINT32_MAX_PRIMARY_TRADE_SKILL
));
18866 void Player::SendComboPoints()
18868 Unit
*combotarget
= ObjectAccessor::GetUnit(*this, m_comboTarget
);
18871 WorldPacket
data(SMSG_UPDATE_COMBO_POINTS
, combotarget
->GetPackGUID().size()+1);
18872 data
<< combotarget
->GetPackGUID();
18873 data
<< uint8(m_comboPoints
);
18874 GetSession()->SendPacket(&data
);
18878 void Player::AddComboPoints(Unit
* target
, int8 count
)
18883 // without combo points lost (duration checked in aura)
18884 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
18886 if(target
->GetGUID() == m_comboTarget
)
18888 m_comboPoints
+= count
;
18893 if(Unit
* target2
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
18894 target2
->RemoveComboPointHolder(GetGUIDLow());
18896 m_comboTarget
= target
->GetGUID();
18897 m_comboPoints
= count
;
18899 target
->AddComboPointHolder(GetGUIDLow());
18902 if (m_comboPoints
> 5) m_comboPoints
= 5;
18903 if (m_comboPoints
< 0) m_comboPoints
= 0;
18908 void Player::ClearComboPoints()
18913 // without combopoints lost (duration checked in aura)
18914 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
18920 if(Unit
* target
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
18921 target
->RemoveComboPointHolder(GetGUIDLow());
18926 void Player::SetGroup(Group
*group
, int8 subgroup
)
18932 // never use SetGroup without a subgroup unless you specify NULL for group
18933 ASSERT(subgroup
>= 0);
18934 m_group
.link(group
, this);
18935 m_group
.setSubGroup((uint8
)subgroup
);
18939 void Player::SendInitialPacketsBeforeAddToMap()
18941 GetSocial()->SendSocialList();
18944 WorldPacket
data(SMSG_BINDPOINTUPDATE
, 5*4);
18945 data
<< m_homebindX
<< m_homebindY
<< m_homebindZ
;
18946 data
<< (uint32
) m_homebindMapId
;
18947 data
<< (uint32
) m_homebindAreaId
;
18948 GetSession()->SendPacket(&data
);
18950 // SMSG_SET_PROFICIENCY
18951 // SMSG_SET_PCT_SPELL_MODIFIER
18952 // SMSG_SET_FLAT_SPELL_MODIFIER
18954 SendTalentsInfoData(false);
18956 data
.Initialize(SMSG_INSTANCE_DIFFICULTY
, 4+4);
18959 GetSession()->SendPacket(&data
);
18961 SendInitialSpells();
18963 data
.Initialize(SMSG_SEND_UNLEARN_SPELLS
, 4);
18964 data
<< uint32(0); // count, for(count) uint32;
18965 GetSession()->SendPacket(&data
);
18967 SendInitialActionButtons();
18968 m_reputationMgr
.SendInitialReputations();
18971 SendCorpseReclaimDelay(true);
18973 SendInitWorldStates(GetZoneId(), GetAreaId());
18975 SendEquipmentSetList();
18977 m_achievementMgr
.SendAllAchievementData();
18979 data
.Initialize(SMSG_LOGIN_SETTIMESPEED
, 4 + 4 + 4);
18980 data
<< uint32(secsToTimeBitFields(sWorld
.GetGameTime()));
18981 data
<< (float)0.01666667f
; // game speed
18982 data
<< uint32(0); // added in 3.1.2
18983 GetSession()->SendPacket( &data
);
18985 // SMSG_TALENTS_INFO x 2 for pet (unspent points and talents in separate packets...)
18987 // SMSG_POWER_UPDATE
18989 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
18990 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
) || HasAuraType(SPELL_AURA_FLY
) || isInFlight())
18991 m_movementInfo
.AddMovementFlag(MOVEFLAG_FLYING
);
18996 void Player::SendInitialPacketsAfterAddToMap()
18999 uint32 newzone
, newarea
;
19000 GetZoneAndAreaId(newzone
,newarea
);
19001 UpdateZone(newzone
,newarea
); // also call SendInitWorldStates();
19003 WorldPacket
data(SMSG_TIME_SYNC_REQ
, 4); // new 2.0.x, enable movement
19004 data
<< uint32(0x00000000); // on blizz it increments periodically
19005 GetSession()->SendPacket(&data
);
19007 CastSpell(this, 836, true); // LOGINEFFECT
19009 // set some aura effects that send packet to player client after add player to map
19010 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
19011 // same auras state lost at far teleport, send it one more time in this case also
19012 static const AuraType auratypes
[] =
19014 SPELL_AURA_MOD_FEAR
, SPELL_AURA_TRANSFORM
, SPELL_AURA_WATER_WALK
,
19015 SPELL_AURA_FEATHER_FALL
, SPELL_AURA_HOVER
, SPELL_AURA_SAFE_FALL
,
19016 SPELL_AURA_FLY
, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
, SPELL_AURA_NONE
19018 for(AuraType
const* itr
= &auratypes
[0]; itr
&& itr
[0] != SPELL_AURA_NONE
; ++itr
)
19020 Unit::AuraList
const& auraList
= GetAurasByType(*itr
);
19021 if(!auraList
.empty())
19022 auraList
.front()->ApplyModifier(true,true);
19025 if(HasAuraType(SPELL_AURA_MOD_STUN
))
19026 SetMovement(MOVE_ROOT
);
19028 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
19029 if(HasAuraType(SPELL_AURA_MOD_ROOT
))
19031 WorldPacket
data2(SMSG_FORCE_MOVE_ROOT
, 10);
19032 data2
<< GetPackGUID();
19033 data2
<< (uint32
)2;
19034 SendMessageToSet(&data2
,true);
19037 SendAurasForTarget(this);
19038 SendEnchantmentDurations(); // must be after add to map
19039 SendItemDurations(); // must be after add to map
19042 void Player::SendUpdateToOutOfRangeGroupMembers()
19044 if (m_groupUpdateMask
== GROUP_UPDATE_FLAG_NONE
)
19046 if(Group
* group
= GetGroup())
19047 group
->UpdatePlayerOutOfRange(this);
19049 m_groupUpdateMask
= GROUP_UPDATE_FLAG_NONE
;
19050 m_auraUpdateMask
= 0;
19051 if(Pet
*pet
= GetPet())
19052 pet
->ResetAuraUpdateMask();
19055 void Player::SendTransferAborted(uint32 mapid
, uint8 reason
, uint8 arg
)
19057 WorldPacket
data(SMSG_TRANSFER_ABORTED
, 4+2);
19058 data
<< uint32(mapid
);
19059 data
<< uint8(reason
); // transfer abort reason
19062 case TRANSFER_ABORT_INSUF_EXPAN_LVL
:
19063 case TRANSFER_ABORT_DIFFICULTY
:
19064 case TRANSFER_ABORT_UNIQUE_MESSAGE
:
19065 data
<< uint8(arg
);
19068 GetSession()->SendPacket(&data
);
19071 void Player::SendInstanceResetWarning( uint32 mapid
, Difficulty difficulty
, uint32 time
)
19073 // type of warning, based on the time remaining until reset
19076 type
= RAID_INSTANCE_WELCOME
;
19077 else if(time
> 900 && time
<= 3600)
19078 type
= RAID_INSTANCE_WARNING_HOURS
;
19079 else if(time
> 300 && time
<= 900)
19080 type
= RAID_INSTANCE_WARNING_MIN
;
19082 type
= RAID_INSTANCE_WARNING_MIN_SOON
;
19084 WorldPacket
data(SMSG_RAID_INSTANCE_MESSAGE
, 4+4+4+4);
19085 data
<< uint32(type
);
19086 data
<< uint32(mapid
);
19087 data
<< uint32(difficulty
); // difficulty
19088 data
<< uint32(time
);
19089 if(type
== RAID_INSTANCE_WELCOME
)
19091 data
<< uint8(0); // is your (1)
19092 data
<< uint8(0); // is extended (1), ignored if prev field is 0
19094 GetSession()->SendPacket(&data
);
19097 void Player::ApplyEquipCooldown( Item
* pItem
)
19099 for(int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
19101 _Spell
const& spellData
= pItem
->GetProto()->Spells
[i
];
19104 if( !spellData
.SpellId
)
19107 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
19108 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
)
19111 AddSpellCooldown(spellData
.SpellId
, pItem
->GetEntry(), time(NULL
) + 30);
19113 WorldPacket
data(SMSG_ITEM_COOLDOWN
, 12);
19114 data
<< pItem
->GetGUID();
19115 data
<< uint32(spellData
.SpellId
);
19116 GetSession()->SendPacket(&data
);
19120 void Player::resetSpells()
19122 // not need after this call
19123 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS
))
19124 RemoveAtLoginFlag(AT_LOGIN_RESET_SPELLS
,true);
19126 // make full copy of map (spells removed and marked as deleted at another spell remove
19127 // and we can't use original map for safe iterative with visit each spell at loop end
19128 PlayerSpellMap smap
= GetSpellMap();
19130 for(PlayerSpellMap::const_iterator iter
= smap
.begin();iter
!= smap
.end(); ++iter
)
19131 removeSpell(iter
->first
,false,false); // only iter->first can be accessed, object by iter->second can be deleted already
19133 learnDefaultSpells();
19134 learnQuestRewardedSpells();
19137 void Player::learnDefaultSpells()
19139 // learn default race/class spells
19140 PlayerInfo
const *info
= sObjectMgr
.GetPlayerInfo(getRace(),getClass());
19141 for (PlayerCreateInfoSpells::const_iterator itr
= info
->spell
.begin(); itr
!=info
->spell
.end(); ++itr
)
19143 uint32 tspell
= *itr
;
19144 sLog
.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell
);
19145 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
19146 addSpell(tspell
,true,true,true,false);
19147 else // but send in normal spell in game learn case
19148 learnSpell(tspell
,true);
19152 void Player::learnQuestRewardedSpells(Quest
const* quest
)
19154 uint32 spell_id
= quest
->GetRewSpellCast();
19156 // skip quests without rewarded spell
19160 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
19164 // check learned spells state
19165 bool found
= false;
19166 for(int i
=0; i
< MAX_EFFECT_INDEX
; ++i
)
19168 if(spellInfo
->Effect
[i
] == SPELL_EFFECT_LEARN_SPELL
&& !HasSpell(spellInfo
->EffectTriggerSpell
[i
]))
19175 // skip quests with not teaching spell or already known spell
19179 // prevent learn non first rank unknown profession and second specialization for same profession)
19180 uint32 learned_0
= spellInfo
->EffectTriggerSpell
[EFFECT_INDEX_0
];
19181 if( sSpellMgr
.GetSpellRank(learned_0
) > 1 && !HasSpell(learned_0
) )
19183 // not have first rank learned (unlearned prof?)
19184 uint32 first_spell
= sSpellMgr
.GetFirstSpellInChain(learned_0
);
19185 if( !HasSpell(first_spell
) )
19188 SpellEntry
const *learnedInfo
= sSpellStore
.LookupEntry(learned_0
);
19193 if (learnedInfo
->Effect
[EFFECT_INDEX_0
] == SPELL_EFFECT_TRADE_SKILL
&& learnedInfo
->Effect
[EFFECT_INDEX_1
] == 0)
19195 // search other specialization for same prof
19196 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
19198 if(itr
->second
.state
== PLAYERSPELL_REMOVED
|| itr
->first
==learned_0
)
19201 SpellEntry
const *itrInfo
= sSpellStore
.LookupEntry(itr
->first
);
19205 // compare only specializations
19206 if (itrInfo
->Effect
[EFFECT_INDEX_0
] != SPELL_EFFECT_TRADE_SKILL
|| itrInfo
->Effect
[EFFECT_INDEX_1
] != 0)
19209 // compare same chain spells
19210 if(sSpellMgr
.GetFirstSpellInChain(itr
->first
) != first_spell
)
19213 // now we have 2 specialization, learn possible only if found is lesser specialization rank
19214 if(!sSpellMgr
.IsHighRankOfSpell(learned_0
,itr
->first
))
19220 CastSpell( this, spell_id
, true);
19223 void Player::learnQuestRewardedSpells()
19225 // learn spells received from quest completing
19226 for(QuestStatusMap::const_iterator itr
= mQuestStatus
.begin(); itr
!= mQuestStatus
.end(); ++itr
)
19228 // skip no rewarded quests
19229 if(!itr
->second
.m_rewarded
)
19232 Quest
const* quest
= sObjectMgr
.GetQuestTemplate(itr
->first
);
19236 learnQuestRewardedSpells(quest
);
19240 void Player::learnSkillRewardedSpells(uint32 skill_id
, uint32 skill_value
)
19242 uint32 raceMask
= getRaceMask();
19243 uint32 classMask
= getClassMask();
19244 for (uint32 j
=0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
19246 SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
);
19247 if (!pAbility
|| pAbility
->skillId
!=skill_id
|| pAbility
->learnOnGetSkill
!= ABILITY_LEARNED_ON_GET_PROFESSION_SKILL
)
19249 // Check race if set
19250 if (pAbility
->racemask
&& !(pAbility
->racemask
& raceMask
))
19252 // Check class if set
19253 if (pAbility
->classmask
&& !(pAbility
->classmask
& classMask
))
19256 if (sSpellStore
.LookupEntry(pAbility
->spellId
))
19258 // need unlearn spell
19259 if (skill_value
< pAbility
->req_skill_value
)
19260 removeSpell(pAbility
->spellId
);
19262 else if (!IsInWorld())
19263 addSpell(pAbility
->spellId
,true,true,true,false);
19265 learnSpell(pAbility
->spellId
,true);
19270 void Player::SendAurasForTarget(Unit
*target
)
19272 if(target
->GetVisibleAuras()->empty()) // speedup things
19275 WorldPacket
data(SMSG_AURA_UPDATE_ALL
);
19276 data
<< target
->GetPackGUID();
19278 Unit::VisibleAuraMap
const *visibleAuras
= target
->GetVisibleAuras();
19279 for(Unit::VisibleAuraMap::const_iterator itr
= visibleAuras
->begin(); itr
!= visibleAuras
->end(); ++itr
)
19281 for(int j
= 0; j
< MAX_EFFECT_INDEX
; ++j
)
19283 if(Aura
*aura
= target
->GetAura(itr
->second
, SpellEffectIndex(j
)))
19285 data
<< uint8(aura
->GetAuraSlot());
19286 data
<< uint32(aura
->GetId());
19290 uint8 auraFlags
= aura
->GetAuraFlags();
19292 data
<< uint8(auraFlags
);
19294 data
<< uint8(aura
->GetAuraLevel());
19296 if (aura
->GetAuraCharges())
19297 data
<< uint8(aura
->GetAuraCharges() * aura
->GetStackAmount());
19299 data
<< uint8(aura
->GetStackAmount());
19301 if(!(auraFlags
& AFLAG_NOT_CASTER
)) // packed GUID of caster
19303 data
.appendPackGUID(aura
->GetCasterGUID());
19306 if(auraFlags
& AFLAG_DURATION
) // include aura duration
19308 data
<< uint32(aura
->GetAuraMaxDuration());
19309 data
<< uint32(aura
->GetAuraDuration());
19317 GetSession()->SendPacket(&data
);
19320 void Player::SetDailyQuestStatus( uint32 quest_id
)
19322 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
19324 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
19326 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
19327 m_lastDailyQuestTime
= time(NULL
); // last daily quest time
19328 m_DailyQuestChanged
= true;
19334 void Player::ResetDailyQuestStatus()
19336 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
19337 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
19339 // DB data deleted in caller
19340 m_DailyQuestChanged
= false;
19341 m_lastDailyQuestTime
= 0;
19344 BattleGround
* Player::GetBattleGround() const
19346 if(GetBattleGroundId()==0)
19349 return sBattleGroundMgr
.GetBattleGround(GetBattleGroundId(), m_bgData
.bgTypeID
);
19352 bool Player::InArena() const
19354 BattleGround
*bg
= GetBattleGround();
19355 if(!bg
|| !bg
->isArena())
19361 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId
) const
19363 // get a template bg instead of running one
19364 BattleGround
*bg
= sBattleGroundMgr
.GetBattleGroundTemplate(bgTypeId
);
19368 // limit check leel to dbc compatible level range
19369 uint32 level
= getLevel();
19370 if (level
> DEFAULT_MAX_LEVEL
)
19371 level
= DEFAULT_MAX_LEVEL
;
19373 if(level
< bg
->GetMinLevel() || level
> bg
->GetMaxLevel())
19379 float Player::GetReputationPriceDiscount( Creature
const* pCreature
) const
19381 FactionTemplateEntry
const* vendor_faction
= pCreature
->getFactionTemplateEntry();
19382 if(!vendor_faction
|| !vendor_faction
->faction
)
19385 ReputationRank rank
= GetReputationRank(vendor_faction
->faction
);
19386 if(rank
<= REP_NEUTRAL
)
19389 return 1.0f
- 0.05f
* (rank
- REP_NEUTRAL
);
19392 bool Player::IsSpellFitByClassAndRace( uint32 spell_id
) const
19394 uint32 racemask
= getRaceMask();
19395 uint32 classmask
= getClassMask();
19397 SkillLineAbilityMapBounds bounds
= sSpellMgr
.GetSkillLineAbilityMapBounds(spell_id
);
19398 if (bounds
.first
==bounds
.second
)
19401 for(SkillLineAbilityMap::const_iterator _spell_idx
= bounds
.first
; _spell_idx
!= bounds
.second
; ++_spell_idx
)
19403 // skip wrong race skills
19404 if (_spell_idx
->second
->racemask
&& (_spell_idx
->second
->racemask
& racemask
) == 0)
19407 // skip wrong class skills
19408 if (_spell_idx
->second
->classmask
&& (_spell_idx
->second
->classmask
& classmask
) == 0)
19417 bool Player::HasQuestForGO(int32 GOId
) const
19419 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
19421 uint32 questid
= GetQuestSlotQuestId(i
);
19422 if ( questid
== 0 )
19425 QuestStatusMap::const_iterator qs_itr
= mQuestStatus
.find(questid
);
19426 if(qs_itr
== mQuestStatus
.end())
19429 QuestStatusData
const& qs
= qs_itr
->second
;
19431 if (qs
.m_status
== QUEST_STATUS_INCOMPLETE
)
19433 Quest
const* qinfo
= sObjectMgr
.GetQuestTemplate(questid
);
19437 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
19440 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
19442 if (qinfo
->ReqCreatureOrGOId
[j
]>=0) //skip non GO case
19445 if((-1)*GOId
== qinfo
->ReqCreatureOrGOId
[j
] && qs
.m_creatureOrGOcount
[j
] < qinfo
->ReqCreatureOrGOCount
[j
])
19453 void Player::UpdateForQuestWorldObjects()
19455 if(m_clientGUIDs
.empty())
19459 WorldPacket packet
;
19460 for(ObjectGuidSet::const_iterator itr
=m_clientGUIDs
.begin(); itr
!=m_clientGUIDs
.end(); ++itr
)
19462 if (itr
->IsGameobject())
19464 if (GameObject
*obj
= GetMap()->GetGameObject(*itr
))
19465 obj
->BuildValuesUpdateBlockForPlayer(&udata
,this);
19467 else if (itr
->IsCreatureOrVehicle())
19469 Creature
*obj
= GetMap()->GetCreatureOrPetOrVehicle(*itr
);
19473 // check if this unit requires quest specific flags
19474 if(!obj
->HasFlag(UNIT_NPC_FLAGS
,UNIT_NPC_FLAG_SPELLCLICK
))
19477 SpellClickInfoMapBounds clickPair
= sObjectMgr
.GetSpellClickInfoMapBounds(obj
->GetEntry());
19478 for(SpellClickInfoMap::const_iterator _itr
= clickPair
.first
; _itr
!= clickPair
.second
; ++_itr
)
19480 if(_itr
->second
.questStart
|| _itr
->second
.questEnd
)
19482 obj
->BuildCreateUpdateBlockForPlayer(&udata
,this);
19488 udata
.BuildPacket(&packet
);
19489 GetSession()->SendPacket(&packet
);
19492 void Player::SummonIfPossible(bool agree
)
19496 m_summon_expire
= 0;
19500 // expire and auto declined
19501 if(m_summon_expire
< time(NULL
))
19504 // stop taxi flight at summon
19507 GetMotionMaster()->MovementExpired();
19508 m_taxi
.ClearTaxiDestinations();
19511 // drop flag at summon
19512 // 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
19513 if(BattleGround
*bg
= GetBattleGround())
19514 bg
->EventPlayerDroppedFlag(this);
19516 m_summon_expire
= 0;
19518 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS
, 1);
19520 TeleportTo(m_summon_mapid
, m_summon_x
, m_summon_y
, m_summon_z
,GetOrientation());
19523 void Player::RemoveItemDurations( Item
*item
)
19525 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); ++itr
)
19529 m_itemDuration
.erase(itr
);
19535 void Player::AddItemDurations( Item
*item
)
19537 if(item
->GetUInt32Value(ITEM_FIELD_DURATION
))
19539 m_itemDuration
.push_back(item
);
19540 item
->SendTimeUpdate(this);
19544 void Player::AutoUnequipOffhandIfNeed()
19546 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
19550 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
19551 if (CanTitanGrip() || (offItem
->GetProto()->InventoryType
!= INVTYPE_2HWEAPON
&& !IsTwoHandUsed()))
19554 ItemPosCountVec off_dest
;
19555 uint8 off_msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false );
19556 if( off_msg
== EQUIP_ERR_OK
)
19558 RemoveItem(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
, true);
19559 StoreItem( off_dest
, offItem
, true );
19563 MoveItemFromInventory(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
, true);
19564 CharacterDatabase
.BeginTransaction();
19565 offItem
->DeleteFromInventoryDB(); // deletes item from character's inventory
19566 offItem
->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
19567 CharacterDatabase
.CommitTransaction();
19569 std::string subject
= GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM
);
19570 MailDraft(subject
).AddItem(offItem
).SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM
));
19574 bool Player::HasItemFitToSpellReqirements(SpellEntry
const* spellInfo
, Item
const* ignoreItem
)
19576 if(spellInfo
->EquippedItemClass
< 0)
19579 // scan other equipped items for same requirements (mostly 2 daggers/etc)
19580 // for optimize check 2 used cases only
19581 switch(spellInfo
->EquippedItemClass
)
19583 case ITEM_CLASS_WEAPON
:
19585 for(int i
= EQUIPMENT_SLOT_MAINHAND
; i
< EQUIPMENT_SLOT_TABARD
; ++i
)
19586 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
19587 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
19591 case ITEM_CLASS_ARMOR
:
19593 // tabard not have dependent spells
19594 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_MAINHAND
; ++i
)
19595 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
19596 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
19599 // shields can be equipped to offhand slot
19600 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
))
19601 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
19604 // ranged slot can have some armor subclasses
19605 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_RANGED
))
19606 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
19612 sLog
.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo
->EquippedItemClass
);
19619 bool Player::CanNoReagentCast(SpellEntry
const* spellInfo
) const
19621 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
19622 if (spellInfo
->AttributesEx5
& SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
&&
19623 HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PREPARATION
))
19626 // Check no reagent use mask
19627 uint64 noReagentMask_0_1
= GetUInt64Value(PLAYER_NO_REAGENT_COST_1
);
19628 uint32 noReagentMask_2
= GetUInt32Value(PLAYER_NO_REAGENT_COST_1
+2);
19629 if (spellInfo
->SpellFamilyFlags
& noReagentMask_0_1
||
19630 spellInfo
->SpellFamilyFlags2
& noReagentMask_2
)
19636 void Player::RemoveItemDependentAurasAndCasts( Item
* pItem
)
19638 AuraMap
& auras
= GetAuras();
19639 for(AuraMap::const_iterator itr
= auras
.begin(); itr
!= auras
.end(); )
19641 Aura
* aura
= itr
->second
;
19643 // skip passive (passive item dependent spells work in another way) and not self applied auras
19644 SpellEntry
const* spellInfo
= aura
->GetSpellProto();
19645 if(aura
->IsPassive() || aura
->GetCasterGUID()!=GetGUID())
19651 // skip if not item dependent or have alternative item
19652 if(HasItemFitToSpellReqirements(spellInfo
,pItem
))
19658 // no alt item, remove aura, restart check
19659 RemoveAurasDueToSpell(aura
->GetId());
19660 itr
= auras
.begin();
19663 // currently casted spells can be dependent from item
19664 for (uint32 i
= 0; i
< CURRENT_MAX_SPELL
; ++i
)
19665 if (Spell
* spell
= GetCurrentSpell(CurrentSpellTypes(i
)))
19666 if (spell
->getState()!=SPELL_STATE_DELAYED
&& !HasItemFitToSpellReqirements(spell
->m_spellInfo
,pItem
) )
19667 InterruptSpell(CurrentSpellTypes(i
));
19670 uint32
Player::GetResurrectionSpellId()
19672 // search priceless resurrection possibilities
19674 uint32 spell_id
= 0;
19675 AuraList
const& dummyAuras
= GetAurasByType(SPELL_AURA_DUMMY
);
19676 for(AuraList::const_iterator itr
= dummyAuras
.begin(); itr
!= dummyAuras
.end(); ++itr
)
19678 // Soulstone Resurrection // prio: 3 (max, non death persistent)
19679 if( prio
< 2 && (*itr
)->GetSpellProto()->SpellVisual
[0] == 99 && (*itr
)->GetSpellProto()->SpellIconID
== 92 )
19681 switch((*itr
)->GetId())
19683 case 20707: spell_id
= 3026; break; // rank 1
19684 case 20762: spell_id
= 20758; break; // rank 2
19685 case 20763: spell_id
= 20759; break; // rank 3
19686 case 20764: spell_id
= 20760; break; // rank 4
19687 case 20765: spell_id
= 20761; break; // rank 5
19688 case 27239: spell_id
= 27240; break; // rank 6
19689 case 47883: spell_id
= 47882; break; // rank 7
19691 sLog
.outError("Unhandled spell %u: S.Resurrection",(*itr
)->GetId());
19697 // Twisting Nether // prio: 2 (max)
19698 else if((*itr
)->GetId()==23701 && roll_chance_i(10))
19705 // Reincarnation (passive spell) // prio: 1
19706 // Glyph of Renewed Life remove reagent requiremnnt
19707 if (prio
< 1 && HasSpell(20608) && !HasSpellCooldown(21169) && (HasItemCount(17030,1) || HasAura(58059, EFFECT_INDEX_0
)))
19713 // Used in triggers for check "Only to targets that grant experience or honor" req
19714 bool Player::isHonorOrXPTarget(Unit
* pVictim
) const
19716 uint32 v_level
= pVictim
->getLevel();
19717 uint32 k_grey
= MaNGOS::XP::GetGrayLevel(getLevel());
19719 // Victim level less gray level
19720 if(v_level
<=k_grey
)
19723 if(pVictim
->GetTypeId() == TYPEID_UNIT
)
19725 if (((Creature
*)pVictim
)->isTotem() ||
19726 ((Creature
*)pVictim
)->isPet() ||
19727 ((Creature
*)pVictim
)->GetCreatureInfo()->flags_extra
& CREATURE_FLAG_EXTRA_NO_XP_AT_KILL
)
19733 bool Player::RewardPlayerAndGroupAtKill(Unit
* pVictim
)
19735 bool PvP
= pVictim
->isCharmedOwnedByPlayerOrPlayer();
19737 // prepare data for near group iteration (PvP and !PvP cases)
19739 bool honored_kill
= false;
19741 if(Group
*pGroup
= GetGroup())
19744 uint32 sum_level
= 0;
19745 Player
* member_with_max_level
= NULL
;
19746 Player
* not_gray_member_with_max_level
= NULL
;
19748 pGroup
->GetDataForXPAtKill(pVictim
,count
,sum_level
,member_with_max_level
,not_gray_member_with_max_level
);
19750 if(member_with_max_level
)
19752 /// not get Xp in PvP or no not gray players in group
19753 xp
= (PvP
|| !not_gray_member_with_max_level
) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level
, pVictim
);
19755 /// skip in check PvP case (for speed, not used)
19756 bool is_raid
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsRaid() && pGroup
->isRaidGroup();
19757 bool is_dungeon
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsDungeon();
19758 float group_rate
= MaNGOS::XP::xp_in_group_rate(count
,is_raid
);
19760 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
19762 Player
* pGroupGuy
= itr
->getSource();
19766 if(!pGroupGuy
->IsAtGroupRewardDistance(pVictim
))
19767 continue; // member (alive or dead) or his corpse at req. distance
19769 // honor can be in PvP and !PvP (racial leader) cases (for alive)
19770 if(pGroupGuy
->isAlive() && pGroupGuy
->RewardHonor(pVictim
,count
) && pGroupGuy
==this)
19771 honored_kill
= true;
19773 // xp and reputation only in !PvP case
19776 float rate
= group_rate
* float(pGroupGuy
->getLevel()) / sum_level
;
19778 // if is in dungeon then all receive full reputation at kill
19779 // rewarded any alive/dead/near_corpse group member
19780 pGroupGuy
->RewardReputation(pVictim
,is_dungeon
? 1.0f
: rate
);
19782 // XP updated only for alive group member
19783 if(pGroupGuy
->isAlive() && not_gray_member_with_max_level
&&
19784 pGroupGuy
->getLevel() <= not_gray_member_with_max_level
->getLevel())
19786 uint32 itr_xp
= (member_with_max_level
== not_gray_member_with_max_level
) ? uint32(xp
*rate
) : uint32((xp
*rate
/2)+1);
19788 pGroupGuy
->GiveXP(itr_xp
, pVictim
);
19789 if(Pet
* pet
= pGroupGuy
->GetPet())
19790 pet
->GivePetXP(itr_xp
/2);
19793 // quest objectives updated only for alive group member or dead but with not released body
19794 if(pGroupGuy
->isAlive()|| !pGroupGuy
->HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
))
19796 // normal creature (not pet/etc) can be only in !PvP case
19797 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
19798 pGroupGuy
->KilledMonster(((Creature
*)pVictim
)->GetCreatureInfo(), pVictim
->GetObjectGuid());
19804 else // if (!pGroup)
19806 xp
= PvP
? 0 : MaNGOS::XP::Gain(this, pVictim
);
19808 // honor can be in PvP and !PvP (racial leader) cases
19809 if(RewardHonor(pVictim
,1))
19810 honored_kill
= true;
19812 // xp and reputation only in !PvP case
19815 RewardReputation(pVictim
,1);
19816 GiveXP(xp
, pVictim
);
19818 if(Pet
* pet
= GetPet())
19819 pet
->GivePetXP(xp
);
19821 // normal creature (not pet/etc) can be only in !PvP case
19822 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
19823 KilledMonster(((Creature
*)pVictim
)->GetCreatureInfo(), pVictim
->GetObjectGuid());
19826 return xp
|| honored_kill
;
19829 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id
, WorldObject
* pRewardSource
)
19831 uint64 creature_guid
= pRewardSource
->GetTypeId()==TYPEID_UNIT
? pRewardSource
->GetGUID() : uint64(0);
19833 // prepare data for near group iteration
19834 if(Group
*pGroup
= GetGroup())
19836 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
19838 Player
* pGroupGuy
= itr
->getSource();
19842 if(!pGroupGuy
->IsAtGroupRewardDistance(pRewardSource
))
19843 continue; // member (alive or dead) or his corpse at req. distance
19845 // quest objectives updated only for alive group member or dead but with not released body
19846 if(pGroupGuy
->isAlive()|| !pGroupGuy
->HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
))
19847 pGroupGuy
->KilledMonsterCredit(creature_id
, creature_guid
);
19850 else // if (!pGroup)
19851 KilledMonsterCredit(creature_id
, creature_guid
);
19854 bool Player::IsAtGroupRewardDistance(WorldObject
const* pRewardSource
) const
19856 if (pRewardSource
->IsWithinDistInMap(this,sWorld
.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE
)))
19862 Corpse
* corpse
= GetCorpse();
19866 return pRewardSource
->IsWithinDistInMap(corpse
,sWorld
.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE
));
19869 uint32
Player::GetBaseWeaponSkillValue (WeaponAttackType attType
) const
19871 Item
* item
= GetWeaponForAttack(attType
,true,true);
19873 // unarmed only with base attack
19874 if(attType
!= BASE_ATTACK
&& !item
)
19877 // weapon skill or (unarmed for base attack)
19878 uint32 skill
= item
? item
->GetSkill() : uint32(SKILL_UNARMED
);
19879 return GetBaseSkillValue(skill
);
19882 void Player::ResurectUsingRequestData()
19884 /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
19885 if(IS_PLAYER_GUID(m_resurrectGUID
))
19886 TeleportTo(m_resurrectMap
, m_resurrectX
, m_resurrectY
, m_resurrectZ
, GetOrientation());
19888 //we cannot resurrect player when we triggered far teleport
19889 //player will be resurrected upon teleportation
19890 if(IsBeingTeleportedFar())
19892 ScheduleDelayedOperation(DELAYED_RESURRECT_PLAYER
);
19896 ResurrectPlayer(0.0f
,false);
19898 if(GetMaxHealth() > m_resurrectHealth
)
19899 SetHealth( m_resurrectHealth
);
19901 SetHealth( GetMaxHealth() );
19903 if(GetMaxPower(POWER_MANA
) > m_resurrectMana
)
19904 SetPower(POWER_MANA
, m_resurrectMana
);
19906 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
) );
19908 SetPower(POWER_RAGE
, 0 );
19910 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
) );
19912 SpawnCorpseBones();
19915 void Player::SetClientControl(Unit
* target
, uint8 allowMove
)
19917 WorldPacket
data(SMSG_CLIENT_CONTROL_UPDATE
, target
->GetPackGUID().size()+1);
19918 data
<< target
->GetPackGUID();
19919 data
<< uint8(allowMove
);
19920 GetSession()->SendPacket(&data
);
19923 void Player::UpdateZoneDependentAuras( uint32 newZone
)
19925 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
19926 SpellAreaForAreaMapBounds saBounds
= sSpellMgr
.GetSpellAreaForAreaMapBounds(newZone
);
19927 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
19928 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,newZone
,0))
19929 if (!HasAura(itr
->second
->spellId
, EFFECT_INDEX_0
))
19930 CastSpell(this,itr
->second
->spellId
,true);
19933 void Player::UpdateAreaDependentAuras( uint32 newArea
)
19935 // remove auras from spells with area limitations
19936 for(AuraMap::iterator iter
= m_Auras
.begin(); iter
!= m_Auras
.end();)
19938 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
19939 if(sSpellMgr
.GetSpellAllowedInLocationError(iter
->second
->GetSpellProto(),GetMapId(),m_zoneUpdateId
,newArea
,this) != SPELL_CAST_OK
)
19945 // some auras applied at subzone enter
19946 SpellAreaForAreaMapBounds saBounds
= sSpellMgr
.GetSpellAreaForAreaMapBounds(newArea
);
19947 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
19948 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,m_zoneUpdateId
,newArea
))
19949 if (!HasAura(itr
->second
->spellId
, EFFECT_INDEX_0
))
19950 CastSpell(this,itr
->second
->spellId
,true);
19953 uint32
Player::GetCorpseReclaimDelay(bool pvp
) const
19955 if ((pvp
&& !sWorld
.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP
)) ||
19956 (!pvp
&& !sWorld
.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE
) ))
19958 return copseReclaimDelay
[0];
19961 time_t now
= time(NULL
);
19962 // 0..2 full period
19963 uint32 count
= (now
< m_deathExpireTime
) ? uint32((m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
) : 0;
19964 return copseReclaimDelay
[count
];
19967 void Player::UpdateCorpseReclaimDelay()
19969 bool pvp
= m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
;
19971 if ((pvp
&& !sWorld
.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP
)) ||
19972 (!pvp
&& !sWorld
.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE
) ))
19975 time_t now
= time(NULL
);
19976 if(now
< m_deathExpireTime
)
19978 // full and partly periods 1..3
19979 uint32 count
= uint32((m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
+1);
19980 if(count
< MAX_DEATH_COUNT
)
19981 m_deathExpireTime
= now
+(count
+1)*DEATH_EXPIRE_STEP
;
19983 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
;
19986 m_deathExpireTime
= now
+DEATH_EXPIRE_STEP
;
19989 void Player::SendCorpseReclaimDelay(bool load
)
19991 Corpse
* corpse
= GetCorpse();
19998 if(corpse
->GetGhostTime() > m_deathExpireTime
)
20001 bool pvp
= corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
;
20004 if( pvp
&& sWorld
.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
20005 !pvp
&& sWorld
.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
20007 count
= uint32(m_deathExpireTime
-corpse
->GetGhostTime())/DEATH_EXPIRE_STEP
;
20008 if(count
>=MAX_DEATH_COUNT
)
20009 count
= MAX_DEATH_COUNT
-1;
20014 time_t expected_time
= corpse
->GetGhostTime()+copseReclaimDelay
[count
];
20016 time_t now
= time(NULL
);
20017 if(now
>= expected_time
)
20020 delay
= uint32(expected_time
-now
);
20023 delay
= GetCorpseReclaimDelay(corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
);
20025 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
20026 WorldPacket
data(SMSG_CORPSE_RECLAIM_DELAY
, 4);
20027 data
<< uint32(delay
*IN_MILLISECONDS
);
20028 GetSession()->SendPacket( &data
);
20031 Player
* Player::GetNextRandomRaidMember(float radius
)
20033 Group
*pGroup
= GetGroup();
20037 std::vector
<Player
*> nearMembers
;
20038 nearMembers
.reserve(pGroup
->GetMembersCount());
20040 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
20042 Player
* Target
= itr
->getSource();
20044 // IsHostileTo check duel and controlled by enemy
20045 if( Target
&& Target
!= this && IsWithinDistInMap(Target
, radius
) &&
20046 !Target
->HasInvisibilityAura() && !IsHostileTo(Target
) )
20047 nearMembers
.push_back(Target
);
20050 if (nearMembers
.empty())
20053 uint32 randTarget
= urand(0,nearMembers
.size()-1);
20054 return nearMembers
[randTarget
];
20057 PartyResult
Player::CanUninviteFromGroup() const
20059 const Group
* grp
= GetGroup();
20061 return PARTY_RESULT_YOU_NOT_IN_GROUP
;
20063 if(!grp
->IsLeader(GetGUID()) && !grp
->IsAssistant(GetGUID()))
20064 return PARTY_RESULT_YOU_NOT_LEADER
;
20066 if(InBattleGround())
20067 return PARTY_RESULT_INVITE_RESTRICTED
;
20069 return PARTY_RESULT_OK
;
20072 void Player::SetBattleGroundRaid(Group
* group
, int8 subgroup
)
20074 //we must move references from m_group to m_originalGroup
20075 SetOriginalGroup(GetGroup(), GetSubGroup());
20078 m_group
.link(group
, this);
20079 m_group
.setSubGroup((uint8
)subgroup
);
20082 void Player::RemoveFromBattleGroundRaid()
20084 //remove existing reference
20086 if( Group
* group
= GetOriginalGroup() )
20088 m_group
.link(group
, this);
20089 m_group
.setSubGroup(GetOriginalSubGroup());
20091 SetOriginalGroup(NULL
);
20094 void Player::SetOriginalGroup(Group
*group
, int8 subgroup
)
20096 if( group
== NULL
)
20097 m_originalGroup
.unlink();
20100 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
20101 ASSERT(subgroup
>= 0);
20102 m_originalGroup
.link(group
, this);
20103 m_originalGroup
.setSubGroup((uint8
)subgroup
);
20107 void Player::UpdateUnderwaterState( Map
* m
, float x
, float y
, float z
)
20109 LiquidData liquid_status
;
20110 ZLiquidStatus res
= m
->getLiquidStatus(x
, y
, z
, MAP_ALL_LIQUIDS
, &liquid_status
);
20113 m_MirrorTimerFlags
&= ~(UNDERWATER_INWATER
|UNDERWATER_INLAVA
|UNDERWATER_INSLIME
|UNDERWATER_INDARKWATER
);
20114 // Small hack for enable breath in WMO
20116 m_MirrorTimerFlags
|=UNDERWATER_INWATER
;
20120 // All liquids type - check under water position
20121 if (liquid_status
.type
&(MAP_LIQUID_TYPE_WATER
|MAP_LIQUID_TYPE_OCEAN
|MAP_LIQUID_TYPE_MAGMA
|MAP_LIQUID_TYPE_SLIME
))
20123 if ( res
& LIQUID_MAP_UNDER_WATER
)
20124 m_MirrorTimerFlags
|= UNDERWATER_INWATER
;
20126 m_MirrorTimerFlags
&= ~UNDERWATER_INWATER
;
20129 // Allow travel in dark water on taxi or transport
20130 if ((liquid_status
.type
& MAP_LIQUID_TYPE_DARK_WATER
) && !isInFlight() && !GetTransport())
20131 m_MirrorTimerFlags
|= UNDERWATER_INDARKWATER
;
20133 m_MirrorTimerFlags
&= ~UNDERWATER_INDARKWATER
;
20135 // in lava check, anywhere in lava level
20136 if (liquid_status
.type
&MAP_LIQUID_TYPE_MAGMA
)
20138 if (res
& (LIQUID_MAP_UNDER_WATER
|LIQUID_MAP_IN_WATER
|LIQUID_MAP_WATER_WALK
))
20139 m_MirrorTimerFlags
|= UNDERWATER_INLAVA
;
20141 m_MirrorTimerFlags
&= ~UNDERWATER_INLAVA
;
20143 // in slime check, anywhere in slime level
20144 if (liquid_status
.type
&MAP_LIQUID_TYPE_SLIME
)
20146 if (res
& (LIQUID_MAP_UNDER_WATER
|LIQUID_MAP_IN_WATER
|LIQUID_MAP_WATER_WALK
))
20147 m_MirrorTimerFlags
|= UNDERWATER_INSLIME
;
20149 m_MirrorTimerFlags
&= ~UNDERWATER_INSLIME
;
20153 void Player::SetCanParry( bool value
)
20155 if(m_canParry
==value
)
20158 m_canParry
= value
;
20159 UpdateParryPercentage();
20162 void Player::SetCanBlock( bool value
)
20164 if(m_canBlock
==value
)
20167 m_canBlock
= value
;
20168 UpdateBlockPercentage();
20171 bool ItemPosCount::isContainedIn(ItemPosCountVec
const& vec
) const
20173 for(ItemPosCountVec::const_iterator itr
= vec
.begin(); itr
!= vec
.end();++itr
)
20174 if(itr
->pos
== pos
)
20180 bool Player::CanUseBattleGroundObject()
20182 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
20183 // maybe gameobject code should handle that ForceReaction usage
20184 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
20185 return ( //InBattleGround() && // in battleground - not need, check in other cases
20186 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
20187 //player cannot use object when he is invulnerable (immune)
20188 !isTotalImmune() && // not totally immune
20189 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
20190 !HasStealthAura() && // not stealthed
20191 !HasInvisibilityAura() && // not invisible
20192 !HasAura(SPELL_RECENTLY_DROPPED_FLAG
, EFFECT_INDEX_0
) &&// can't pickup
20193 isAlive() // live player
20197 bool Player::CanCaptureTowerPoint()
20199 return ( !HasStealthAura() && // not stealthed
20200 !HasInvisibilityAura() && // not invisible
20201 isAlive() // live player
20205 uint32
Player::GetBarberShopCost(uint8 newhairstyle
, uint8 newhaircolor
, uint8 newfacialhair
)
20207 uint32 level
= getLevel();
20209 if(level
> GT_MAX_LEVEL
)
20210 level
= GT_MAX_LEVEL
; // max level in this dbc
20212 uint8 hairstyle
= GetByteValue(PLAYER_BYTES
, 2);
20213 uint8 haircolor
= GetByteValue(PLAYER_BYTES
, 3);
20214 uint8 facialhair
= GetByteValue(PLAYER_BYTES_2
, 0);
20216 if((hairstyle
== newhairstyle
) && (haircolor
== newhaircolor
) && (facialhair
== newfacialhair
))
20219 GtBarberShopCostBaseEntry
const *bsc
= sGtBarberShopCostBaseStore
.LookupEntry(level
- 1);
20221 if(!bsc
) // shouldn't happen
20226 if(hairstyle
!= newhairstyle
)
20227 cost
+= bsc
->cost
; // full price
20229 if((haircolor
!= newhaircolor
) && (hairstyle
== newhairstyle
))
20230 cost
+= bsc
->cost
* 0.5f
; // +1/2 of price
20232 if(facialhair
!= newfacialhair
)
20233 cost
+= bsc
->cost
* 0.75f
; // +3/4 of price
20235 return uint32(cost
);
20238 void Player::InitGlyphsForLevel()
20240 for(uint32 i
= 0; i
< sGlyphSlotStore
.GetNumRows(); ++i
)
20241 if(GlyphSlotEntry
const * gs
= sGlyphSlotStore
.LookupEntry(i
))
20243 SetGlyphSlot(gs
->Order
- 1, gs
->Id
);
20245 uint32 level
= getLevel();
20248 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
20250 value
|= (0x01 | 0x02);
20260 SetUInt32Value(PLAYER_GLYPHS_ENABLED
, value
);
20263 void Player::ApplyGlyph(uint8 slot
, bool apply
)
20265 if (uint32 glyph
= GetGlyph(slot
))
20267 if(GlyphPropertiesEntry
const *gp
= sGlyphPropertiesStore
.LookupEntry(glyph
))
20271 CastSpell(this, gp
->SpellId
, true);
20272 SetUInt32Value(PLAYER_FIELD_GLYPHS_1
+ slot
, glyph
);
20276 RemoveAurasDueToSpell(gp
->SpellId
);
20277 SetUInt32Value(PLAYER_FIELD_GLYPHS_1
+ slot
, 0);
20283 void Player::ApplyGlyphs(bool apply
)
20285 for (uint8 i
= 0; i
< MAX_GLYPH_SLOT_INDEX
; ++i
)
20286 ApplyGlyph(i
,apply
);
20289 void Player::EnterVehicle(Vehicle
*vehicle
)
20291 VehicleEntry
const *ve
= sVehicleStore
.LookupEntry(vehicle
->GetVehicleId());
20295 VehicleSeatEntry
const *veSeat
= sVehicleSeatStore
.LookupEntry(ve
->m_seatID
[0]);
20299 vehicle
->SetCharmerGUID(GetGUID());
20300 vehicle
->RemoveFlag(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_SPELLCLICK
);
20301 vehicle
->SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PLAYER_CONTROLLED
);
20302 vehicle
->setFaction(getFaction());
20304 SetCharm(vehicle
); // charm
20305 SetFarSightGUID(vehicle
->GetGUID()); // set view
20307 SetClientControl(vehicle
, 1); // redirect controls to vehicle
20310 WorldPacket
data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA
, 0);
20311 GetSession()->SendPacket(&data
);
20313 data
.Initialize(MSG_MOVE_TELEPORT_ACK
, 30);
20314 data
<< GetPackGUID();
20315 data
<< uint32(0); // counter?
20316 data
<< uint32(MOVEFLAG_ONTRANSPORT
); // transport
20317 data
<< uint16(0); // special flags
20318 data
<< uint32(getMSTime()); // time
20319 data
<< vehicle
->GetPositionX(); // x
20320 data
<< vehicle
->GetPositionY(); // y
20321 data
<< vehicle
->GetPositionZ(); // z
20322 data
<< vehicle
->GetOrientation(); // o
20323 // transport part, TODO: load/calculate seat offsets
20324 data
<< uint64(vehicle
->GetGUID()); // transport guid
20325 data
<< float(veSeat
->m_attachmentOffsetX
); // transport offsetX
20326 data
<< float(veSeat
->m_attachmentOffsetY
); // transport offsetY
20327 data
<< float(veSeat
->m_attachmentOffsetZ
); // transport offsetZ
20328 data
<< float(0); // transport orientation
20329 data
<< uint32(getMSTime()); // transport time
20330 data
<< uint8(0); // seat
20331 // end of transport part
20332 data
<< uint32(0); // fall time
20333 GetSession()->SendPacket(&data
);
20335 data
.Initialize(SMSG_PET_SPELLS
, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX
+1+1);
20336 data
<< uint64(vehicle
->GetGUID());
20339 data
<< uint32(0x00000101);
20341 for(uint32 i
= 0; i
< 10; ++i
)
20342 data
<< uint16(0) << uint8(0) << uint8(i
+8);
20346 GetSession()->SendPacket(&data
);
20349 void Player::ExitVehicle(Vehicle
*vehicle
)
20351 vehicle
->SetCharmerGUID(0);
20352 vehicle
->SetFlag(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_SPELLCLICK
);
20353 vehicle
->RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PLAYER_CONTROLLED
);
20354 vehicle
->setFaction((GetTeam() == ALLIANCE
) ? vehicle
->GetCreatureInfo()->faction_A
: vehicle
->GetCreatureInfo()->faction_H
);
20357 SetFarSightGUID(0);
20359 SetClientControl(vehicle
, 0);
20362 WorldPacket
data(MSG_MOVE_TELEPORT_ACK
, 30);
20363 data
<< GetPackGUID();
20364 data
<< uint32(0); // counter?
20365 data
<< uint32(MOVEFLAG_ROOT
); // fly unk
20366 data
<< uint16(MOVEFLAG2_UNK4
); // special flags
20367 data
<< uint32(getMSTime()); // time
20368 data
<< vehicle
->GetPositionX(); // x
20369 data
<< vehicle
->GetPositionY(); // y
20370 data
<< vehicle
->GetPositionZ(); // z
20371 data
<< vehicle
->GetOrientation(); // o
20372 data
<< uint32(0); // fall time
20373 GetSession()->SendPacket(&data
);
20375 RemovePetActionBar();
20377 // maybe called at dummy aura remove?
20378 // CastSpell(this, 45472, true); // Parachute
20381 bool Player::isTotalImmune()
20383 AuraList
const& immune
= GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY
);
20385 uint32 immuneMask
= 0;
20386 for(AuraList::const_iterator itr
= immune
.begin(); itr
!= immune
.end(); ++itr
)
20388 immuneMask
|= (*itr
)->GetModifier()->m_miscvalue
;
20389 if( immuneMask
& SPELL_SCHOOL_MASK_ALL
) // total immunity
20395 bool Player::HasTitle(uint32 bitIndex
)
20397 if (bitIndex
> MAX_TITLE_INDEX
)
20400 uint32 fieldIndexOffset
= bitIndex
/ 32;
20401 uint32 flag
= 1 << (bitIndex
% 32);
20402 return HasFlag(PLAYER__FIELD_KNOWN_TITLES
+ fieldIndexOffset
, flag
);
20405 void Player::SetTitle(CharTitlesEntry
const* title
, bool lost
)
20407 uint32 fieldIndexOffset
= title
->bit_index
/ 32;
20408 uint32 flag
= 1 << (title
->bit_index
% 32);
20412 if(!HasFlag(PLAYER__FIELD_KNOWN_TITLES
+ fieldIndexOffset
, flag
))
20415 RemoveFlag(PLAYER__FIELD_KNOWN_TITLES
+ fieldIndexOffset
, flag
);
20419 if(HasFlag(PLAYER__FIELD_KNOWN_TITLES
+ fieldIndexOffset
, flag
))
20422 SetFlag(PLAYER__FIELD_KNOWN_TITLES
+ fieldIndexOffset
, flag
);
20425 WorldPacket
data(SMSG_TITLE_EARNED
, 4 + 4);
20426 data
<< uint32(title
->bit_index
);
20427 data
<< uint32(lost
? 0 : 1); // 1 - earned, 0 - lost
20428 GetSession()->SendPacket(&data
);
20431 void Player::ConvertRune(uint8 index
, RuneType newType
)
20433 SetCurrentRune(index
, newType
);
20435 WorldPacket
data(SMSG_CONVERT_RUNE
, 2);
20436 data
<< uint8(index
);
20437 data
<< uint8(newType
);
20438 GetSession()->SendPacket(&data
);
20441 void Player::ResyncRunes(uint8 count
)
20443 WorldPacket
data(SMSG_RESYNC_RUNES
, count
* 2);
20444 for(uint32 i
= 0; i
< count
; ++i
)
20446 data
<< uint8(GetCurrentRune(i
)); // rune type
20447 data
<< uint8(255 - ((GetRuneCooldown(i
) / REGEN_TIME_FULL
) * 51)); // passed cooldown time (0-255)
20449 GetSession()->SendPacket(&data
);
20452 void Player::AddRunePower(uint8 index
)
20454 WorldPacket
data(SMSG_ADD_RUNE_POWER
, 4);
20455 data
<< uint32(1 << index
); // mask (0x00-0x3F probably)
20456 GetSession()->SendPacket(&data
);
20459 static RuneType runeSlotTypes
[MAX_RUNES
] = {
20468 void Player::InitRunes()
20470 if(getClass() != CLASS_DEATH_KNIGHT
)
20473 m_runes
= new Runes
;
20475 m_runes
->runeState
= 0;
20477 for(uint32 i
= 0; i
< MAX_RUNES
; ++i
)
20479 SetBaseRune(i
, runeSlotTypes
[i
]); // init base types
20480 SetCurrentRune(i
, runeSlotTypes
[i
]); // init current types
20481 SetRuneCooldown(i
, 0); // reset cooldowns
20482 m_runes
->SetRuneState(i
);
20485 for(uint32 i
= 0; i
< NUM_RUNE_TYPES
; ++i
)
20486 SetFloatValue(PLAYER_RUNE_REGEN_1
+ i
, 0.1f
);
20490 bool Player::IsBaseRuneSlotsOnCooldown( RuneType runeType
) const
20492 for(uint32 i
= 0; i
< MAX_RUNES
; ++i
)
20493 if (GetBaseRune(i
) == runeType
&& GetRuneCooldown(i
) == 0)
20499 void Player::AutoStoreLoot(uint8 bag
, uint8 slot
, uint32 loot_id
, LootStore
const& store
, bool broadcast
)
20502 loot
.FillLoot (loot_id
,store
,this,true);
20504 uint32 max_slot
= loot
.GetMaxSlotInLootFor(this);
20505 for(uint32 i
= 0; i
< max_slot
; ++i
)
20507 LootItem
* lootItem
= loot
.LootItemInSlot(i
,this);
20509 ItemPosCountVec dest
;
20510 uint8 msg
= CanStoreNewItem (bag
,slot
,dest
,lootItem
->itemid
,lootItem
->count
);
20511 if(msg
!= EQUIP_ERR_OK
&& slot
!= NULL_SLOT
)
20512 msg
= CanStoreNewItem( bag
, NULL_SLOT
,dest
,lootItem
->itemid
,lootItem
->count
);
20513 if( msg
!= EQUIP_ERR_OK
&& bag
!= NULL_BAG
)
20514 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
,dest
,lootItem
->itemid
,lootItem
->count
);
20515 if(msg
!= EQUIP_ERR_OK
)
20517 SendEquipError( msg
, NULL
, NULL
, lootItem
->itemid
);
20521 Item
* pItem
= StoreNewItem (dest
,lootItem
->itemid
,true,lootItem
->randomPropertyId
);
20522 SendNewItem(pItem
, lootItem
->count
, false, false, broadcast
);
20526 uint32
Player::CalculateTalentsPoints() const
20528 uint32 base_talent
= getLevel() < 10 ? 0 : getLevel()-9;
20530 if(getClass() != CLASS_DEATH_KNIGHT
)
20531 return uint32(base_talent
* sWorld
.getConfig(CONFIG_FLOAT_RATE_TALENT
));
20533 uint32 talentPointsForLevel
= getLevel() < 56 ? 0 : getLevel() - 55;
20534 talentPointsForLevel
+= m_questRewardTalentCount
;
20536 if(talentPointsForLevel
> base_talent
)
20537 talentPointsForLevel
= base_talent
;
20539 return uint32(talentPointsForLevel
* sWorld
.getConfig(CONFIG_FLOAT_RATE_TALENT
));
20542 bool Player::IsKnowHowFlyIn(uint32 mapid
, uint32 zone
) const
20544 // continent checked in SpellMgr::GetSpellAllowedInLocationError at cast and area update
20545 uint32 v_map
= GetVirtualMapForMapAndZone(mapid
, zone
);
20546 return v_map
!= 571 || HasSpell(54197); // Cold Weather Flying
20549 struct DoPlayerLearnSpell
20551 DoPlayerLearnSpell(Player
& _player
) : player(_player
) {}
20552 void operator() (uint32 spell_id
) { player
.learnSpell(spell_id
,false); }
20556 void Player::learnSpellHighRank(uint32 spellid
)
20558 learnSpell(spellid
,false);
20560 DoPlayerLearnSpell
worker(*this);
20561 sSpellMgr
.doForHighRanks(spellid
,worker
);
20564 void Player::_LoadSkills(QueryResult
*result
)
20567 // SetPQuery(PLAYER_LOGIN_QUERY_LOADSKILLS, "SELECT skill, value, max FROM character_skills WHERE guid = '%u'", GUID_LOPART(m_guid));
20574 Field
*fields
= result
->Fetch();
20576 uint16 skill
= fields
[0].GetUInt16();
20577 uint16 value
= fields
[1].GetUInt16();
20578 uint16 max
= fields
[2].GetUInt16();
20580 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(skill
);
20583 sLog
.outError("Character %u has skill %u that does not exist.", GetGUIDLow(), skill
);
20587 // set fixed skill ranges
20588 switch(GetSkillRangeType(pSkill
,false))
20590 case SKILL_RANGE_LANGUAGE
: // 300..300
20593 case SKILL_RANGE_MONO
: // 1..1, grey monolite bar
20602 sLog
.outError("Character %u has skill %u with value 0. Will be deleted.", GetGUIDLow(), skill
);
20603 CharacterDatabase
.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), skill
);
20607 // enable unlearn button for primary professions only
20608 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
20609 SetUInt32Value(PLAYER_SKILL_INDEX(count
), MAKE_PAIR32(skill
,1));
20611 SetUInt32Value(PLAYER_SKILL_INDEX(count
), MAKE_PAIR32(skill
,0));
20613 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count
),MAKE_SKILL_VALUE(value
, max
));
20614 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count
),0);
20616 mSkillStatus
.insert(SkillStatusMap::value_type(skill
, SkillStatusData(count
, SKILL_UNCHANGED
)));
20618 learnSkillRewardedSpells(skill
, value
);
20622 if(count
>= PLAYER_MAX_SKILLS
) // client limit
20624 sLog
.outError("Character %u has more than %u skills.", GetGUIDLow(), PLAYER_MAX_SKILLS
);
20627 } while (result
->NextRow());
20631 for (; count
< PLAYER_MAX_SKILLS
; ++count
)
20633 SetUInt32Value(PLAYER_SKILL_INDEX(count
), 0);
20634 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count
),0);
20635 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count
),0);
20638 // special settings
20639 if(getClass()==CLASS_DEATH_KNIGHT
)
20641 uint32 base_level
= std::min(getLevel(),sWorld
.getConfig (CONFIG_UINT32_START_HEROIC_PLAYER_LEVEL
));
20644 uint32 base_skill
= (base_level
-1)*5; // 270 at starting level 55
20646 base_skill
= 1; // skill mast be known and then > 0 in any case
20648 if(GetPureSkillValue (SKILL_FIRST_AID
) < base_skill
)
20649 SetSkill(SKILL_FIRST_AID
,base_skill
, base_skill
);
20650 if(GetPureSkillValue (SKILL_AXES
) < base_skill
)
20651 SetSkill(SKILL_AXES
, base_skill
,base_skill
);
20652 if(GetPureSkillValue (SKILL_DEFENSE
) < base_skill
)
20653 SetSkill(SKILL_DEFENSE
, base_skill
,base_skill
);
20654 if(GetPureSkillValue (SKILL_POLEARMS
) < base_skill
)
20655 SetSkill(SKILL_POLEARMS
, base_skill
,base_skill
);
20656 if(GetPureSkillValue (SKILL_SWORDS
) < base_skill
)
20657 SetSkill(SKILL_SWORDS
, base_skill
,base_skill
);
20658 if(GetPureSkillValue (SKILL_2H_AXES
) < base_skill
)
20659 SetSkill(SKILL_2H_AXES
, base_skill
,base_skill
);
20660 if(GetPureSkillValue (SKILL_2H_SWORDS
) < base_skill
)
20661 SetSkill(SKILL_2H_SWORDS
, base_skill
,base_skill
);
20662 if(GetPureSkillValue (SKILL_UNARMED
) < base_skill
)
20663 SetSkill(SKILL_UNARMED
, base_skill
,base_skill
);
20667 uint32
Player::GetPhaseMaskForSpawn() const
20669 uint32 phase
= PHASEMASK_NORMAL
;
20670 if(!isGameMaster())
20671 phase
= GetPhaseMask();
20674 AuraList
const& phases
= GetAurasByType(SPELL_AURA_PHASE
);
20675 if(!phases
.empty())
20676 phase
= phases
.front()->GetMiscValue();
20679 // some aura phases include 1 normal map in addition to phase itself
20680 if(uint32 n_phase
= phase
& ~PHASEMASK_NORMAL
)
20683 return PHASEMASK_NORMAL
;
20686 uint8
Player::CanEquipUniqueItem(Item
* pItem
, uint8 eslot
, uint32 limit_count
) const
20688 ItemPrototype
const* pProto
= pItem
->GetProto();
20690 // proto based limitations
20691 if(uint8 res
= CanEquipUniqueItem(pProto
,eslot
,limit_count
))
20694 // check unique-equipped on gems
20695 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
20697 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
20700 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
20704 ItemPrototype
const* pGem
= ObjectMgr::GetItemPrototype(enchantEntry
->GemID
);
20708 // include for check equip another gems with same limit category for not equipped item (and then not counted)
20709 uint32 gem_limit_count
= !pItem
->IsEquipped() && pGem
->ItemLimitCategory
20710 ? pItem
->GetGemCountWithLimitCategory(pGem
->ItemLimitCategory
) : 1;
20712 if(uint8 res
= CanEquipUniqueItem(pGem
, eslot
,gem_limit_count
))
20716 return EQUIP_ERR_OK
;
20719 uint8
Player::CanEquipUniqueItem( ItemPrototype
const* itemProto
, uint8 except_slot
, uint32 limit_count
) const
20721 // check unique-equipped on item
20722 if (itemProto
->Flags
& ITEM_FLAGS_UNIQUE_EQUIPPED
)
20724 // there is an equip limit on this item
20725 if(HasItemOrGemWithIdEquipped(itemProto
->ItemId
,1,except_slot
))
20726 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
20729 // check unique-equipped limit
20730 if (itemProto
->ItemLimitCategory
)
20732 ItemLimitCategoryEntry
const* limitEntry
= sItemLimitCategoryStore
.LookupEntry(itemProto
->ItemLimitCategory
);
20734 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
20736 // NOTE: limitEntry->mode not checked because if item have have-limit then it applied and to equip case
20738 if(limit_count
> limitEntry
->maxCount
)
20739 return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS
;
20741 // there is an equip limit on this item
20742 if(HasItemOrGemWithLimitCategoryEquipped(itemProto
->ItemLimitCategory
,limitEntry
->maxCount
-limit_count
+1,except_slot
))
20743 return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS
;
20746 return EQUIP_ERR_OK
;
20749 void Player::HandleFall(MovementInfo
const& movementInfo
)
20751 // calculate total z distance of the fall
20752 float z_diff
= m_lastFallZ
- movementInfo
.GetPos()->z
;
20753 sLog
.outDebug("zDiff = %f", z_diff
);
20755 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
20756 // 14.57 can be calculated by resolving damageperc formula below to 0
20757 if (z_diff
>= 14.57f
&& !isDead() && !isGameMaster() &&
20758 !HasAuraType(SPELL_AURA_HOVER
) && !HasAuraType(SPELL_AURA_FEATHER_FALL
) &&
20759 !HasAuraType(SPELL_AURA_FLY
) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL
) )
20761 //Safe fall, fall height reduction
20762 int32 safe_fall
= GetTotalAuraModifier(SPELL_AURA_SAFE_FALL
);
20764 float damageperc
= 0.018f
*(z_diff
-safe_fall
)-0.2426f
;
20768 uint32 damage
= (uint32
)(damageperc
* GetMaxHealth()*sWorld
.getConfig(CONFIG_FLOAT_RATE_DAMAGE_FALL
));
20770 float height
= movementInfo
.GetPos()->z
;
20771 UpdateGroundPositionZ(movementInfo
.GetPos()->x
, movementInfo
.GetPos()->y
, height
);
20775 //Prevent fall damage from being more than the player maximum health
20776 if (damage
> GetMaxHealth())
20777 damage
= GetMaxHealth();
20780 if (GetDummyAura(43621))
20781 damage
= GetMaxHealth()/2;
20783 uint32 original_health
= GetHealth();
20784 uint32 final_damage
= EnvironmentalDamage(DAMAGE_FALL
, damage
);
20786 // recheck alive, might have died of EnvironmentalDamage, avoid cases when player die in fact like Spirit of Redemption case
20787 if (isAlive() && final_damage
< original_health
)
20788 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING
, uint32(z_diff
*100));
20791 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
20792 DEBUG_LOG("FALLDAMAGE z=%f sz=%f pZ=%f FallTime=%d mZ=%f damage=%d SF=%d" , movementInfo
.GetPos()->z
, height
, GetPositionZ(), movementInfo
.GetFallTime(), height
, damage
, safe_fall
);
20797 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type
, uint32 miscvalue1
/*=0*/, uint32 miscvalue2
/*=0*/, Unit
*unit
/*=NULL*/, uint32 time
/*=0*/ )
20799 GetAchievementMgr().UpdateAchievementCriteria(type
, miscvalue1
,miscvalue2
,unit
,time
);
20802 void Player::LearnTalent(uint32 talentId
, uint32 talentRank
)
20804 uint32 CurTalentPoints
= GetFreeTalentPoints();
20806 if(CurTalentPoints
== 0)
20809 if (talentRank
>= MAX_TALENT_RANK
)
20812 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry( talentId
);
20817 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentInfo
->TalentTab
);
20822 // prevent learn talent for different class (cheating)
20823 if( (getClassMask() & talentTabInfo
->ClassMask
) == 0 )
20826 // find current max talent rank
20827 uint32 curtalent_maxrank
= 0;
20828 for(int32 k
= MAX_TALENT_RANK
-1; k
> -1; --k
)
20830 if(talentInfo
->RankID
[k
] && HasSpell(talentInfo
->RankID
[k
]))
20832 curtalent_maxrank
= k
+ 1;
20837 // we already have same or higher talent rank learned
20838 if(curtalent_maxrank
>= (talentRank
+ 1))
20841 // check if we have enough talent points
20842 if(CurTalentPoints
< (talentRank
- curtalent_maxrank
+ 1))
20845 // Check if it requires another talent
20846 if (talentInfo
->DependsOn
> 0)
20848 if(TalentEntry
const *depTalentInfo
= sTalentStore
.LookupEntry(talentInfo
->DependsOn
))
20850 bool hasEnoughRank
= false;
20851 for (int i
= talentInfo
->DependsOnRank
; i
< MAX_TALENT_RANK
; ++i
)
20853 if (depTalentInfo
->RankID
[i
] != 0)
20854 if (HasSpell(depTalentInfo
->RankID
[i
]))
20855 hasEnoughRank
= true;
20857 if (!hasEnoughRank
)
20862 // Find out how many points we have in this field
20863 uint32 spentPoints
= 0;
20865 uint32 tTab
= talentInfo
->TalentTab
;
20866 if (talentInfo
->Row
> 0)
20868 unsigned int numRows
= sTalentStore
.GetNumRows();
20869 for (unsigned int i
= 0; i
< numRows
; ++i
) // Loop through all talents.
20871 // Someday, someone needs to revamp
20872 const TalentEntry
*tmpTalent
= sTalentStore
.LookupEntry(i
);
20873 if (tmpTalent
) // the way talents are tracked
20875 if (tmpTalent
->TalentTab
== tTab
)
20877 for (int j
= 0; j
< MAX_TALENT_RANK
; ++j
)
20879 if (tmpTalent
->RankID
[j
] != 0)
20881 if (HasSpell(tmpTalent
->RankID
[j
]))
20883 spentPoints
+= j
+ 1;
20892 // not have required min points spent in talent tree
20893 if(spentPoints
< (talentInfo
->Row
* MAX_TALENT_RANK
))
20896 // spell not set in talent.dbc
20897 uint32 spellid
= talentInfo
->RankID
[talentRank
];
20900 sLog
.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId
, talentRank
);
20905 if(HasSpell(spellid
))
20908 // learn! (other talent ranks will unlearned at learning)
20909 learnSpell(spellid
, false);
20910 sLog
.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId
, talentRank
, spellid
);
20913 void Player::LearnPetTalent(uint64 petGuid
, uint32 talentId
, uint32 talentRank
)
20915 Pet
*pet
= GetPet();
20920 if(petGuid
!= pet
->GetGUID())
20923 uint32 CurTalentPoints
= pet
->GetFreeTalentPoints();
20925 if(CurTalentPoints
== 0)
20928 if (talentRank
>= MAX_PET_TALENT_RANK
)
20931 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry(talentId
);
20936 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry(talentInfo
->TalentTab
);
20941 CreatureInfo
const *ci
= pet
->GetCreatureInfo();
20946 CreatureFamilyEntry
const *pet_family
= sCreatureFamilyStore
.LookupEntry(ci
->family
);
20951 if(pet_family
->petTalentType
< 0) // not hunter pet
20954 // prevent learn talent for different family (cheating)
20955 if(!((1 << pet_family
->petTalentType
) & talentTabInfo
->petTalentMask
))
20958 // find current max talent rank
20959 int32 curtalent_maxrank
= 0;
20960 for(int32 k
= MAX_TALENT_RANK
-1; k
> -1; --k
)
20962 if(talentInfo
->RankID
[k
] && pet
->HasSpell(talentInfo
->RankID
[k
]))
20964 curtalent_maxrank
= k
+ 1;
20969 // we already have same or higher talent rank learned
20970 if(curtalent_maxrank
>= int32(talentRank
+ 1))
20973 // check if we have enough talent points
20974 if(CurTalentPoints
< (talentRank
- curtalent_maxrank
+ 1))
20977 // Check if it requires another talent
20978 if (talentInfo
->DependsOn
> 0)
20980 if(TalentEntry
const *depTalentInfo
= sTalentStore
.LookupEntry(talentInfo
->DependsOn
))
20982 bool hasEnoughRank
= false;
20983 for (int i
= talentInfo
->DependsOnRank
; i
< MAX_TALENT_RANK
; ++i
)
20985 if (depTalentInfo
->RankID
[i
] != 0)
20986 if (pet
->HasSpell(depTalentInfo
->RankID
[i
]))
20987 hasEnoughRank
= true;
20989 if (!hasEnoughRank
)
20994 // Find out how many points we have in this field
20995 uint32 spentPoints
= 0;
20997 uint32 tTab
= talentInfo
->TalentTab
;
20998 if (talentInfo
->Row
> 0)
21000 unsigned int numRows
= sTalentStore
.GetNumRows();
21001 for (unsigned int i
= 0; i
< numRows
; ++i
) // Loop through all talents.
21003 // Someday, someone needs to revamp
21004 const TalentEntry
*tmpTalent
= sTalentStore
.LookupEntry(i
);
21005 if (tmpTalent
) // the way talents are tracked
21007 if (tmpTalent
->TalentTab
== tTab
)
21009 for (int j
= 0; j
< MAX_TALENT_RANK
; ++j
)
21011 if (tmpTalent
->RankID
[j
] != 0)
21013 if (pet
->HasSpell(tmpTalent
->RankID
[j
]))
21015 spentPoints
+= j
+ 1;
21024 // not have required min points spent in talent tree
21025 if(spentPoints
< (talentInfo
->Row
* MAX_PET_TALENT_RANK
))
21028 // spell not set in talent.dbc
21029 uint32 spellid
= talentInfo
->RankID
[talentRank
];
21032 sLog
.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId
, talentRank
);
21037 if(pet
->HasSpell(spellid
))
21040 // learn! (other talent ranks will unlearned at learning)
21041 pet
->learnSpell(spellid
);
21042 sLog
.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId
, talentRank
, spellid
);
21044 // update free talent points
21045 pet
->SetFreeTalentPoints(CurTalentPoints
- (talentRank
- curtalent_maxrank
+ 1));
21048 void Player::UpdateKnownCurrencies(uint32 itemId
, bool apply
)
21050 if(CurrencyTypesEntry
const* ctEntry
= sCurrencyTypesStore
.LookupEntry(itemId
))
21053 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES
, (UI64LIT(1) << (ctEntry
->BitIndex
- 1)));
21055 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES
, (UI64LIT(1) << (ctEntry
->BitIndex
- 1)));
21059 void Player::UpdateFallInformationIfNeed( MovementInfo
const& minfo
,uint16 opcode
)
21061 if (m_lastFallTime
>= minfo
.GetFallTime() || m_lastFallZ
<= minfo
.GetPos()->z
|| opcode
== MSG_MOVE_FALL_LAND
)
21062 SetFallInformation(minfo
.GetFallTime(), minfo
.GetPos()->z
);
21065 void Player::UnsummonPetTemporaryIfAny()
21067 Pet
* pet
= GetPet();
21071 if(!m_temporaryUnsummonedPetNumber
&& pet
->isControlled() && !pet
->isTemporarySummoned() )
21073 m_temporaryUnsummonedPetNumber
= pet
->GetCharmInfo()->GetPetNumber();
21074 m_oldpetspell
= pet
->GetUInt32Value(UNIT_CREATED_BY_SPELL
);
21077 RemovePet(pet
, PET_SAVE_AS_CURRENT
);
21080 void Player::ResummonPetTemporaryUnSummonedIfAny()
21082 if(!m_temporaryUnsummonedPetNumber
)
21085 // not resummon in not appropriate state
21086 if(IsPetNeedBeTemporaryUnsummoned())
21092 Pet
* NewPet
= new Pet
;
21093 if(!NewPet
->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber
, true))
21096 m_temporaryUnsummonedPetNumber
= 0;
21099 bool Player::canSeeSpellClickOn(Creature
const *c
) const
21101 if(!c
->HasFlag(UNIT_NPC_FLAGS
,UNIT_NPC_FLAG_SPELLCLICK
))
21104 SpellClickInfoMapBounds clickPair
= sObjectMgr
.GetSpellClickInfoMapBounds(c
->GetEntry());
21105 for(SpellClickInfoMap::const_iterator itr
= clickPair
.first
; itr
!= clickPair
.second
; ++itr
)
21106 if(itr
->second
.IsFitToRequirements(this))
21112 void Player::BuildPlayerTalentsInfoData(WorldPacket
*data
)
21114 *data
<< uint32(GetFreeTalentPoints()); // unspentTalentPoints
21115 *data
<< uint8(m_specsCount
); // talent group count (0, 1 or 2)
21116 *data
<< uint8(m_activeSpec
); // talent group index (0 or 1)
21120 // loop through all specs (only 1 for now)
21121 for(uint32 specIdx
= 0; specIdx
< m_specsCount
; ++specIdx
)
21123 uint8 talentIdCount
= 0;
21124 size_t pos
= data
->wpos();
21125 *data
<< uint8(talentIdCount
); // [PH], talentIdCount
21127 // find class talent tabs (all players have 3 talent tabs)
21128 uint32
const* talentTabIds
= GetTalentTabPages(getClass());
21130 for(uint32 i
= 0; i
< 3; ++i
)
21132 uint32 talentTabId
= talentTabIds
[i
];
21134 for(uint32 talentId
= 0; talentId
< sTalentStore
.GetNumRows(); ++talentId
)
21136 TalentEntry
const* talentInfo
= sTalentStore
.LookupEntry(talentId
);
21140 // skip another tab talents
21141 if(talentInfo
->TalentTab
!= talentTabId
)
21144 // find max talent rank
21145 int32 curtalent_maxrank
= -1;
21146 for(int32 k
= MAX_TALENT_RANK
-1; k
> -1; --k
)
21148 if(talentInfo
->RankID
[k
] && HasSpell(talentInfo
->RankID
[k
]))
21150 curtalent_maxrank
= k
;
21155 // not learned talent
21156 if(curtalent_maxrank
< 0)
21159 *data
<< uint32(talentInfo
->TalentID
); // Talent.dbc
21160 *data
<< uint8(curtalent_maxrank
); // talentMaxRank (0-4)
21166 data
->put
<uint8
>(pos
, talentIdCount
); // put real count
21168 *data
<< uint8(MAX_GLYPH_SLOT_INDEX
); // glyphs count
21170 // GlyphProperties.dbc
21171 for(uint8 i
= 0; i
< MAX_GLYPH_SLOT_INDEX
; ++i
)
21172 *data
<< uint16(m_glyphs
[specIdx
][i
].GetId());
21177 void Player::BuildPetTalentsInfoData(WorldPacket
*data
)
21179 uint32 unspentTalentPoints
= 0;
21180 size_t pointsPos
= data
->wpos();
21181 *data
<< uint32(unspentTalentPoints
); // [PH], unspentTalentPoints
21183 uint8 talentIdCount
= 0;
21184 size_t countPos
= data
->wpos();
21185 *data
<< uint8(talentIdCount
); // [PH], talentIdCount
21187 Pet
*pet
= GetPet();
21191 unspentTalentPoints
= pet
->GetFreeTalentPoints();
21193 data
->put
<uint32
>(pointsPos
, unspentTalentPoints
); // put real points
21195 CreatureInfo
const *ci
= pet
->GetCreatureInfo();
21199 CreatureFamilyEntry
const *pet_family
= sCreatureFamilyStore
.LookupEntry(ci
->family
);
21200 if(!pet_family
|| pet_family
->petTalentType
< 0)
21203 for(uint32 talentTabId
= 1; talentTabId
< sTalentTabStore
.GetNumRows(); ++talentTabId
)
21205 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentTabId
);
21209 if(!((1 << pet_family
->petTalentType
) & talentTabInfo
->petTalentMask
))
21212 for(uint32 talentId
= 0; talentId
< sTalentStore
.GetNumRows(); ++talentId
)
21214 TalentEntry
const* talentInfo
= sTalentStore
.LookupEntry(talentId
);
21218 // skip another tab talents
21219 if(talentInfo
->TalentTab
!= talentTabId
)
21222 // find max talent rank
21223 int32 curtalent_maxrank
= -1;
21224 for(int32 k
= 4; k
> -1; --k
)
21226 if(talentInfo
->RankID
[k
] && pet
->HasSpell(talentInfo
->RankID
[k
]))
21228 curtalent_maxrank
= k
;
21233 // not learned talent
21234 if(curtalent_maxrank
< 0)
21237 *data
<< uint32(talentInfo
->TalentID
); // Talent.dbc
21238 *data
<< uint8(curtalent_maxrank
); // talentMaxRank (0-4)
21243 data
->put
<uint8
>(countPos
, talentIdCount
); // put real count
21249 void Player::SendTalentsInfoData(bool pet
)
21251 WorldPacket
data(SMSG_TALENTS_INFO
, 50);
21252 data
<< uint8(pet
? 1 : 0);
21254 BuildPetTalentsInfoData(&data
);
21256 BuildPlayerTalentsInfoData(&data
);
21257 GetSession()->SendPacket(&data
);
21260 void Player::BuildEnchantmentsInfoData(WorldPacket
*data
)
21262 uint32 slotUsedMask
= 0;
21263 size_t slotUsedMaskPos
= data
->wpos();
21264 *data
<< uint32(slotUsedMask
); // slotUsedMask < 0x80000
21266 for(uint32 i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
21268 Item
*item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
);
21273 slotUsedMask
|= (1 << i
);
21275 *data
<< uint32(item
->GetEntry()); // item entry
21277 uint16 enchantmentMask
= 0;
21278 size_t enchantmentMaskPos
= data
->wpos();
21279 *data
<< uint16(enchantmentMask
); // enchantmentMask < 0x1000
21281 for(uint32 j
= 0; j
< MAX_ENCHANTMENT_SLOT
; ++j
)
21283 uint32 enchId
= item
->GetEnchantmentId(EnchantmentSlot(j
));
21288 enchantmentMask
|= (1 << j
);
21290 *data
<< uint16(enchId
); // enchantmentId?
21293 data
->put
<uint16
>(enchantmentMaskPos
, enchantmentMask
);
21295 *data
<< uint16(0); // ?
21296 *data
<< uint8(0); // PGUID!
21297 *data
<< uint32(0); // seed?
21300 data
->put
<uint32
>(slotUsedMaskPos
, slotUsedMask
);
21303 void Player::SendEquipmentSetList()
21306 WorldPacket
data(SMSG_EQUIPMENT_SET_LIST
, 4);
21307 size_t count_pos
= data
.wpos();
21308 data
<< uint32(count
); // count placeholder
21309 for(EquipmentSets::iterator itr
= m_EquipmentSets
.begin(); itr
!= m_EquipmentSets
.end(); ++itr
)
21311 if(itr
->second
.state
==EQUIPMENT_SET_DELETED
)
21313 data
.appendPackGUID(itr
->second
.Guid
);
21314 data
<< uint32(itr
->first
);
21315 data
<< itr
->second
.Name
;
21316 data
<< itr
->second
.IconName
;
21317 for(uint32 i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
21318 data
.appendPackGUID(MAKE_NEW_GUID(itr
->second
.Items
[i
], 0, HIGHGUID_ITEM
));
21320 ++count
; // client have limit but it checked at loading and set
21322 data
.put
<uint32
>(count_pos
, count
);
21323 GetSession()->SendPacket(&data
);
21326 void Player::SetEquipmentSet(uint32 index
, EquipmentSet eqset
)
21328 if(eqset
.Guid
!= 0)
21330 bool found
= false;
21332 for(EquipmentSets::iterator itr
= m_EquipmentSets
.begin(); itr
!= m_EquipmentSets
.end(); ++itr
)
21334 if((itr
->second
.Guid
== eqset
.Guid
) && (itr
->first
== index
))
21341 if(!found
) // something wrong...
21343 sLog
.outError("Player %s tried to save equipment set "UI64FMTD
" (index %u), but that equipment set not found!", GetName(), eqset
.Guid
, index
);
21348 EquipmentSet
& eqslot
= m_EquipmentSets
[index
];
21350 EquipmentSetUpdateState old_state
= eqslot
.state
;
21354 if(eqset
.Guid
== 0)
21356 eqslot
.Guid
= sObjectMgr
.GenerateEquipmentSetGuid();
21358 WorldPacket
data(SMSG_EQUIPMENT_SET_SAVED
, 4 + 1);
21359 data
<< uint32(index
);
21360 data
.appendPackGUID(eqslot
.Guid
);
21361 GetSession()->SendPacket(&data
);
21364 eqslot
.state
= old_state
== EQUIPMENT_SET_NEW
? EQUIPMENT_SET_NEW
: EQUIPMENT_SET_CHANGED
;
21367 void Player::_SaveEquipmentSets()
21369 for(EquipmentSets::iterator itr
= m_EquipmentSets
.begin(); itr
!= m_EquipmentSets
.end();)
21371 uint32 index
= itr
->first
;
21372 EquipmentSet
& eqset
= itr
->second
;
21373 switch(eqset
.state
)
21375 case EQUIPMENT_SET_UNCHANGED
:
21377 break; // nothing do
21378 case EQUIPMENT_SET_CHANGED
:
21379 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'",
21380 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],
21381 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
);
21382 eqset
.state
= EQUIPMENT_SET_UNCHANGED
;
21385 case EQUIPMENT_SET_NEW
:
21386 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')",
21387 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],
21388 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]);
21389 eqset
.state
= EQUIPMENT_SET_UNCHANGED
;
21392 case EQUIPMENT_SET_DELETED
:
21393 CharacterDatabase
.PExecute("DELETE FROM character_equipmentsets WHERE setguid="UI64FMTD
, eqset
.Guid
);
21394 m_EquipmentSets
.erase(itr
++);
21400 void Player::_SaveBGData()
21402 CharacterDatabase
.PExecute("DELETE FROM character_battleground_data WHERE guid='%u'", GetGUIDLow());
21403 if (m_bgData
.bgInstanceID
)
21405 /* guid, bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
21406 CharacterDatabase
.PExecute("INSERT INTO character_battleground_data VALUES ('%u', '%u', '%u', '%f', '%f', '%f', '%f', '%u', '%u', '%u', '%u')",
21407 GetGUIDLow(), m_bgData
.bgInstanceID
, m_bgData
.bgTeam
, m_bgData
.joinPos
.coord_x
, m_bgData
.joinPos
.coord_y
, m_bgData
.joinPos
.coord_z
,
21408 m_bgData
.joinPos
.orientation
, m_bgData
.joinPos
.mapid
, m_bgData
.taxiPath
[0], m_bgData
.taxiPath
[1], m_bgData
.mountSpell
);
21412 void Player::DeleteEquipmentSet(uint64 setGuid
)
21414 for(EquipmentSets::iterator itr
= m_EquipmentSets
.begin(); itr
!= m_EquipmentSets
.end(); ++itr
)
21416 if(itr
->second
.Guid
== setGuid
)
21418 if(itr
->second
.state
== EQUIPMENT_SET_NEW
)
21419 m_EquipmentSets
.erase(itr
);
21421 itr
->second
.state
= EQUIPMENT_SET_DELETED
;
21427 void Player::ActivateSpec(uint8 specNum
)
21429 if(GetActiveSpec() == specNum
)
21432 if(specNum
>= GetSpecsCount())
21435 // unlearn GetActiveSpec() talents (not learned in specNum);
21436 // learn specNum talents
21438 ApplyGlyphs(false);
21440 SetActiveSpec(specNum
);
21442 // recheck action buttons (not checked at loading/spec copy)
21443 ActionButtonList
const& currentActionButtonList
= m_actionButtons
[m_activeSpec
];
21444 for(ActionButtonList::const_iterator itr
= currentActionButtonList
.begin(); itr
!= currentActionButtonList
.end(); ++itr
)
21445 if (itr
->second
.uState
!= ACTIONBUTTON_DELETED
)
21446 // remove broken without any output (it can be not correct because talents not copied at spec creating)
21447 if (!IsActionButtonDataValid(itr
->first
,itr
->second
.GetAction(),itr
->second
.GetType(), this, false))
21448 removeActionButton(m_activeSpec
,itr
->first
);
21452 SendInitialActionButtons();
21454 InitTalentForLevel();
21457 void Player::UpdateSpecCount(uint8 count
)
21459 uint8 curCount
= GetSpecsCount();
21460 if (curCount
== count
)
21463 // maybe current spec data must be copied to 0 spec?
21464 if (m_activeSpec
>= count
)
21467 // copy spec data from new specs
21468 if (count
> curCount
)
21470 // copy action buttons from active spec (more easy in this case iterate first by button)
21471 ActionButtonList
const& currentActionButtonList
= m_actionButtons
[m_activeSpec
];
21473 for(ActionButtonList::const_iterator itr
= currentActionButtonList
.begin(); itr
!= currentActionButtonList
.end(); ++itr
)
21475 if (itr
->second
.uState
!= ACTIONBUTTON_DELETED
)
21477 for(uint8 spec
= curCount
; spec
< count
; ++spec
)
21478 addActionButton(spec
,itr
->first
,itr
->second
.GetAction(),itr
->second
.GetType());
21482 // delete spec data for removed specs
21483 else if (count
< curCount
)
21485 // delete action buttons for removed spec
21486 for(uint8 spec
= count
; spec
< curCount
; ++spec
)
21488 // delete action buttons for removed spec
21489 for(uint8 button
= 0; button
< MAX_ACTION_BUTTONS
; ++button
)
21490 removeActionButton(spec
,button
);
21494 SetSpecsCount(count
);
21496 SendTalentsInfoData(false);
21499 void Player::RemoveAtLoginFlag( AtLoginFlags f
, bool in_db_also
/*= false*/ )
21501 m_atLoginFlags
&= ~f
;
21504 CharacterDatabase
.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(f
), GetGUIDLow());
21507 void Player::SendClearCooldown( uint32 spell_id
, Unit
* target
)
21509 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, 4+8);
21510 data
<< uint32(spell_id
);
21511 data
<< uint64(target
->GetGUID());
21512 SendDirectMessage(&data
);
21515 void Player::BuildTeleportAckMsg( WorldPacket
*data
, float x
, float y
, float z
, float ang
) const
21517 data
->Initialize(MSG_MOVE_TELEPORT_ACK
, 41);
21518 *data
<< GetPackGUID();
21519 *data
<< uint32(0); // this value increments every time
21520 *data
<< uint32(m_movementInfo
.GetMovementFlags()); // movement flags
21521 *data
<< uint16(0); // 2.3.0
21522 *data
<< uint32(getMSTime()); // time
21527 *data
<< uint32(0);
21530 bool Player::HasMovementFlag( MovementFlags f
) const
21532 return m_movementInfo
.HasMovementFlag(f
);
21535 void Player::SetFarSightGUID( uint64 guid
)
21537 if(GetFarSight() == guid
)
21540 SetUInt64Value(PLAYER_FARSIGHT
, guid
);
21542 // need triggering load grids around new view point
21543 UpdateVisibilityForPlayer();
21546 void Player::UpdateVisibilityForPlayer()
21548 WorldObject
const* viewPoint
= GetViewPoint();
21551 CellPair
p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
21554 m
->UpdatePlayerVisibility(this, cell
, p
);
21556 if (this != viewPoint
)
21558 CellPair
pView(MaNGOS::ComputeCellPair(viewPoint
->GetPositionX(), viewPoint
->GetPositionY()));
21559 Cell
cellView(pView
);
21561 m
->UpdateObjectsVisibilityFor(this, cellView
, pView
);
21564 m
->UpdateObjectsVisibilityFor(this, cell
, p
);
21567 void Player::SendDuelCountdown(uint32 counter
)
21569 WorldPacket
data(SMSG_DUEL_COUNTDOWN
, 4);
21570 data
<< uint32(counter
); // seconds
21571 GetSession()->SendPacket(&data
);
21574 bool Player::IsImmunedToSpellEffect(SpellEntry
const* spellInfo
, SpellEffectIndex index
) const
21576 switch(spellInfo
->Effect
[index
])
21578 case SPELL_EFFECT_ATTACK_ME
:
21583 switch(spellInfo
->EffectApplyAuraName
[index
])
21585 case SPELL_AURA_MOD_TAUNT
:
21590 return Unit::IsImmunedToSpellEffect(spellInfo
, index
);
21593 void Player::SetHomebindToLocation(WorldLocation
const& loc
, uint32 area_id
)
21595 m_homebindMapId
= loc
.mapid
;
21596 m_homebindAreaId
= area_id
;
21597 m_homebindX
= loc
.coord_x
;
21598 m_homebindY
= loc
.coord_y
;
21599 m_homebindZ
= loc
.coord_z
;
21601 // update sql homebind
21602 CharacterDatabase
.PExecute("UPDATE character_homebind SET map = '%u', zone = '%u', position_x = '%f', position_y = '%f', position_z = '%f' WHERE guid = '%u'",
21603 m_homebindMapId
, m_homebindAreaId
, m_homebindX
, m_homebindY
, m_homebindZ
, GetGUIDLow());
21606 Object
* Player::GetObjectByTypeMask(ObjectGuid guid
, TypeMask typemask
)
21608 switch(guid
.GetHigh())
21610 case HIGHGUID_ITEM
:
21611 if (typemask
& TYPEMASK_ITEM
)
21612 return GetItemByGuid(guid
);
21614 case HIGHGUID_PLAYER
:
21615 if (GetObjectGuid()==guid
)
21617 if ((typemask
& TYPEMASK_PLAYER
) && IsInWorld())
21618 return ObjectAccessor::FindPlayer(guid
);
21620 case HIGHGUID_GAMEOBJECT
:
21621 if ((typemask
& TYPEMASK_GAMEOBJECT
) && IsInWorld())
21622 return GetMap()->GetGameObject(guid
);
21624 case HIGHGUID_UNIT
:
21625 if ((typemask
& TYPEMASK_UNIT
) && IsInWorld())
21626 return GetMap()->GetCreature(guid
);
21629 if ((typemask
& TYPEMASK_UNIT
) && IsInWorld())
21630 return GetMap()->GetPet(guid
);
21632 case HIGHGUID_VEHICLE
:
21633 if ((typemask
& TYPEMASK_UNIT
) && IsInWorld())
21634 return GetMap()->GetVehicle(guid
);
21636 case HIGHGUID_DYNAMICOBJECT
:
21637 if ((typemask
& TYPEMASK_DYNAMICOBJECT
) && IsInWorld())
21638 return GetMap()->GetDynamicObject(guid
);
21640 case HIGHGUID_TRANSPORT
:
21641 case HIGHGUID_CORPSE
:
21642 case HIGHGUID_MO_TRANSPORT
:
21649 void Player::SetRestType( RestType n_r_type
, uint32 areaTriggerId
/*= 0*/)
21651 rest_type
= n_r_type
;
21653 if (rest_type
== REST_TYPE_NO
)
21655 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
21657 // Set player to FFA PVP when not in rested environment.
21658 if(sWorld
.IsFFAPvPRealm())
21663 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
21665 inn_trigger_id
= areaTriggerId
;
21666 time_inn_enter
= time(NULL
);
21668 if(sWorld
.IsFFAPvPRealm())