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"
66 #define ZONE_UPDATE_INTERVAL (1*IN_MILISECONDS)
68 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
69 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
70 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
72 #define SKILL_VALUE(x) PAIR32_LOPART(x)
73 #define SKILL_MAX(x) PAIR32_HIPART(x)
74 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
76 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
77 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
78 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
82 CHARACTER_FLAG_NONE
= 0x00000000,
83 CHARACTER_FLAG_UNK1
= 0x00000001,
84 CHARACTER_FLAG_UNK2
= 0x00000002,
85 CHARACTER_LOCKED_FOR_TRANSFER
= 0x00000004,
86 CHARACTER_FLAG_UNK4
= 0x00000008,
87 CHARACTER_FLAG_UNK5
= 0x00000010,
88 CHARACTER_FLAG_UNK6
= 0x00000020,
89 CHARACTER_FLAG_UNK7
= 0x00000040,
90 CHARACTER_FLAG_UNK8
= 0x00000080,
91 CHARACTER_FLAG_UNK9
= 0x00000100,
92 CHARACTER_FLAG_UNK10
= 0x00000200,
93 CHARACTER_FLAG_HIDE_HELM
= 0x00000400,
94 CHARACTER_FLAG_HIDE_CLOAK
= 0x00000800,
95 CHARACTER_FLAG_UNK13
= 0x00001000,
96 CHARACTER_FLAG_GHOST
= 0x00002000,
97 CHARACTER_FLAG_RENAME
= 0x00004000,
98 CHARACTER_FLAG_UNK16
= 0x00008000,
99 CHARACTER_FLAG_UNK17
= 0x00010000,
100 CHARACTER_FLAG_UNK18
= 0x00020000,
101 CHARACTER_FLAG_UNK19
= 0x00040000,
102 CHARACTER_FLAG_UNK20
= 0x00080000,
103 CHARACTER_FLAG_UNK21
= 0x00100000,
104 CHARACTER_FLAG_UNK22
= 0x00200000,
105 CHARACTER_FLAG_UNK23
= 0x00400000,
106 CHARACTER_FLAG_UNK24
= 0x00800000,
107 CHARACTER_FLAG_LOCKED_BY_BILLING
= 0x01000000,
108 CHARACTER_FLAG_DECLINED
= 0x02000000,
109 CHARACTER_FLAG_UNK27
= 0x04000000,
110 CHARACTER_FLAG_UNK28
= 0x08000000,
111 CHARACTER_FLAG_UNK29
= 0x10000000,
112 CHARACTER_FLAG_UNK30
= 0x20000000,
113 CHARACTER_FLAG_UNK31
= 0x40000000,
114 CHARACTER_FLAG_UNK32
= 0x80000000
117 enum CharacterCustomizeFlags
119 CHAR_CUSTOMIZE_FLAG_NONE
= 0x00000000,
120 CHAR_CUSTOMIZE_FLAG_CUSTOMIZE
= 0x00000001, // name, gender, etc...
121 CHAR_CUSTOMIZE_FLAG_FACTION
= 0x00010000, // name, gender, faction, etc...
122 CHAR_CUSTOMIZE_FLAG_RACE
= 0x00100000 // name, gender, race, etc...
125 // corpse reclaim times
126 #define DEATH_EXPIRE_STEP (5*MINUTE)
127 #define MAX_DEATH_COUNT 3
129 static uint32 copseReclaimDelay
[MAX_DEATH_COUNT
] = { 30, 60, 120 };
131 //== PlayerTaxi ================================================
133 PlayerTaxi::PlayerTaxi()
136 memset(m_taximask
, 0, sizeof(m_taximask
));
139 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race
, uint32 chrClass
, uint32 level
)
141 // class specific initial known nodes
144 case CLASS_DEATH_KNIGHT
:
146 for(int i
= 0; i
< TaxiMaskSize
; ++i
)
147 m_taximask
[i
] |= sOldContinentsNodesMask
[i
];
152 // race specific initial known nodes: capital and taxi hub masks
155 case RACE_HUMAN
: SetTaximaskNode(2); break; // Human
156 case RACE_ORC
: SetTaximaskNode(23); break; // Orc
157 case RACE_DWARF
: SetTaximaskNode(6); break; // Dwarf
158 case RACE_NIGHTELF
: SetTaximaskNode(26);
159 SetTaximaskNode(27); break; // Night Elf
160 case RACE_UNDEAD_PLAYER
: SetTaximaskNode(11); break;// Undead
161 case RACE_TAUREN
: SetTaximaskNode(22); break; // Tauren
162 case RACE_GNOME
: SetTaximaskNode(6); break; // Gnome
163 case RACE_TROLL
: SetTaximaskNode(23); break; // Troll
164 case RACE_BLOODELF
: SetTaximaskNode(82); break; // Blood Elf
165 case RACE_DRAENEI
: SetTaximaskNode(94); break; // Draenei
168 // new continent starting masks (It will be accessible only at new map)
169 switch(Player::TeamForRace(race
))
171 case ALLIANCE
: SetTaximaskNode(100); break;
172 case HORDE
: SetTaximaskNode(99); break;
174 // level dependent taxi hubs
176 SetTaximaskNode(213); //Shattered Sun Staging Area
179 void PlayerTaxi::LoadTaxiMask(const char* data
)
181 Tokens tokens
= StrSplit(data
, " ");
184 Tokens::iterator iter
;
185 for (iter
= tokens
.begin(), index
= 0;
186 (index
< TaxiMaskSize
) && (iter
!= tokens
.end()); ++iter
, ++index
)
188 // load and set bits only for existed taxi nodes
189 m_taximask
[index
] = sTaxiNodesMask
[index
] & uint32(atol((*iter
).c_str()));
193 void PlayerTaxi::AppendTaximaskTo( ByteBuffer
& data
, bool all
)
197 for (uint8 i
=0; i
<TaxiMaskSize
; ++i
)
198 data
<< uint32(sTaxiNodesMask
[i
]); // all existed nodes
202 for (uint8 i
=0; i
<TaxiMaskSize
; ++i
)
203 data
<< uint32(m_taximask
[i
]); // known nodes
207 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string
& values
, uint32 team
)
209 ClearTaxiDestinations();
211 Tokens tokens
= StrSplit(values
," ");
213 for(Tokens::iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
)
215 uint32 node
= uint32(atol(iter
->c_str()));
216 AddTaxiDestination(node
);
219 if(m_TaxiDestinations
.empty())
223 if(m_TaxiDestinations
.size() < 2)
226 for(size_t i
= 1; i
< m_TaxiDestinations
.size(); ++i
)
230 sObjectMgr
.GetTaxiPath(m_TaxiDestinations
[i
-1],m_TaxiDestinations
[i
],path
,cost
);
235 // can't load taxi path without mount set (quest taxi path?)
236 if(!sObjectMgr
.GetTaxiMountDisplayId(GetTaxiSource(),team
,true))
242 std::string
PlayerTaxi::SaveTaxiDestinationsToString()
244 if(m_TaxiDestinations
.empty())
247 std::ostringstream ss
;
249 for(size_t i
=0; i
< m_TaxiDestinations
.size(); ++i
)
250 ss
<< m_TaxiDestinations
[i
] << " ";
255 uint32
PlayerTaxi::GetCurrentTaxiPath() const
257 if(m_TaxiDestinations
.size() < 2)
263 sObjectMgr
.GetTaxiPath(m_TaxiDestinations
[0],m_TaxiDestinations
[1],path
,cost
);
268 std::ostringstream
& operator<< (std::ostringstream
& ss
, PlayerTaxi
const& taxi
)
271 for(int i
= 0; i
< TaxiMaskSize
; ++i
)
272 ss
<< taxi
.m_taximask
[i
] << " ";
277 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
)
279 uint32
const* ptr
= spellEntry
->GetEffectSpellClassMask(eff
);
280 mask
= uint64(ptr
[0]) | (uint64(ptr
[1]) << 32);
284 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
)
286 uint32
const* ptr
= aura
->getAuraSpellClassMask();
287 mask
= uint64(ptr
[0]) | (uint64(ptr
[1]) << 32);
291 bool SpellModifier::isAffectedOnSpell( SpellEntry
const *spell
) const
293 SpellEntry
const *affect_spell
= sSpellStore
.LookupEntry(spellId
);
294 // False if affect_spell == NULL or spellFamily not equal
295 if (!affect_spell
|| affect_spell
->SpellFamilyName
!= spell
->SpellFamilyName
)
297 if (mask
& spell
->SpellFamilyFlags
)
299 if (mask2
& spell
->SpellFamilyFlags2
)
304 //== Player ====================================================
306 UpdateMask
Player::updateVisualBits
;
308 Player::Player (WorldSession
*session
): Unit(), m_achievementMgr(this), m_reputationMgr(this)
315 m_objectType
|= TYPEMASK_PLAYER
;
316 m_objectTypeId
= TYPEID_PLAYER
;
318 m_valuesCount
= PLAYER_END
;
325 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER
)
326 SetAcceptTicket(true);
328 // players always accept
329 if(GetSession()->GetSecurity() == SEC_PLAYER
)
330 SetAcceptWhispers(true);
338 m_usedTalentCount
= 0;
339 m_questRewardTalentCount
= 0;
342 m_weaponChangeTimer
= 0;
345 m_zoneUpdateTimer
= 0;
349 m_nextSave
= sWorld
.getConfig(CONFIG_UINT32_INTERVAL_SAVE
);
351 // randomize first save time in range [CONFIG_UINT32_INTERVAL_SAVE] around [CONFIG_UINT32_INTERVAL_SAVE]
352 // this must help in case next save after mass player load after server startup
353 m_nextSave
= urand(m_nextSave
/2,m_nextSave
*3/2);
355 clearResurrectRequestData();
357 m_SpellModRemoveCount
= 0;
359 memset(m_items
, 0, sizeof(Item
*)*PLAYER_SLOTS_COUNT
);
363 // group is initialized in the reference constructor
364 SetGroupInvite(NULL
);
365 m_groupUpdateMask
= 0;
366 m_auraUpdateMask
= 0;
370 m_GuildIdInvited
= 0;
371 m_ArenaTeamIdInvited
= 0;
373 m_atLoginFlags
= AT_LOGIN_NONE
;
375 mSemaphoreTeleport_Near
= false;
376 mSemaphoreTeleport_Far
= false;
378 m_DelayedOperations
= 0;
379 m_bCanDelayTeleport
= false;
380 m_bHasDelayedTeleport
= false;
381 m_teleport_options
= 0;
388 PlayerTalkClass
= new PlayerMenu( GetSession() );
389 m_currentBuybackSlot
= BUYBACK_SLOT_START
;
391 m_DailyQuestChanged
= false;
392 m_lastDailyQuestTime
= 0;
394 for (int i
=0; i
<MAX_TIMERS
; ++i
)
395 m_MirrorTimer
[i
] = DISABLED_MIRROR_TIMER
;
397 m_MirrorTimerFlags
= UNDERWATER_NONE
;
398 m_MirrorTimerFlagsLast
= UNDERWATER_NONE
;
404 m_deathExpireTime
= 0;
408 m_DetectInvTimer
= 1*IN_MILISECONDS
;
410 for (int j
=0; j
< PLAYER_MAX_BATTLEGROUND_QUEUES
; ++j
)
412 m_bgBattleGroundQueueID
[j
].bgQueueTypeId
= BATTLEGROUND_QUEUE_NONE
;
413 m_bgBattleGroundQueueID
[j
].invitedToInstance
= 0;
416 m_logintime
= time(NULL
);
417 m_Last_tick
= m_logintime
;
418 m_WeaponProficiency
= 0;
419 m_ArmorProficiency
= 0;
422 m_canDualWield
= false;
423 m_canTitanGrip
= false;
426 m_temporaryUnsummonedPetNumber
= 0;
427 //cache for UNIT_CREATED_BY_SPELL to allow
428 //returning reagents for temporarily removed pets
429 //when dying/logging out
432 ////////////////////Rest System/////////////////////
439 rest_type
=REST_TYPE_NO
;
440 ////////////////////Rest System/////////////////////
442 m_mailsUpdated
= false;
444 m_nextMailDelivereTime
= 0;
446 m_resetTalentsCost
= 0;
447 m_resetTalentsTime
= 0;
448 m_itemUpdateQueueBlocked
= false;
450 for (int i
= 0; i
< MAX_MOVE_TYPE
; ++i
)
451 m_forced_speed_changes
[i
] = 0;
455 /////////////////// Instance System /////////////////////
458 m_InstanceValid
= true;
459 m_dungeonDifficulty
= DUNGEON_DIFFICULTY_NORMAL
;
460 m_raidDifficulty
= RAID_DIFFICULTY_10MAN_NORMAL
;
467 for (int i
= 0; i
< BASEMOD_END
; ++i
)
469 m_auraBaseMod
[i
][FLAT_MOD
] = 0.0f
;
470 m_auraBaseMod
[i
][PCT_MOD
] = 1.0f
;
473 for (int i
= 0; i
< MAX_COMBAT_RATING
; ++i
)
474 m_baseRatingValue
[i
] = 0;
476 m_baseSpellPower
= 0;
479 m_armorPenetrationPct
= 0.0f
;
482 m_lastHonorUpdateTime
= time(NULL
);
494 m_contestedPvPTimer
= 0;
496 m_declinedname
= NULL
;
505 CleanupsBeforeDelete();
507 // it must be unloaded already in PlayerLogout and accessed only for loggined player
510 // Note: buy back item already deleted from DB when player was saved
511 for(int i
= 0; i
< PLAYER_SLOTS_COUNT
; ++i
)
518 //all mailed items should be deleted, also all mail should be deallocated
519 for (PlayerMails::const_iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
522 for (ItemMap::const_iterator iter
= mMitems
.begin(); iter
!= mMitems
.end(); ++iter
)
523 delete iter
->second
; //if item is duplicated... then server may crash ... but that item should be deallocated
525 delete PlayerTalkClass
;
529 m_transport
->RemovePassenger(this);
532 for(size_t x
= 0; x
< ItemSetEff
.size(); x
++)
534 delete ItemSetEff
[x
];
536 // clean up player-instance binds, may unload some instance saves
537 for(uint8 i
= 0; i
< MAX_DIFFICULTY
; ++i
)
538 for(BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
539 itr
->second
.save
->RemovePlayer(this);
541 delete m_declinedname
;
545 void Player::CleanupsBeforeDelete()
547 if(m_uint32Values
) // only for fully created Object
550 DuelComplete(DUEL_INTERUPTED
);
552 Unit::CleanupsBeforeDelete();
555 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 */)
557 //FIXME: outfitId not used in player creating
559 Object::_Create(guidlow
, 0, HIGHGUID_PLAYER
);
563 PlayerInfo
const* info
= sObjectMgr
.GetPlayerInfo(race
, class_
);
566 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
570 for (int i
= 0; i
< PLAYER_SLOTS_COUNT
; ++i
)
573 SetLocationMapId(info
->mapId
);
574 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
);
576 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(class_
);
579 sLog
.outError("Class %u not found in DBC (Wrong DBC files?)",class_
);
583 SetMap(sMapMgr
.CreateMap(info
->mapId
, this));
585 uint8 powertype
= cEntry
->powerType
;
587 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, DEFAULT_WORLD_OBJECT_SIZE
);
588 SetFloatValue(UNIT_FIELD_COMBATREACH
, 1.5f
);
590 setFactionForRace(race
);
592 uint32 RaceClassGender
= ( race
) | ( class_
<< 8 ) | ( gender
<< 16 );
594 SetUInt32Value(UNIT_FIELD_BYTES_0
, ( RaceClassGender
| ( powertype
<< 24 ) ) );
596 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_PVP
);
597 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
);
598 SetFlag(UNIT_FIELD_FLAGS_2
, UNIT_FLAG2_REGENERATE_POWER
);
599 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
); // fix cast time showed in spell tooltip on client
600 SetFloatValue(UNIT_FIELD_HOVERHEIGHT
, 1.0f
); // default for players in 3.0.3
602 // -1 is default value
603 SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX
, -1);
605 SetUInt32Value(PLAYER_BYTES
, (skin
| (face
<< 8) | (hairStyle
<< 16) | (hairColor
<< 24)));
606 SetUInt32Value(PLAYER_BYTES_2
, (facialHair
| (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
607 SetByteValue(PLAYER_BYTES_3
, 0, gender
);
609 SetUInt32Value( PLAYER_GUILDID
, 0 );
610 SetUInt32Value( PLAYER_GUILDRANK
, 0 );
611 SetUInt32Value( PLAYER_GUILD_TIMESTAMP
, 0 );
613 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES
, 0 ); // 0=disabled
614 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1
, 0 ); // 0=disabled
615 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES2
, 0 ); // 0=disabled
616 SetUInt32Value( PLAYER_CHOSEN_TITLE
, 0 );
617 SetUInt32Value( PLAYER_FIELD_KILLS
, 0 );
618 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 0 );
619 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION
, 0 );
620 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0 );
622 // set starting level
623 uint32 start_level
= getClass() != CLASS_DEATH_KNIGHT
624 ? sWorld
.getConfig(CONFIG_UINT32_START_PLAYER_LEVEL
)
625 : sWorld
.getConfig(CONFIG_UINT32_START_HEROIC_PLAYER_LEVEL
);
627 if (GetSession()->GetSecurity() >= SEC_MODERATOR
)
629 uint32 gm_level
= sWorld
.getConfig(CONFIG_UINT32_START_GM_LEVEL
);
630 if(gm_level
> start_level
)
631 start_level
= gm_level
;
634 SetUInt32Value(UNIT_FIELD_LEVEL
, start_level
);
638 SetUInt32Value (PLAYER_FIELD_COINAGE
, sWorld
.getConfig(CONFIG_UINT32_START_PLAYER_MONEY
));
639 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_UINT32_START_HONOR_POINTS
));
640 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_UINT32_START_ARENA_POINTS
));
643 m_Last_tick
= time(NULL
);
644 m_Played_time
[PLAYED_TIME_TOTAL
] = 0;
645 m_Played_time
[PLAYED_TIME_LEVEL
] = 0;
647 // base stats and related field values
649 InitTaxiNodesForLevel();
650 InitGlyphsForLevel();
651 InitTalentForLevel();
652 InitPrimaryProfessions(); // to max set before any spell added
654 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
655 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
656 SetHealth(GetMaxHealth());
657 if (getPowerType()==POWER_MANA
)
659 UpdateMaxPower(POWER_MANA
); // Update max Mana (for add bonus from intellect)
660 SetPower(POWER_MANA
,GetMaxPower(POWER_MANA
));
663 if(getPowerType() == POWER_RUNIC_POWER
)
665 SetPower(POWER_RUNE
, 8);
666 SetMaxPower(POWER_RUNE
, 8);
667 SetPower(POWER_RUNIC_POWER
, 0);
668 SetMaxPower(POWER_RUNIC_POWER
, 1000);
672 learnDefaultSpells();
674 // original action bar
675 for (PlayerCreateInfoActions::const_iterator action_itr
= info
->action
.begin(); action_itr
!= info
->action
.end(); ++action_itr
)
676 addActionButton(0, action_itr
->button
,action_itr
->action
,action_itr
->type
);
679 CharStartOutfitEntry
const* oEntry
= NULL
;
680 for (uint32 i
= 1; i
< sCharStartOutfitStore
.GetNumRows(); ++i
)
682 if(CharStartOutfitEntry
const* entry
= sCharStartOutfitStore
.LookupEntry(i
))
684 if(entry
->RaceClassGender
== RaceClassGender
)
694 for(int j
= 0; j
< MAX_OUTFIT_ITEMS
; ++j
)
696 if(oEntry
->ItemId
[j
] <= 0)
699 uint32 item_id
= oEntry
->ItemId
[j
];
701 // just skip, reported in ObjectMgr::LoadItemPrototypes
702 ItemPrototype
const* iProto
= ObjectMgr::GetItemPrototype(item_id
);
706 // BuyCount by default
707 int32 count
= iProto
->BuyCount
;
709 // special amount for foor/drink
710 if(iProto
->Class
==ITEM_CLASS_CONSUMABLE
&& iProto
->SubClass
==ITEM_SUBCLASS_FOOD
)
712 switch(iProto
->Spells
[0].SpellCategory
)
715 count
= getClass()==CLASS_DEATH_KNIGHT
? 10 : 4;
721 if(iProto
->Stackable
< count
)
722 count
= iProto
->Stackable
;
724 // special amount for daggers
725 else if(iProto
->Class
==ITEM_CLASS_WEAPON
&& iProto
->SubClass
==ITEM_SUBCLASS_WEAPON_DAGGER
)
727 count
= 2; // will placed to 2 slots
730 StoreNewItemInBestSlots(item_id
, count
);
734 for (PlayerCreateInfoItems::const_iterator item_id_itr
= info
->item
.begin(); item_id_itr
!=info
->item
.end(); ++item_id_itr
++)
735 StoreNewItemInBestSlots(item_id_itr
->item_id
, item_id_itr
->item_amount
);
737 // bags and main-hand weapon must equipped at this moment
738 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
739 // or ammo not equipped in special bag
740 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
742 if(Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
745 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
746 uint8 msg
= CanEquipItem( NULL_SLOT
, eDest
, pItem
, false );
747 if( msg
== EQUIP_ERR_OK
)
749 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
750 EquipItem( eDest
, pItem
, true);
752 // move other items to more appropriate slots (ammo not equipped in special bag)
755 ItemPosCountVec sDest
;
756 msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, sDest
, pItem
, false );
757 if( msg
== EQUIP_ERR_OK
)
759 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
760 pItem
= StoreItem( sDest
, pItem
, true);
763 // if this is ammo then use it
764 msg
= CanUseAmmo( pItem
->GetEntry() );
765 if( msg
== EQUIP_ERR_OK
)
766 SetAmmo( pItem
->GetEntry() );
770 // all item positions resolved
775 bool Player::StoreNewItemInBestSlots(uint32 titem_id
, uint32 titem_amount
)
777 sLog
.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id
, titem_amount
);
779 // attempt equip by one
780 while(titem_amount
> 0)
783 uint8 msg
= CanEquipNewItem( NULL_SLOT
, eDest
, titem_id
, false );
784 if( msg
!= EQUIP_ERR_OK
)
787 EquipNewItem( eDest
, titem_id
, true);
788 AutoUnequipOffhandIfNeed();
792 if(titem_amount
== 0)
793 return true; // equipped
796 ItemPosCountVec sDest
;
797 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
798 uint8 msg
= CanStoreNewItem( INVENTORY_SLOT_BAG_0
, NULL_SLOT
, sDest
, titem_id
, titem_amount
);
799 if( msg
== EQUIP_ERR_OK
)
801 StoreNewItem( sDest
, titem_id
, true, Item::GenerateItemRandomPropertyId(titem_id
) );
802 return true; // stored
805 // item can't be added
806 sLog
.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id
,getRace(),getClass(),msg
);
810 // helper function, mainly for script side, but can be used for simple task in mangos also.
811 Item
* Player::StoreNewItemInInventorySlot(uint32 itemEntry
, uint32 amount
)
813 ItemPosCountVec vDest
;
815 uint8 msg
= CanStoreNewItem(INVENTORY_SLOT_BAG_0
, NULL_SLOT
, vDest
, itemEntry
, amount
);
817 if (msg
== EQUIP_ERR_OK
)
819 if (Item
* pItem
= StoreNewItem(vDest
, itemEntry
, true, Item::GenerateItemRandomPropertyId(itemEntry
)))
826 void Player::SendMirrorTimer(MirrorTimerType Type
, uint32 MaxValue
, uint32 CurrentValue
, int32 Regen
)
828 if (int(MaxValue
) == DISABLED_MIRROR_TIMER
)
830 if (int(CurrentValue
) != DISABLED_MIRROR_TIMER
)
831 StopMirrorTimer(Type
);
834 WorldPacket
data(SMSG_START_MIRROR_TIMER
, (21));
835 data
<< (uint32
)Type
;
836 data
<< CurrentValue
;
840 data
<< (uint32
)0; // spell id
841 GetSession()->SendPacket( &data
);
844 void Player::StopMirrorTimer(MirrorTimerType Type
)
846 m_MirrorTimer
[Type
] = DISABLED_MIRROR_TIMER
;
847 WorldPacket
data(SMSG_STOP_MIRROR_TIMER
, 4);
848 data
<< (uint32
)Type
;
849 GetSession()->SendPacket( &data
);
852 uint32
Player::EnvironmentalDamage(EnviromentalDamage type
, uint32 damage
)
854 if(!isAlive() || isGameMaster())
857 // Absorb, resist some environmental damage type
860 if (type
== DAMAGE_LAVA
)
861 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE
, DIRECT_DAMAGE
, damage
, &absorb
, &resist
);
862 else if (type
== DAMAGE_SLIME
)
863 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE
, DIRECT_DAMAGE
, damage
, &absorb
, &resist
);
865 damage
-=absorb
+resist
;
867 DealDamageMods(this,damage
,&absorb
);
869 WorldPacket
data(SMSG_ENVIRONMENTALDAMAGELOG
, (21));
870 data
<< uint64(GetGUID());
871 data
<< uint8(type
!=DAMAGE_FALL_TO_VOID
? type
: DAMAGE_FALL
);
872 data
<< uint32(damage
);
873 data
<< uint32(absorb
);
874 data
<< uint32(resist
);
875 SendMessageToSet(&data
, true);
877 uint32 final_damage
= DealDamage(this, damage
, NULL
, SELF_DAMAGE
, SPELL_SCHOOL_MASK_NORMAL
, NULL
, false);
881 if(type
==DAMAGE_FALL
) // DealDamage not apply item durability loss at self damage
883 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
884 DurabilityLossAll(0.10f
,false);
885 // durability lost message
886 WorldPacket
data2(SMSG_DURABILITY_DAMAGE_DEATH
, 0);
887 GetSession()->SendPacket(&data2
);
890 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM
, 1, type
);
896 int32
Player::getMaxTimer(MirrorTimerType timer
)
901 if (GetSession()->GetSecurity() >= (AccountTypes
)sWorld
.getConfig(CONFIG_UINT32_TIMERBAR_FATIGUE_GMLEVEL
))
902 return DISABLED_MIRROR_TIMER
;
903 return sWorld
.getConfig(CONFIG_UINT32_TIMERBAR_FATIGUE_MAX
)*IN_MILISECONDS
;
906 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING
) ||
907 GetSession()->GetSecurity() >= (AccountTypes
)sWorld
.getConfig(CONFIG_UINT32_TIMERBAR_BREATH_GMLEVEL
))
908 return DISABLED_MIRROR_TIMER
;
909 int32 UnderWaterTime
= sWorld
.getConfig(CONFIG_UINT32_TIMERBAR_BREATH_MAX
)*IN_MILISECONDS
;
910 AuraList
const& mModWaterBreathing
= GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING
);
911 for(AuraList::const_iterator i
= mModWaterBreathing
.begin(); i
!= mModWaterBreathing
.end(); ++i
)
912 UnderWaterTime
= uint32(UnderWaterTime
* (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
);
913 return UnderWaterTime
;
917 if (!isAlive() || GetSession()->GetSecurity() >= (AccountTypes
)sWorld
.getConfig(CONFIG_UINT32_TIMERBAR_FIRE_GMLEVEL
))
918 return DISABLED_MIRROR_TIMER
;
919 return sWorld
.getConfig(CONFIG_UINT32_TIMERBAR_FIRE_MAX
)*IN_MILISECONDS
;
927 void Player::UpdateMirrorTimers()
929 // Desync flags for update on next HandleDrowning
930 if (m_MirrorTimerFlags
)
931 m_MirrorTimerFlagsLast
= ~m_MirrorTimerFlags
;
934 void Player::HandleDrowning(uint32 time_diff
)
936 if (!m_MirrorTimerFlags
)
940 if (m_MirrorTimerFlags
& UNDERWATER_INWATER
)
942 // Breath timer not activated - activate it
943 if (m_MirrorTimer
[BREATH_TIMER
] == DISABLED_MIRROR_TIMER
)
945 m_MirrorTimer
[BREATH_TIMER
] = getMaxTimer(BREATH_TIMER
);
946 SendMirrorTimer(BREATH_TIMER
, m_MirrorTimer
[BREATH_TIMER
], m_MirrorTimer
[BREATH_TIMER
], -1);
948 else // If activated - do tick
950 m_MirrorTimer
[BREATH_TIMER
]-=time_diff
;
951 // Timer limit - need deal damage
952 if (m_MirrorTimer
[BREATH_TIMER
] < 0)
954 m_MirrorTimer
[BREATH_TIMER
]+= 1*IN_MILISECONDS
;
955 // Calculate and deal damage
956 // TODO: Check this formula
957 uint32 damage
= GetMaxHealth() / 5 + urand(0, getLevel()-1);
958 EnvironmentalDamage(DAMAGE_DROWNING
, damage
);
960 else if (!(m_MirrorTimerFlagsLast
& UNDERWATER_INWATER
)) // Update time in client if need
961 SendMirrorTimer(BREATH_TIMER
, getMaxTimer(BREATH_TIMER
), m_MirrorTimer
[BREATH_TIMER
], -1);
964 else if (m_MirrorTimer
[BREATH_TIMER
] != DISABLED_MIRROR_TIMER
) // Regen timer
966 int32 UnderWaterTime
= getMaxTimer(BREATH_TIMER
);
968 m_MirrorTimer
[BREATH_TIMER
]+=10*time_diff
;
969 if (m_MirrorTimer
[BREATH_TIMER
] >= UnderWaterTime
|| !isAlive())
970 StopMirrorTimer(BREATH_TIMER
);
971 else if (m_MirrorTimerFlagsLast
& UNDERWATER_INWATER
)
972 SendMirrorTimer(BREATH_TIMER
, UnderWaterTime
, m_MirrorTimer
[BREATH_TIMER
], 10);
976 if (m_MirrorTimerFlags
& UNDERWARER_INDARKWATER
)
978 // Fatigue timer not activated - activate it
979 if (m_MirrorTimer
[FATIGUE_TIMER
] == DISABLED_MIRROR_TIMER
)
981 m_MirrorTimer
[FATIGUE_TIMER
] = getMaxTimer(FATIGUE_TIMER
);
982 SendMirrorTimer(FATIGUE_TIMER
, m_MirrorTimer
[FATIGUE_TIMER
], m_MirrorTimer
[FATIGUE_TIMER
], -1);
986 m_MirrorTimer
[FATIGUE_TIMER
]-=time_diff
;
987 // Timer limit - need deal damage or teleport ghost to graveyard
988 if (m_MirrorTimer
[FATIGUE_TIMER
] < 0)
990 m_MirrorTimer
[FATIGUE_TIMER
]+= 1*IN_MILISECONDS
;
991 if (isAlive()) // Calculate and deal damage
993 uint32 damage
= GetMaxHealth() / 5 + urand(0, getLevel()-1);
994 EnvironmentalDamage(DAMAGE_EXHAUSTED
, damage
);
996 else if (HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
)) // Teleport ghost to graveyard
999 else if (!(m_MirrorTimerFlagsLast
& UNDERWARER_INDARKWATER
))
1000 SendMirrorTimer(FATIGUE_TIMER
, getMaxTimer(FATIGUE_TIMER
), m_MirrorTimer
[FATIGUE_TIMER
], -1);
1003 else if (m_MirrorTimer
[FATIGUE_TIMER
] != DISABLED_MIRROR_TIMER
) // Regen timer
1005 int32 DarkWaterTime
= getMaxTimer(FATIGUE_TIMER
);
1006 m_MirrorTimer
[FATIGUE_TIMER
]+=10*time_diff
;
1007 if (m_MirrorTimer
[FATIGUE_TIMER
] >= DarkWaterTime
|| !isAlive())
1008 StopMirrorTimer(FATIGUE_TIMER
);
1009 else if (m_MirrorTimerFlagsLast
& UNDERWARER_INDARKWATER
)
1010 SendMirrorTimer(FATIGUE_TIMER
, DarkWaterTime
, m_MirrorTimer
[FATIGUE_TIMER
], 10);
1013 if (m_MirrorTimerFlags
& (UNDERWATER_INLAVA
|UNDERWATER_INSLIME
))
1015 // Breath timer not activated - activate it
1016 if (m_MirrorTimer
[FIRE_TIMER
] == DISABLED_MIRROR_TIMER
)
1017 m_MirrorTimer
[FIRE_TIMER
] = getMaxTimer(FIRE_TIMER
);
1020 m_MirrorTimer
[FIRE_TIMER
]-=time_diff
;
1021 if (m_MirrorTimer
[FIRE_TIMER
] < 0)
1023 m_MirrorTimer
[FIRE_TIMER
]+= 1*IN_MILISECONDS
;
1024 // Calculate and deal damage
1025 // TODO: Check this formula
1026 uint32 damage
= urand(600, 700);
1027 if (m_MirrorTimerFlags
&UNDERWATER_INLAVA
)
1028 EnvironmentalDamage(DAMAGE_LAVA
, damage
);
1030 EnvironmentalDamage(DAMAGE_SLIME
, damage
);
1035 m_MirrorTimer
[FIRE_TIMER
] = DISABLED_MIRROR_TIMER
;
1037 // Recheck timers flag
1038 m_MirrorTimerFlags
&=~UNDERWATER_EXIST_TIMERS
;
1039 for (int i
= 0; i
< MAX_TIMERS
; ++i
)
1040 if (m_MirrorTimer
[i
]!=DISABLED_MIRROR_TIMER
)
1042 m_MirrorTimerFlags
|=UNDERWATER_EXIST_TIMERS
;
1045 m_MirrorTimerFlagsLast
= m_MirrorTimerFlags
;
1048 ///The player sobers by 256 every 10 seconds
1049 void Player::HandleSobering()
1053 uint32 drunk
= (m_drunk
<= 256) ? 0 : (m_drunk
- 256);
1054 SetDrunkValue(drunk
);
1057 DrunkenState
Player::GetDrunkenstateByValue(uint16 value
)
1060 return DRUNKEN_SMASHED
;
1062 return DRUNKEN_DRUNK
;
1064 return DRUNKEN_TIPSY
;
1065 return DRUNKEN_SOBER
;
1068 void Player::SetDrunkValue(uint16 newDrunkenValue
, uint32 itemId
)
1070 uint32 oldDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
1072 m_drunk
= newDrunkenValue
;
1073 SetUInt32Value(PLAYER_BYTES_3
,(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFF0001) | (m_drunk
& 0xFFFE));
1075 uint32 newDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
1077 // special drunk invisibility detection
1078 if(newDrunkenState
>= DRUNKEN_DRUNK
)
1079 m_detectInvisibilityMask
|= (1<<6);
1081 m_detectInvisibilityMask
&= ~(1<<6);
1083 if(newDrunkenState
== oldDrunkenState
)
1086 WorldPacket
data(SMSG_CROSSED_INEBRIATION_THRESHOLD
, (8+4+4));
1087 data
<< uint64(GetGUID());
1088 data
<< uint32(newDrunkenState
);
1089 data
<< uint32(itemId
);
1091 SendMessageToSet(&data
, true);
1094 void Player::Update( uint32 p_time
)
1100 if(m_nextMailDelivereTime
&& m_nextMailDelivereTime
<= time(NULL
))
1105 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1106 m_nextMailDelivereTime
= 0;
1109 //used to implement delayed far teleports
1110 SetCanDelayTeleport(true);
1111 Unit::Update( p_time
);
1112 SetCanDelayTeleport(false);
1114 // update player only attacks
1115 if(uint32 ranged_att
= getAttackTimer(RANGED_ATTACK
))
1117 setAttackTimer(RANGED_ATTACK
, (p_time
>= ranged_att
? 0 : ranged_att
- p_time
) );
1120 if(uint32 off_att
= getAttackTimer(OFF_ATTACK
))
1122 setAttackTimer(OFF_ATTACK
, (p_time
>= off_att
? 0 : off_att
- p_time
) );
1125 time_t now
= time (NULL
);
1129 UpdateContestedPvP(p_time
);
1131 UpdateDuelFlag(now
);
1133 CheckDuelDistance(now
);
1135 UpdateAfkReport(now
);
1137 // Update items that have just a limited lifetime
1138 if (now
>m_Last_tick
)
1139 UpdateItemDuration(uint32(now
- m_Last_tick
));
1141 if (!m_timedquests
.empty())
1143 std::set
<uint32
>::iterator iter
= m_timedquests
.begin();
1144 while (iter
!= m_timedquests
.end())
1146 QuestStatusData
& q_status
= mQuestStatus
[*iter
];
1147 if( q_status
.m_timer
<= p_time
)
1149 uint32 quest_id
= *iter
;
1150 ++iter
; // current iter will be removed in FailQuest
1151 FailQuest(quest_id
);
1155 q_status
.m_timer
-= p_time
;
1156 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
1162 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING
))
1164 Unit
*pVictim
= getVictim();
1165 if (pVictim
&& !IsNonMeleeSpellCasted(false))
1167 // default combat reach 10
1168 // TODO add weapon,skill check
1170 float pldistance
= ATTACK_DISTANCE
;
1172 if (isAttackReady(BASE_ATTACK
))
1174 if(!IsWithinDistInMap(pVictim
, pldistance
))
1176 setAttackTimer(BASE_ATTACK
,100);
1177 if(m_swingErrorMsg
!= 1) // send single time (client auto repeat)
1179 SendAttackSwingNotInRange();
1180 m_swingErrorMsg
= 1;
1183 //120 degrees of radiant range
1184 else if( !HasInArc( 2*M_PI_F
/3, pVictim
))
1186 setAttackTimer(BASE_ATTACK
,100);
1187 if(m_swingErrorMsg
!= 2) // send single time (client auto repeat)
1189 SendAttackSwingBadFacingAttack();
1190 m_swingErrorMsg
= 2;
1195 m_swingErrorMsg
= 0; // reset swing error state
1197 // prevent base and off attack in same time, delay attack at 0.2 sec
1198 if(haveOffhandWeapon())
1200 uint32 off_att
= getAttackTimer(OFF_ATTACK
);
1201 if(off_att
< ATTACK_DISPLAY_DELAY
)
1202 setAttackTimer(OFF_ATTACK
,ATTACK_DISPLAY_DELAY
);
1204 AttackerStateUpdate(pVictim
, BASE_ATTACK
);
1205 resetAttackTimer(BASE_ATTACK
);
1209 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK
))
1211 if(!IsWithinDistInMap(pVictim
, pldistance
))
1213 setAttackTimer(OFF_ATTACK
,100);
1215 else if( !HasInArc( 2*M_PI_F
/3, pVictim
))
1217 setAttackTimer(OFF_ATTACK
,100);
1221 // prevent base and off attack in same time, delay attack at 0.2 sec
1222 uint32 base_att
= getAttackTimer(BASE_ATTACK
);
1223 if(base_att
< ATTACK_DISPLAY_DELAY
)
1224 setAttackTimer(BASE_ATTACK
,ATTACK_DISPLAY_DELAY
);
1226 AttackerStateUpdate(pVictim
, OFF_ATTACK
);
1227 resetAttackTimer(OFF_ATTACK
);
1231 Unit
*owner
= pVictim
->GetOwner();
1232 Unit
*u
= owner
? owner
: pVictim
;
1233 if(u
->IsPvP() && (!duel
|| duel
->opponent
!= u
))
1236 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT
);
1241 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
))
1243 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1245 time_t time_inn
= time(NULL
)-GetTimeInnEnter();
1246 if (time_inn
>= 10) //freeze update
1248 float bubble
= 0.125f
*sWorld
.getConfig(CONFIG_FLOAT_RATE_REST_INGAME
);
1249 //speed collect rest bonus (section/in hour)
1250 SetRestBonus( float(GetRestBonus()+ time_inn
*(GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
));
1251 UpdateInnerTime(time(NULL
));
1258 if(p_time
>= m_regenTimer
)
1261 m_regenTimer
-= p_time
;
1264 if (m_weaponChangeTimer
> 0)
1266 if(p_time
>= m_weaponChangeTimer
)
1267 m_weaponChangeTimer
= 0;
1269 m_weaponChangeTimer
-= p_time
;
1272 if (m_zoneUpdateTimer
> 0)
1274 if(p_time
>= m_zoneUpdateTimer
)
1276 uint32 newzone
, newarea
;
1277 GetZoneAndAreaId(newzone
,newarea
);
1279 if( m_zoneUpdateId
!= newzone
)
1280 UpdateZone(newzone
,newarea
); // also update area
1283 // use area updates as well
1284 // needed for free far all arenas for example
1285 if( m_areaUpdateId
!= newarea
)
1286 UpdateArea(newarea
);
1288 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
1292 m_zoneUpdateTimer
-= p_time
;
1297 // if no longer casting, set regen power as soon as it is up.
1298 if (!IsUnderLastManaUseEffect())
1299 SetFlag(UNIT_FIELD_FLAGS_2
, UNIT_FLAG2_REGENERATE_POWER
);
1305 if (m_deathState
== JUST_DIED
)
1312 if(p_time
>= m_nextSave
)
1314 // m_nextSave reseted in SaveToDB call
1316 sLog
.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1320 m_nextSave
-= p_time
;
1324 //Handle Water/drowning
1325 HandleDrowning(p_time
);
1327 //Handle detect stealth players
1328 if (m_DetectInvTimer
> 0)
1330 if (p_time
>= m_DetectInvTimer
)
1332 HandleStealthedUnitsDetection();
1333 m_DetectInvTimer
= 3000;
1336 m_DetectInvTimer
-= p_time
;
1340 if (now
> m_Last_tick
)
1342 uint32 elapsed
= uint32(now
- m_Last_tick
);
1343 m_Played_time
[PLAYED_TIME_TOTAL
] += elapsed
; // Total played time
1344 m_Played_time
[PLAYED_TIME_LEVEL
] += elapsed
; // Level played time
1350 m_drunkTimer
+= p_time
;
1352 if (m_drunkTimer
> 10*IN_MILISECONDS
)
1356 // not auto-free ghost from body in instances
1357 if(m_deathTimer
> 0 && !GetBaseMap()->Instanceable())
1359 if(p_time
>= m_deathTimer
)
1366 m_deathTimer
-= p_time
;
1369 UpdateEnchantTime(p_time
);
1370 UpdateHomebindTime(p_time
);
1373 SendUpdateToOutOfRangeGroupMembers();
1375 Pet
* pet
= GetPet();
1376 if(pet
&& !pet
->IsWithinDistInMap(this, GetMap()->GetVisibilityDistance()) && (GetCharmGUID() && (pet
->GetGUID() != GetCharmGUID())))
1378 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
, true);
1381 //we should execute delayed teleports only for alive(!) players
1382 //because we don't want player's ghost teleported from graveyard
1383 if(IsHasDelayedTeleport() && isAlive())
1384 TeleportTo(m_teleport_dest
, m_teleport_options
);
1387 void Player::setDeathState(DeathState s
)
1389 uint32 ressSpellId
= 0;
1391 bool cur
= isAlive();
1393 if(s
== JUST_DIED
&& cur
)
1395 // drunken state is cleared on death
1397 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1400 clearResurrectRequestData();
1402 // remove form before other mods to prevent incorrect stats calculation
1403 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId
);
1405 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1406 RemovePet(NULL
, PET_SAVE_NOT_IN_SLOT
, true);
1408 // remove uncontrolled pets
1411 // save value before aura remove in Unit::setDeathState
1412 ressSpellId
= GetUInt32Value(PLAYER_SELF_RES_SPELL
);
1416 ressSpellId
= GetResurrectionSpellId();
1417 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP
, 1);
1418 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH
, 1);
1419 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON
, 1);
1421 Unit::setDeathState(s
);
1423 // restore resurrection spell id for player after aura remove
1424 if(s
== JUST_DIED
&& cur
&& ressSpellId
)
1425 SetUInt32Value(PLAYER_SELF_RES_SPELL
, ressSpellId
);
1427 if(isAlive() && !cur
)
1429 //clear aura case after resurrection by another way (spells will be applied before next death)
1430 SetUInt32Value(PLAYER_SELF_RES_SPELL
, 0);
1432 // restore default warrior stance
1433 if(getClass()== CLASS_WARRIOR
)
1434 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
1438 bool Player::BuildEnumData( QueryResult
* result
, WorldPacket
* p_data
)
1441 // "SELECT characters.guid, characters.name, characters.race, characters.class, characters.gender, characters.playerBytes, characters.playerBytes2, characters.level, "
1442 // 8 9 10 11 12 13 14
1443 // "characters.zone, characters.map, characters.position_x, characters.position_y, characters.position_z, guild_member.guildid, characters.playerFlags, "
1444 // 15 16 17 18 19 20
1445 // "characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, characters.data, character_declinedname.genitive "
1447 Field
*fields
= result
->Fetch();
1449 uint32 guid
= fields
[0].GetUInt32();
1450 uint8 pRace
= fields
[2].GetUInt8();
1451 uint8 pClass
= fields
[3].GetUInt8();
1453 PlayerInfo
const *info
= sObjectMgr
.GetPlayerInfo(pRace
, pClass
);
1456 sLog
.outError("Player %u has incorrect race/class pair. Don't build enum.", guid
);
1460 *p_data
<< uint64(MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
1461 *p_data
<< fields
[1].GetString(); // name
1462 *p_data
<< uint8(pRace
); // race
1463 *p_data
<< uint8(pClass
); // class
1464 *p_data
<< uint8(fields
[4].GetUInt8()); // gender
1466 uint32 playerBytes
= fields
[5].GetUInt32();
1467 *p_data
<< uint8(playerBytes
); // skin
1468 *p_data
<< uint8(playerBytes
>> 8); // face
1469 *p_data
<< uint8(playerBytes
>> 16); // hair style
1470 *p_data
<< uint8(playerBytes
>> 24); // hair color
1472 uint32 playerBytes2
= fields
[6].GetUInt32();
1473 *p_data
<< uint8(playerBytes2
& 0xFF); // facial hair
1475 *p_data
<< uint8(fields
[7].GetUInt8()); // level
1476 *p_data
<< uint32(fields
[8].GetUInt32()); // zone
1477 *p_data
<< uint32(fields
[9].GetUInt32()); // map
1479 *p_data
<< fields
[10].GetFloat(); // x
1480 *p_data
<< fields
[11].GetFloat(); // y
1481 *p_data
<< fields
[12].GetFloat(); // z
1483 *p_data
<< uint32(fields
[13].GetUInt32()); // guild id
1485 uint32 char_flags
= 0;
1486 uint32 playerFlags
= fields
[14].GetUInt32();
1487 uint32 atLoginFlags
= fields
[15].GetUInt32();
1488 if(playerFlags
& PLAYER_FLAGS_HIDE_HELM
)
1489 char_flags
|= CHARACTER_FLAG_HIDE_HELM
;
1490 if(playerFlags
& PLAYER_FLAGS_HIDE_CLOAK
)
1491 char_flags
|= CHARACTER_FLAG_HIDE_CLOAK
;
1492 if(playerFlags
& PLAYER_FLAGS_GHOST
)
1493 char_flags
|= CHARACTER_FLAG_GHOST
;
1494 if(atLoginFlags
& AT_LOGIN_RENAME
)
1495 char_flags
|= CHARACTER_FLAG_RENAME
;
1496 if(sWorld
.getConfig(CONFIG_BOOL_DECLINED_NAMES_USED
))
1498 if(!fields
[20].GetCppString().empty())
1499 char_flags
|= CHARACTER_FLAG_DECLINED
;
1502 char_flags
|= CHARACTER_FLAG_DECLINED
;
1504 *p_data
<< uint32(char_flags
); // character flags
1505 // character customize flags
1506 *p_data
<< uint32(atLoginFlags
& AT_LOGIN_CUSTOMIZE
? CHAR_CUSTOMIZE_FLAG_CUSTOMIZE
: CHAR_CUSTOMIZE_FLAG_NONE
);
1508 *p_data
<< uint8(atLoginFlags
& AT_LOGIN_FIRST
? 1 : 0);
1512 uint32 petDisplayId
= 0;
1513 uint32 petLevel
= 0;
1514 uint32 petFamily
= 0;
1516 // show pet at selection character in character list only for non-ghost character
1517 if (result
&& !(playerFlags
& PLAYER_FLAGS_GHOST
) && (pClass
== CLASS_WARLOCK
|| pClass
== CLASS_HUNTER
|| pClass
== CLASS_DEATH_KNIGHT
))
1519 uint32 entry
= fields
[16].GetUInt32();
1520 CreatureInfo
const* cInfo
= sCreatureStorage
.LookupEntry
<CreatureInfo
>(entry
);
1523 petDisplayId
= fields
[17].GetUInt32();
1524 petLevel
= fields
[18].GetUInt32();
1525 petFamily
= cInfo
->family
;
1529 *p_data
<< uint32(petDisplayId
);
1530 *p_data
<< uint32(petLevel
);
1531 *p_data
<< uint32(petFamily
);
1534 // TODO: do not access data field here
1535 Tokens data
= StrSplit(fields
[19].GetCppString(), " ");
1537 for (uint8 slot
= 0; slot
< EQUIPMENT_SLOT_END
; slot
++)
1539 uint32 visualbase
= PLAYER_VISIBLE_ITEM_1_ENTRYID
+ (slot
* 2);
1540 uint32 item_id
= GetUInt32ValueFromArray(data
, visualbase
);
1541 const ItemPrototype
* proto
= ObjectMgr::GetItemPrototype(item_id
);
1544 *p_data
<< uint32(0);
1545 *p_data
<< uint8(0);
1546 *p_data
<< uint32(0);
1550 SpellItemEnchantmentEntry
const *enchant
= NULL
;
1552 uint32 enchants
= GetUInt32ValueFromArray(data
, visualbase
+ 1);
1553 for(uint8 enchantSlot
= PERM_ENCHANTMENT_SLOT
; enchantSlot
<= TEMP_ENCHANTMENT_SLOT
; ++enchantSlot
)
1555 // values stored in 2 uint16
1556 uint32 enchantId
= 0x0000FFFF & (enchants
>> enchantSlot
*16);
1560 if ((enchant
= sSpellItemEnchantmentStore
.LookupEntry(enchantId
)))
1564 *p_data
<< uint32(proto
->DisplayInfoID
);
1565 *p_data
<< uint8(proto
->InventoryType
);
1566 *p_data
<< uint32(enchant
? enchant
->aura_id
: 0);
1568 *p_data
<< uint32(0); // first bag display id
1569 *p_data
<< uint8(0); // first bag inventory type
1570 *p_data
<< uint32(0); // enchant?
1575 bool Player::ToggleAFK()
1577 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1579 bool state
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1581 // afk player not allowed in battleground
1582 if(state
&& InBattleGround())
1583 LeaveBattleground();
1588 bool Player::ToggleDND()
1590 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1592 return HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1595 uint8
Player::chatTag() const
1612 bool Player::TeleportTo(uint32 mapid
, float x
, float y
, float z
, float orientation
, uint32 options
)
1614 if(!MapManager::IsValidMapCoord(mapid
, x
, y
, z
, orientation
))
1616 sLog
.outError("TeleportTo: invalid map %d or absent instance template.", mapid
);
1620 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1621 Pet
* pet
= GetPet();
1623 MapEntry
const* mEntry
= sMapStore
.LookupEntry(mapid
);
1625 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1626 // don't let gm level > 1 either
1627 if(!InBattleGround() && mEntry
->IsBattleGroundOrArena())
1630 // client without expansion support
1631 if(GetSession()->Expansion() < mEntry
->Expansion())
1633 sLog
.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid
);
1636 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1638 SendTransferAborted(mapid
, TRANSFER_ABORT_INSUF_EXPAN_LVL
, mEntry
->Expansion());
1640 return false; // normal client can't teleport to this map...
1644 sLog
.outDebug("Player %s is being teleported to map %u", GetName(), mapid
);
1647 // if we were on a transport, leave
1648 if (!(options
& TELE_TO_NOT_LEAVE_TRANSPORT
) && m_transport
)
1650 m_transport
->RemovePassenger(this);
1652 m_movementInfo
.SetTransportData(0, 0.0f
, 0.0f
, 0.0f
, 0.0f
, 0, -1);
1655 // The player was ported to another map and looses the duel immediately.
1656 // We have to perform this check before the teleport, otherwise the
1657 // ObjectAccessor won't find the flag.
1658 if (duel
&& GetMapId() != mapid
)
1660 GameObject
* obj
= GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER
));
1662 DuelComplete(DUEL_FLED
);
1665 // reset movement flags at teleport, because player will continue move with these flags after teleport
1666 m_movementInfo
.SetMovementFlags(MOVEFLAG_NONE
);
1668 if ((GetMapId() == mapid
) && (!m_transport
))
1670 //lets reset far teleport flag if it wasn't reset during chained teleports
1671 SetSemaphoreTeleportFar(false);
1672 //setup delayed teleport flag
1673 SetDelayedTeleportFlag(IsCanDelayTeleport());
1674 //if teleport spell is casted in Unit::Update() func
1675 //then we need to delay it until update process will be finished
1676 if(IsHasDelayedTeleport())
1678 SetSemaphoreTeleportNear(true);
1679 //lets save teleport destination for player
1680 m_teleport_dest
= WorldLocation(mapid
, x
, y
, z
, orientation
);
1681 m_teleport_options
= options
;
1685 if (!(options
& TELE_TO_NOT_UNSUMMON_PET
))
1687 //same map, only remove pet if out of range for new position
1688 if(pet
&& !pet
->IsWithinDist3d(x
, y
, z
, GetMap()->GetVisibilityDistance()))
1689 UnsummonPetTemporaryIfAny();
1692 if(!(options
& TELE_TO_NOT_LEAVE_COMBAT
))
1695 // this will be used instead of the current location in SaveToDB
1696 m_teleport_dest
= WorldLocation(mapid
, x
, y
, z
, orientation
);
1697 SetFallInformation(0, z
);
1699 // code for finish transfer called in WorldSession::HandleMovementOpcodes()
1700 // at client packet MSG_MOVE_TELEPORT_ACK
1701 SetSemaphoreTeleportNear(true);
1702 // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
1703 if(!GetSession()->PlayerLogout())
1706 BuildTeleportAckMsg(&data
, x
, y
, z
, orientation
);
1707 GetSession()->SendPacket(&data
);
1712 // far teleport to another map
1713 Map
* oldmap
= IsInWorld() ? GetMap() : NULL
;
1714 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1716 // Check enter rights before map getting to avoid creating instance copy for player
1717 // this check not dependent from map instance copy and same for all instance copies of selected map
1718 if (!sMapMgr
.CanPlayerEnter(mapid
, this))
1721 // If the map is not created, assume it is possible to enter it.
1722 // It will be created in the WorldPortAck.
1723 Map
*map
= sMapMgr
.FindMap(mapid
);
1724 if (!map
|| map
->CanEnter(this))
1726 //lets reset near teleport flag if it wasn't reset during chained teleports
1727 SetSemaphoreTeleportNear(false);
1728 //setup delayed teleport flag
1729 SetDelayedTeleportFlag(IsCanDelayTeleport());
1730 //if teleport spell is casted in Unit::Update() func
1731 //then we need to delay it until update process will be finished
1732 if(IsHasDelayedTeleport())
1734 SetSemaphoreTeleportFar(true);
1735 //lets save teleport destination for player
1736 m_teleport_dest
= WorldLocation(mapid
, x
, y
, z
, orientation
);
1737 m_teleport_options
= options
;
1745 ResetContestedPvP();
1747 // remove player from battleground on far teleport (when changing maps)
1748 if(BattleGround
const* bg
= GetBattleGround())
1750 // Note: at battleground join battleground id set before teleport
1751 // and we already will found "current" battleground
1752 // just need check that this is targeted map or leave
1753 if(bg
->GetMapId() != mapid
)
1754 LeaveBattleground(false); // don't teleport to entry point
1757 // remove pet on map change
1759 UnsummonPetTemporaryIfAny();
1761 // remove all dyn objects
1762 RemoveAllDynObjects();
1764 // stop spellcasting
1765 // not attempt interrupt teleportation spell at caster teleport
1766 if(!(options
& TELE_TO_SPELL
))
1767 if(IsNonMeleeSpellCasted(true))
1768 InterruptNonMeleeSpells(true);
1770 //remove auras before removing from map...
1771 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP
| AURA_INTERRUPT_FLAG_MOVE
| AURA_INTERRUPT_FLAG_TURNING
);
1773 if(!GetSession()->PlayerLogout())
1775 // send transfer packets
1776 WorldPacket
data(SMSG_TRANSFER_PENDING
, (4+4+4));
1777 data
<< uint32(mapid
);
1780 data
<< uint32(m_transport
->GetEntry());
1781 data
<< uint32(GetMapId());
1783 GetSession()->SendPacket(&data
);
1785 data
.Initialize(SMSG_NEW_WORLD
, (20));
1788 data
<< uint32(mapid
);
1789 data
<< float(m_movementInfo
.GetTransportPos()->x
);
1790 data
<< float(m_movementInfo
.GetTransportPos()->y
);
1791 data
<< float(m_movementInfo
.GetTransportPos()->z
);
1792 data
<< float(m_movementInfo
.GetTransportPos()->o
);
1796 data
<< uint32(mapid
);
1800 data
<< float(orientation
);
1802 GetSession()->SendPacket( &data
);
1803 SendSavedInstances();
1806 // remove from old map now
1808 oldmap
->Remove(this, false);
1810 // new final coordinates
1814 float final_o
= orientation
;
1818 final_x
+= m_movementInfo
.GetTransportPos()->x
;
1819 final_y
+= m_movementInfo
.GetTransportPos()->y
;
1820 final_z
+= m_movementInfo
.GetTransportPos()->z
;
1821 final_o
+= m_movementInfo
.GetTransportPos()->o
;
1824 m_teleport_dest
= WorldLocation(mapid
, final_x
, final_y
, final_z
, final_o
);
1825 SetFallInformation(0, final_z
);
1826 // if the player is saved before worldport ack (at logout for example)
1827 // this will be used instead of the current location in SaveToDB
1829 // move packet sent by client always after far teleport
1830 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1831 SetSemaphoreTeleportFar(true);
1839 bool Player::TeleportToBGEntryPoint()
1841 ScheduleDelayedOperation(DELAYED_BG_MOUNT_RESTORE
);
1842 ScheduleDelayedOperation(DELAYED_BG_TAXI_RESTORE
);
1843 return TeleportTo(m_bgData
.joinPos
);
1846 void Player::ProcessDelayedOperations()
1848 if(m_DelayedOperations
== 0)
1851 if(m_DelayedOperations
& DELAYED_RESURRECT_PLAYER
)
1853 ResurrectPlayer(0.0f
, false);
1855 if(GetMaxHealth() > m_resurrectHealth
)
1856 SetHealth( m_resurrectHealth
);
1858 SetHealth( GetMaxHealth() );
1860 if(GetMaxPower(POWER_MANA
) > m_resurrectMana
)
1861 SetPower(POWER_MANA
, m_resurrectMana
);
1863 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
) );
1865 SetPower(POWER_RAGE
, 0 );
1866 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
) );
1871 if(m_DelayedOperations
& DELAYED_SAVE_PLAYER
)
1876 if(m_DelayedOperations
& DELAYED_SPELL_CAST_DESERTER
)
1878 CastSpell(this, 26013, true); // Deserter
1881 if (m_DelayedOperations
& DELAYED_BG_MOUNT_RESTORE
)
1883 if (m_bgData
.mountSpell
)
1885 CastSpell(this, m_bgData
.mountSpell
, true);
1886 m_bgData
.mountSpell
= 0;
1890 if (m_DelayedOperations
& DELAYED_BG_TAXI_RESTORE
)
1892 if (m_bgData
.HasTaxiPath())
1894 m_taxi
.AddTaxiDestination(m_bgData
.taxiPath
[0]);
1895 m_taxi
.AddTaxiDestination(m_bgData
.taxiPath
[1]);
1896 m_bgData
.ClearTaxiPath();
1898 ContinueTaxiFlight();
1902 //we have executed ALL delayed ops, so clear the flag
1903 m_DelayedOperations
= 0;
1906 void Player::AddToWorld()
1908 ///- Do not add/remove the player from the object storage
1909 ///- It will crash when updating the ObjectAccessor
1910 ///- The player should only be added when logging in
1913 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; ++i
)
1916 m_items
[i
]->AddToWorld();
1920 void Player::RemoveFromWorld()
1925 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1926 UnsummonAllTotems();
1930 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; ++i
)
1933 m_items
[i
]->RemoveFromWorld();
1936 ///- Do not add/remove the player from the object storage
1937 ///- It will crash when updating the ObjectAccessor
1938 ///- The player should only be removed when logging out
1939 Unit::RemoveFromWorld();
1942 void Player::RewardRage( uint32 damage
, uint32 weaponSpeedHitFactor
, bool attacker
)
1946 float rageconversion
= float((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911f
;
1950 addRage
= ((damage
/rageconversion
*7.5f
+ weaponSpeedHitFactor
)/2.0f
);
1952 // talent who gave more rage on attack
1953 addRage
*= 1.0f
+ GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT
) / 100.0f
;
1957 addRage
= damage
/rageconversion
*2.5f
;
1959 // Berserker Rage effect
1960 if (HasAura(18499, EFFECT_INDEX_0
))
1964 addRage
*= sWorld
.getConfig(CONFIG_FLOAT_RATE_POWER_RAGE_INCOME
);
1966 ModifyPower(POWER_RAGE
, uint32(addRage
*10));
1969 void Player::RegenerateAll(uint32 diff
)
1971 // Not in combat or they have regeneration
1972 if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) ||
1973 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
) || IsPolymorphed() )
1975 RegenerateHealth(diff
);
1976 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN
))
1978 Regenerate(POWER_RAGE
, diff
);
1979 if(getClass() == CLASS_DEATH_KNIGHT
)
1980 Regenerate(POWER_RUNIC_POWER
, diff
);
1984 Regenerate(POWER_ENERGY
, diff
);
1986 Regenerate(POWER_MANA
, diff
);
1988 if (getClass() == CLASS_DEATH_KNIGHT
)
1989 Regenerate(POWER_RUNE
, diff
);
1991 m_regenTimer
= REGEN_TIME_FULL
;
1994 // diff contains the time in milliseconds since last regen.
1995 void Player::Regenerate(Powers power
, uint32 diff
)
1997 uint32 curValue
= GetPower(power
);
1998 uint32 maxValue
= GetMaxPower(power
);
2000 float addvalue
= 0.0f
;
2006 bool recentCast
= IsUnderLastManaUseEffect();
2007 float ManaIncreaseRate
= sWorld
.getConfig(CONFIG_FLOAT_RATE_POWER_MANA
);
2010 // Mangos Updates Mana in intervals of 2s, which is correct
2011 addvalue
= GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER
) * ManaIncreaseRate
* 2.00f
;
2015 addvalue
= GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER
) * ManaIncreaseRate
* 2.00f
;
2018 case POWER_RAGE
: // Regenerate rage
2020 float RageDecreaseRate
= sWorld
.getConfig(CONFIG_FLOAT_RATE_POWER_RAGE_LOSS
);
2021 addvalue
= 20 * RageDecreaseRate
; // 2 rage by tick (= 2 seconds => 1 rage/sec)
2023 case POWER_ENERGY
: // Regenerate energy (rogue)
2026 case POWER_RUNIC_POWER
:
2028 float RunicPowerDecreaseRate
= sWorld
.getConfig(CONFIG_FLOAT_RATE_POWER_RUNICPOWER_LOSS
);
2029 addvalue
= 30 * RunicPowerDecreaseRate
; // 3 RunicPower by tick
2033 if (getClass() != CLASS_DEATH_KNIGHT
)
2036 for(uint32 rune
= 0; rune
< MAX_RUNES
; ++rune
)
2038 if(uint16 cd
= GetRuneCooldown(rune
)) // if we have cooldown, reduce it...
2040 uint32 cd_diff
= diff
;
2041 AuraList
const& ModPowerRegenPCTAuras
= GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT
);
2042 for(AuraList::const_iterator i
= ModPowerRegenPCTAuras
.begin(); i
!= ModPowerRegenPCTAuras
.end(); ++i
)
2043 if ((*i
)->GetModifier()->m_miscvalue
== power
&& (*i
)->GetMiscBValue()==GetCurrentRune(rune
))
2044 cd_diff
= cd_diff
* ((*i
)->GetModifier()->m_amount
+ 100) / 100.0f
;
2046 SetRuneCooldown(rune
, (cd
< cd_diff
) ? 0 : cd
- cd_diff
);
2051 case POWER_HAPPINESS
:
2056 // Mana regen calculated in Player::UpdateManaRegen()
2057 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
2058 if(power
!= POWER_MANA
)
2060 AuraList
const& ModPowerRegenPCTAuras
= GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT
);
2061 for(AuraList::const_iterator i
= ModPowerRegenPCTAuras
.begin(); i
!= ModPowerRegenPCTAuras
.end(); ++i
)
2062 if ((*i
)->GetModifier()->m_miscvalue
== power
)
2063 addvalue
*= ((*i
)->GetModifier()->m_amount
+ 100) / 100.0f
;
2066 // addvalue computed on a 2sec basis. => update to diff time
2067 addvalue
*= float(diff
) / REGEN_TIME_FULL
;
2069 if (power
!= POWER_RAGE
&& power
!= POWER_RUNIC_POWER
)
2071 curValue
+= uint32(addvalue
);
2072 if (curValue
> maxValue
)
2073 curValue
= maxValue
;
2077 if(curValue
<= uint32(addvalue
))
2080 curValue
-= uint32(addvalue
);
2082 SetPower(power
, curValue
);
2085 void Player::RegenerateHealth(uint32 diff
)
2087 uint32 curValue
= GetHealth();
2088 uint32 maxValue
= GetMaxHealth();
2090 if (curValue
>= maxValue
) return;
2092 float HealthIncreaseRate
= sWorld
.getConfig(CONFIG_FLOAT_RATE_HEALTH
);
2094 float addvalue
= 0.0f
;
2097 if ( IsPolymorphed() )
2098 addvalue
= (float)GetMaxHealth()/3;
2099 // normal regen case (maybe partly in combat case)
2100 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) )
2102 addvalue
= OCTRegenHPPerSpirit()* HealthIncreaseRate
;
2105 AuraList
const& mModHealthRegenPct
= GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT
);
2106 for(AuraList::const_iterator i
= mModHealthRegenPct
.begin(); i
!= mModHealthRegenPct
.end(); ++i
)
2107 addvalue
*= (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
;
2109 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
))
2110 addvalue
*= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) / 100.0f
;
2116 // always regeneration bonus (including combat)
2117 addvalue
+= GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
);
2122 addvalue
*= (float)diff
/ REGEN_TIME_FULL
;
2124 ModifyHealth(int32(addvalue
));
2127 Creature
* Player::GetNPCIfCanInteractWith(ObjectGuid guid
, uint32 npcflagmask
)
2129 // some basic checks
2130 if (guid
.IsEmpty() || !IsInWorld() || isInFlight())
2133 // exist (we need look pets also for some interaction (quest/etc)
2134 Creature
*unit
= GetMap()->GetCreatureOrPetOrVehicle(guid
);
2138 // appropriate npc type
2139 if (npcflagmask
&& !unit
->HasFlag( UNIT_NPC_FLAGS
, npcflagmask
))
2142 if (npcflagmask
== UNIT_NPC_FLAG_STABLEMASTER
)
2144 if (getClass() != CLASS_HUNTER
)
2148 // if a dead unit should be able to talk - the creature must be alive and have special flags
2149 if (!unit
->isAlive())
2152 if (isAlive() && unit
->isInvisibleForAlive())
2155 // not allow interaction under control, but allow with own pets
2156 if (unit
->GetCharmerGUID())
2160 if (unit
->IsHostileTo(this))
2164 if(FactionTemplateEntry
const* factionTemplate
= sFactionTemplateStore
.LookupEntry(unit
->getFaction()))
2165 if(factionTemplate
->faction
)
2166 if(FactionEntry
const* faction
= sFactionStore
.LookupEntry(factionTemplate
->faction
))
2167 if(faction
->reputationListID
>= 0 && GetReputationMgr().GetRank(faction
) <= REP_UNFRIENDLY
)
2171 if(!unit
->IsWithinDistInMap(this,INTERACTION_DISTANCE
))
2177 GameObject
* Player::GetGameObjectIfCanInteractWith(ObjectGuid guid
, uint32 gameobject_type
) const
2179 // some basic checks
2180 if (guid
.IsEmpty() || !IsInWorld() || isInFlight())
2183 if (GameObject
*go
= GetMap()->GetGameObject(guid
))
2185 if (uint32(go
->GetGoType()) == gameobject_type
|| gameobject_type
== MAX_GAMEOBJECT_TYPE
)
2188 switch(go
->GetGoType())
2190 // TODO: find out how the client calculates the maximal usage distance to spellless working
2191 // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
2192 case GAMEOBJECT_TYPE_GUILD_BANK
:
2193 case GAMEOBJECT_TYPE_MAILBOX
:
2196 case GAMEOBJECT_TYPE_FISHINGHOLE
:
2197 maxdist
= 20.0f
+CONTACT_DISTANCE
; // max spell range
2200 maxdist
= INTERACTION_DISTANCE
;
2204 if (go
->IsWithinDistInMap(this, maxdist
) && go
->isSpawned())
2207 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
,
2208 go
->GetGUIDLow(), GetName(), GetGUIDLow(), go
->GetDistance(this));
2214 bool Player::IsUnderWater() const
2216 return IsInWater() &&
2217 GetPositionZ() < (GetBaseMap()->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2220 void Player::SetInWater(bool apply
)
2222 if(m_isInWater
==apply
)
2225 //define player in water by opcodes
2226 //move player's guid into HateOfflineList of those mobs
2227 //which can't swim and move guid back into ThreatList when
2229 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2230 m_isInWater
= apply
;
2232 // remove auras that need water/land
2233 RemoveAurasWithInterruptFlags(apply
? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER
: AURA_INTERRUPT_FLAG_NOT_UNDERWATER
);
2235 getHostileRefManager().updateThreatTables();
2238 struct SetGameMasterOnHelper
2240 explicit SetGameMasterOnHelper() {}
2241 void operator()(Unit
* unit
) const
2243 unit
->setFaction(35);
2244 unit
->getHostileRefManager().setOnlineOfflineState(false);
2248 struct SetGameMasterOffHelper
2250 explicit SetGameMasterOffHelper(uint32 _faction
) : faction(_faction
) {}
2251 void operator()(Unit
* unit
) const
2253 unit
->setFaction(faction
);
2254 unit
->getHostileRefManager().setOnlineOfflineState(true);
2259 void Player::SetGameMaster(bool on
)
2263 m_ExtraFlags
|= PLAYER_EXTRA_GM_ON
;
2265 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
2267 CallForAllControlledUnits(SetGameMasterOnHelper(),true,true,true,false);
2270 ResetContestedPvP();
2272 getHostileRefManager().setOnlineOfflineState(false);
2273 CombatStopWithPets();
2275 SetPhaseMask(PHASEMASK_ANYWHERE
,false); // see and visible in all phases
2280 AuraList
const& phases
= GetAurasByType(SPELL_AURA_PHASE
);
2281 SetPhaseMask(!phases
.empty() ? phases
.front()->GetMiscValue() : PHASEMASK_NORMAL
,false);
2283 m_ExtraFlags
&= ~ PLAYER_EXTRA_GM_ON
;
2284 setFactionForRace(getRace());
2285 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
2287 CallForAllControlledUnits(SetGameMasterOffHelper(getFaction()),true,true,true,false);
2289 // restore FFA PvP Server state
2290 if(sWorld
.IsFFAPvPRealm())
2293 // restore FFA PvP area state, remove not allowed for GM mounts
2294 UpdateArea(m_areaUpdateId
);
2296 getHostileRefManager().setOnlineOfflineState(true);
2299 UpdateVisibilityForPlayer();
2302 void Player::SetGMVisible(bool on
)
2306 m_ExtraFlags
&= ~PLAYER_EXTRA_GM_INVISIBLE
; //remove flag
2308 // Reapply stealth/invisibility if active or show if not any
2309 if(HasAuraType(SPELL_AURA_MOD_STEALTH
))
2310 SetVisibility(VISIBILITY_GROUP_STEALTH
);
2311 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY
))
2312 SetVisibility(VISIBILITY_GROUP_INVISIBILITY
);
2314 SetVisibility(VISIBILITY_ON
);
2318 m_ExtraFlags
|= PLAYER_EXTRA_GM_INVISIBLE
; //add flag
2320 SetAcceptWhispers(false);
2321 SetGameMaster(true);
2323 SetVisibility(VISIBILITY_OFF
);
2327 bool Player::IsGroupVisibleFor(Player
* p
) const
2329 switch(sWorld
.getConfig(CONFIG_UINT32_GROUP_VISIBILITY
))
2331 default: return IsInSameGroupWith(p
);
2332 case 1: return IsInSameRaidWith(p
);
2333 case 2: return GetTeam()==p
->GetTeam();
2337 bool Player::IsInSameGroupWith(Player
const* p
) const
2339 return (p
==this || (GetGroup() != NULL
&&
2340 GetGroup()->SameSubGroup((Player
*)this, (Player
*)p
)));
2343 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2344 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2345 void Player::UninviteFromGroup()
2347 Group
* group
= GetGroupInvite();
2351 group
->RemoveInvite(this);
2353 if(group
->GetMembersCount() <= 1) // group has just 1 member => disband
2355 if(group
->IsCreated())
2357 group
->Disband(true);
2358 sObjectMgr
.RemoveGroup(group
);
2361 group
->RemoveAllInvites();
2367 void Player::RemoveFromGroup(Group
* group
, uint64 guid
)
2371 if (group
->RemoveMember(guid
, 0) <= 1)
2373 // group->Disband(); already disbanded in RemoveMember
2374 sObjectMgr
.RemoveGroup(group
);
2376 // removemember sets the player's group pointer to NULL
2381 void Player::SendLogXPGain(uint32 GivenXP
, Unit
* victim
, uint32 RestXP
)
2383 WorldPacket
data(SMSG_LOG_XPGAIN
, 21);
2384 data
<< uint64(victim
? victim
->GetGUID() : 0); // guid
2385 data
<< uint32(GivenXP
+RestXP
); // given experience
2386 data
<< uint8(victim
? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2389 data
<< uint32(GivenXP
); // experience without rested bonus
2390 data
<< float(1); // 1 - none 0 - 100% group bonus output
2392 data
<< uint8(0); // new 2.4.0
2393 GetSession()->SendPacket(&data
);
2396 void Player::GiveXP(uint32 xp
, Unit
* victim
)
2404 uint32 level
= getLevel();
2406 // XP to money conversion processed in Player::RewardQuest
2407 if(level
>= sWorld
.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL
))
2412 // handle SPELL_AURA_MOD_KILL_XP_PCT auras
2413 Unit::AuraList
const& ModXPPctAuras
= GetAurasByType(SPELL_AURA_MOD_KILL_XP_PCT
);
2414 for(Unit::AuraList::const_iterator i
= ModXPPctAuras
.begin();i
!= ModXPPctAuras
.end(); ++i
)
2415 xp
= uint32(xp
*(1.0f
+ (*i
)->GetModifier()->m_amount
/ 100.0f
));
2419 // handle SPELL_AURA_MOD_QUEST_XP_PCT auras
2420 Unit::AuraList
const& ModXPPctAuras
= GetAurasByType(SPELL_AURA_MOD_QUEST_XP_PCT
);
2421 for(Unit::AuraList::const_iterator i
= ModXPPctAuras
.begin();i
!= ModXPPctAuras
.end(); ++i
)
2422 xp
= uint32(xp
*(1.0f
+ (*i
)->GetModifier()->m_amount
/ 100.0f
));
2425 // XP resting bonus for kill
2426 uint32 rested_bonus_xp
= victim
? GetXPRestBonus(xp
) : 0;
2428 SendLogXPGain(xp
,victim
,rested_bonus_xp
);
2430 uint32 curXP
= GetUInt32Value(PLAYER_XP
);
2431 uint32 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2432 uint32 newXP
= curXP
+ xp
+ rested_bonus_xp
;
2434 while( newXP
>= nextLvlXP
&& level
< sWorld
.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL
) )
2438 if ( level
< sWorld
.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL
) )
2439 GiveLevel(level
+ 1);
2442 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2445 SetUInt32Value(PLAYER_XP
, newXP
);
2448 // Update player to next level
2449 // Current player experience not update (must be update by caller)
2450 void Player::GiveLevel(uint32 level
)
2452 if ( level
== getLevel() )
2455 PlayerLevelInfo info
;
2456 sObjectMgr
.GetPlayerLevelInfo(getRace(),getClass(),level
,&info
);
2458 PlayerClassLevelInfo classInfo
;
2459 sObjectMgr
.GetPlayerClassLevelInfo(getClass(),level
,&classInfo
);
2461 // send levelup info to client
2462 WorldPacket
data(SMSG_LEVELUP_INFO
, (4+4+MAX_POWERS
*4+MAX_STATS
*4));
2463 data
<< uint32(level
);
2464 data
<< uint32(int32(classInfo
.basehealth
) - int32(GetCreateHealth()));
2465 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2466 data
<< uint32(int32(classInfo
.basemana
) - int32(GetCreateMana()));
2474 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
) // Stats loop (0-4)
2475 data
<< uint32(int32(info
.stats
[i
]) - GetCreateStat(Stats(i
)));
2477 GetSession()->SendPacket(&data
);
2479 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, sObjectMgr
.GetXPForLevel(level
));
2481 //update level, max level of skills
2482 m_Played_time
[PLAYED_TIME_LEVEL
] = 0; // Level Played Time reset
2484 _ApplyAllLevelScaleItemMods(false);
2488 UpdateSkillsForLevel ();
2490 // save base values (bonuses already included in stored stats
2491 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2492 SetCreateStat(Stats(i
), info
.stats
[i
]);
2494 SetCreateHealth(classInfo
.basehealth
);
2495 SetCreateMana(classInfo
.basemana
);
2497 InitTalentForLevel();
2498 InitTaxiNodesForLevel();
2499 InitGlyphsForLevel();
2503 // set current level health and mana/energy to maximum after applying all mods.
2504 SetHealth(GetMaxHealth());
2505 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2506 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2507 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2508 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2509 SetPower(POWER_FOCUS
, 0);
2510 SetPower(POWER_HAPPINESS
, 0);
2512 _ApplyAllLevelScaleItemMods(true);
2514 // update level to hunter/summon pet
2515 if (Pet
* pet
= GetPet())
2516 pet
->SynchronizeLevelWithOwner();
2518 if (MailLevelReward
const* mailReward
= sObjectMgr
.GetMailLevelReward(level
,getRaceMask()))
2519 MailDraft(mailReward
->mailTemplateId
).SendMailTo(this,MailSender(MAIL_CREATURE
,mailReward
->senderEntry
));
2521 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL
);
2524 void Player::InitTalentForLevel()
2526 uint32 level
= getLevel();
2527 // talents base at level diff ( talents = level - 9 but some can be used already)
2530 // Remove all talent points
2531 if(m_usedTalentCount
> 0) // Free any used talents
2534 SetFreeTalentPoints(0);
2539 uint32 talentPointsForLevel
= CalculateTalentsPoints();
2541 // if used more that have then reset
2542 if(m_usedTalentCount
> talentPointsForLevel
)
2544 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR
)
2547 SetFreeTalentPoints(0);
2549 // else update amount of free points
2551 SetFreeTalentPoints(talentPointsForLevel
-m_usedTalentCount
);
2554 if(!GetSession()->PlayerLoading())
2555 SendTalentsInfoData(false); // update at client
2558 void Player::InitStatsForLevel(bool reapplyMods
)
2560 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2561 _RemoveAllStatBonuses();
2563 PlayerClassLevelInfo classInfo
;
2564 sObjectMgr
.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo
);
2566 PlayerLevelInfo info
;
2567 sObjectMgr
.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info
);
2569 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL
, sWorld
.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL
) );
2570 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, sObjectMgr
.GetXPForLevel(getLevel()));
2572 // reset before any aura state sources (health set/aura apply)
2573 SetUInt32Value(UNIT_FIELD_AURASTATE
, 0);
2575 UpdateSkillsForLevel ();
2577 // set default cast time multiplier
2578 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
);
2580 // reset size before reapply auras
2581 SetFloatValue(OBJECT_FIELD_SCALE_X
,1.0f
);
2583 // save base values (bonuses already included in stored stats
2584 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2585 SetCreateStat(Stats(i
), info
.stats
[i
]);
2587 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2588 SetStat(Stats(i
), info
.stats
[i
]);
2590 SetCreateHealth(classInfo
.basehealth
);
2593 SetCreateMana(classInfo
.basemana
);
2595 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2599 //reset rating fields values
2600 for(uint16 index
= PLAYER_FIELD_COMBAT_RATING_1
; index
< PLAYER_FIELD_COMBAT_RATING_1
+ MAX_COMBAT_RATING
; ++index
)
2601 SetUInt32Value(index
, 0);
2603 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS
,0);
2604 for (int i
= 0; i
< 7; ++i
)
2606 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG
+i
, 0);
2607 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS
+i
, 0);
2608 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT
+i
, 1.00f
);
2611 //reset attack power, damage and attack speed fields
2612 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
, 2000.0f
);
2613 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
+ 1, 2000.0f
); // offhand attack time
2614 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME
, 2000.0f
);
2616 SetFloatValue(UNIT_FIELD_MINDAMAGE
, 0.0f
);
2617 SetFloatValue(UNIT_FIELD_MAXDAMAGE
, 0.0f
);
2618 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
, 0.0f
);
2619 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
, 0.0f
);
2620 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
, 0.0f
);
2621 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
, 0.0f
);
2623 SetInt32Value(UNIT_FIELD_ATTACK_POWER
, 0 );
2624 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS
, 0 );
2625 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER
,0.0f
);
2626 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER
, 0 );
2627 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS
,0 );
2628 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER
,0.0f
);
2630 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2631 SetFloatValue(PLAYER_CRIT_PERCENTAGE
,0.0f
);
2632 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE
,0.0f
);
2633 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE
,0.0f
);
2635 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2636 for (uint8 i
= 0; i
< 7; ++i
)
2637 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1
+i
, 0.0f
);
2639 SetFloatValue(PLAYER_PARRY_PERCENTAGE
, 0.0f
);
2640 SetFloatValue(PLAYER_BLOCK_PERCENTAGE
, 0.0f
);
2641 SetUInt32Value(PLAYER_SHIELD_BLOCK
, 0);
2644 SetFloatValue(PLAYER_DODGE_PERCENTAGE
, 0.0f
);
2646 // set armor (resistance 0) to original value (create_agility*2)
2647 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2648 SetResistanceBuffMods(SpellSchools(0), true, 0.0f
);
2649 SetResistanceBuffMods(SpellSchools(0), false, 0.0f
);
2650 // set other resistance to original value (0)
2651 for (int i
= 1; i
< MAX_SPELL_SCHOOL
; ++i
)
2653 SetResistance(SpellSchools(i
), 0);
2654 SetResistanceBuffMods(SpellSchools(i
), true, 0.0f
);
2655 SetResistanceBuffMods(SpellSchools(i
), false, 0.0f
);
2658 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE
,0);
2659 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE
,0);
2660 for(int i
= 0; i
< MAX_SPELL_SCHOOL
; ++i
)
2662 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER
+i
,0);
2663 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER
+i
,0.0f
);
2665 // Reset no reagent cost field
2666 for(int i
= 0; i
< 3; ++i
)
2667 SetUInt32Value(PLAYER_NO_REAGENT_COST_1
+ i
, 0);
2668 // Init data for form but skip reapply item mods for form
2669 InitDataForForm(reapplyMods
);
2672 for (int i
= POWER_MANA
; i
< MAX_POWERS
; ++i
)
2673 SetMaxPower(Powers(i
), uint32(GetCreatePowers(Powers(i
))));
2675 SetMaxHealth(classInfo
.basehealth
); // stamina bonus will applied later
2677 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2678 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID
, 0);
2680 // cleanup unit flags (will be re-applied if need at aura load).
2681 RemoveFlag( UNIT_FIELD_FLAGS
,
2682 UNIT_FLAG_NON_ATTACKABLE
| UNIT_FLAG_DISABLE_MOVE
| UNIT_FLAG_NOT_ATTACKABLE_1
|
2683 UNIT_FLAG_PET_IN_COMBAT
| UNIT_FLAG_SILENCED
| UNIT_FLAG_PACIFIED
|
2684 UNIT_FLAG_STUNNED
| UNIT_FLAG_IN_COMBAT
| UNIT_FLAG_DISARMED
|
2685 UNIT_FLAG_CONFUSED
| UNIT_FLAG_FLEEING
| UNIT_FLAG_NOT_SELECTABLE
|
2686 UNIT_FLAG_SKINNABLE
| UNIT_FLAG_MOUNT
| UNIT_FLAG_TAXI_FLIGHT
);
2687 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
); // must be set
2689 SetFlag(UNIT_FIELD_FLAGS_2
,UNIT_FLAG2_REGENERATE_POWER
);// must be set
2691 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2692 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
| PLAYER_FLAGS_DND
| PLAYER_FLAGS_GM
| PLAYER_FLAGS_GHOST
);
2694 RemoveStandFlags(UNIT_STAND_FLAGS_ALL
); // one form stealth modified bytes
2695 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
| UNIT_BYTE2_FLAG_SANCTUARY
);
2697 // restore if need some important flags
2698 SetUInt32Value(PLAYER_FIELD_BYTES2
, 0 ); // flags empty by default
2700 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2701 _ApplyAllStatBonuses();
2703 // set current level health and mana/energy to maximum after applying all mods.
2704 SetHealth(GetMaxHealth());
2705 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2706 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2707 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2708 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2709 SetPower(POWER_FOCUS
, 0);
2710 SetPower(POWER_HAPPINESS
, 0);
2711 SetPower(POWER_RUNIC_POWER
, 0);
2713 // update level to hunter/summon pet
2714 if (Pet
* pet
= GetPet())
2715 pet
->SynchronizeLevelWithOwner();
2718 void Player::SendInitialSpells()
2720 time_t curTime
= time(NULL
);
2721 time_t infTime
= curTime
+ infinityCooldownDelayCheck
;
2723 uint16 spellCount
= 0;
2725 WorldPacket
data(SMSG_INITIAL_SPELLS
, (1+2+4*m_spells
.size()+2+m_spellCooldowns
.size()*(2+2+2+4+4)));
2728 size_t countPos
= data
.wpos();
2729 data
<< uint16(spellCount
); // spell count placeholder
2731 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2733 if(itr
->second
.state
== PLAYERSPELL_REMOVED
)
2736 if(!itr
->second
.active
|| itr
->second
.disabled
)
2739 data
<< uint32(itr
->first
);
2740 data
<< uint16(0); // it's not slot id
2745 data
.put
<uint16
>(countPos
,spellCount
); // write real count value
2747 uint16 spellCooldowns
= m_spellCooldowns
.size();
2748 data
<< uint16(spellCooldowns
);
2749 for(SpellCooldowns::const_iterator itr
=m_spellCooldowns
.begin(); itr
!=m_spellCooldowns
.end(); ++itr
)
2751 SpellEntry
const *sEntry
= sSpellStore
.LookupEntry(itr
->first
);
2755 data
<< uint32(itr
->first
);
2757 data
<< uint16(itr
->second
.itemid
); // cast item id
2758 data
<< uint16(sEntry
->Category
); // spell category
2760 // send infinity cooldown in special format
2761 if(itr
->second
.end
>= infTime
)
2763 data
<< uint32(1); // cooldown
2764 data
<< uint32(0x80000000); // category cooldown
2768 time_t cooldown
= itr
->second
.end
> curTime
? (itr
->second
.end
-curTime
)*IN_MILISECONDS
: 0;
2770 if(sEntry
->Category
) // may be wrong, but anyway better than nothing...
2772 data
<< uint32(0); // cooldown
2773 data
<< uint32(cooldown
); // category cooldown
2777 data
<< uint32(cooldown
); // cooldown
2778 data
<< uint32(0); // category cooldown
2782 GetSession()->SendPacket(&data
);
2784 sLog
.outDetail( "CHARACTER: Sent Initial Spells" );
2787 void Player::RemoveMail(uint32 id
)
2789 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
2791 if ((*itr
)->messageID
== id
)
2793 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2800 void Player::SendMailResult(uint32 mailId
, MailResponseType mailAction
, MailResponseResult mailError
, uint32 equipError
, uint32 item_guid
, uint32 item_count
)
2802 WorldPacket
data(SMSG_SEND_MAIL_RESULT
, (4+4+4+(mailError
== MAIL_ERR_EQUIP_ERROR
?4:(mailAction
== MAIL_ITEM_TAKEN
?4+4:0))));
2803 data
<< (uint32
) mailId
;
2804 data
<< (uint32
) mailAction
;
2805 data
<< (uint32
) mailError
;
2806 if ( mailError
== MAIL_ERR_EQUIP_ERROR
)
2807 data
<< (uint32
) equipError
;
2808 else if( mailAction
== MAIL_ITEM_TAKEN
)
2810 data
<< (uint32
) item_guid
; // item guid low?
2811 data
<< (uint32
) item_count
; // item count?
2813 GetSession()->SendPacket(&data
);
2816 void Player::SendNewMail()
2818 // deliver undelivered mail
2819 WorldPacket
data(SMSG_RECEIVED_MAIL
, 4);
2821 GetSession()->SendPacket(&data
);
2824 void Player::UpdateNextMailTimeAndUnreads()
2826 // calculate next delivery time (min. from non-delivered mails
2827 // and recalculate unReadMail
2828 time_t cTime
= time(NULL
);
2829 m_nextMailDelivereTime
= 0;
2831 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
2833 if((*itr
)->deliver_time
> cTime
)
2835 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> (*itr
)->deliver_time
)
2836 m_nextMailDelivereTime
= (*itr
)->deliver_time
;
2838 else if(((*itr
)->checked
& MAIL_CHECK_MASK_READ
) == 0)
2843 void Player::AddNewMailDeliverTime(time_t deliver_time
)
2845 if(deliver_time
<= time(NULL
)) // ready now
2850 else // not ready and no have ready mails
2852 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> deliver_time
)
2853 m_nextMailDelivereTime
= deliver_time
;
2857 bool Player::addSpell(uint32 spell_id
, bool active
, bool learning
, bool dependent
, bool disabled
)
2859 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
2862 // do character spell book cleanup (all characters)
2863 if(!IsInWorld() && !learning
) // spell load case
2865 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id
);
2866 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2869 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id
);
2874 if(!SpellMgr::IsSpellValid(spellInfo
,this,false))
2876 // do character spell book cleanup (all characters)
2877 if(!IsInWorld() && !learning
) // spell load case
2879 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id
);
2880 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2883 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id
);
2888 PlayerSpellState state
= learning
? PLAYERSPELL_NEW
: PLAYERSPELL_UNCHANGED
;
2890 bool dependent_set
= false;
2891 bool disabled_case
= false;
2892 bool superceded_old
= false;
2894 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2895 if (itr
!= m_spells
.end())
2897 uint32 next_active_spell_id
= 0;
2898 // fix activate state for non-stackable low rank (and find next spell for !active case)
2899 if(!SpellMgr::canStackSpellRanks(spellInfo
) && sSpellMgr
.GetSpellRank(spellInfo
->Id
) != 0)
2901 SpellChainMapNext
const& nextMap
= sSpellMgr
.GetSpellChainNext();
2902 for(SpellChainMapNext::const_iterator next_itr
= nextMap
.lower_bound(spell_id
); next_itr
!= nextMap
.upper_bound(spell_id
); ++next_itr
)
2904 if(HasSpell(next_itr
->second
))
2906 // high rank already known so this must !active
2908 next_active_spell_id
= next_itr
->second
;
2914 // not do anything if already known in expected state
2915 if(itr
->second
.state
!= PLAYERSPELL_REMOVED
&& itr
->second
.active
== active
&&
2916 itr
->second
.dependent
== dependent
&& itr
->second
.disabled
== disabled
)
2918 if(!IsInWorld() && !learning
) // explicitly load from DB and then exist in it already and set correctly
2919 itr
->second
.state
= PLAYERSPELL_UNCHANGED
;
2924 // dependent spell known as not dependent, overwrite state
2925 if (itr
->second
.state
!= PLAYERSPELL_REMOVED
&& !itr
->second
.dependent
&& dependent
)
2927 itr
->second
.dependent
= dependent
;
2928 if (itr
->second
.state
!= PLAYERSPELL_NEW
)
2929 itr
->second
.state
= PLAYERSPELL_CHANGED
;
2930 dependent_set
= true;
2933 // update active state for known spell
2934 if(itr
->second
.active
!= active
&& itr
->second
.state
!= PLAYERSPELL_REMOVED
&& !itr
->second
.disabled
)
2936 itr
->second
.active
= active
;
2938 if(!IsInWorld() && !learning
&& !dependent_set
) // explicitly load from DB and then exist in it already and set correctly
2939 itr
->second
.state
= PLAYERSPELL_UNCHANGED
;
2940 else if(itr
->second
.state
!= PLAYERSPELL_NEW
)
2941 itr
->second
.state
= PLAYERSPELL_CHANGED
;
2945 if (IsPassiveSpell(spell_id
) && IsNeedCastPassiveSpellAtLearn(spellInfo
))
2946 CastSpell (this,spell_id
,true);
2948 else if(IsInWorld())
2950 if(next_active_spell_id
)
2952 // update spell ranks in spellbook and action bar
2953 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, 4 + 4);
2954 data
<< uint32(spell_id
);
2955 data
<< uint32(next_active_spell_id
);
2956 GetSession()->SendPacket( &data
);
2960 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
2961 data
<< uint32(spell_id
);
2962 GetSession()->SendPacket(&data
);
2966 return active
; // learn (show in spell book if active now)
2969 if(itr
->second
.disabled
!= disabled
&& itr
->second
.state
!= PLAYERSPELL_REMOVED
)
2971 if(itr
->second
.state
!= PLAYERSPELL_NEW
)
2972 itr
->second
.state
= PLAYERSPELL_CHANGED
;
2973 itr
->second
.disabled
= disabled
;
2978 disabled_case
= true;
2980 else switch(itr
->second
.state
)
2982 case PLAYERSPELL_UNCHANGED
: // known saved spell
2984 case PLAYERSPELL_REMOVED
: // re-learning removed not saved spell
2986 m_spells
.erase(itr
);
2987 state
= PLAYERSPELL_CHANGED
;
2988 break; // need re-add
2990 default: // known not saved yet spell (new or modified)
2992 // can be in case spell loading but learned at some previous spell loading
2993 if(!IsInWorld() && !learning
&& !dependent_set
)
2994 itr
->second
.state
= PLAYERSPELL_UNCHANGED
;
3001 if(!disabled_case
) // skip new spell adding if spell already known (disabled spells case)
3003 // talent: unlearn all other talent ranks (high and low)
3004 if(TalentSpellPos
const* talentPos
= GetTalentSpellPos(spell_id
))
3006 if(TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry( talentPos
->talent_id
))
3008 for(int i
=0; i
< MAX_TALENT_RANK
; ++i
)
3010 // skip learning spell and no rank spell case
3011 uint32 rankSpellId
= talentInfo
->RankID
[i
];
3012 if(!rankSpellId
|| rankSpellId
==spell_id
)
3015 removeSpell(rankSpellId
,false,false);
3019 // non talent spell: learn low ranks (recursive call)
3020 else if(uint32 prev_spell
= sSpellMgr
.GetPrevSpellInChain(spell_id
))
3022 if(!IsInWorld() || disabled
) // at spells loading, no output, but allow save
3023 addSpell(prev_spell
,active
,true,true,disabled
);
3024 else // at normal learning
3025 learnSpell(prev_spell
,true);
3028 PlayerSpell newspell
;
3029 newspell
.state
= state
;
3030 newspell
.active
= active
;
3031 newspell
.dependent
= dependent
;
3032 newspell
.disabled
= disabled
;
3034 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
3035 if(newspell
.active
&& !newspell
.disabled
&& !SpellMgr::canStackSpellRanks(spellInfo
) && sSpellMgr
.GetSpellRank(spellInfo
->Id
) != 0)
3037 for( PlayerSpellMap::iterator itr2
= m_spells
.begin(); itr2
!= m_spells
.end(); ++itr2
)
3039 if(itr2
->second
.state
== PLAYERSPELL_REMOVED
) continue;
3040 SpellEntry
const *i_spellInfo
= sSpellStore
.LookupEntry(itr2
->first
);
3041 if(!i_spellInfo
) continue;
3043 if( sSpellMgr
.IsRankSpellDueToSpell(spellInfo
,itr2
->first
) )
3045 if(itr2
->second
.active
)
3047 if(sSpellMgr
.IsHighRankOfSpell(spell_id
,itr2
->first
))
3049 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
3051 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, 4 + 4);
3052 data
<< uint32(itr2
->first
);
3053 data
<< uint32(spell_id
);
3054 GetSession()->SendPacket( &data
);
3057 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
3058 itr2
->second
.active
= false;
3059 if(itr2
->second
.state
!= PLAYERSPELL_NEW
)
3060 itr2
->second
.state
= PLAYERSPELL_CHANGED
;
3061 superceded_old
= true; // new spell replace old in action bars and spell book.
3063 else if(sSpellMgr
.IsHighRankOfSpell(itr2
->first
,spell_id
))
3065 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
3067 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, 4 + 4);
3068 data
<< uint32(spell_id
);
3069 data
<< uint32(itr2
->first
);
3070 GetSession()->SendPacket( &data
);
3073 // mark new spell as disable (not learned yet for client and will not learned)
3074 newspell
.active
= false;
3075 if(newspell
.state
!= PLAYERSPELL_NEW
)
3076 newspell
.state
= PLAYERSPELL_CHANGED
;
3083 m_spells
[spell_id
] = newspell
;
3085 // return false if spell disabled
3086 if (newspell
.disabled
)
3090 uint32 talentCost
= GetTalentSpellCost(spell_id
);
3092 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
3093 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
3094 if (talentCost
> 0 && IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_LEARN_SPELL
))
3096 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
3097 CastSpell(this, spell_id
, true);
3099 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
3100 else if (IsPassiveSpell(spell_id
))
3102 if (IsNeedCastPassiveSpellAtLearn(spellInfo
))
3103 CastSpell(this, spell_id
, true);
3105 else if (IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_SKILL_STEP
))
3107 CastSpell(this, spell_id
, true);
3111 // update used talent points count
3112 m_usedTalentCount
+= talentCost
;
3114 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
3115 if (uint32 freeProfs
= GetFreePrimaryProfessionPoints())
3117 if(sSpellMgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
3118 SetFreePrimaryProfessions(freeProfs
-1);
3121 // add dependent skills
3122 uint16 maxskill
= GetMaxSkillValueForLevel();
3124 SpellLearnSkillNode
const* spellLearnSkill
= sSpellMgr
.GetSpellLearnSkill(spell_id
);
3126 SkillLineAbilityMapBounds skill_bounds
= sSpellMgr
.GetSkillLineAbilityMapBounds(spell_id
);
3128 if (spellLearnSkill
)
3130 uint32 skill_value
= GetPureSkillValue(spellLearnSkill
->skill
);
3131 uint32 skill_max_value
= GetPureMaxSkillValue(spellLearnSkill
->skill
);
3133 if (skill_value
< spellLearnSkill
->value
)
3134 skill_value
= spellLearnSkill
->value
;
3136 uint32 new_skill_max_value
= spellLearnSkill
->maxvalue
== 0 ? maxskill
: spellLearnSkill
->maxvalue
;
3138 if (skill_max_value
< new_skill_max_value
)
3139 skill_max_value
= new_skill_max_value
;
3141 SetSkill(spellLearnSkill
->skill
,skill_value
,skill_max_value
);
3145 // not ranked skills
3146 for(SkillLineAbilityMap::const_iterator _spell_idx
= skill_bounds
.first
; _spell_idx
!= skill_bounds
.second
; ++_spell_idx
)
3148 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
3152 if (HasSkill(pSkill
->id
))
3155 if (_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
3156 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3157 ((pSkill
->id
==SKILL_LOCKPICKING
|| pSkill
->id
==SKILL_RUNEFORGING
) && _spell_idx
->second
->max_value
==0))
3159 switch(GetSkillRangeType(pSkill
,_spell_idx
->second
->racemask
!=0))
3161 case SKILL_RANGE_LANGUAGE
:
3162 SetSkill(pSkill
->id
, 300, 300 );
3164 case SKILL_RANGE_LEVEL
:
3165 SetSkill(pSkill
->id
, 1, GetMaxSkillValueForLevel() );
3167 case SKILL_RANGE_MONO
:
3168 SetSkill(pSkill
->id
, 1, 1 );
3177 // learn dependent spells
3178 SpellLearnSpellMapBounds spell_bounds
= sSpellMgr
.GetSpellLearnSpellMapBounds(spell_id
);
3180 for(SpellLearnSpellMap::const_iterator itr2
= spell_bounds
.first
; itr2
!= spell_bounds
.second
; ++itr2
)
3182 if (!itr2
->second
.autoLearned
)
3184 if (!IsInWorld() || !itr2
->second
.active
) // at spells loading, no output, but allow save
3185 addSpell(itr2
->second
.spell
,itr2
->second
.active
,true,true,false);
3186 else // at normal learning
3187 learnSpell(itr2
->second
.spell
,true);
3191 if (!GetSession()->PlayerLoading())
3193 // not ranked skills
3194 for(SkillLineAbilityMap::const_iterator _spell_idx
= skill_bounds
.first
; _spell_idx
!= skill_bounds
.second
; ++_spell_idx
)
3196 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE
,_spell_idx
->second
->skillId
);
3197 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS
,_spell_idx
->second
->skillId
);
3200 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL
,spell_id
);
3203 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
3204 return active
&& !disabled
&& !superceded_old
;
3207 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry
const* spellInfo
) const
3209 // note: form passives activated with shapeshift spells be implemented by HandleShapeshiftBoosts instead of spell_learn_spell
3210 // talent dependent passives activated at form apply have proper stance data
3211 bool need_cast
= (!spellInfo
->Stances
|| (m_form
!= 0 && (spellInfo
->Stances
& (1<<(m_form
-1)))));
3213 //Check CasterAuraStates
3214 return need_cast
&& (!spellInfo
->CasterAuraState
|| HasAuraState(AuraState(spellInfo
->CasterAuraState
)));
3217 void Player::learnSpell(uint32 spell_id
, bool dependent
)
3219 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
3221 bool disabled
= (itr
!= m_spells
.end()) ? itr
->second
.disabled
: false;
3222 bool active
= disabled
? itr
->second
.active
: true;
3224 bool learning
= addSpell(spell_id
,active
,true,dependent
,false);
3226 // learn all disabled higher ranks (recursive)
3229 SpellChainMapNext
const& nextMap
= sSpellMgr
.GetSpellChainNext();
3230 for(SpellChainMapNext::const_iterator i
= nextMap
.lower_bound(spell_id
); i
!= nextMap
.upper_bound(spell_id
); ++i
)
3232 PlayerSpellMap::iterator iter
= m_spells
.find(i
->second
);
3233 if (iter
!= m_spells
.end() && iter
->second
.disabled
)
3234 learnSpell(i
->second
,false);
3238 // prevent duplicated entires in spell book, also not send if not in world (loading)
3239 if(!learning
|| !IsInWorld ())
3242 WorldPacket
data(SMSG_LEARNED_SPELL
, 4);
3243 data
<< uint32(spell_id
);
3244 GetSession()->SendPacket(&data
);
3247 void Player::removeSpell(uint32 spell_id
, bool disabled
, bool learn_low_rank
, bool sendUpdate
)
3249 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
3250 if (itr
== m_spells
.end())
3253 if (itr
->second
.state
== PLAYERSPELL_REMOVED
|| (disabled
&& itr
->second
.disabled
))
3256 // unlearn non talent higher ranks (recursive)
3257 SpellChainMapNext
const& nextMap
= sSpellMgr
.GetSpellChainNext();
3258 for(SpellChainMapNext::const_iterator itr2
= nextMap
.lower_bound(spell_id
); itr2
!= nextMap
.upper_bound(spell_id
); ++itr2
)
3259 if(HasSpell(itr2
->second
) && !GetTalentSpellPos(itr2
->second
))
3260 removeSpell(itr2
->second
,disabled
,false);
3262 // re-search, it can be corrupted in prev loop
3263 itr
= m_spells
.find(spell_id
);
3264 if (itr
== m_spells
.end())
3265 return; // already unleared
3267 bool cur_active
= itr
->second
.active
;
3268 bool cur_dependent
= itr
->second
.dependent
;
3272 itr
->second
.disabled
= disabled
;
3273 if(itr
->second
.state
!= PLAYERSPELL_NEW
)
3274 itr
->second
.state
= PLAYERSPELL_CHANGED
;
3278 if(itr
->second
.state
== PLAYERSPELL_NEW
)
3279 m_spells
.erase(itr
);
3281 itr
->second
.state
= PLAYERSPELL_REMOVED
;
3284 RemoveAurasDueToSpell(spell_id
);
3287 for(int i
= 0; i
< MAX_EFFECT_INDEX
; ++i
)
3288 if(PetAura
const* petSpell
= sSpellMgr
.GetPetAura(spell_id
, SpellEffectIndex(i
)))
3289 RemovePetAura(petSpell
);
3291 // free talent points
3292 uint32 talentCosts
= GetTalentSpellCost(spell_id
);
3295 if(talentCosts
< m_usedTalentCount
)
3296 m_usedTalentCount
-= talentCosts
;
3298 m_usedTalentCount
= 0;
3301 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3302 if(sSpellMgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
3304 uint32 freeProfs
= GetFreePrimaryProfessionPoints()+1;
3305 if(freeProfs
<= sWorld
.getConfig(CONFIG_UINT32_MAX_PRIMARY_TRADE_SKILL
))
3306 SetFreePrimaryProfessions(freeProfs
);
3309 // remove dependent skill
3310 SpellLearnSkillNode
const* spellLearnSkill
= sSpellMgr
.GetSpellLearnSkill(spell_id
);
3313 uint32 prev_spell
= sSpellMgr
.GetPrevSpellInChain(spell_id
);
3314 if(!prev_spell
) // first rank, remove skill
3315 SetSkill(spellLearnSkill
->skill
,0,0);
3318 // search prev. skill setting by spell ranks chain
3319 SpellLearnSkillNode
const* prevSkill
= sSpellMgr
.GetSpellLearnSkill(prev_spell
);
3320 while(!prevSkill
&& prev_spell
)
3322 prev_spell
= sSpellMgr
.GetPrevSpellInChain(prev_spell
);
3323 prevSkill
= sSpellMgr
.GetSpellLearnSkill(sSpellMgr
.GetFirstSpellInChain(prev_spell
));
3326 if (!prevSkill
) // not found prev skill setting, remove skill
3327 SetSkill(spellLearnSkill
->skill
,0,0);
3328 else // set to prev. skill setting values
3330 uint32 skill_value
= GetPureSkillValue(prevSkill
->skill
);
3331 uint32 skill_max_value
= GetPureMaxSkillValue(prevSkill
->skill
);
3333 if (skill_value
> prevSkill
->value
)
3334 skill_value
= prevSkill
->value
;
3336 uint32 new_skill_max_value
= prevSkill
->maxvalue
== 0 ? GetMaxSkillValueForLevel() : prevSkill
->maxvalue
;
3338 if (skill_max_value
> new_skill_max_value
)
3339 skill_max_value
= new_skill_max_value
;
3341 SetSkill(prevSkill
->skill
,skill_value
,skill_max_value
);
3348 // not ranked skills
3349 SkillLineAbilityMapBounds bounds
= sSpellMgr
.GetSkillLineAbilityMapBounds(spell_id
);
3351 for(SkillLineAbilityMap::const_iterator _spell_idx
= bounds
.first
; _spell_idx
!= bounds
.second
; ++_spell_idx
)
3353 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
3357 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
&&
3358 pSkill
->categoryId
!= SKILL_CATEGORY_CLASS
||// not unlearn class skills (spellbook/talent pages)
3359 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3360 ((pSkill
->id
==SKILL_LOCKPICKING
|| pSkill
->id
==SKILL_RUNEFORGING
) && _spell_idx
->second
->max_value
==0))
3362 // not reset skills for professions and racial abilities
3363 if ((pSkill
->categoryId
==SKILL_CATEGORY_SECONDARY
|| pSkill
->categoryId
==SKILL_CATEGORY_PROFESSION
) &&
3364 (IsProfessionSkill(pSkill
->id
) || _spell_idx
->second
->racemask
!=0))
3367 SetSkill(pSkill
->id
, 0, 0 );
3372 // remove dependent spells
3373 SpellLearnSpellMapBounds spell_bounds
= sSpellMgr
.GetSpellLearnSpellMapBounds(spell_id
);
3375 for(SpellLearnSpellMap::const_iterator itr2
= spell_bounds
.first
; itr2
!= spell_bounds
.second
; ++itr2
)
3376 removeSpell(itr2
->second
.spell
, disabled
);
3378 // activate lesser rank in spellbook/action bar, and cast it if need
3379 bool prev_activate
= false;
3381 if (uint32 prev_id
= sSpellMgr
.GetPrevSpellInChain (spell_id
))
3383 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
3385 // if talent then lesser rank also talent and need learn
3389 learnSpell (prev_id
,false);
3391 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3392 else if (cur_active
&& !SpellMgr::canStackSpellRanks(spellInfo
) && sSpellMgr
.GetSpellRank(spellInfo
->Id
) != 0)
3394 // need manually update dependence state (learn spell ignore like attempts)
3395 PlayerSpellMap::iterator prev_itr
= m_spells
.find(prev_id
);
3396 if (prev_itr
!= m_spells
.end())
3398 if (prev_itr
->second
.dependent
!= cur_dependent
)
3400 prev_itr
->second
.dependent
= cur_dependent
;
3401 if (prev_itr
->second
.state
!= PLAYERSPELL_NEW
)
3402 prev_itr
->second
.state
= PLAYERSPELL_CHANGED
;
3405 // now re-learn if need re-activate
3406 if (cur_active
&& !prev_itr
->second
.active
&& learn_low_rank
)
3408 if (addSpell(prev_id
,true,false,prev_itr
->second
.dependent
,prev_itr
->second
.disabled
))
3410 // downgrade spell ranks in spellbook and action bar
3411 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, 4 + 4);
3412 data
<< uint32(spell_id
);
3413 data
<< uint32(prev_id
);
3414 GetSession()->SendPacket( &data
);
3415 prev_activate
= true;
3422 // remove from spell book if not replaced by lesser rank
3423 if (!prev_activate
&& sendUpdate
)
3425 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
3426 data
<< uint32(spell_id
);
3427 GetSession()->SendPacket(&data
);
3431 void Player::RemoveSpellCooldown( uint32 spell_id
, bool update
/* = false */ )
3433 m_spellCooldowns
.erase(spell_id
);
3436 SendClearCooldown(spell_id
, this);
3439 void Player::RemoveSpellCategoryCooldown(uint32 cat
, bool update
/* = false */)
3441 SpellCategoryStore::const_iterator ct
= sSpellCategoryStore
.find(cat
);
3442 if (ct
== sSpellCategoryStore
.end())
3445 const SpellCategorySet
& ct_set
= ct
->second
;
3446 for (SpellCooldowns::const_iterator i
= m_spellCooldowns
.begin(); i
!= m_spellCooldowns
.end();)
3448 if (ct_set
.find(i
->first
) != ct_set
.end())
3449 RemoveSpellCooldown((i
++)->first
, update
);
3455 void Player::RemoveArenaSpellCooldowns()
3457 // remove cooldowns on spells that has < 15 min CD
3458 SpellCooldowns::iterator itr
, next
;
3459 // iterate spell cooldowns
3460 for(itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); itr
= next
)
3464 SpellEntry
const * entry
= sSpellStore
.LookupEntry(itr
->first
);
3465 // check if spellentry is present and if the cooldown is less than 15 mins
3467 entry
->RecoveryTime
<= 15 * MINUTE
* IN_MILISECONDS
&&
3468 entry
->CategoryRecoveryTime
<= 15 * MINUTE
* IN_MILISECONDS
)
3471 RemoveSpellCooldown(itr
->first
, true);
3476 void Player::RemoveAllSpellCooldown()
3478 if(!m_spellCooldowns
.empty())
3480 for(SpellCooldowns::const_iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); ++itr
)
3481 SendClearCooldown(itr
->first
, this);
3483 m_spellCooldowns
.clear();
3487 void Player::_LoadSpellCooldowns(QueryResult
*result
)
3489 // some cooldowns can be already set at aura loading...
3491 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3495 time_t curTime
= time(NULL
);
3499 Field
*fields
= result
->Fetch();
3501 uint32 spell_id
= fields
[0].GetUInt32();
3502 uint32 item_id
= fields
[1].GetUInt32();
3503 time_t db_time
= (time_t)fields
[2].GetUInt64();
3505 if(!sSpellStore
.LookupEntry(spell_id
))
3507 sLog
.outError("Player %u has unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id
);
3511 // skip outdated cooldown
3512 if(db_time
<= curTime
)
3515 AddSpellCooldown(spell_id
, item_id
, db_time
);
3517 sLog
.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id
, item_id
, uint32(db_time
-curTime
));
3519 while( result
->NextRow() );
3525 void Player::_SaveSpellCooldowns()
3527 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3529 time_t curTime
= time(NULL
);
3530 time_t infTime
= curTime
+ infinityCooldownDelayCheck
;
3532 /* copied following sql-code partly from achievementmgr */
3533 bool first_round
= true;
3534 std::ostringstream ss
;
3536 // remove outdated and save active
3537 for(SpellCooldowns::iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end();)
3539 if(itr
->second
.end
<= curTime
)
3540 m_spellCooldowns
.erase(itr
++);
3541 else if(itr
->second
.end
<= infTime
) // not save locked cooldowns, it will be reset or set at reload
3545 ss
<< "INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ";
3546 first_round
= false;
3548 // next new/changed record prefix
3551 ss
<< "(" << GetGUIDLow() << "," << itr
->first
<< "," << itr
->second
.itemid
<< "," << uint64(itr
->second
.end
) << ")";
3558 // if something changed execute
3560 CharacterDatabase
.Execute( ss
.str().c_str() );
3563 uint32
Player::resetTalentsCost() const
3565 // The first time reset costs 1 gold
3566 if(m_resetTalentsCost
< 1*GOLD
)
3569 else if(m_resetTalentsCost
< 5*GOLD
)
3571 // After that it increases in increments of 5 gold
3572 else if(m_resetTalentsCost
< 10*GOLD
)
3576 time_t months
= (sWorld
.GetGameTime() - m_resetTalentsTime
)/MONTH
;
3579 // This cost will be reduced by a rate of 5 gold per month
3580 int32 new_cost
= int32((m_resetTalentsCost
) - 5*GOLD
*months
);
3581 // to a minimum of 10 gold.
3582 return uint32(new_cost
< 10*GOLD
? 10*GOLD
: new_cost
);
3586 // After that it increases in increments of 5 gold
3587 int32 new_cost
= m_resetTalentsCost
+ 5*GOLD
;
3588 // until it hits a cap of 50 gold.
3589 if(new_cost
> 50*GOLD
)
3596 bool Player::resetTalents(bool no_cost
)
3598 // not need after this call
3599 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS
))
3600 RemoveAtLoginFlag(AT_LOGIN_RESET_TALENTS
,true);
3602 uint32 talentPointsForLevel
= CalculateTalentsPoints();
3604 if (m_usedTalentCount
== 0)
3606 SetFreeTalentPoints(talentPointsForLevel
);
3614 cost
= resetTalentsCost();
3616 if (GetMoney() < cost
)
3618 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, 0, 0, 0);
3623 for (unsigned int i
= 0; i
< sTalentStore
.GetNumRows(); ++i
)
3625 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry(i
);
3627 if (!talentInfo
) continue;
3629 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentInfo
->TalentTab
);
3634 // unlearn only talents for character class
3635 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3636 // to prevent unexpected lost normal learned spell skip another class talents
3637 if( (getClassMask() & talentTabInfo
->ClassMask
) == 0 )
3640 for (int j
= 0; j
< MAX_TALENT_RANK
; ++j
)
3642 for(PlayerSpellMap::iterator itr
= GetSpellMap().begin(); itr
!= GetSpellMap().end();)
3644 if(itr
->second
.state
== PLAYERSPELL_REMOVED
|| itr
->second
.disabled
)
3650 // remove learned spells (all ranks)
3651 uint32 itrFirstId
= sSpellMgr
.GetFirstSpellInChain(itr
->first
);
3653 // unlearn if first rank is talent or learned by talent
3654 if (itrFirstId
== talentInfo
->RankID
[j
])
3656 removeSpell(itr
->first
,!IsPassiveSpell(itr
->first
),false);
3657 itr
= GetSpellMap().begin();
3660 else if (sSpellMgr
.IsSpellLearnToSpell(talentInfo
->RankID
[j
],itrFirstId
))
3662 removeSpell(itr
->first
,!IsPassiveSpell(itr
->first
));
3663 itr
= GetSpellMap().begin();
3672 SetFreeTalentPoints(talentPointsForLevel
);
3676 ModifyMoney(-(int32
)cost
);
3677 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS
, cost
);
3678 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS
, 1);
3680 m_resetTalentsCost
= cost
;
3681 m_resetTalentsTime
= time(NULL
);
3684 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3685 RemovePet(NULL
,PET_SAVE_NOT_IN_SLOT
, true);
3686 /* when prev line will dropped use next line
3687 if(Pet* pet = GetPet())
3689 if(pet->getPetType()==HUNTER_PET && !pet->GetCreatureInfo()->isTameable(CanTameExoticPets()))
3690 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3697 m_canTitanGrip
= false;
3698 if(sWorld
.getConfig(CONFIG_BOOL_OFFHAND_CHECK_AT_TALENTS_RESET
))
3699 AutoUnequipOffhandIfNeed();
3705 Mail
* Player::GetMail(uint32 id
)
3707 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
3709 if ((*itr
)->messageID
== id
)
3717 void Player::_SetCreateBits(UpdateMask
*updateMask
, Player
*target
) const
3721 Object::_SetCreateBits(updateMask
, target
);
3725 for(uint16 index
= 0; index
< m_valuesCount
; index
++)
3727 if(GetUInt32Value(index
) != 0 && updateVisualBits
.GetBit(index
))
3728 updateMask
->SetBit(index
);
3733 void Player::_SetUpdateBits(UpdateMask
*updateMask
, Player
*target
) const
3737 Object::_SetUpdateBits(updateMask
, target
);
3741 Object::_SetUpdateBits(updateMask
, target
);
3742 *updateMask
&= updateVisualBits
;
3746 void Player::InitVisibleBits()
3748 updateVisualBits
.SetCount(PLAYER_END
);
3750 updateVisualBits
.SetBit(OBJECT_FIELD_GUID
);
3751 updateVisualBits
.SetBit(OBJECT_FIELD_TYPE
);
3752 updateVisualBits
.SetBit(OBJECT_FIELD_ENTRY
);
3753 updateVisualBits
.SetBit(OBJECT_FIELD_SCALE_X
);
3754 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 0);
3755 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 1);
3756 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 0);
3757 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 1);
3758 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 0);
3759 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 1);
3760 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 0);
3761 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 1);
3762 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 0);
3763 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 1);
3764 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_0
);
3765 updateVisualBits
.SetBit(UNIT_FIELD_HEALTH
);
3766 updateVisualBits
.SetBit(UNIT_FIELD_POWER1
);
3767 updateVisualBits
.SetBit(UNIT_FIELD_POWER2
);
3768 updateVisualBits
.SetBit(UNIT_FIELD_POWER3
);
3769 updateVisualBits
.SetBit(UNIT_FIELD_POWER4
);
3770 updateVisualBits
.SetBit(UNIT_FIELD_POWER5
);
3771 updateVisualBits
.SetBit(UNIT_FIELD_POWER6
);
3772 updateVisualBits
.SetBit(UNIT_FIELD_POWER7
);
3773 updateVisualBits
.SetBit(UNIT_FIELD_MAXHEALTH
);
3774 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER1
);
3775 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER2
);
3776 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER3
);
3777 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER4
);
3778 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER5
);
3779 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER6
);
3780 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER7
);
3781 updateVisualBits
.SetBit(UNIT_FIELD_LEVEL
);
3782 updateVisualBits
.SetBit(UNIT_FIELD_FACTIONTEMPLATE
);
3783 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 0);
3784 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 1);
3785 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 2);
3786 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS
);
3787 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS_2
);
3788 updateVisualBits
.SetBit(UNIT_FIELD_AURASTATE
);
3789 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 0);
3790 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 1);
3791 updateVisualBits
.SetBit(UNIT_FIELD_BOUNDINGRADIUS
);
3792 updateVisualBits
.SetBit(UNIT_FIELD_COMBATREACH
);
3793 updateVisualBits
.SetBit(UNIT_FIELD_DISPLAYID
);
3794 updateVisualBits
.SetBit(UNIT_FIELD_NATIVEDISPLAYID
);
3795 updateVisualBits
.SetBit(UNIT_FIELD_MOUNTDISPLAYID
);
3796 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_1
);
3797 updateVisualBits
.SetBit(UNIT_FIELD_PETNUMBER
);
3798 updateVisualBits
.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP
);
3799 updateVisualBits
.SetBit(UNIT_DYNAMIC_FLAGS
);
3800 updateVisualBits
.SetBit(UNIT_CHANNEL_SPELL
);
3801 updateVisualBits
.SetBit(UNIT_MOD_CAST_SPEED
);
3802 updateVisualBits
.SetBit(UNIT_FIELD_BASE_MANA
);
3803 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_2
);
3804 updateVisualBits
.SetBit(UNIT_FIELD_HOVERHEIGHT
);
3806 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 0);
3807 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 1);
3808 updateVisualBits
.SetBit(PLAYER_FLAGS
);
3809 updateVisualBits
.SetBit(PLAYER_GUILDID
);
3810 updateVisualBits
.SetBit(PLAYER_GUILDRANK
);
3811 updateVisualBits
.SetBit(PLAYER_BYTES
);
3812 updateVisualBits
.SetBit(PLAYER_BYTES_2
);
3813 updateVisualBits
.SetBit(PLAYER_BYTES_3
);
3814 updateVisualBits
.SetBit(PLAYER_DUEL_TEAM
);
3815 updateVisualBits
.SetBit(PLAYER_GUILD_TIMESTAMP
);
3817 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3818 for(uint16 i
= PLAYER_QUEST_LOG_1_1
; i
< PLAYER_QUEST_LOG_25_2
; i
+= MAX_QUEST_OFFSET
)
3819 updateVisualBits
.SetBit(i
);
3821 // Players visible items are not inventory stuff
3822 for(uint16 i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
3824 uint32 offset
= i
* 2;
3827 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_ENTRYID
+ offset
);
3829 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT
+ offset
);
3832 updateVisualBits
.SetBit(PLAYER_CHOSEN_TITLE
);
3835 void Player::BuildCreateUpdateBlockForPlayer( UpdateData
*data
, Player
*target
) const
3837 for(int i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
3839 if(m_items
[i
] == NULL
)
3842 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3847 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
3849 if(m_items
[i
] == NULL
)
3852 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3854 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
3856 if(m_items
[i
] == NULL
)
3859 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3863 Unit::BuildCreateUpdateBlockForPlayer( data
, target
);
3866 void Player::DestroyForPlayer( Player
*target
, bool anim
) const
3868 Unit::DestroyForPlayer( target
, anim
);
3870 for(int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
3872 if(m_items
[i
] == NULL
)
3875 m_items
[i
]->DestroyForPlayer( target
);
3880 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
3882 if(m_items
[i
] == NULL
)
3885 m_items
[i
]->DestroyForPlayer( target
);
3887 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
3889 if(m_items
[i
] == NULL
)
3892 m_items
[i
]->DestroyForPlayer( target
);
3897 bool Player::HasSpell(uint32 spell
) const
3899 PlayerSpellMap::const_iterator itr
= m_spells
.find(spell
);
3900 return (itr
!= m_spells
.end() && itr
->second
.state
!= PLAYERSPELL_REMOVED
&&
3901 !itr
->second
.disabled
);
3904 bool Player::HasActiveSpell(uint32 spell
) const
3906 PlayerSpellMap::const_iterator itr
= m_spells
.find(spell
);
3907 return (itr
!= m_spells
.end() && itr
->second
.state
!= PLAYERSPELL_REMOVED
&&
3908 itr
->second
.active
&& !itr
->second
.disabled
);
3911 TrainerSpellState
Player::GetTrainerSpellState(TrainerSpell
const* trainer_spell
) const
3914 return TRAINER_SPELL_RED
;
3916 if (!trainer_spell
->learnedSpell
)
3917 return TRAINER_SPELL_RED
;
3920 if(HasSpell(trainer_spell
->learnedSpell
))
3921 return TRAINER_SPELL_GRAY
;
3923 // check race/class requirement
3924 if(!IsSpellFitByClassAndRace(trainer_spell
->learnedSpell
))
3925 return TRAINER_SPELL_RED
;
3927 // check level requirement
3928 if(getLevel() < trainer_spell
->reqLevel
)
3929 return TRAINER_SPELL_RED
;
3931 if(SpellChainNode
const* spell_chain
= sSpellMgr
.GetSpellChainNode(trainer_spell
->learnedSpell
))
3933 // check prev.rank requirement
3934 if(spell_chain
->prev
&& !HasSpell(spell_chain
->prev
))
3935 return TRAINER_SPELL_RED
;
3937 // check additional spell requirement
3938 if(spell_chain
->req
&& !HasSpell(spell_chain
->req
))
3939 return TRAINER_SPELL_RED
;
3942 // check skill requirement
3943 if(trainer_spell
->reqSkill
&& GetBaseSkillValue(trainer_spell
->reqSkill
) < trainer_spell
->reqSkillValue
)
3944 return TRAINER_SPELL_RED
;
3946 // exist, already checked at loading
3947 SpellEntry
const* spell
= sSpellStore
.LookupEntry(trainer_spell
->learnedSpell
);
3949 // secondary prof. or not prof. spell
3950 uint32 skill
= spell
->EffectMiscValue
[1];
3952 if(spell
->Effect
[1] != SPELL_EFFECT_SKILL
|| !IsPrimaryProfessionSkill(skill
))
3953 return TRAINER_SPELL_GREEN
;
3955 // check primary prof. limit
3956 if(sSpellMgr
.IsPrimaryProfessionFirstRankSpell(spell
->Id
) && GetFreePrimaryProfessionPoints() == 0)
3957 return TRAINER_SPELL_GREEN_DISABLED
;
3959 return TRAINER_SPELL_GREEN
;
3962 void Player::DeleteFromDB(uint64 playerguid
, uint32 accountId
, bool updateRealmChars
)
3964 uint32 guid
= GUID_LOPART(playerguid
);
3966 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3967 // bones will be deleted by corpse/bones deleting thread shortly
3968 sObjectAccessor
.ConvertCorpseForPlayer(playerguid
);
3970 // remove from guild
3971 uint32 guildId
= GetGuildIdFromDB(playerguid
);
3974 Guild
* guild
= sObjectMgr
.GetGuildById(guildId
);
3976 guild
->DelMember(guid
);
3979 // remove from arena teams
3980 LeaveAllArenaTeams(playerguid
);
3982 // the player was uninvited already on logout so just remove from group
3983 QueryResult
*resultGroup
= CharacterDatabase
.PQuery("SELECT groupId FROM group_member WHERE memberGuid='%u'", guid
);
3986 uint32 groupId
= (*resultGroup
)[0].GetUInt32();
3988 if (Group
* group
= sObjectMgr
.GetGroupById(groupId
))
3989 RemoveFromGroup(group
, playerguid
);
3992 // remove signs from petitions (also remove petitions if owner);
3993 RemovePetitionsAndSigns(playerguid
, 10);
3995 // return back all mails with COD and Item 0 1 2 3 4 5 6 7
3996 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
);
4001 Field
*fields
= resultMail
->Fetch();
4003 uint32 mail_id
= fields
[0].GetUInt32();
4004 uint16 mailType
= fields
[1].GetUInt16();
4005 uint16 mailTemplateId
= fields
[2].GetUInt16();
4006 uint32 sender
= fields
[3].GetUInt32();
4007 std::string subject
= fields
[4].GetCppString();
4008 uint32 itemTextId
= fields
[5].GetUInt32();
4009 uint32 money
= fields
[6].GetUInt32();
4010 bool has_items
= fields
[7].GetBool();
4012 //we can return mail now
4013 //so firstly delete the old one
4014 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id
);
4016 // mail not from player
4017 if (mailType
!= MAIL_NORMAL
)
4020 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id
);
4024 MailDraft
draft(subject
, itemTextId
);
4026 draft
= MailDraft(mailTemplateId
,false); // itesm already included
4030 // data needs to be at first place for Item::LoadFromDB
4031 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
);
4036 Field
*fields2
= resultItems
->Fetch();
4038 uint32 item_guidlow
= fields2
[1].GetUInt32();
4039 uint32 item_template
= fields2
[2].GetUInt32();
4041 ItemPrototype
const* itemProto
= ObjectMgr::GetItemPrototype(item_template
);
4044 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow
);
4048 Item
*pItem
= NewItemOrBag(itemProto
);
4049 if(!pItem
->LoadFromDB(item_guidlow
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
),resultItems
))
4051 pItem
->FSetState(ITEM_REMOVED
);
4052 pItem
->SaveToDB(); // it also deletes item object !
4056 draft
.AddItem(pItem
);
4058 while (resultItems
->NextRow());
4064 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id
);
4066 uint32 pl_account
= sObjectMgr
.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
4068 draft
.AddMoney(money
).SendReturnToSender(pl_account
, guid
, sender
);
4070 while (resultMail
->NextRow());
4075 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
4076 // Get guids of character's pets, will deleted in transaction
4077 QueryResult
*resultPets
= CharacterDatabase
.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid
);
4079 // NOW we can finally clear other DB data related to character
4080 CharacterDatabase
.BeginTransaction();
4085 Field
*fields3
= resultPets
->Fetch();
4086 uint32 petguidlow
= fields3
[0].GetUInt32();
4087 Pet::DeleteFromDB(petguidlow
);
4088 } while (resultPets
->NextRow());
4092 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",guid
);
4093 CharacterDatabase
.PExecute("DELETE FROM character_account_data WHERE guid = '%u'",guid
);
4094 CharacterDatabase
.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid
);
4095 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid
);
4096 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid
);
4097 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid
);
4098 CharacterDatabase
.PExecute("DELETE FROM character_glyphs WHERE guid = '%u'",guid
);
4099 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid
);
4100 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid
);
4101 CharacterDatabase
.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid
);
4102 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid
);
4103 CharacterDatabase
.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid
);
4104 CharacterDatabase
.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",guid
);
4105 CharacterDatabase
.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid
);
4106 CharacterDatabase
.PExecute("DELETE FROM character_skills WHERE guid = '%u'",guid
);
4107 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid
);
4108 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid
);
4109 CharacterDatabase
.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid
);
4110 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid
);
4111 CharacterDatabase
.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid
,guid
);
4112 CharacterDatabase
.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid
);
4113 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid
);
4114 CharacterDatabase
.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid
);
4115 CharacterDatabase
.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid
);
4116 CharacterDatabase
.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid
);
4117 CharacterDatabase
.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid
);
4118 CharacterDatabase
.PExecute("DELETE FROM character_equipmentsets WHERE guid = '%u'",guid
);
4119 CharacterDatabase
.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid1 = '%u'",guid
);
4120 CharacterDatabase
.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid2 = '%u'",guid
);
4121 CharacterDatabase
.PExecute("DELETE FROM guild_bank_eventlog WHERE PlayerGuid = '%u'",guid
);
4122 CharacterDatabase
.CommitTransaction();
4124 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
4125 if(updateRealmChars
) sWorld
.UpdateRealmCharCount(accountId
);
4128 void Player::SetMovement(PlayerMovementType pType
)
4133 case MOVE_ROOT
: data
.Initialize(SMSG_FORCE_MOVE_ROOT
, GetPackGUID().size()+4); break;
4134 case MOVE_UNROOT
: data
.Initialize(SMSG_FORCE_MOVE_UNROOT
, GetPackGUID().size()+4); break;
4135 case MOVE_WATER_WALK
: data
.Initialize(SMSG_MOVE_WATER_WALK
, GetPackGUID().size()+4); break;
4136 case MOVE_LAND_WALK
: data
.Initialize(SMSG_MOVE_LAND_WALK
, GetPackGUID().size()+4); break;
4138 sLog
.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType
);
4141 data
<< GetPackGUID();
4143 GetSession()->SendPacket( &data
);
4147 - a resurrectable corpse must not be loaded for the player (only bones)
4148 - the player must be in world
4150 void Player::BuildPlayerRepop()
4152 WorldPacket
data(SMSG_PRE_RESURRECT
, GetPackGUID().size());
4153 data
<< GetPackGUID();
4154 GetSession()->SendPacket(&data
);
4156 if(getRace() == RACE_NIGHTELF
)
4157 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)
4158 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
4160 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
4161 // there must be SMSG.STOP_MIRROR_TIMER
4162 // there we must send 888 opcode
4164 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
4167 sLog
.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
4171 // create a corpse and place it at the player's location
4173 Corpse
*corpse
= GetCorpse();
4176 sLog
.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
4179 GetMap()->Add(corpse
);
4181 // convert player body to ghost
4184 SetMovement(MOVE_WATER_WALK
);
4185 if(!GetSession()->isLogingOut())
4186 SetMovement(MOVE_UNROOT
);
4188 // BG - remove insignia related
4189 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_SKINNABLE
);
4191 SendCorpseReclaimDelay();
4193 // to prevent cheating
4194 corpse
->ResetGhostTime();
4196 StopMirrorTimers(); //disable timers(bars)
4198 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, (float)1.0); //see radius of death player?
4200 // set and clear other
4201 SetByteValue(UNIT_FIELD_BYTES_1
, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND
);
4204 void Player::ResurrectPlayer(float restore_percent
, bool applySickness
)
4206 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // remove spirit healer position
4211 GetSession()->SendPacket(&data
);
4213 // speed change, land walk
4215 // remove death flag + set aura
4216 SetByteValue(UNIT_FIELD_BYTES_1
, 3, 0x00);
4217 if(getRace() == RACE_NIGHTELF
)
4218 RemoveAurasDueToSpell(20584); // speed bonuses
4219 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
4221 setDeathState(ALIVE
);
4223 SetMovement(MOVE_LAND_WALK
);
4224 SetMovement(MOVE_UNROOT
);
4228 // set health/powers (0- will be set in caller)
4229 if(restore_percent
>0.0f
)
4231 SetHealth(uint32(GetMaxHealth()*restore_percent
));
4232 SetPower(POWER_MANA
, uint32(GetMaxPower(POWER_MANA
)*restore_percent
));
4233 SetPower(POWER_RAGE
, 0);
4234 SetPower(POWER_ENERGY
, uint32(GetMaxPower(POWER_ENERGY
)*restore_percent
));
4237 // trigger update zone for alive state zone updates
4238 uint32 newzone
, newarea
;
4239 GetZoneAndAreaId(newzone
,newarea
);
4240 UpdateZone(newzone
,newarea
);
4242 // update visibility
4243 UpdateVisibilityForPlayer();
4248 //Characters from level 1-10 are not affected by resurrection sickness.
4249 //Characters from level 11-19 will suffer from one minute of sickness
4250 //for each level they are above 10.
4251 //Characters level 20 and up suffer from ten minutes of sickness.
4252 int32 startLevel
= sWorld
.getConfig(CONFIG_INT32_DEATH_SICKNESS_LEVEL
);
4254 if(int32(getLevel()) >= startLevel
)
4256 // set resurrection sickness
4257 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,true);
4259 // not full duration
4260 if(int32(getLevel()) < startLevel
+9)
4262 int32 delta
= (int32(getLevel()) - startLevel
+ 1)*MINUTE
;
4264 for(int i
= 0; i
< MAX_EFFECT_INDEX
; ++i
)
4266 if(Aura
* Aur
= GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,SpellEffectIndex(i
)))
4268 Aur
->SetAuraDuration(delta
*IN_MILISECONDS
);
4269 Aur
->SendAuraUpdate(false);
4276 void Player::KillPlayer()
4278 SetMovement(MOVE_ROOT
);
4280 StopMirrorTimers(); //disable timers(bars)
4282 setDeathState(CORPSE
);
4283 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4285 SetFlag(UNIT_DYNAMIC_FLAGS
, 0x00);
4286 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, !sMapStore
.LookupEntry(GetMapId())->Instanceable());
4288 // 6 minutes until repop at graveyard
4289 m_deathTimer
= 6*MINUTE
*IN_MILISECONDS
;
4291 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4293 // don't create corpse at this moment, player might be falling
4295 // update visibility
4296 UpdateObjectVisibility();
4299 void Player::CreateCorpse()
4301 // prevent existence 2 corpse for player
4304 uint32 _uf
, _pb
, _pb2
, _cfb1
, _cfb2
;
4306 Corpse
*corpse
= new Corpse( (m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
) ? CORPSE_RESURRECTABLE_PVP
: CORPSE_RESURRECTABLE_PVE
);
4309 if(!corpse
->Create(sObjectMgr
.GenerateLowGuid(HIGHGUID_CORPSE
), this))
4315 _uf
= GetUInt32Value(UNIT_FIELD_BYTES_0
);
4316 _pb
= GetUInt32Value(PLAYER_BYTES
);
4317 _pb2
= GetUInt32Value(PLAYER_BYTES_2
);
4319 uint8 race
= (uint8
)(_uf
);
4320 uint8 skin
= (uint8
)(_pb
);
4321 uint8 face
= (uint8
)(_pb
>> 8);
4322 uint8 hairstyle
= (uint8
)(_pb
>> 16);
4323 uint8 haircolor
= (uint8
)(_pb
>> 24);
4324 uint8 facialhair
= (uint8
)(_pb2
);
4326 _cfb1
= ((0x00) | (race
<< 8) | (getGender() << 16) | (skin
<< 24));
4327 _cfb2
= ((face
) | (hairstyle
<< 8) | (haircolor
<< 16) | (facialhair
<< 24));
4329 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_1
, _cfb1
);
4330 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_2
, _cfb2
);
4332 uint32 flags
= CORPSE_FLAG_UNK2
;
4333 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
4334 flags
|= CORPSE_FLAG_HIDE_HELM
;
4335 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
4336 flags
|= CORPSE_FLAG_HIDE_CLOAK
;
4337 if(InBattleGround() && !InArena())
4338 flags
|= CORPSE_FLAG_LOOTABLE
; // to be able to remove insignia
4339 corpse
->SetUInt32Value( CORPSE_FIELD_FLAGS
, flags
);
4341 corpse
->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID
, GetNativeDisplayId() );
4343 corpse
->SetUInt32Value( CORPSE_FIELD_GUILD
, GetGuildId() );
4346 uint32 iIventoryType
;
4348 for (int i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
4352 iDisplayID
= m_items
[i
]->GetProto()->DisplayInfoID
;
4353 iIventoryType
= m_items
[i
]->GetProto()->InventoryType
;
4355 _cfi
= iDisplayID
| (iIventoryType
<< 24);
4356 corpse
->SetUInt32Value(CORPSE_FIELD_ITEM
+ i
, _cfi
);
4360 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4361 const MapEntry
*entry
= sMapStore
.LookupEntry(corpse
->GetMapId());
4363 if(entry
->map_type
!= MAP_BATTLEGROUND
)
4366 // register for player, but not show
4367 sObjectAccessor
.AddCorpse(corpse
);
4370 void Player::SpawnCorpseBones()
4372 if(sObjectAccessor
.ConvertCorpseForPlayer(GetGUID()))
4373 if (!GetSession()->PlayerLogoutWithSave()) // at logout we will already store the player
4374 SaveToDB(); // prevent loading as ghost without corpse
4377 Corpse
* Player::GetCorpse() const
4379 return sObjectAccessor
.GetCorpseForPlayerGUID(GetGUID());
4382 void Player::DurabilityLossAll(double percent
, bool inventory
)
4384 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
4385 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4386 DurabilityLoss(pItem
,percent
);
4390 // bags not have durability
4391 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4393 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
4394 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4395 DurabilityLoss(pItem
,percent
);
4397 // keys not have durability
4398 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4400 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
4401 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4402 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
4403 if(Item
* pItem
= GetItemByPos( i
, j
))
4404 DurabilityLoss(pItem
,percent
);
4408 void Player::DurabilityLoss(Item
* item
, double percent
)
4413 uint32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4418 uint32 pDurabilityLoss
= uint32(pMaxDurability
*percent
);
4420 if(pDurabilityLoss
< 1 )
4421 pDurabilityLoss
= 1;
4423 DurabilityPointsLoss(item
,pDurabilityLoss
);
4426 void Player::DurabilityPointsLossAll(int32 points
, bool inventory
)
4428 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
4429 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4430 DurabilityPointsLoss(pItem
,points
);
4434 // bags not have durability
4435 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4437 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
4438 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4439 DurabilityPointsLoss(pItem
,points
);
4441 // keys not have durability
4442 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4444 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
4445 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4446 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
4447 if(Item
* pItem
= GetItemByPos( i
, j
))
4448 DurabilityPointsLoss(pItem
,points
);
4452 void Player::DurabilityPointsLoss(Item
* item
, int32 points
)
4454 int32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4455 int32 pOldDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4456 int32 pNewDurability
= pOldDurability
- points
;
4458 if (pNewDurability
< 0)
4460 else if (pNewDurability
> pMaxDurability
)
4461 pNewDurability
= pMaxDurability
;
4463 if (pOldDurability
!= pNewDurability
)
4465 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4466 if ( pNewDurability
== 0 && pOldDurability
> 0 && item
->IsEquipped())
4467 _ApplyItemMods(item
,item
->GetSlot(), false);
4469 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, pNewDurability
);
4471 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4472 if ( pNewDurability
> 0 && pOldDurability
== 0 && item
->IsEquipped())
4473 _ApplyItemMods(item
,item
->GetSlot(), true);
4475 item
->SetState(ITEM_CHANGED
, this);
4479 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot
)
4481 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
))
4482 DurabilityPointsLoss(pItem
,1);
4485 uint32
Player::DurabilityRepairAll(bool cost
, float discountMod
, bool guildBank
)
4487 uint32 TotalCost
= 0;
4488 // equipped, backpack, bags itself
4489 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
4490 TotalCost
+= DurabilityRepair(( (INVENTORY_SLOT_BAG_0
<< 8) | i
),cost
,discountMod
, guildBank
);
4492 // bank, buyback and keys not repaired
4494 // items in inventory bags
4495 for(int j
= INVENTORY_SLOT_BAG_START
; j
< INVENTORY_SLOT_BAG_END
; ++j
)
4496 for(int i
= 0; i
< MAX_BAG_SIZE
; ++i
)
4497 TotalCost
+= DurabilityRepair(( (j
<< 8) | i
),cost
,discountMod
, guildBank
);
4501 uint32
Player::DurabilityRepair(uint16 pos
, bool cost
, float discountMod
, bool guildBank
)
4503 Item
* item
= GetItemByPos(pos
);
4505 uint32 TotalCost
= 0;
4509 uint32 maxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4513 uint32 curDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4517 uint32 LostDurability
= maxDurability
- curDurability
;
4518 if(LostDurability
>0)
4520 ItemPrototype
const *ditemProto
= item
->GetProto();
4522 DurabilityCostsEntry
const *dcost
= sDurabilityCostsStore
.LookupEntry(ditemProto
->ItemLevel
);
4525 sLog
.outError("RepairDurability: Wrong item lvl %u", ditemProto
->ItemLevel
);
4529 uint32 dQualitymodEntryId
= (ditemProto
->Quality
+1)*2;
4530 DurabilityQualityEntry
const *dQualitymodEntry
= sDurabilityQualityStore
.LookupEntry(dQualitymodEntryId
);
4531 if(!dQualitymodEntry
)
4533 sLog
.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId
);
4537 uint32 dmultiplier
= dcost
->multiplier
[ItemSubClassToDurabilityMultiplierId(ditemProto
->Class
,ditemProto
->SubClass
)];
4538 uint32 costs
= uint32(LostDurability
*dmultiplier
*double(dQualitymodEntry
->quality_mod
));
4540 costs
= uint32(costs
* discountMod
);
4542 if (costs
==0) //fix for ITEM_QUALITY_ARTIFACT
4547 if (GetGuildId()==0)
4549 DEBUG_LOG("You are not member of a guild");
4553 Guild
*pGuild
= sObjectMgr
.GetGuildById(GetGuildId());
4557 if (!pGuild
->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR
))
4559 DEBUG_LOG("You do not have rights to withdraw for repairs");
4563 if (pGuild
->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs
)
4565 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4569 if (pGuild
->GetGuildBankMoney() < costs
)
4571 DEBUG_LOG("There is not enough money in bank");
4575 pGuild
->MemberMoneyWithdraw(costs
, GetGUIDLow());
4578 else if (GetMoney() < costs
)
4580 DEBUG_LOG("You do not have enough money");
4584 ModifyMoney( -int32(costs
) );
4588 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, maxDurability
);
4589 item
->SetState(ITEM_CHANGED
, this);
4591 // reapply mods for total broken and repaired item if equipped
4592 if(IsEquipmentPos(pos
) && !curDurability
)
4593 _ApplyItemMods(item
,pos
& 255, true);
4597 void Player::RepopAtGraveyard()
4599 // note: this can be called also when the player is alive
4600 // for example from WorldSession::HandleMovementOpcodes
4602 AreaTableEntry
const *zone
= GetAreaEntryByAreaID(GetAreaId());
4604 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4605 if ((!isAlive() && zone
&& zone
->flags
& AREA_FLAG_NEED_FLY
) || GetTransport())
4607 ResurrectPlayer(0.5f
);
4611 WorldSafeLocsEntry
const *ClosestGrave
= NULL
;
4613 // Special handle for battleground maps
4614 if( BattleGround
*bg
= GetBattleGround() )
4615 ClosestGrave
= bg
->GetClosestGraveYard(this);
4617 ClosestGrave
= sObjectMgr
.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4619 // stop countdown until repop
4622 // if no grave found, stay at the current location
4623 // and don't show spirit healer location
4626 TeleportTo(ClosestGrave
->map_id
, ClosestGrave
->x
, ClosestGrave
->y
, ClosestGrave
->z
, GetOrientation());
4627 if(isDead()) // not send if alive, because it used in TeleportTo()
4629 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // show spirit healer position on minimap
4630 data
<< ClosestGrave
->map_id
;
4631 data
<< ClosestGrave
->x
;
4632 data
<< ClosestGrave
->y
;
4633 data
<< ClosestGrave
->z
;
4634 GetSession()->SendPacket(&data
);
4639 void Player::JoinedChannel(Channel
*c
)
4641 m_channels
.push_back(c
);
4644 void Player::LeftChannel(Channel
*c
)
4646 m_channels
.remove(c
);
4649 void Player::CleanupChannels()
4651 while(!m_channels
.empty())
4653 Channel
* ch
= *m_channels
.begin();
4654 m_channels
.erase(m_channels
.begin()); // remove from player's channel list
4655 ch
->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4656 if (ChannelMgr
* cMgr
= channelMgr(GetTeam()))
4657 cMgr
->LeftChannel(ch
->GetName()); // deleted channel if empty
4660 sLog
.outDebug("Player: channels cleaned up!");
4663 void Player::UpdateLocalChannels(uint32 newZone
)
4665 if(m_channels
.empty())
4668 AreaTableEntry
const* current_zone
= GetAreaEntryByAreaID(newZone
);
4672 ChannelMgr
* cMgr
= channelMgr(GetTeam());
4676 std::string current_zone_name
= current_zone
->area_name
[GetSession()->GetSessionDbcLocale()];
4678 for(JoinedChannelsList::iterator i
= m_channels
.begin(), next
; i
!= m_channels
.end(); i
= next
)
4682 // skip non built-in channels
4683 if(!(*i
)->IsConstant())
4686 ChatChannelsEntry
const* ch
= GetChannelEntryFor((*i
)->GetChannelId());
4690 if((ch
->flags
& 4) == 4) // global channel without zone name in pattern
4694 char new_channel_name_buf
[100];
4695 snprintf(new_channel_name_buf
,100,ch
->pattern
[m_session
->GetSessionDbcLocale()],current_zone_name
.c_str());
4696 Channel
* new_channel
= cMgr
->GetJoinChannel(new_channel_name_buf
,ch
->ChannelID
);
4698 if((*i
)!=new_channel
)
4700 new_channel
->Join(GetGUID(),""); // will output Changed Channel: N. Name
4702 // leave old channel
4703 (*i
)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4704 std::string name
= (*i
)->GetName(); // store name, (*i)erase in LeftChannel
4705 LeftChannel(*i
); // remove from player's channel list
4706 cMgr
->LeftChannel(name
); // delete if empty
4709 sLog
.outDebug("Player: channels cleaned up!");
4712 void Player::LeaveLFGChannel()
4714 for(JoinedChannelsList::iterator i
= m_channels
.begin(); i
!= m_channels
.end(); ++i
)
4718 (*i
)->Leave(GetGUID());
4724 void Player::UpdateDefense()
4726 uint32 defense_skill_gain
= sWorld
.getConfig(CONFIG_UINT32_SKILL_GAIN_DEFENSE
);
4728 if(UpdateSkill(SKILL_DEFENSE
,defense_skill_gain
))
4730 // update dependent from defense skill part
4731 UpdateDefenseBonusesMod();
4735 void Player::HandleBaseModValue(BaseModGroup modGroup
, BaseModType modType
, float amount
, bool apply
)
4737 if(modGroup
>= BASEMOD_END
|| modType
>= MOD_END
)
4739 sLog
.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4748 m_auraBaseMod
[modGroup
][modType
] += apply
? amount
: -amount
;
4751 if(amount
<= -100.0f
)
4754 val
= (100.0f
+ amount
) / 100.0f
;
4755 m_auraBaseMod
[modGroup
][modType
] *= apply
? val
: (1.0f
/val
);
4759 if(!CanModifyStats())
4764 case CRIT_PERCENTAGE
: UpdateCritPercentage(BASE_ATTACK
); break;
4765 case RANGED_CRIT_PERCENTAGE
: UpdateCritPercentage(RANGED_ATTACK
); break;
4766 case OFFHAND_CRIT_PERCENTAGE
: UpdateCritPercentage(OFF_ATTACK
); break;
4767 case SHIELD_BLOCK_VALUE
: UpdateShieldBlockValue(); break;
4772 float Player::GetBaseModValue(BaseModGroup modGroup
, BaseModType modType
) const
4774 if(modGroup
>= BASEMOD_END
|| modType
> MOD_END
)
4776 sLog
.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4780 if(modType
== PCT_MOD
&& m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4783 return m_auraBaseMod
[modGroup
][modType
];
4786 float Player::GetTotalBaseModValue(BaseModGroup modGroup
) const
4788 if(modGroup
>= BASEMOD_END
)
4790 sLog
.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4794 if(m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4797 return m_auraBaseMod
[modGroup
][FLAT_MOD
] * m_auraBaseMod
[modGroup
][PCT_MOD
];
4800 uint32
Player::GetShieldBlockValue() const
4802 float value
= (m_auraBaseMod
[SHIELD_BLOCK_VALUE
][FLAT_MOD
] + GetStat(STAT_STRENGTH
) * 0.5f
- 10)*m_auraBaseMod
[SHIELD_BLOCK_VALUE
][PCT_MOD
];
4804 value
= (value
< 0) ? 0 : value
;
4806 return uint32(value
);
4809 float Player::GetMeleeCritFromAgility()
4811 uint32 level
= getLevel();
4812 uint32 pclass
= getClass();
4814 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4816 GtChanceToMeleeCritBaseEntry
const *critBase
= sGtChanceToMeleeCritBaseStore
.LookupEntry(pclass
-1);
4817 GtChanceToMeleeCritEntry
const *critRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4818 if (critBase
==NULL
|| critRatio
==NULL
)
4821 float crit
=critBase
->base
+ GetStat(STAT_AGILITY
)*critRatio
->ratio
;
4825 float Player::GetDodgeFromAgility()
4827 // Table for base dodge values
4828 float dodge_base
[MAX_CLASSES
] = {
4830 0.00652f
, // Paladin
4837 0.02011f
, // Warlock
4841 // Crit/agility to dodge/agility coefficient multipliers
4842 float crit_to_dodge
[MAX_CLASSES
] = {
4856 uint32 level
= getLevel();
4857 uint32 pclass
= getClass();
4859 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4861 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4862 GtChanceToMeleeCritEntry
const *dodgeRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4863 if (dodgeRatio
==NULL
|| pclass
> MAX_CLASSES
)
4866 float dodge
=dodge_base
[pclass
-1] + GetStat(STAT_AGILITY
) * dodgeRatio
->ratio
* crit_to_dodge
[pclass
-1];
4867 return dodge
*100.0f
;
4870 float Player::GetSpellCritFromIntellect()
4872 uint32 level
= getLevel();
4873 uint32 pclass
= getClass();
4875 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4877 GtChanceToSpellCritBaseEntry
const *critBase
= sGtChanceToSpellCritBaseStore
.LookupEntry(pclass
-1);
4878 GtChanceToSpellCritEntry
const *critRatio
= sGtChanceToSpellCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4879 if (critBase
==NULL
|| critRatio
==NULL
)
4882 float crit
=critBase
->base
+ GetStat(STAT_INTELLECT
)*critRatio
->ratio
;
4886 float Player::GetRatingCoefficient(CombatRating cr
) const
4888 uint32 level
= getLevel();
4890 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4892 GtCombatRatingsEntry
const *Rating
= sGtCombatRatingsStore
.LookupEntry(cr
*GT_MAX_LEVEL
+level
-1);
4894 return 1.0f
; // By default use minimum coefficient (not must be called)
4896 return Rating
->ratio
;
4899 float Player::GetRatingBonusValue(CombatRating cr
) const
4901 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
)) / GetRatingCoefficient(cr
);
4904 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType
) const
4909 return GetUInt32Value(PLAYER_EXPERTISE
) / 4.0f
;
4911 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE
) / 4.0f
;
4918 float Player::OCTRegenHPPerSpirit()
4920 uint32 level
= getLevel();
4921 uint32 pclass
= getClass();
4923 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4925 GtOCTRegenHPEntry
const *baseRatio
= sGtOCTRegenHPStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4926 GtRegenHPPerSptEntry
const *moreRatio
= sGtRegenHPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4927 if (baseRatio
==NULL
|| moreRatio
==NULL
)
4930 // Formula from PaperDollFrame script
4931 float spirit
= GetStat(STAT_SPIRIT
);
4932 float baseSpirit
= spirit
;
4933 if (baseSpirit
>50) baseSpirit
= 50;
4934 float moreSpirit
= spirit
- baseSpirit
;
4935 float regen
= baseSpirit
* baseRatio
->ratio
+ moreSpirit
* moreRatio
->ratio
;
4939 float Player::OCTRegenMPPerSpirit()
4941 uint32 level
= getLevel();
4942 uint32 pclass
= getClass();
4944 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4946 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4947 GtRegenMPPerSptEntry
const *moreRatio
= sGtRegenMPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4948 if (moreRatio
==NULL
)
4951 // Formula get from PaperDollFrame script
4952 float spirit
= GetStat(STAT_SPIRIT
);
4953 float regen
= spirit
* moreRatio
->ratio
;
4957 void Player::ApplyRatingMod(CombatRating cr
, int32 value
, bool apply
)
4959 m_baseRatingValue
[cr
]+=(apply
? value
: -value
);
4961 // explicit affected values
4964 case CR_HASTE_MELEE
:
4966 float RatingChange
= value
/ GetRatingCoefficient(cr
);
4967 ApplyAttackTimePercentMod(BASE_ATTACK
,RatingChange
,apply
);
4968 ApplyAttackTimePercentMod(OFF_ATTACK
,RatingChange
,apply
);
4971 case CR_HASTE_RANGED
:
4973 float RatingChange
= value
/ GetRatingCoefficient(cr
);
4974 ApplyAttackTimePercentMod(RANGED_ATTACK
, RatingChange
, apply
);
4977 case CR_HASTE_SPELL
:
4979 float RatingChange
= value
/ GetRatingCoefficient(cr
);
4980 ApplyCastTimePercentMod(RatingChange
,apply
);
4988 void Player::UpdateRating(CombatRating cr
)
4990 int32 amount
= m_baseRatingValue
[cr
];
4991 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4992 // stat used stored in miscValueB for this aura
4993 AuraList
const& modRatingFromStat
= GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT
);
4994 for(AuraList::const_iterator i
= modRatingFromStat
.begin();i
!= modRatingFromStat
.end(); ++i
)
4995 if ((*i
)->GetMiscValue() & (1<<cr
))
4996 amount
+= int32(GetStat(Stats((*i
)->GetMiscBValue())) * (*i
)->GetModifier()->m_amount
/ 100.0f
);
4999 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
, uint32(amount
));
5001 bool affectStats
= CanModifyStats();
5005 case CR_WEAPON_SKILL
: // Implemented in Unit::RollMeleeOutcomeAgainst
5006 case CR_DEFENSE_SKILL
:
5007 UpdateDefenseBonusesMod();
5010 UpdateDodgePercentage();
5013 UpdateParryPercentage();
5016 UpdateBlockPercentage();
5019 UpdateMeleeHitChances();
5022 UpdateRangedHitChances();
5025 UpdateSpellHitChances();
5030 UpdateCritPercentage(BASE_ATTACK
);
5031 UpdateCritPercentage(OFF_ATTACK
);
5034 case CR_CRIT_RANGED
:
5036 UpdateCritPercentage(RANGED_ATTACK
);
5040 UpdateAllSpellCritChances();
5042 case CR_HIT_TAKEN_MELEE
: // Implemented in Unit::MeleeMissChanceCalc
5043 case CR_HIT_TAKEN_RANGED
:
5045 case CR_HIT_TAKEN_SPELL
: // Implemented in Unit::MagicSpellHitResult
5047 case CR_CRIT_TAKEN_MELEE
: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
5048 case CR_CRIT_TAKEN_RANGED
:
5050 case CR_CRIT_TAKEN_SPELL
: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
5052 case CR_HASTE_MELEE
: // Implemented in Player::ApplyRatingMod
5053 case CR_HASTE_RANGED
:
5054 case CR_HASTE_SPELL
:
5056 case CR_WEAPON_SKILL_MAINHAND
: // Implemented in Unit::RollMeleeOutcomeAgainst
5057 case CR_WEAPON_SKILL_OFFHAND
:
5058 case CR_WEAPON_SKILL_RANGED
:
5063 UpdateExpertise(BASE_ATTACK
);
5064 UpdateExpertise(OFF_ATTACK
);
5067 case CR_ARMOR_PENETRATION
:
5069 UpdateArmorPenetration();
5074 void Player::UpdateAllRatings()
5076 for(int cr
= 0; cr
< MAX_COMBAT_RATING
; ++cr
)
5077 UpdateRating(CombatRating(cr
));
5080 void Player::SetRegularAttackTime()
5082 for(int i
= 0; i
< MAX_ATTACK
; ++i
)
5084 Item
*tmpitem
= GetWeaponForAttack(WeaponAttackType(i
),true,false);
5087 ItemPrototype
const *proto
= tmpitem
->GetProto();
5089 SetAttackTime(WeaponAttackType(i
), proto
->Delay
);
5091 SetAttackTime(WeaponAttackType(i
), BASE_ATTACK_TIME
);
5096 //skill+step, checking for max value
5097 bool Player::UpdateSkill(uint32 skill_id
, uint32 step
)
5102 SkillStatusMap::iterator itr
= mSkillStatus
.find(skill_id
);
5103 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5106 uint32 valueIndex
= PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
);
5107 uint32 data
= GetUInt32Value(valueIndex
);
5108 uint32 value
= SKILL_VALUE(data
);
5109 uint32 max
= SKILL_MAX(data
);
5111 if ((!max
) || (!value
) || (value
>= max
))
5114 if (value
*512 < max
*urand(0,512))
5116 uint32 new_value
= value
+step
;
5120 SetUInt32Value(valueIndex
,MAKE_SKILL_VALUE(new_value
,max
));
5121 if(itr
->second
.uState
!= SKILL_NEW
)
5122 itr
->second
.uState
= SKILL_CHANGED
;
5123 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,skill_id
);
5130 inline int SkillGainChance(uint32 SkillValue
, uint32 GrayLevel
, uint32 GreenLevel
, uint32 YellowLevel
)
5132 if ( SkillValue
>= GrayLevel
)
5133 return sWorld
.getConfig(CONFIG_UINT32_SKILL_CHANCE_GREY
)*10;
5134 if ( SkillValue
>= GreenLevel
)
5135 return sWorld
.getConfig(CONFIG_UINT32_SKILL_CHANCE_GREEN
)*10;
5136 if ( SkillValue
>= YellowLevel
)
5137 return sWorld
.getConfig(CONFIG_UINT32_SKILL_CHANCE_YELLOW
)*10;
5138 return sWorld
.getConfig(CONFIG_UINT32_SKILL_CHANCE_ORANGE
)*10;
5141 bool Player::UpdateCraftSkill(uint32 spellid
)
5143 sLog
.outDebug("UpdateCraftSkill spellid %d", spellid
);
5145 SkillLineAbilityMapBounds bounds
= sSpellMgr
.GetSkillLineAbilityMapBounds(spellid
);
5147 for(SkillLineAbilityMap::const_iterator _spell_idx
= bounds
.first
; _spell_idx
!= bounds
.second
; ++_spell_idx
)
5149 if (_spell_idx
->second
->skillId
)
5151 uint32 SkillValue
= GetPureSkillValue(_spell_idx
->second
->skillId
);
5153 // Alchemy Discoveries here
5154 SpellEntry
const* spellEntry
= sSpellStore
.LookupEntry(spellid
);
5155 if (spellEntry
&& spellEntry
->Mechanic
==MECHANIC_DISCOVERY
)
5157 if (uint32 discoveredSpell
= GetSkillDiscoverySpell(_spell_idx
->second
->skillId
, spellid
, this))
5158 learnSpell(discoveredSpell
,false);
5161 uint32 craft_skill_gain
= sWorld
.getConfig(CONFIG_UINT32_SKILL_GAIN_CRAFTING
);
5163 return UpdateSkillPro(_spell_idx
->second
->skillId
, SkillGainChance(SkillValue
,
5164 _spell_idx
->second
->max_value
,
5165 (_spell_idx
->second
->max_value
+ _spell_idx
->second
->min_value
)/2,
5166 _spell_idx
->second
->min_value
),
5173 bool Player::UpdateGatherSkill(uint32 SkillId
, uint32 SkillValue
, uint32 RedLevel
, uint32 Multiplicator
)
5175 sLog
.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId
, SkillValue
, RedLevel
);
5177 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_UINT32_SKILL_GAIN_GATHERING
);
5179 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
5182 case SKILL_HERBALISM
:
5183 case SKILL_LOCKPICKING
:
5184 case SKILL_JEWELCRAFTING
:
5185 case SKILL_INSCRIPTION
:
5186 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
5187 case SKILL_SKINNING
:
5188 if( sWorld
.getConfig(CONFIG_UINT32_SKILL_CHANCE_SKINNING_STEPS
)==0)
5189 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
5191 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_UINT32_SKILL_CHANCE_SKINNING_STEPS
)), gathering_skill_gain
);
5193 if (sWorld
.getConfig(CONFIG_UINT32_SKILL_CHANCE_MINING_STEPS
)==0)
5194 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
5196 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_UINT32_SKILL_CHANCE_MINING_STEPS
)),gathering_skill_gain
);
5201 bool Player::UpdateFishingSkill()
5203 sLog
.outDebug("UpdateFishingSkill");
5205 uint32 SkillValue
= GetPureSkillValue(SKILL_FISHING
);
5207 int32 chance
= SkillValue
< 75 ? 100 : 2500/(SkillValue
-50);
5209 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_UINT32_SKILL_GAIN_GATHERING
);
5211 return UpdateSkillPro(SKILL_FISHING
,chance
*10,gathering_skill_gain
);
5214 // levels sync. with spell requirement for skill levels to learn
5215 // bonus abilities in sSkillLineAbilityStore
5216 // Used only to avoid scan DBC at each skill grow
5217 static uint32 bonusSkillLevels
[] = {75,150,225,300,375,450};
5219 bool Player::UpdateSkillPro(uint16 SkillId
, int32 Chance
, uint32 step
)
5221 sLog
.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId
, Chance
/10.0);
5225 if(Chance
<= 0) // speedup in 0 chance case
5227 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
5231 SkillStatusMap::iterator itr
= mSkillStatus
.find(SkillId
);
5232 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5235 uint32 valueIndex
= PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
);
5237 uint32 data
= GetUInt32Value(valueIndex
);
5238 uint16 SkillValue
= SKILL_VALUE(data
);
5239 uint16 MaxValue
= SKILL_MAX(data
);
5241 if ( !MaxValue
|| !SkillValue
|| SkillValue
>= MaxValue
)
5244 int32 Roll
= irand(1,1000);
5246 if ( Roll
<= Chance
)
5248 uint32 new_value
= SkillValue
+step
;
5249 if(new_value
> MaxValue
)
5250 new_value
= MaxValue
;
5252 SetUInt32Value(valueIndex
,MAKE_SKILL_VALUE(new_value
,MaxValue
));
5253 if(itr
->second
.uState
!= SKILL_NEW
)
5254 itr
->second
.uState
= SKILL_CHANGED
;
5255 for(uint32
* bsl
= &bonusSkillLevels
[0]; *bsl
; ++bsl
)
5257 if((SkillValue
< *bsl
&& new_value
>= *bsl
))
5259 learnSkillRewardedSpells( SkillId
, new_value
);
5263 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,SkillId
);
5264 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance
/10.0);
5268 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
5272 void Player::UpdateWeaponSkill (WeaponAttackType attType
)
5274 // no skill gain in pvp
5275 Unit
*pVictim
= getVictim();
5276 if(pVictim
&& pVictim
->IsCharmerOrOwnerPlayerOrPlayerItself())
5280 return; // always maximized SKILL_FERAL_COMBAT in fact
5282 if(m_form
== FORM_TREE
)
5283 return; // use weapon but not skill up
5285 uint32 weapon_skill_gain
= sWorld
.getConfig(CONFIG_UINT32_SKILL_GAIN_WEAPON
);
5291 Item
*tmpitem
= GetWeaponForAttack(attType
,true,true);
5294 UpdateSkill(SKILL_UNARMED
,weapon_skill_gain
);
5295 else if(tmpitem
->GetProto()->SubClass
!= ITEM_SUBCLASS_WEAPON_FISHING_POLE
)
5296 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
5302 Item
*tmpitem
= GetWeaponForAttack(attType
,true,true);
5304 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
5308 UpdateAllCritPercentages();
5311 void Player::UpdateCombatSkills(Unit
*pVictim
, WeaponAttackType attType
, bool defence
)
5313 uint32 plevel
= getLevel(); // if defense than pVictim == attacker
5314 uint32 greylevel
= MaNGOS::XP::GetGrayLevel(plevel
);
5315 uint32 moblevel
= pVictim
->getLevelForTarget(this);
5316 if(moblevel
< greylevel
)
5319 if (moblevel
> plevel
+ 5)
5320 moblevel
= plevel
+ 5;
5322 uint32 lvldif
= moblevel
- greylevel
;
5326 uint32 skilldif
= 5 * plevel
- (defence
? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType
));
5330 float chance
= float(3 * lvldif
* skilldif
) / plevel
;
5333 if(getClass() == CLASS_WARRIOR
|| getClass() == CLASS_ROGUE
)
5334 chance
*= 0.1f
* GetStat(STAT_INTELLECT
);
5337 chance
= chance
< 1.0f
? 1.0f
: chance
; //minimum chance to increase skill is 1%
5339 if(roll_chance_f(chance
))
5344 UpdateWeaponSkill(attType
);
5350 void Player::ModifySkillBonus(uint32 skillid
,int32 val
, bool talent
)
5352 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skillid
);
5353 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5356 uint32 bonusIndex
= PLAYER_SKILL_BONUS_INDEX(itr
->second
.pos
);
5358 uint32 bonus_val
= GetUInt32Value(bonusIndex
);
5359 int16 temp_bonus
= SKILL_TEMP_BONUS(bonus_val
);
5360 int16 perm_bonus
= SKILL_PERM_BONUS(bonus_val
);
5362 if(talent
) // permanent bonus stored in high part
5363 SetUInt32Value(bonusIndex
,MAKE_SKILL_BONUS(temp_bonus
,perm_bonus
+val
));
5364 else // temporary/item bonus stored in low part
5365 SetUInt32Value(bonusIndex
,MAKE_SKILL_BONUS(temp_bonus
+val
,perm_bonus
));
5368 void Player::UpdateSkillsForLevel()
5370 uint16 maxconfskill
= sWorld
.GetConfigMaxSkillValue();
5371 uint32 maxSkill
= GetMaxSkillValueForLevel();
5373 bool alwaysMaxSkill
= sWorld
.getConfig(CONFIG_BOOL_ALWAYS_MAX_SKILL_FOR_LEVEL
);
5375 for(SkillStatusMap::iterator itr
= mSkillStatus
.begin(); itr
!= mSkillStatus
.end(); ++itr
)
5377 if(itr
->second
.uState
== SKILL_DELETED
)
5380 uint32 pskill
= itr
->first
;
5382 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(pskill
);
5386 if(GetSkillRangeType(pSkill
,false) != SKILL_RANGE_LEVEL
)
5389 uint32 valueIndex
= PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
);
5390 uint32 data
= GetUInt32Value(valueIndex
);
5391 uint32 max
= SKILL_MAX(data
);
5392 uint32 val
= SKILL_VALUE(data
);
5394 /// update only level dependent max skill values
5397 /// maximize skill always
5400 SetUInt32Value(valueIndex
, MAKE_SKILL_VALUE(maxSkill
,maxSkill
));
5401 if(itr
->second
.uState
!= SKILL_NEW
)
5402 itr
->second
.uState
= SKILL_CHANGED
;
5404 else if(max
!= maxconfskill
) /// update max skill value if current max skill not maximized
5406 SetUInt32Value(valueIndex
, MAKE_SKILL_VALUE(val
,maxSkill
));
5407 if(itr
->second
.uState
!= SKILL_NEW
)
5408 itr
->second
.uState
= SKILL_CHANGED
;
5414 void Player::UpdateSkillsToMaxSkillsForLevel()
5416 for(SkillStatusMap::iterator itr
= mSkillStatus
.begin(); itr
!= mSkillStatus
.end(); ++itr
)
5418 if(itr
->second
.uState
== SKILL_DELETED
)
5421 uint32 pskill
= itr
->first
;
5422 if( IsProfessionOrRidingSkill(pskill
))
5424 uint32 valueIndex
= PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
);
5425 uint32 data
= GetUInt32Value(valueIndex
);
5427 uint32 max
= SKILL_MAX(data
);
5431 SetUInt32Value(valueIndex
,MAKE_SKILL_VALUE(max
,max
));
5432 if(itr
->second
.uState
!= SKILL_NEW
)
5433 itr
->second
.uState
= SKILL_CHANGED
;
5436 if(pskill
== SKILL_DEFENSE
)
5437 UpdateDefenseBonusesMod();
5441 // This functions sets a skill line value (and adds if doesn't exist yet)
5442 // To "remove" a skill line, set it's values to zero
5443 void Player::SetSkill(uint32 id
, uint16 currVal
, uint16 maxVal
)
5448 SkillStatusMap::iterator itr
= mSkillStatus
.find(id
);
5451 if(itr
!= mSkillStatus
.end() && itr
->second
.uState
!= SKILL_DELETED
)
5455 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
),MAKE_SKILL_VALUE(currVal
,maxVal
));
5456 if(itr
->second
.uState
!= SKILL_NEW
)
5457 itr
->second
.uState
= SKILL_CHANGED
;
5458 learnSkillRewardedSpells(id
, currVal
);
5459 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,id
);
5460 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL
,id
);
5464 // clear skill fields
5465 SetUInt32Value(PLAYER_SKILL_INDEX(itr
->second
.pos
),0);
5466 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
),0);
5467 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr
->second
.pos
),0);
5469 // mark as deleted or simply remove from map if not saved yet
5470 if(itr
->second
.uState
!= SKILL_NEW
)
5471 itr
->second
.uState
= SKILL_DELETED
;
5473 mSkillStatus
.erase(itr
);
5475 // remove all spells that related to this skill
5476 for (uint32 j
=0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
5477 if(SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
))
5478 if (pAbility
->skillId
==id
)
5479 removeSpell(sSpellMgr
.GetFirstSpellInChain(pAbility
->spellId
));
5482 else if(currVal
) //add
5484 for (int i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5485 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5487 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
5490 sLog
.outError("Skill not found in SkillLineStore: skill #%u", id
);
5493 // enable unlearn button for primary professions only
5494 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
5495 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
5497 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
5498 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
5499 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,id
);
5500 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL
,id
);
5502 // insert new entry or update if not deleted old entry yet
5503 if(itr
!= mSkillStatus
.end())
5505 itr
->second
.pos
= i
;
5506 itr
->second
.uState
= SKILL_CHANGED
;
5509 mSkillStatus
.insert(SkillStatusMap::value_type(id
, SkillStatusData(i
, SKILL_NEW
)));
5511 // apply skill bonuses
5512 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
5514 // temporary bonuses
5515 AuraList
const& mModSkill
= GetAurasByType(SPELL_AURA_MOD_SKILL
);
5516 for(AuraList::const_iterator j
= mModSkill
.begin(); j
!= mModSkill
.end(); ++j
)
5517 if ((*j
)->GetModifier()->m_miscvalue
== int32(id
))
5518 (*j
)->ApplyModifier(true);
5520 // permanent bonuses
5521 AuraList
const& mModSkillTalent
= GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT
);
5522 for(AuraList::const_iterator j
= mModSkillTalent
.begin(); j
!= mModSkillTalent
.end(); ++j
)
5523 if ((*j
)->GetModifier()->m_miscvalue
== int32(id
))
5524 (*j
)->ApplyModifier(true);
5526 // Learn all spells for skill
5527 learnSkillRewardedSpells(id
, currVal
);
5533 bool Player::HasSkill(uint32 skill
) const
5538 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skill
);
5539 return (itr
!= mSkillStatus
.end() && itr
->second
.uState
!= SKILL_DELETED
);
5542 uint16
Player::GetSkillValue(uint32 skill
) const
5547 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skill
);
5548 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5551 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr
->second
.pos
));
5553 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
))));
5554 result
+= SKILL_TEMP_BONUS(bonus
);
5555 result
+= SKILL_PERM_BONUS(bonus
);
5556 return result
< 0 ? 0 : result
;
5559 uint16
Player::GetMaxSkillValue(uint32 skill
) const
5564 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skill
);
5565 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5568 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr
->second
.pos
));
5570 int32 result
= int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
))));
5571 result
+= SKILL_TEMP_BONUS(bonus
);
5572 result
+= SKILL_PERM_BONUS(bonus
);
5573 return result
< 0 ? 0 : result
;
5576 uint16
Player::GetPureMaxSkillValue(uint32 skill
) const
5581 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skill
);
5582 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5585 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
)));
5588 uint16
Player::GetBaseSkillValue(uint32 skill
) const
5593 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skill
);
5594 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5597 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
))));
5598 result
+= SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr
->second
.pos
)));
5599 return result
< 0 ? 0 : result
;
5602 uint16
Player::GetPureSkillValue(uint32 skill
) const
5607 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skill
);
5608 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5611 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
)));
5614 int16
Player::GetSkillPermBonusValue(uint32 skill
) const
5619 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skill
);
5620 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5623 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr
->second
.pos
)));
5626 int16
Player::GetSkillTempBonusValue(uint32 skill
) const
5631 SkillStatusMap::const_iterator itr
= mSkillStatus
.find(skill
);
5632 if(itr
== mSkillStatus
.end() || itr
->second
.uState
== SKILL_DELETED
)
5635 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(itr
->second
.pos
)));
5638 void Player::SendInitialActionButtons() const
5640 sLog
.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5642 WorldPacket
data(SMSG_ACTION_BUTTONS
, 1+(MAX_ACTION_BUTTONS
*4));
5643 data
<< uint8(1); // can be 0, 1, 2 (talent spec)
5644 ActionButtonList
const& currentActionButtonList
= m_actionButtons
[m_activeSpec
];
5645 for(uint8 button
= 0; button
< MAX_ACTION_BUTTONS
; ++button
)
5647 ActionButtonList::const_iterator itr
= currentActionButtonList
.find(button
);
5648 if(itr
!= currentActionButtonList
.end() && itr
->second
.uState
!= ACTIONBUTTON_DELETED
)
5649 data
<< uint32(itr
->second
.packedData
);
5654 GetSession()->SendPacket( &data
);
5655 sLog
.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5658 bool Player::IsActionButtonDataValid(uint8 button
, uint32 action
, uint8 type
, Player
* player
, bool msg
)
5660 if(button
>= MAX_ACTION_BUTTONS
)
5665 sLog
.outError( "Action %u not added into button %u for player %s: button must be < %u", action
, button
, player
->GetName(), MAX_ACTION_BUTTONS
);
5667 sLog
.outError( "Table `playercreateinfo_action` have action %u into button %u : button must be < %u", action
, button
, MAX_ACTION_BUTTONS
);
5673 if(action
>= MAX_ACTION_BUTTON_ACTION_VALUE
)
5678 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
);
5680 sLog
.outError( "Table `playercreateinfo_action` have action %u into button %u : action must be < %u", action
, button
, MAX_ACTION_BUTTON_ACTION_VALUE
);
5687 case ACTION_BUTTON_SPELL
:
5688 if(!sSpellStore
.LookupEntry(action
))
5693 sLog
.outError( "Spell action %u not added into button %u for player %s: spell not exist", action
, button
, player
->GetName() );
5695 sLog
.outError( "Table `playercreateinfo_action` have spell action %u into button %u: spell not exist", action
, button
);
5700 if(player
&& !player
->HasSpell(action
))
5703 sLog
.outError( "Spell action %u not added into button %u for player %s: player don't known this spell", action
, button
, player
->GetName() );
5707 case ACTION_BUTTON_ITEM
:
5708 if(!ObjectMgr::GetItemPrototype(action
))
5713 sLog
.outError( "Item action %u not added into button %u for player %s: item not exist", action
, button
, player
->GetName() );
5715 sLog
.outError( "Table `playercreateinfo_action` have item action %u into button %u: item not exist", action
, button
);
5721 break; // other cases not checked at this moment
5727 ActionButton
* Player::addActionButton(uint8 spec
, uint8 button
, uint32 action
, uint8 type
)
5729 // check action only for active spec (so not check at copy/load passive spec)
5730 if (spec
== GetActiveSpec() && !IsActionButtonDataValid(button
,action
,type
,this))
5733 // it create new button (NEW state) if need or return existed
5734 ActionButton
& ab
= m_actionButtons
[spec
][button
];
5736 // set data and update to CHANGED if not NEW
5737 ab
.SetActionAndType(action
,ActionButtonType(type
));
5739 sLog
.outDetail("Player '%u' Added Action '%u' (type %u) to Button '%u' for spec %u", GetGUIDLow(), action
, uint32(type
), button
, spec
);
5743 void Player::removeActionButton(uint8 spec
, uint8 button
)
5745 ActionButtonList
& currentActionButtonList
= m_actionButtons
[spec
];
5746 ActionButtonList::iterator buttonItr
= currentActionButtonList
.find(button
);
5747 if (buttonItr
== currentActionButtonList
.end() || buttonItr
->second
.uState
== ACTIONBUTTON_DELETED
)
5750 if (buttonItr
->second
.uState
== ACTIONBUTTON_NEW
)
5751 currentActionButtonList
.erase(buttonItr
); // new and not saved
5753 buttonItr
->second
.uState
= ACTIONBUTTON_DELETED
; // saved, will deleted at next save
5755 sLog
.outDetail("Action Button '%u' Removed from Player '%u' for spec %u", button
, GetGUIDLow(), spec
);
5758 ActionButton
const* Player::GetActionButton(uint8 button
)
5760 ActionButtonList
& currentActionButtonList
= m_actionButtons
[m_activeSpec
];
5761 ActionButtonList::iterator buttonItr
= currentActionButtonList
.find(button
);
5762 if (buttonItr
==currentActionButtonList
.end() || buttonItr
->second
.uState
== ACTIONBUTTON_DELETED
)
5765 return &buttonItr
->second
;
5768 bool Player::SetPosition(float x
, float y
, float z
, float orientation
, bool teleport
)
5770 // prevent crash when a bad coord is sent by the client
5771 if(!MaNGOS::IsValidMapCoord(x
,y
,z
,orientation
))
5773 sLog
.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x
,y
,z
,orientation
,teleport
,GetGUIDLow());
5779 const float old_x
= GetPositionX();
5780 const float old_y
= GetPositionY();
5781 const float old_z
= GetPositionZ();
5782 const float old_r
= GetOrientation();
5784 if( teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
|| old_r
!= orientation
)
5786 if (teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
)
5787 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE
| AURA_INTERRUPT_FLAG_TURNING
);
5789 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING
);
5791 // move and update visible state if need
5792 m
->PlayerRelocation(this, x
, y
, z
, orientation
);
5794 // reread after Map::Relocation
5801 if(GetGroup() && (old_x
!= x
|| old_y
!= y
))
5802 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION
);
5805 // code block for underwater state update
5806 UpdateUnderwaterState(m
, x
, y
, z
);
5808 CheckExploreSystem();
5813 void Player::SaveRecallPosition()
5815 m_recallMap
= GetMapId();
5816 m_recallX
= GetPositionX();
5817 m_recallY
= GetPositionY();
5818 m_recallZ
= GetPositionZ();
5819 m_recallO
= GetOrientation();
5822 void Player::SendMessageToSet(WorldPacket
*data
, bool self
)
5824 Map
* _map
= IsInWorld() ? GetMap() : sMapMgr
.FindMap(GetMapId(), GetInstanceId());
5827 _map
->MessageBroadcast(this, data
, self
);
5831 //if player is not in world and map in not created/already destroyed
5832 //no need to create one, just send packet for itself!
5834 GetSession()->SendPacket(data
);
5837 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
)
5839 Map
* _map
= IsInWorld() ? GetMap() : sMapMgr
.FindMap(GetMapId(), GetInstanceId());
5842 _map
->MessageDistBroadcast(this, data
, dist
, self
);
5847 GetSession()->SendPacket(data
);
5850 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
, bool own_team_only
)
5852 Map
* _map
= IsInWorld() ? GetMap() : sMapMgr
.FindMap(GetMapId(), GetInstanceId());
5855 _map
->MessageDistBroadcast(this, data
, dist
, self
, own_team_only
);
5860 GetSession()->SendPacket(data
);
5863 void Player::SendDirectMessage(WorldPacket
*data
)
5865 GetSession()->SendPacket(data
);
5868 void Player::SendCinematicStart(uint32 CinematicSequenceId
)
5870 WorldPacket
data(SMSG_TRIGGER_CINEMATIC
, 4);
5871 data
<< uint32(CinematicSequenceId
);
5872 SendDirectMessage(&data
);
5875 void Player::SendMovieStart(uint32 MovieId
)
5877 WorldPacket
data(SMSG_TRIGGER_MOVIE
, 4);
5878 data
<< uint32(MovieId
);
5879 SendDirectMessage(&data
);
5882 void Player::CheckExploreSystem()
5890 uint16 areaFlag
= GetBaseMap()->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5891 if(areaFlag
==0xffff)
5893 int offset
= areaFlag
/ 32;
5897 sLog
.outError("Wrong area flag %u in map data for (X: %f Y: %f) point to field PLAYER_EXPLORED_ZONES_1 + %u ( %u must be < 128 ).",areaFlag
,GetPositionX(),GetPositionY(),offset
,offset
);
5901 uint32 val
= (uint32
)(1 << (areaFlag
% 32));
5902 uint32 currFields
= GetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
);
5904 if( !(currFields
& val
) )
5906 SetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
, (uint32
)(currFields
| val
));
5908 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA
);
5910 AreaTableEntry
const *p
= GetAreaEntryByAreaFlagAndMap(areaFlag
,GetMapId());
5913 sLog
.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5915 else if(p
->area_level
> 0)
5917 uint32 area
= p
->ID
;
5918 if (getLevel() >= sWorld
.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL
))
5920 SendExplorationExperience(area
,0);
5924 int32 diff
= int32(getLevel()) - p
->area_level
;
5928 XP
= uint32(sObjectMgr
.GetBaseXP(getLevel()+5)*sWorld
.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE
));
5932 int32 exploration_percent
= (100-((diff
-5)*5));
5933 if (exploration_percent
> 100)
5934 exploration_percent
= 100;
5935 else if (exploration_percent
< 0)
5936 exploration_percent
= 0;
5938 XP
= uint32(sObjectMgr
.GetBaseXP(p
->area_level
)*exploration_percent
/100*sWorld
.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE
));
5942 XP
= uint32(sObjectMgr
.GetBaseXP(p
->area_level
)*sWorld
.getConfig(CONFIG_FLOAT_RATE_XP_EXPLORE
));
5946 SendExplorationExperience(area
,XP
);
5948 sLog
.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area
);
5953 uint32
Player::TeamForRace(uint8 race
)
5955 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5958 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5962 switch(rEntry
->TeamID
)
5964 case 7: return ALLIANCE
;
5965 case 1: return HORDE
;
5968 sLog
.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race
),rEntry
->TeamID
);
5972 uint32
Player::getFactionForRace(uint8 race
)
5974 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5977 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5981 return rEntry
->FactionID
;
5984 void Player::setFactionForRace(uint8 race
)
5986 m_team
= TeamForRace(race
);
5987 setFaction( getFactionForRace(race
) );
5990 ReputationRank
Player::GetReputationRank(uint32 faction
) const
5992 FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(faction
);
5993 return GetReputationMgr().GetRank(factionEntry
);
5996 //Calculate total reputation percent player gain with quest/creature level
5997 int32
Player::CalculateReputationGain(uint32 creatureOrQuestLevel
, int32 rep
, int32 faction
, bool for_quest
)
5999 float percent
= 100.0f
;
6001 float rate
= for_quest
? sWorld
.getConfig(CONFIG_FLOAT_RATE_REPUTATION_LOWLEVEL_QUEST
) : sWorld
.getConfig(CONFIG_FLOAT_RATE_REPUTATION_LOWLEVEL_KILL
);
6003 if (rate
!= 1.0f
&& creatureOrQuestLevel
<= MaNGOS::XP::GetGrayLevel(getLevel()))
6006 float repMod
= (float)GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN
);
6009 repMod
+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN
, faction
);
6011 percent
+= rep
> 0 ? repMod
: -repMod
;
6013 if (percent
<= 0.0f
)
6016 return int32(sWorld
.getConfig(CONFIG_FLOAT_RATE_REPUTATION_GAIN
)*rep
*percent
/100.0f
);
6019 //Calculates how many reputation points player gains in victim's enemy factions
6020 void Player::RewardReputation(Unit
*pVictim
, float rate
)
6022 if(!pVictim
|| pVictim
->GetTypeId() == TYPEID_PLAYER
)
6025 ReputationOnKillEntry
const* Rep
= sObjectMgr
.GetReputationOnKilEntry(((Creature
*)pVictim
)->GetCreatureInfo()->Entry
);
6030 if(Rep
->repfaction1
&& (!Rep
->team_dependent
|| GetTeam()==ALLIANCE
))
6032 int32 donerep1
= CalculateReputationGain(pVictim
->getLevel(), Rep
->repvalue1
, Rep
->repfaction1
, false);
6033 donerep1
= int32(donerep1
*rate
);
6034 FactionEntry
const *factionEntry1
= sFactionStore
.LookupEntry(Rep
->repfaction1
);
6035 uint32 current_reputation_rank1
= GetReputationMgr().GetRank(factionEntry1
);
6036 if (factionEntry1
&& current_reputation_rank1
<= Rep
->reputation_max_cap1
)
6037 GetReputationMgr().ModifyReputation(factionEntry1
, donerep1
);
6039 // Wiki: Team factions value divided by 2
6040 if (factionEntry1
&& Rep
->is_teamaward1
)
6042 FactionEntry
const *team1_factionEntry
= sFactionStore
.LookupEntry(factionEntry1
->team
);
6043 if(team1_factionEntry
)
6044 GetReputationMgr().ModifyReputation(team1_factionEntry
, donerep1
/ 2);
6048 if(Rep
->repfaction2
&& (!Rep
->team_dependent
|| GetTeam()==HORDE
))
6050 int32 donerep2
= CalculateReputationGain(pVictim
->getLevel(), Rep
->repvalue2
, Rep
->repfaction2
, false);
6051 donerep2
= int32(donerep2
*rate
);
6052 FactionEntry
const *factionEntry2
= sFactionStore
.LookupEntry(Rep
->repfaction2
);
6053 uint32 current_reputation_rank2
= GetReputationMgr().GetRank(factionEntry2
);
6054 if (factionEntry2
&& current_reputation_rank2
<= Rep
->reputation_max_cap2
)
6055 GetReputationMgr().ModifyReputation(factionEntry2
, donerep2
);
6057 // Wiki: Team factions value divided by 2
6058 if (factionEntry2
&& Rep
->is_teamaward2
)
6060 FactionEntry
const *team2_factionEntry
= sFactionStore
.LookupEntry(factionEntry2
->team
);
6061 if(team2_factionEntry
)
6062 GetReputationMgr().ModifyReputation(team2_factionEntry
, donerep2
/ 2);
6067 //Calculate how many reputation points player gain with the quest
6068 void Player::RewardReputation(Quest
const *pQuest
)
6070 // quest reputation reward/loss
6071 for(int i
= 0; i
< QUEST_REPUTATIONS_COUNT
; ++i
)
6073 if (!pQuest
->RewRepFaction
[i
])
6076 // For future, this row should be used as "override". Example quests are 10298 and 10870.
6077 // Typically, no diplomacy mod must apply to the final value (flat). Note the formula must be (finalValue = DBvalue/100)
6078 if (pQuest
->RewRepValue
[i
])
6080 int32 rep
= CalculateReputationGain(GetQuestLevelForPlayer(pQuest
), pQuest
->RewRepValue
[i
], pQuest
->RewRepFaction
[i
], true);
6082 if (FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(pQuest
->RewRepFaction
[i
]))
6083 GetReputationMgr().ModifyReputation(factionEntry
, rep
);
6087 uint32 row
= ((pQuest
->RewRepValueId
[i
] < 0) ? 1 : 0) + 1;
6088 uint32 field
= abs(pQuest
->RewRepValueId
[i
]);
6090 if (const QuestFactionRewardEntry
*pRow
= sQuestFactionRewardStore
.LookupEntry(row
))
6092 int32 repPoints
= pRow
->rewardValue
[field
];
6097 repPoints
= CalculateReputationGain(GetQuestLevelForPlayer(pQuest
), repPoints
, pQuest
->RewRepFaction
[i
], true);
6099 if (const FactionEntry
* factionEntry
= sFactionStore
.LookupEntry(pQuest
->RewRepFaction
[i
]))
6100 GetReputationMgr().ModifyReputation(factionEntry
, repPoints
);
6105 // TODO: implement reputation spillover
6108 void Player::UpdateArenaFields(void)
6110 /* arena calcs go here */
6113 void Player::UpdateHonorFields()
6115 /// called when rewarding honor and at each save
6116 time_t now
= time(NULL
);
6117 time_t today
= (time(NULL
) / DAY
) * DAY
;
6119 if(m_lastHonorUpdateTime
< today
)
6121 time_t yesterday
= today
- DAY
;
6123 uint16 kills_today
= PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS
));
6125 // update yesterday's contribution
6126 if(m_lastHonorUpdateTime
>= yesterday
)
6128 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
));
6130 // this is the first update today, reset today's contribution
6131 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, 0);
6132 SetUInt32Value(PLAYER_FIELD_KILLS
, MAKE_PAIR32(0,kills_today
));
6136 // no honor/kills yesterday or today, reset
6137 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0);
6138 SetUInt32Value(PLAYER_FIELD_KILLS
, 0);
6142 m_lastHonorUpdateTime
= now
;
6145 ///Calculate the amount of honor gained based on the victim
6146 ///and the size of the group for which the honor is divided
6147 ///An exact honor value can also be given (overriding the calcs)
6148 bool Player::RewardHonor(Unit
*uVictim
, uint32 groupsize
, float honor
)
6150 // do not reward honor in arenas, but enable onkill spellproc
6153 if(!uVictim
|| uVictim
== this || uVictim
->GetTypeId() != TYPEID_PLAYER
)
6156 if( GetBGTeam() == ((Player
*)uVictim
)->GetBGTeam() )
6162 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
6163 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE
))
6166 uint64 victim_guid
= 0;
6167 uint32 victim_rank
= 0;
6169 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
6170 UpdateHonorFields();
6174 if(!uVictim
|| uVictim
== this || uVictim
->HasAuraType(SPELL_AURA_NO_PVP_CREDIT
))
6177 victim_guid
= uVictim
->GetGUID();
6179 if( uVictim
->GetTypeId() == TYPEID_PLAYER
)
6181 Player
*pVictim
= (Player
*)uVictim
;
6183 if( GetTeam() == pVictim
->GetTeam() && !sWorld
.IsFFAPvPRealm() )
6186 float f
= 1; //need for total kills (?? need more info)
6188 uint32 k_level
= getLevel();
6189 uint32 v_level
= pVictim
->getLevel();
6192 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6194 // [1..14] Alliance honor titles and player name
6195 // [15..28] Horde honor titles and player name
6196 // [29..38] Other title and player name
6198 uint32 victim_title
= pVictim
->GetUInt32Value(PLAYER_CHOSEN_TITLE
);
6199 // Get Killer titles, CharTitlesEntry::bit_index
6201 // title[1..14] -> rank[5..18]
6202 // title[15..28] -> rank[5..18]
6203 // title[other] -> 0
6204 if (victim_title
== 0)
6205 victim_guid
= 0; // Don't show HK: <rank> message, only log.
6206 else if (victim_title
< 15)
6207 victim_rank
= victim_title
+ 4;
6208 else if (victim_title
< 29)
6209 victim_rank
= victim_title
- 14 + 4;
6211 victim_guid
= 0; // Don't show HK: <rank> message, only log.
6214 k_grey
= MaNGOS::XP::GetGrayLevel(k_level
);
6219 float diff_level
= (k_level
== k_grey
) ? 1 : ((float(v_level
) - float(k_grey
)) / (float(k_level
) - float(k_grey
)));
6221 int32 v_rank
=1; //need more info
6223 honor
= ((f
* diff_level
* (190 + v_rank
*10))/6);
6224 honor
*= ((float)k_level
) / 70.0f
; //factor of dependence on levels of the killer
6226 // count the number of playerkills in one day
6227 ApplyModUInt32Value(PLAYER_FIELD_KILLS
, 1, true);
6228 // and those in a lifetime
6229 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 1, true);
6230 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL
);
6231 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS
, pVictim
->getClass());
6232 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE
, pVictim
->getRace());
6236 Creature
*cVictim
= (Creature
*)uVictim
;
6238 if (!cVictim
->isRacialLeader())
6241 honor
= 100; // ??? need more info
6242 victim_rank
= 19; // HK: Leader
6246 if (uVictim
!= NULL
)
6248 honor
*= sWorld
.getConfig(CONFIG_FLOAT_RATE_HONOR
);
6249 honor
*= (GetMaxPositiveAuraModifier(SPELL_AURA_MOD_HONOR_GAIN
) + 100.0f
)/100.0f
;
6254 honor
*= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6257 // honor - for show honor points in log
6258 // victim_guid - for show victim name in log
6259 // victim_rank [1..4] HK: <dishonored rank>
6260 // victim_rank [5..19] HK: <alliance\horde rank>
6261 // victim_rank [0,20+] HK: <>
6262 WorldPacket
data(SMSG_PVP_CREDIT
,4+8+4);
6263 data
<< (uint32
) honor
;
6264 data
<< (uint64
) victim_guid
;
6265 data
<< (uint32
) victim_rank
;
6267 GetSession()->SendPacket(&data
);
6270 ModifyHonorPoints(int32(honor
));
6272 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, uint32(honor
), true);
6276 void Player::ModifyHonorPoints( int32 value
)
6280 if (GetHonorPoints() > sWorld
.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS
))
6281 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS
) + value
);
6283 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() > uint32(-value
) ? GetHonorPoints() + value
: 0);
6286 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() < sWorld
.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS
) - value
? GetHonorPoints() + value
: sWorld
.getConfig(CONFIG_UINT32_MAX_HONOR_POINTS
));
6289 void Player::ModifyArenaPoints( int32 value
)
6293 if (GetArenaPoints() > sWorld
.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS
))
6294 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS
) + value
);
6296 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() > uint32(-value
) ? GetArenaPoints() + value
: 0);
6299 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() < sWorld
.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS
) - value
? GetArenaPoints() + value
: sWorld
.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS
));
6302 uint32
Player::GetGuildIdFromDB(uint64 guid
)
6304 QueryResult
* result
= CharacterDatabase
.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid
));
6308 uint32 id
= result
->Fetch()[0].GetUInt32();
6313 uint32
Player::GetRankFromDB(uint64 guid
)
6315 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid
) );
6318 uint32 v
= result
->Fetch()[0].GetUInt32();
6326 uint32
Player::GetArenaTeamIdFromDB(uint64 guid
, uint8 type
)
6328 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
);
6332 uint32 id
= (*result
)[0].GetUInt32();
6337 uint32
Player::GetZoneIdFromDB(uint64 guid
)
6339 uint32 guidLow
= GUID_LOPART(guid
);
6340 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow
);
6343 Field
* fields
= result
->Fetch();
6344 uint32 zone
= fields
[0].GetUInt32();
6349 // stored zone is zero, use generic and slow zone detection
6350 result
= CharacterDatabase
.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow
);
6353 fields
= result
->Fetch();
6354 uint32 map
= fields
[0].GetUInt32();
6355 float posx
= fields
[1].GetFloat();
6356 float posy
= fields
[2].GetFloat();
6357 float posz
= fields
[3].GetFloat();
6360 zone
= sMapMgr
.GetZoneId(map
,posx
,posy
,posz
);
6363 CharacterDatabase
.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone
, guidLow
);
6369 uint32
Player::GetLevelFromDB(uint64 guid
)
6371 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT level FROM characters WHERE guid='%u'", GUID_LOPART(guid
) );
6375 Field
* fields
= result
->Fetch();
6376 uint32 level
= fields
[0].GetUInt32();
6382 void Player::UpdateArea(uint32 newArea
)
6384 // FFA_PVP flags are area and not zone id dependent
6385 // so apply them accordingly
6386 m_areaUpdateId
= newArea
;
6388 AreaTableEntry
const* area
= GetAreaEntryByAreaID(newArea
);
6390 if(area
&& (area
->flags
& AREA_FLAG_ARENA
))
6397 // remove ffa flag only if not ffapvp realm
6398 // removal in sanctuaries and capitals is handled in zone update
6399 if(IsFFAPvP() && !sWorld
.IsFFAPvPRealm())
6403 UpdateAreaDependentAuras(newArea
);
6406 void Player::UpdateZone(uint32 newZone
, uint32 newArea
)
6408 AreaTableEntry
const* zone
= GetAreaEntryByAreaID(newZone
);
6412 if(m_zoneUpdateId
!= newZone
)
6414 SendInitWorldStates(newZone
, newArea
); // only if really enters to new zone, not just area change, works strange...
6416 if (sWorld
.getConfig(CONFIG_BOOL_WEATHER
))
6418 if(Weather
*wth
= sWorld
.FindWeather(zone
->ID
))
6419 wth
->SendWeatherUpdateToPlayer(this);
6420 else if(!sWorld
.AddWeather(zone
->ID
))
6422 // send fine weather packet to remove old zone's weather
6423 Weather::SendFineWeatherUpdateToPlayer(this);
6428 m_zoneUpdateId
= newZone
;
6429 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
6431 // zone changed, so area changed as well, update it
6432 UpdateArea(newArea
);
6434 // in PvP, any not controlled zone (except zone->team == 6, default case)
6435 // in PvE, only opposition team capital
6439 pvpInfo
.inHostileArea
= GetTeam() != ALLIANCE
&& (sWorld
.IsPvPRealm() || zone
->flags
& AREA_FLAG_CAPITAL
);
6441 case AREATEAM_HORDE
:
6442 pvpInfo
.inHostileArea
= GetTeam() != HORDE
&& (sWorld
.IsPvPRealm() || zone
->flags
& AREA_FLAG_CAPITAL
);
6445 // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6446 pvpInfo
.inHostileArea
= sWorld
.IsPvPRealm() || InBattleGround();
6448 default: // 6 in fact
6449 pvpInfo
.inHostileArea
= false;
6453 if(pvpInfo
.inHostileArea
) // in hostile area
6455 if(!IsPvP() || pvpInfo
.endTimer
!= 0)
6456 UpdatePvP(true, true);
6458 else // in friendly area
6460 if(IsPvP() && !HasFlag(PLAYER_FLAGS
,PLAYER_FLAGS_IN_PVP
) && pvpInfo
.endTimer
== 0)
6461 pvpInfo
.endTimer
= time(0); // start toggle-off
6464 if(zone
->flags
& AREA_FLAG_SANCTUARY
) // in sanctuary
6466 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_SANCTUARY
);
6467 if(sWorld
.IsFFAPvPRealm())
6472 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_SANCTUARY
);
6475 if(zone
->flags
& AREA_FLAG_CAPITAL
) // in capital city
6477 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6478 SetRestType(REST_TYPE_IN_CITY
);
6479 InnEnter(time(0),GetMapId(),0,0,0);
6481 if(sWorld
.IsFFAPvPRealm())
6484 else // anywhere else
6486 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6488 if(GetRestType()==REST_TYPE_IN_TAVERN
) // has been in tavern. Is still in?
6490 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6492 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6493 SetRestType(REST_TYPE_NO
);
6495 if(sWorld
.IsFFAPvPRealm())
6499 else // not in tavern (leave city then)
6501 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6502 SetRestType(REST_TYPE_NO
);
6504 // Set player to FFA PVP when not in rested environment.
6505 if(sWorld
.IsFFAPvPRealm())
6511 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6512 // if player resurrected at teleport this will be applied in resurrect code
6514 DestroyZoneLimitedItem( true, newZone
);
6516 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6517 AutoUnequipOffhandIfNeed();
6519 // recent client version not send leave/join channel packets for built-in local channels
6520 UpdateLocalChannels( newZone
);
6524 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE
);
6526 UpdateZoneDependentAuras(newZone
);
6529 //If players are too far way of duel flag... then player loose the duel
6530 void Player::CheckDuelDistance(time_t currTime
)
6535 uint64 duelFlagGUID
= GetUInt64Value(PLAYER_DUEL_ARBITER
);
6536 GameObject
* obj
= GetMap()->GetGameObject(duelFlagGUID
);
6540 if(duel
->outOfBound
== 0)
6542 if(!IsWithinDistInMap(obj
, 50))
6544 duel
->outOfBound
= currTime
;
6546 WorldPacket
data(SMSG_DUEL_OUTOFBOUNDS
, 0);
6547 GetSession()->SendPacket(&data
);
6552 if(IsWithinDistInMap(obj
, 40))
6554 duel
->outOfBound
= 0;
6556 WorldPacket
data(SMSG_DUEL_INBOUNDS
, 0);
6557 GetSession()->SendPacket(&data
);
6559 else if(currTime
>= (duel
->outOfBound
+10))
6561 DuelComplete(DUEL_FLED
);
6566 void Player::DuelComplete(DuelCompleteType type
)
6568 // duel not requested
6572 WorldPacket
data(SMSG_DUEL_COMPLETE
, (1));
6573 data
<< (uint8
)((type
!= DUEL_INTERUPTED
) ? 1 : 0);
6574 GetSession()->SendPacket(&data
);
6575 duel
->opponent
->GetSession()->SendPacket(&data
);
6577 if(type
!= DUEL_INTERUPTED
)
6579 data
.Initialize(SMSG_DUEL_WINNER
, (1+20)); // we guess size
6580 data
<< (uint8
)((type
==DUEL_WON
) ? 0 : 1); // 0 = just won; 1 = fled
6581 data
<< duel
->opponent
->GetName();
6583 SendMessageToSet(&data
,true);
6586 if (type
== DUEL_WON
)
6588 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL
, 1);
6590 duel
->opponent
->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL
, 1);
6593 //Remove Duel Flag object
6594 GameObject
* obj
= GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER
));
6596 duel
->initiator
->RemoveGameObject(obj
,true);
6599 std::vector
<uint32
> auras2remove
;
6600 AuraMap
const& vAuras
= duel
->opponent
->GetAuras();
6601 for (AuraMap::const_iterator i
= vAuras
.begin(); i
!= vAuras
.end(); ++i
)
6603 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6604 auras2remove
.push_back(i
->second
->GetId());
6607 for(size_t i
=0; i
<auras2remove
.size(); ++i
)
6608 duel
->opponent
->RemoveAurasDueToSpell(auras2remove
[i
]);
6610 auras2remove
.clear();
6611 AuraMap
const& auras
= GetAuras();
6612 for (AuraMap::const_iterator i
= auras
.begin(); i
!= auras
.end(); ++i
)
6614 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == duel
->opponent
->GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6615 auras2remove
.push_back(i
->second
->GetId());
6617 for(size_t i
=0; i
<auras2remove
.size(); ++i
)
6618 RemoveAurasDueToSpell(auras2remove
[i
]);
6620 // cleanup combo points
6621 if(GetComboTarget()==duel
->opponent
->GetGUID())
6623 else if(GetComboTarget()==duel
->opponent
->GetPetGUID())
6626 if(duel
->opponent
->GetComboTarget()==GetGUID())
6627 duel
->opponent
->ClearComboPoints();
6628 else if(duel
->opponent
->GetComboTarget()==GetPetGUID())
6629 duel
->opponent
->ClearComboPoints();
6632 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6633 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6634 duel
->opponent
->SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6635 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6637 delete duel
->opponent
->duel
;
6638 duel
->opponent
->duel
= NULL
;
6643 //---------------------------------------------------------//
6645 void Player::_ApplyItemMods(Item
*item
, uint8 slot
,bool apply
)
6647 if(slot
>= INVENTORY_SLOT_BAG_END
|| !item
)
6650 // not apply/remove mods for broken item
6651 if(item
->IsBroken())
6654 ItemPrototype
const *proto
= item
->GetProto();
6659 sLog
.outDetail("applying mods for item %u ",item
->GetGUIDLow());
6661 uint32 attacktype
= Player::GetAttackBySlot(slot
);
6662 if(attacktype
< MAX_ATTACK
)
6663 _ApplyWeaponDependentAuraMods(item
,WeaponAttackType(attacktype
),apply
);
6665 _ApplyItemBonuses(proto
,slot
,apply
);
6667 if( slot
==EQUIPMENT_SLOT_RANGED
)
6668 _ApplyAmmoBonuses();
6670 ApplyItemEquipSpell(item
,apply
);
6671 ApplyEnchantment(item
, apply
);
6673 if(proto
->Socket
[0].Color
) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6674 CorrectMetaGemEnchants(slot
, apply
);
6676 sLog
.outDebug("_ApplyItemMods complete.");
6679 void Player::_ApplyItemBonuses(ItemPrototype
const *proto
, uint8 slot
, bool apply
, bool only_level_scale
/*= false*/)
6681 if (slot
>= INVENTORY_SLOT_BAG_END
|| !proto
)
6684 ScalingStatDistributionEntry
const *ssd
= proto
->ScalingStatDistribution
? sScalingStatDistributionStore
.LookupEntry(proto
->ScalingStatDistribution
) : NULL
;
6685 if (only_level_scale
&& !ssd
)
6688 // req. check at equip, but allow use for extended range if range limit max level, set proper level
6689 uint32 ssd_level
= getLevel();
6690 if (ssd
&& ssd_level
> ssd
->MaxLevel
)
6691 ssd_level
= ssd
->MaxLevel
;
6693 ScalingStatValuesEntry
const *ssv
= proto
->ScalingStatValue
? sScalingStatValuesStore
.LookupEntry(ssd_level
) : NULL
;
6694 if (only_level_scale
&& !ssv
)
6697 for (uint32 i
= 0; i
< MAX_ITEM_PROTO_STATS
; ++i
)
6699 uint32 statType
= 0;
6701 // If set ScalingStatDistribution need get stats and values from it
6704 if (ssd
->StatMod
[i
] < 0)
6706 statType
= ssd
->StatMod
[i
];
6707 val
= (ssv
->getssdMultiplier(proto
->ScalingStatValue
) * ssd
->Modifier
[i
]) / 10000;
6711 if (i
>= proto
->StatsCount
)
6713 statType
= proto
->ItemStat
[i
].ItemStatType
;
6714 val
= proto
->ItemStat
[i
].ItemStatValue
;
6723 HandleStatModifier(UNIT_MOD_MANA
, BASE_VALUE
, float(val
), apply
);
6725 case ITEM_MOD_HEALTH
: // modify HP
6726 HandleStatModifier(UNIT_MOD_HEALTH
, BASE_VALUE
, float(val
), apply
);
6728 case ITEM_MOD_AGILITY
: // modify agility
6729 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, BASE_VALUE
, float(val
), apply
);
6730 ApplyStatBuffMod(STAT_AGILITY
, float(val
), apply
);
6732 case ITEM_MOD_STRENGTH
: //modify strength
6733 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, BASE_VALUE
, float(val
), apply
);
6734 ApplyStatBuffMod(STAT_STRENGTH
, float(val
), apply
);
6736 case ITEM_MOD_INTELLECT
: //modify intellect
6737 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, BASE_VALUE
, float(val
), apply
);
6738 ApplyStatBuffMod(STAT_INTELLECT
, float(val
), apply
);
6740 case ITEM_MOD_SPIRIT
: //modify spirit
6741 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, BASE_VALUE
, float(val
), apply
);
6742 ApplyStatBuffMod(STAT_SPIRIT
, float(val
), apply
);
6744 case ITEM_MOD_STAMINA
: //modify stamina
6745 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, BASE_VALUE
, float(val
), apply
);
6746 ApplyStatBuffMod(STAT_STAMINA
, float(val
), apply
);
6748 case ITEM_MOD_DEFENSE_SKILL_RATING
:
6749 ApplyRatingMod(CR_DEFENSE_SKILL
, int32(val
), apply
);
6751 case ITEM_MOD_DODGE_RATING
:
6752 ApplyRatingMod(CR_DODGE
, int32(val
), apply
);
6754 case ITEM_MOD_PARRY_RATING
:
6755 ApplyRatingMod(CR_PARRY
, int32(val
), apply
);
6757 case ITEM_MOD_BLOCK_RATING
:
6758 ApplyRatingMod(CR_BLOCK
, int32(val
), apply
);
6760 case ITEM_MOD_HIT_MELEE_RATING
:
6761 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6763 case ITEM_MOD_HIT_RANGED_RATING
:
6764 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6766 case ITEM_MOD_HIT_SPELL_RATING
:
6767 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6769 case ITEM_MOD_CRIT_MELEE_RATING
:
6770 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6772 case ITEM_MOD_CRIT_RANGED_RATING
:
6773 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6775 case ITEM_MOD_CRIT_SPELL_RATING
:
6776 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6778 case ITEM_MOD_HIT_TAKEN_MELEE_RATING
:
6779 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6781 case ITEM_MOD_HIT_TAKEN_RANGED_RATING
:
6782 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6784 case ITEM_MOD_HIT_TAKEN_SPELL_RATING
:
6785 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6787 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING
:
6788 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6790 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING
:
6791 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6793 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING
:
6794 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6796 case ITEM_MOD_HASTE_MELEE_RATING
:
6797 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6799 case ITEM_MOD_HASTE_RANGED_RATING
:
6800 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6802 case ITEM_MOD_HASTE_SPELL_RATING
:
6803 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6805 case ITEM_MOD_HIT_RATING
:
6806 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6807 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6808 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6810 case ITEM_MOD_CRIT_RATING
:
6811 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6812 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6813 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6815 case ITEM_MOD_HIT_TAKEN_RATING
:
6816 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6817 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6818 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6820 case ITEM_MOD_CRIT_TAKEN_RATING
:
6821 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6822 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6823 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6825 case ITEM_MOD_RESILIENCE_RATING
:
6826 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6827 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6828 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6830 case ITEM_MOD_HASTE_RATING
:
6831 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6832 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6833 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6835 case ITEM_MOD_EXPERTISE_RATING
:
6836 ApplyRatingMod(CR_EXPERTISE
, int32(val
), apply
);
6838 case ITEM_MOD_ATTACK_POWER
:
6839 HandleStatModifier(UNIT_MOD_ATTACK_POWER
, TOTAL_VALUE
, float(val
), apply
);
6840 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(val
), apply
);
6842 case ITEM_MOD_RANGED_ATTACK_POWER
:
6843 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(val
), apply
);
6845 case ITEM_MOD_MANA_REGENERATION
:
6846 ApplyManaRegenBonus(int32(val
), apply
);
6848 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
6849 ApplyRatingMod(CR_ARMOR_PENETRATION
, int32(val
), apply
);
6851 case ITEM_MOD_SPELL_POWER
:
6852 ApplySpellPowerBonus(int32(val
), apply
);
6854 // depricated item mods
6855 case ITEM_MOD_FERAL_ATTACK_POWER
:
6856 case ITEM_MOD_SPELL_HEALING_DONE
:
6857 case ITEM_MOD_SPELL_DAMAGE_DONE
:
6862 // Apply Spell Power from ScalingStatValue if set
6865 if (int32 spellbonus
= ssv
->getSpellBonus(proto
->ScalingStatValue
))
6866 ApplySpellPowerBonus(spellbonus
, apply
);
6869 // If set ScalingStatValue armor get it or use item armor
6870 uint32 armor
= proto
->Armor
;
6873 if (uint32 ssvarmor
= ssv
->getArmorMod(proto
->ScalingStatValue
))
6876 // Add armor bonus from ArmorDamageModifier if > 0
6877 if (proto
->ArmorDamageModifier
> 0)
6878 armor
+= uint32(proto
->ArmorDamageModifier
);
6881 HandleStatModifier(UNIT_MOD_ARMOR
, BASE_VALUE
, float(armor
), apply
);
6884 HandleBaseModValue(SHIELD_BLOCK_VALUE
, FLAT_MOD
, float(proto
->Block
), apply
);
6887 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY
, BASE_VALUE
, float(proto
->HolyRes
), apply
);
6890 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE
, BASE_VALUE
, float(proto
->FireRes
), apply
);
6892 if (proto
->NatureRes
)
6893 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE
, BASE_VALUE
, float(proto
->NatureRes
), apply
);
6895 if (proto
->FrostRes
)
6896 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST
, BASE_VALUE
, float(proto
->FrostRes
), apply
);
6898 if (proto
->ShadowRes
)
6899 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW
, BASE_VALUE
, float(proto
->ShadowRes
), apply
);
6901 if (proto
->ArcaneRes
)
6902 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE
, BASE_VALUE
, float(proto
->ArcaneRes
), apply
);
6904 WeaponAttackType attType
= BASE_ATTACK
;
6905 float damage
= 0.0f
;
6907 if( slot
== EQUIPMENT_SLOT_RANGED
&& (
6908 proto
->InventoryType
== INVTYPE_RANGED
|| proto
->InventoryType
== INVTYPE_THROWN
||
6909 proto
->InventoryType
== INVTYPE_RANGEDRIGHT
))
6911 attType
= RANGED_ATTACK
;
6913 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6915 attType
= OFF_ATTACK
;
6918 float minDamage
= proto
->Damage
[0].DamageMin
;
6919 float maxDamage
= proto
->Damage
[0].DamageMax
;
6921 // If set dpsMod in ScalingStatValue use it for min (70% from average), max (130% from average) damage
6924 if ((extraDPS
= ssv
->getDPSMod(proto
->ScalingStatValue
)))
6926 float average
= extraDPS
* proto
->Delay
/ 1000.0f
;
6927 minDamage
= 0.7f
* average
;
6928 maxDamage
= 1.3f
* average
;
6933 damage
= apply
? minDamage
: BASE_MINDAMAGE
;
6934 SetBaseWeaponDamage(attType
, MINDAMAGE
, damage
);
6935 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6940 damage
= apply
? maxDamage
: BASE_MAXDAMAGE
;
6941 SetBaseWeaponDamage(attType
, MAXDAMAGE
, damage
);
6944 // Apply feral bonus from ScalingStatValue if set
6947 if (int32 feral_bonus
= ssv
->getFeralBonus(proto
->ScalingStatValue
))
6948 ApplyFeralAPBonus(feral_bonus
, apply
);
6950 // Druids get feral AP bonus from weapon dps (lso use DPS from ScalingStatValue)
6951 if(getClass() == CLASS_DRUID
)
6953 int32 feral_bonus
= proto
->getFeralBonus(extraDPS
);
6954 if (feral_bonus
> 0)
6955 ApplyFeralAPBonus(feral_bonus
, apply
);
6958 if(!IsUseEquipedWeapon(slot
==EQUIPMENT_SLOT_MAINHAND
))
6963 if(slot
== EQUIPMENT_SLOT_RANGED
)
6964 SetAttackTime(RANGED_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6965 else if(slot
==EQUIPMENT_SLOT_MAINHAND
)
6966 SetAttackTime(BASE_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6967 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6968 SetAttackTime(OFF_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6971 if(CanModifyStats() && (damage
|| proto
->Delay
))
6972 UpdateDamagePhysical(attType
);
6975 void Player::_ApplyWeaponDependentAuraMods(Item
*item
,WeaponAttackType attackType
,bool apply
)
6977 AuraList
const& auraCritList
= GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT
);
6978 for(AuraList::const_iterator itr
= auraCritList
.begin(); itr
!=auraCritList
.end();++itr
)
6979 _ApplyWeaponDependentAuraCritMod(item
,attackType
,*itr
,apply
);
6981 AuraList
const& auraDamageFlatList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE
);
6982 for(AuraList::const_iterator itr
= auraDamageFlatList
.begin(); itr
!=auraDamageFlatList
.end();++itr
)
6983 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6985 AuraList
const& auraDamagePCTList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
);
6986 for(AuraList::const_iterator itr
= auraDamagePCTList
.begin(); itr
!=auraDamagePCTList
.end();++itr
)
6987 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6990 void Player::_ApplyWeaponDependentAuraCritMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6992 // generic not weapon specific case processes in aura code
6993 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6996 BaseModGroup mod
= BASEMOD_END
;
6999 case BASE_ATTACK
: mod
= CRIT_PERCENTAGE
; break;
7000 case OFF_ATTACK
: mod
= OFFHAND_CRIT_PERCENTAGE
;break;
7001 case RANGED_ATTACK
: mod
= RANGED_CRIT_PERCENTAGE
; break;
7005 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
7007 HandleBaseModValue(mod
, FLAT_MOD
, float (aura
->GetModifier()->m_amount
), apply
);
7011 void Player::_ApplyWeaponDependentAuraDamageMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
7013 // ignore spell mods for not wands
7014 Modifier
const* modifier
= aura
->GetModifier();
7015 if((modifier
->m_miscvalue
& SPELL_SCHOOL_MASK_NORMAL
)==0 && (getClassMask() & CLASSMASK_WAND_USERS
)==0)
7018 // generic not weapon specific case processes in aura code
7019 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
7022 UnitMods unitMod
= UNIT_MOD_END
;
7025 case BASE_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_MAINHAND
; break;
7026 case OFF_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_OFFHAND
; break;
7027 case RANGED_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_RANGED
; break;
7031 UnitModifierType unitModType
= TOTAL_VALUE
;
7032 switch(modifier
->m_auraname
)
7034 case SPELL_AURA_MOD_DAMAGE_DONE
: unitModType
= TOTAL_VALUE
; break;
7035 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
: unitModType
= TOTAL_PCT
; break;
7039 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
7041 HandleStatModifier(unitMod
, unitModType
, float(modifier
->m_amount
),apply
);
7045 void Player::ApplyItemEquipSpell(Item
*item
, bool apply
, bool form_change
)
7050 ItemPrototype
const *proto
= item
->GetProto();
7054 for (int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
7056 _Spell
const& spellData
= proto
->Spells
[i
];
7059 if(!spellData
.SpellId
)
7062 // wrong triggering type
7063 if(apply
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_EQUIP
)
7066 // check if it is valid spell
7067 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellData
.SpellId
);
7071 ApplyEquipSpell(spellproto
,item
,apply
,form_change
);
7075 void Player::ApplyEquipSpell(SpellEntry
const* spellInfo
, Item
* item
, bool apply
, bool form_change
)
7079 // Cannot be used in this stance/form
7080 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
) != SPELL_CAST_OK
)
7083 if(form_change
) // check aura active state from other form
7086 for (int k
=0; k
< MAX_EFFECT_INDEX
; ++k
)
7088 spellEffectPair spair
= spellEffectPair(spellInfo
->Id
, SpellEffectIndex(k
));
7089 for (AuraMap::const_iterator iter
= m_Auras
.lower_bound(spair
); iter
!= m_Auras
.upper_bound(spair
); ++iter
)
7091 if(!item
|| iter
->second
->GetCastItemGUID() == item
->GetGUID())
7101 if(found
) // and skip re-cast already active aura at form change
7105 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item
? "item" : "itemset"), spellInfo
->Id
);
7107 CastSpell(this,spellInfo
,true,item
);
7111 if(form_change
) // check aura compatibility
7113 // Cannot be used in this stance/form
7114 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
)==SPELL_CAST_OK
)
7115 return; // and remove only not compatible at form change
7119 RemoveAurasDueToItemSpell(item
,spellInfo
->Id
); // un-apply all spells , not only at-equipped
7121 RemoveAurasDueToSpell(spellInfo
->Id
); // un-apply spell (item set case)
7125 void Player::UpdateEquipSpellsAtFormChange()
7127 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
7129 if(m_items
[i
] && !m_items
[i
]->IsBroken())
7131 ApplyItemEquipSpell(m_items
[i
],false,true); // remove spells that not fit to form
7132 ApplyItemEquipSpell(m_items
[i
],true,true); // add spells that fit form but not active
7136 // item set bonuses not dependent from item broken state
7137 for(size_t setindex
= 0; setindex
< ItemSetEff
.size(); ++setindex
)
7139 ItemSetEffect
* eff
= ItemSetEff
[setindex
];
7143 for(uint32 y
=0;y
<8; ++y
)
7145 SpellEntry
const* spellInfo
= eff
->spells
[y
];
7149 ApplyEquipSpell(spellInfo
,NULL
,false,true); // remove spells that not fit to form
7150 ApplyEquipSpell(spellInfo
,NULL
,true,true); // add spells that fit form but not active
7155 void Player::CastItemCombatSpell(Unit
* Target
, WeaponAttackType attType
)
7157 Item
*item
= GetWeaponForAttack(attType
, true, false);
7161 ItemPrototype
const *proto
= item
->GetProto();
7165 if (!Target
|| Target
== this )
7168 for (int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
7170 _Spell
const& spellData
= proto
->Spells
[i
];
7173 if(!spellData
.SpellId
)
7176 // wrong triggering type
7177 if(spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_CHANCE_ON_HIT
)
7180 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
7183 sLog
.outError("WORLD: unknown Item spellid %i", spellData
.SpellId
);
7187 // not allow proc extra attack spell at extra attack
7188 if( m_extraAttacks
&& IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_ADD_EXTRA_ATTACKS
) )
7191 float chance
= (float)spellInfo
->procChance
;
7193 if(spellData
.SpellPPMRate
)
7195 uint32 WeaponSpeed
= proto
->Delay
;
7196 chance
= GetPPMProcChance(WeaponSpeed
, spellData
.SpellPPMRate
);
7198 else if(chance
> 100.0f
)
7200 chance
= GetWeaponProcChance();
7203 if (roll_chance_f(chance
))
7204 CastSpell(Target
, spellInfo
->Id
, true, item
);
7207 // item combat enchantments
7208 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
7210 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
7211 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
7212 if(!pEnchant
) continue;
7213 for (int s
= 0; s
< 3; ++s
)
7215 if (pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
)
7218 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
7221 sLog
.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
7225 // Use first rank to access spell item enchant procs
7226 float ppmRate
= sSpellMgr
.GetItemEnchantProcChance(spellInfo
->Id
);
7228 float chance
= ppmRate
7229 ? GetPPMProcChance(proto
->Delay
, ppmRate
)
7230 : pEnchant
->amount
[s
] != 0 ? float(pEnchant
->amount
[s
]) : GetWeaponProcChance();
7233 ApplySpellMod(spellInfo
->Id
,SPELLMOD_CHANCE_OF_SUCCESS
,chance
);
7234 ApplySpellMod(spellInfo
->Id
,SPELLMOD_FREQUENCY_OF_SUCCESS
,chance
);
7236 if (roll_chance_f(chance
))
7238 if(IsPositiveSpell(pEnchant
->spellid
[s
]))
7239 CastSpell(this, pEnchant
->spellid
[s
], true, item
);
7241 CastSpell(Target
, pEnchant
->spellid
[s
], true, item
);
7247 void Player::CastItemUseSpell(Item
*item
,SpellCastTargets
const& targets
,uint8 cast_count
, uint32 glyphIndex
)
7249 ItemPrototype
const* proto
= item
->GetProto();
7250 // special learning case
7251 if(proto
->Spells
[0].SpellId
==SPELL_ID_GENERIC_LEARN
|| proto
->Spells
[0].SpellId
==SPELL_ID_GENERIC_LEARN_PET
)
7253 uint32 learn_spell_id
= proto
->Spells
[0].SpellId
;
7254 uint32 learning_spell_id
= proto
->Spells
[1].SpellId
;
7256 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(learn_spell_id
);
7259 sLog
.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto
->ItemId
, learn_spell_id
);
7260 SendEquipError(EQUIP_ERR_NONE
, item
);
7264 Spell
*spell
= new Spell(this, spellInfo
, false);
7265 spell
->m_CastItem
= item
;
7266 spell
->m_cast_count
= cast_count
; //set count of casts
7267 spell
->m_currentBasePoints
[0] = learning_spell_id
;
7268 spell
->prepare(&targets
);
7272 // use triggered flag only for items with many spell casts and for not first cast
7275 // item spells casted at use
7276 for(int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
7278 _Spell
const& spellData
= proto
->Spells
[i
];
7281 if(!spellData
.SpellId
)
7284 // wrong triggering type
7285 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_NO_DELAY_USE
)
7288 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
7291 sLog
.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto
->ItemId
, spellData
.SpellId
);
7295 Spell
*spell
= new Spell(this, spellInfo
, (count
> 0));
7296 spell
->m_CastItem
= item
;
7297 spell
->m_cast_count
= cast_count
; // set count of casts
7298 spell
->m_glyphIndex
= glyphIndex
; // glyph index
7299 spell
->prepare(&targets
);
7304 // Item enchantments spells casted at use
7305 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
7307 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
7308 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
7309 if(!pEnchant
) continue;
7310 for (int s
= 0; s
< 3; ++s
)
7312 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL
)
7315 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
7318 sLog
.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
7322 Spell
*spell
= new Spell(this, spellInfo
, (count
> 0));
7323 spell
->m_CastItem
= item
;
7324 spell
->m_cast_count
= cast_count
; // set count of casts
7325 spell
->m_glyphIndex
= glyphIndex
; // glyph index
7326 spell
->prepare(&targets
);
7333 void Player::_RemoveAllItemMods()
7335 sLog
.outDebug("_RemoveAllItemMods start.");
7337 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
7341 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7345 // item set bonuses not dependent from item broken state
7347 RemoveItemsSetItem(this,proto
);
7349 if(m_items
[i
]->IsBroken())
7352 ApplyItemEquipSpell(m_items
[i
],false);
7353 ApplyEnchantment(m_items
[i
], false);
7357 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
7361 if(m_items
[i
]->IsBroken())
7363 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7367 uint32 attacktype
= Player::GetAttackBySlot(i
);
7368 if(attacktype
< MAX_ATTACK
)
7369 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),false);
7371 _ApplyItemBonuses(proto
,i
, false);
7373 if( i
== EQUIPMENT_SLOT_RANGED
)
7374 _ApplyAmmoBonuses();
7378 sLog
.outDebug("_RemoveAllItemMods complete.");
7381 void Player::_ApplyAllItemMods()
7383 sLog
.outDebug("_ApplyAllItemMods start.");
7385 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
7389 if(m_items
[i
]->IsBroken())
7392 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7396 uint32 attacktype
= Player::GetAttackBySlot(i
);
7397 if(attacktype
< MAX_ATTACK
)
7398 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),true);
7400 _ApplyItemBonuses(proto
,i
, true);
7402 if( i
== EQUIPMENT_SLOT_RANGED
)
7403 _ApplyAmmoBonuses();
7407 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
7411 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7415 // item set bonuses not dependent from item broken state
7417 AddItemsSetItem(this,m_items
[i
]);
7419 if(m_items
[i
]->IsBroken())
7422 ApplyItemEquipSpell(m_items
[i
],true);
7423 ApplyEnchantment(m_items
[i
], true);
7427 sLog
.outDebug("_ApplyAllItemMods complete.");
7430 void Player::_ApplyAllLevelScaleItemMods(bool apply
)
7432 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
7436 if(m_items
[i
]->IsBroken())
7439 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7443 _ApplyItemBonuses(proto
,i
, apply
, true);
7448 void Player::_ApplyAmmoBonuses()
7451 uint32 ammo_id
= GetUInt32Value(PLAYER_AMMO_ID
);
7455 float currentAmmoDPS
;
7457 ItemPrototype
const *ammo_proto
= ObjectMgr::GetItemPrototype( ammo_id
);
7458 if( !ammo_proto
|| ammo_proto
->Class
!=ITEM_CLASS_PROJECTILE
|| !CheckAmmoCompatibility(ammo_proto
))
7459 currentAmmoDPS
= 0.0f
;
7461 currentAmmoDPS
= ammo_proto
->Damage
[0].DamageMin
;
7463 if(currentAmmoDPS
== GetAmmoDPS())
7466 m_ammoDPS
= currentAmmoDPS
;
7468 if(CanModifyStats())
7469 UpdateDamagePhysical(RANGED_ATTACK
);
7472 bool Player::CheckAmmoCompatibility(const ItemPrototype
*ammo_proto
) const
7477 // check ranged weapon
7478 Item
*weapon
= GetWeaponForAttack( RANGED_ATTACK
, true, false );
7482 ItemPrototype
const* weapon_proto
= weapon
->GetProto();
7483 if(!weapon_proto
|| weapon_proto
->Class
!=ITEM_CLASS_WEAPON
)
7486 // check ammo ws. weapon compatibility
7487 switch(weapon_proto
->SubClass
)
7489 case ITEM_SUBCLASS_WEAPON_BOW
:
7490 case ITEM_SUBCLASS_WEAPON_CROSSBOW
:
7491 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_ARROW
)
7494 case ITEM_SUBCLASS_WEAPON_GUN
:
7495 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_BULLET
)
7505 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7506 Called by remove insignia spell effect */
7507 void Player::RemovedInsignia(Player
* looterPlr
)
7509 if (!GetBattleGroundId())
7512 // If not released spirit, do it !
7513 if(m_deathTimer
> 0)
7520 Corpse
*corpse
= GetCorpse();
7524 // We have to convert player corpse to bones, not to be able to resurrect there
7525 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7526 Corpse
*bones
= sObjectAccessor
.ConvertCorpseForPlayer(GetGUID(),true);
7530 // Now we must make bones lootable, and send player loot
7531 bones
->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS
, CORPSE_DYNFLAG_LOOTABLE
);
7533 // We store the level of our player in the gold field
7534 // We retrieve this information at Player::SendLoot()
7535 bones
->loot
.gold
= getLevel();
7536 bones
->lootRecipient
= looterPlr
;
7537 looterPlr
->SendLoot(bones
->GetGUID(), LOOT_INSIGNIA
);
7540 void Player::SendLootRelease(ObjectGuid guid
)
7542 WorldPacket
data( SMSG_LOOT_RELEASE_RESPONSE
, (8+1) );
7545 SendDirectMessage( &data
);
7548 void Player::SendLoot(ObjectGuid guid
, LootType loot_type
)
7550 if (uint64 lguid
= GetLootGUID())
7551 m_session
->DoLootRelease(lguid
);
7554 PermissionTypes permission
= ALL_PERMISSION
;
7556 sLog
.outDebug("Player::SendLoot");
7557 switch(guid
.GetHigh())
7559 case HIGHGUID_GAMEOBJECT
:
7561 sLog
.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7562 GameObject
*go
= GetMap()->GetGameObject(guid
);
7564 // not check distance for GO in case owned GO (fishing bobber case, for example)
7565 // And permit out of range GO with no owner in case fishing hole
7566 if (!go
|| (loot_type
!= LOOT_FISHINGHOLE
&& (loot_type
!= LOOT_FISHING
|| go
->GetOwnerGUID() != GetGUID()) && !go
->IsWithinDistInMap(this,INTERACTION_DISTANCE
)))
7568 SendLootRelease(guid
);
7574 if (go
->getLootState() == GO_READY
)
7576 uint32 lootid
= go
->GetGOInfo()->GetLootId();
7577 if ((go
->GetEntry() == BG_AV_OBJECTID_MINE_N
|| go
->GetEntry() == BG_AV_OBJECTID_MINE_S
))
7578 if (BattleGround
*bg
= GetBattleGround())
7579 if (bg
->GetTypeID() == BATTLEGROUND_AV
)
7580 if (!(((BattleGroundAV
*)bg
)->PlayerCanDoMineQuest(go
->GetEntry(), GetTeam())))
7582 SendLootRelease(guid
);
7588 sLog
.outDebug(" if(lootid)");
7590 loot
->FillLoot(lootid
, LootTemplates_Gameobject
, this, false);
7593 if (loot_type
== LOOT_FISHING
)
7594 go
->getFishLoot(loot
,this);
7596 go
->SetLootState(GO_ACTIVATED
);
7602 Item
*item
= GetItemByGuid( guid
);
7606 SendLootRelease(guid
);
7612 if (!item
->m_lootGenerated
)
7614 item
->m_lootGenerated
= true;
7619 case LOOT_DISENCHANTING
:
7620 loot
->FillLoot(item
->GetProto()->DisenchantID
, LootTemplates_Disenchant
, this,true);
7622 case LOOT_PROSPECTING
:
7623 loot
->FillLoot(item
->GetEntry(), LootTemplates_Prospecting
, this,true);
7626 loot
->FillLoot(item
->GetEntry(), LootTemplates_Milling
, this,true);
7629 loot
->FillLoot(item
->GetEntry(), LootTemplates_Item
, this,true);
7630 loot
->generateMoneyLoot(item
->GetProto()->MinMoneyLoot
,item
->GetProto()->MaxMoneyLoot
);
7636 case HIGHGUID_CORPSE
: // remove insignia
7638 Corpse
*bones
= GetMap()->GetCorpse(guid
);
7640 if (!bones
|| !((loot_type
== LOOT_CORPSE
) || (loot_type
== LOOT_INSIGNIA
)) || (bones
->GetType() != CORPSE_BONES
) )
7642 SendLootRelease(guid
);
7646 loot
= &bones
->loot
;
7648 if (!bones
->lootForBody
)
7650 bones
->lootForBody
= true;
7651 uint32 pLevel
= bones
->loot
.gold
;
7652 bones
->loot
.clear();
7653 if (GetBattleGround()->GetTypeID() == BATTLEGROUND_AV
)
7654 loot
->FillLoot(0, LootTemplates_Creature
, this, false);
7655 // It may need a better formula
7656 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7657 bones
->loot
.gold
= (uint32
)( urand(50, 150) * 0.016f
* pow( ((float)pLevel
)/5.76f
, 2.5f
) * sWorld
.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY
) );
7660 if (bones
->lootRecipient
!= this)
7661 permission
= NONE_PERMISSION
;
7666 Creature
*creature
= GetMap()->GetCreature(guid
);
7668 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7669 if (!creature
|| creature
->isAlive()!=(loot_type
== LOOT_PICKPOCKETING
) || !creature
->IsWithinDistInMap(this,INTERACTION_DISTANCE
))
7671 SendLootRelease(guid
);
7675 if (loot_type
== LOOT_PICKPOCKETING
&& IsFriendlyTo(creature
))
7677 SendLootRelease(guid
);
7681 loot
= &creature
->loot
;
7683 if (loot_type
== LOOT_PICKPOCKETING
)
7685 if (!creature
->lootForPickPocketed
)
7687 creature
->lootForPickPocketed
= true;
7690 if (uint32 lootid
= creature
->GetCreatureInfo()->pickpocketLootId
)
7691 loot
->FillLoot(lootid
, LootTemplates_Pickpocketing
, this, false);
7693 // Generate extra money for pick pocket loot
7694 const uint32 a
= urand(0, creature
->getLevel()/2);
7695 const uint32 b
= urand(0, getLevel()/2);
7696 loot
->gold
= uint32(10 * (a
+ b
) * sWorld
.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY
));
7701 // the player whose group may loot the corpse
7702 Player
*recipient
= creature
->GetLootRecipient();
7705 creature
->SetLootRecipient(this);
7709 if (creature
->lootForPickPocketed
)
7711 creature
->lootForPickPocketed
= false;
7715 if (!creature
->lootForBody
)
7717 creature
->lootForBody
= true;
7720 if (uint32 lootid
= creature
->GetCreatureInfo()->lootid
)
7721 loot
->FillLoot(lootid
, LootTemplates_Creature
, recipient
, false);
7723 loot
->generateMoneyLoot(creature
->GetCreatureInfo()->mingold
,creature
->GetCreatureInfo()->maxgold
);
7725 if (Group
* group
= recipient
->GetGroup())
7727 group
->UpdateLooterGuid(creature
,true);
7729 switch (group
->GetLootMethod())
7732 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7733 group
->GroupLoot(recipient
->GetGUID(), loot
, creature
);
7735 case NEED_BEFORE_GREED
:
7736 group
->NeedBeforeGreed(recipient
->GetGUID(), loot
, creature
);
7739 group
->MasterLoot(recipient
->GetGUID(), loot
, creature
);
7747 // possible only if creature->lootForBody && loot->empty() at spell cast check
7748 if (loot_type
== LOOT_SKINNING
)
7751 loot
->FillLoot(creature
->GetCreatureInfo()->SkinLootId
, LootTemplates_Skinning
, this, false);
7753 // set group rights only for loot_type != LOOT_SKINNING
7756 if(Group
* group
= GetGroup())
7758 if (group
== recipient
->GetGroup())
7760 if (group
->GetLootMethod() == FREE_FOR_ALL
)
7761 permission
= ALL_PERMISSION
;
7762 else if (group
->GetLooterGuid() == GetGUID())
7764 if (group
->GetLootMethod() == MASTER_LOOT
)
7765 permission
= MASTER_PERMISSION
;
7767 permission
= ALL_PERMISSION
;
7770 permission
= GROUP_PERMISSION
;
7773 permission
= NONE_PERMISSION
;
7775 else if (recipient
== this)
7776 permission
= ALL_PERMISSION
;
7778 permission
= NONE_PERMISSION
;
7785 sLog
.outError("%s is unsupported for looting.", guid
.GetString().c_str());
7792 // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
7795 case LOOT_INSIGNIA
: loot_type
= LOOT_SKINNING
; break;
7796 case LOOT_FISHINGHOLE
: loot_type
= LOOT_FISHING
; break;
7800 // need know merged fishing/corpse loot type for achievements
7801 loot
->loot_type
= loot_type
;
7803 WorldPacket
data(SMSG_LOOT_RESPONSE
, (9+50)); // we guess size
7806 data
<< uint8(loot_type
);
7807 data
<< LootView(*loot
, this, permission
);
7809 SendDirectMessage(&data
);
7811 // add 'this' player as one of the players that are looting 'loot'
7812 if (permission
!= NONE_PERMISSION
)
7813 loot
->AddLooter(GetGUID());
7815 if (loot_type
== LOOT_CORPSE
&& !guid
.IsItem())
7816 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_LOOTING
);
7819 void Player::SendNotifyLootMoneyRemoved()
7821 WorldPacket
data(SMSG_LOOT_CLEAR_MONEY
, 0);
7822 GetSession()->SendPacket( &data
);
7825 void Player::SendNotifyLootItemRemoved(uint8 lootSlot
)
7827 WorldPacket
data(SMSG_LOOT_REMOVED
, 1);
7828 data
<< uint8(lootSlot
);
7829 GetSession()->SendPacket( &data
);
7832 void Player::SendUpdateWorldState(uint32 Field
, uint32 Value
)
7834 WorldPacket
data(SMSG_UPDATE_WORLD_STATE
, 8);
7837 GetSession()->SendPacket(&data
);
7840 void Player::SendInitWorldStates(uint32 zoneid
, uint32 areaid
)
7842 // data depends on zoneid/mapid...
7843 BattleGround
* bg
= GetBattleGround();
7844 uint16 NumberOfFields
= 0;
7845 uint32 mapid
= GetMapId();
7847 sLog
.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid
, zoneid
);
7849 // may be exist better way to do this...
7872 NumberOfFields
= 41;
7875 NumberOfFields
= 15;
7878 NumberOfFields
= 83;
7881 NumberOfFields
= 16;
7885 NumberOfFields
= 40;
7888 NumberOfFields
= 27;
7891 NumberOfFields
= 39;
7894 NumberOfFields
= 38;
7897 NumberOfFields
= 37;
7902 NumberOfFields
= 11;
7905 NumberOfFields
= 11;
7908 NumberOfFields
= 12;
7912 WorldPacket
data(SMSG_INIT_WORLD_STATES
, (4+4+4+2+(NumberOfFields
*8)));
7913 data
<< uint32(mapid
); // mapid
7914 data
<< uint32(zoneid
); // zone id
7915 data
<< uint32(areaid
); // area id, new 2.1.0
7916 data
<< uint16(NumberOfFields
); // count of uint64 blocks
7917 data
<< uint32(0x8d8) << uint32(0x0); // 1
7918 data
<< uint32(0x8d7) << uint32(0x0); // 2
7919 data
<< uint32(0x8d6) << uint32(0x0); // 3
7920 data
<< uint32(0x8d5) << uint32(0x0); // 4
7921 data
<< uint32(0x8d4) << uint32(0x0); // 5
7922 data
<< uint32(0x8d3) << uint32(0x0); // 6
7923 // 7 1 - Arena season in progress, 0 - end of season
7924 data
<< uint32(0xC77) << uint32(sWorld
.getConfig(CONFIG_BOOL_ARENA_SEASON_IN_PROGRESS
));
7925 // 8 Arena season id
7926 data
<< uint32(0xF3D) << uint32(sWorld
.getConfig(CONFIG_UINT32_ARENA_SEASON_ID
));
7927 if(mapid
== 530) // Outland
7929 data
<< uint32(0x9bf) << uint32(0x0); // 7
7930 data
<< uint32(0x9bd) << uint32(0xF); // 8
7931 data
<< uint32(0x9bb) << uint32(0xF); // 9
7946 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_AV
)
7947 bg
->FillInitialWorldStates(data
);
7950 data
<< uint32(0x7ae) << uint32(0x1); // 7 snowfall n
7951 data
<< uint32(0x532) << uint32(0x1); // 8 frostwolfhut hc
7952 data
<< uint32(0x531) << uint32(0x0); // 9 frostwolfhut ac
7953 data
<< uint32(0x52e) << uint32(0x0); // 10 stormpike firstaid a_a
7954 data
<< uint32(0x571) << uint32(0x0); // 11 east frostwolf tower horde assaulted -unused
7955 data
<< uint32(0x570) << uint32(0x0); // 12 west frostwolf tower horde assaulted - unused
7956 data
<< uint32(0x567) << uint32(0x1); // 13 frostwolfe c
7957 data
<< uint32(0x566) << uint32(0x1); // 14 frostwolfw c
7958 data
<< uint32(0x550) << uint32(0x1); // 15 irondeep (N) ally
7959 data
<< uint32(0x544) << uint32(0x0); // 16 ice grave a_a
7960 data
<< uint32(0x536) << uint32(0x0); // 17 stormpike grave h_c
7961 data
<< uint32(0x535) << uint32(0x1); // 18 stormpike grave a_c
7962 data
<< uint32(0x518) << uint32(0x0); // 19 stoneheart grave a_a
7963 data
<< uint32(0x517) << uint32(0x0); // 20 stoneheart grave h_a
7964 data
<< uint32(0x574) << uint32(0x0); // 21 1396 unk
7965 data
<< uint32(0x573) << uint32(0x0); // 22 iceblood tower horde assaulted -unused
7966 data
<< uint32(0x572) << uint32(0x0); // 23 towerpoint horde assaulted - unused
7967 data
<< uint32(0x56f) << uint32(0x0); // 24 1391 unk
7968 data
<< uint32(0x56e) << uint32(0x0); // 25 iceblood a
7969 data
<< uint32(0x56d) << uint32(0x0); // 26 towerp a
7970 data
<< uint32(0x56c) << uint32(0x0); // 27 frostwolfe a
7971 data
<< uint32(0x56b) << uint32(0x0); // 28 froswolfw a
7972 data
<< uint32(0x56a) << uint32(0x1); // 29 1386 unk
7973 data
<< uint32(0x569) << uint32(0x1); // 30 iceblood c
7974 data
<< uint32(0x568) << uint32(0x1); // 31 towerp c
7975 data
<< uint32(0x565) << uint32(0x0); // 32 stoneh tower a
7976 data
<< uint32(0x564) << uint32(0x0); // 33 icewing tower a
7977 data
<< uint32(0x563) << uint32(0x0); // 34 dunn a
7978 data
<< uint32(0x562) << uint32(0x0); // 35 duns a
7979 data
<< uint32(0x561) << uint32(0x0); // 36 stoneheart bunker alliance assaulted - unused
7980 data
<< uint32(0x560) << uint32(0x0); // 37 icewing bunker alliance assaulted - unused
7981 data
<< uint32(0x55f) << uint32(0x0); // 38 dunbaldar south alliance assaulted - unused
7982 data
<< uint32(0x55e) << uint32(0x0); // 39 dunbaldar north alliance assaulted - unused
7983 data
<< uint32(0x55d) << uint32(0x0); // 40 stone tower d
7984 data
<< uint32(0x3c6) << uint32(0x0); // 41 966 unk
7985 data
<< uint32(0x3c4) << uint32(0x0); // 42 964 unk
7986 data
<< uint32(0x3c2) << uint32(0x0); // 43 962 unk
7987 data
<< uint32(0x516) << uint32(0x1); // 44 stoneheart grave a_c
7988 data
<< uint32(0x515) << uint32(0x0); // 45 stonheart grave h_c
7989 data
<< uint32(0x3b6) << uint32(0x0); // 46 950 unk
7990 data
<< uint32(0x55c) << uint32(0x0); // 47 icewing tower d
7991 data
<< uint32(0x55b) << uint32(0x0); // 48 dunn d
7992 data
<< uint32(0x55a) << uint32(0x0); // 49 duns d
7993 data
<< uint32(0x559) << uint32(0x0); // 50 1369 unk
7994 data
<< uint32(0x558) << uint32(0x0); // 51 iceblood d
7995 data
<< uint32(0x557) << uint32(0x0); // 52 towerp d
7996 data
<< uint32(0x556) << uint32(0x0); // 53 frostwolfe d
7997 data
<< uint32(0x555) << uint32(0x0); // 54 frostwolfw d
7998 data
<< uint32(0x554) << uint32(0x1); // 55 stoneh tower c
7999 data
<< uint32(0x553) << uint32(0x1); // 56 icewing tower c
8000 data
<< uint32(0x552) << uint32(0x1); // 57 dunn c
8001 data
<< uint32(0x551) << uint32(0x1); // 58 duns c
8002 data
<< uint32(0x54f) << uint32(0x0); // 59 irondeep (N) horde
8003 data
<< uint32(0x54e) << uint32(0x0); // 60 irondeep (N) ally
8004 data
<< uint32(0x54d) << uint32(0x1); // 61 mine (S) neutral
8005 data
<< uint32(0x54c) << uint32(0x0); // 62 mine (S) horde
8006 data
<< uint32(0x54b) << uint32(0x0); // 63 mine (S) ally
8007 data
<< uint32(0x545) << uint32(0x0); // 64 iceblood h_a
8008 data
<< uint32(0x543) << uint32(0x1); // 65 iceblod h_c
8009 data
<< uint32(0x542) << uint32(0x0); // 66 iceblood a_c
8010 data
<< uint32(0x540) << uint32(0x0); // 67 snowfall h_a
8011 data
<< uint32(0x53f) << uint32(0x0); // 68 snowfall a_a
8012 data
<< uint32(0x53e) << uint32(0x0); // 69 snowfall h_c
8013 data
<< uint32(0x53d) << uint32(0x0); // 70 snowfall a_c
8014 data
<< uint32(0x53c) << uint32(0x0); // 71 frostwolf g h_a
8015 data
<< uint32(0x53b) << uint32(0x0); // 72 frostwolf g a_a
8016 data
<< uint32(0x53a) << uint32(0x1); // 73 frostwolf g h_c
8017 data
<< uint32(0x539) << uint32(0x0); // 74 frostwolf g a_c
8018 data
<< uint32(0x538) << uint32(0x0); // 75 stormpike grave h_a
8019 data
<< uint32(0x537) << uint32(0x0); // 76 stormpike grave a_a
8020 data
<< uint32(0x534) << uint32(0x0); // 77 frostwolf hut h_a
8021 data
<< uint32(0x533) << uint32(0x0); // 78 frostwolf hut a_a
8022 data
<< uint32(0x530) << uint32(0x0); // 79 stormpike first aid h_a
8023 data
<< uint32(0x52f) << uint32(0x0); // 80 stormpike first aid h_c
8024 data
<< uint32(0x52d) << uint32(0x1); // 81 stormpike first aid a_c
8028 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_WS
)
8029 bg
->FillInitialWorldStates(data
);
8032 data
<< uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
8033 data
<< uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
8034 data
<< uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
8035 data
<< uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
8036 data
<< uint32(0x60b) << uint32(0x2); // 11 1547 unk
8037 data
<< uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
8038 data
<< uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
8039 data
<< uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
8043 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_AB
)
8044 bg
->FillInitialWorldStates(data
);
8047 data
<< uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
8048 data
<< uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
8049 data
<< uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
8050 data
<< uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
8051 data
<< uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
8052 data
<< uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
8053 data
<< uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
8054 data
<< uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
8055 data
<< uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
8056 data
<< uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
8057 data
<< uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
8058 data
<< uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
8059 data
<< uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
8060 data
<< uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
8061 data
<< uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
8062 data
<< uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
8063 data
<< uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
8064 data
<< uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
8065 data
<< uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
8066 data
<< uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
8067 data
<< uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
8068 data
<< uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
8069 data
<< uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
8070 data
<< uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
8071 data
<< uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
8072 data
<< uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
8073 data
<< uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
8074 data
<< uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
8075 data
<< uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
8076 data
<< uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
8077 data
<< uint32(0x745) << uint32(0x2); // 37 1861 unk
8078 data
<< uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
8082 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_EY
)
8083 bg
->FillInitialWorldStates(data
);
8086 data
<< uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
8087 data
<< uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
8088 data
<< uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
8089 data
<< uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
8090 data
<< uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
8091 data
<< uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
8092 data
<< uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
8093 data
<< uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
8094 data
<< uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
8095 data
<< uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
8096 data
<< uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
8097 data
<< uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
8098 data
<< uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
8099 data
<< uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
8100 data
<< uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
8101 data
<< uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
8102 data
<< uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
8103 data
<< uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
8104 data
<< uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
8105 data
<< uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
8106 data
<< uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
8107 data
<< uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
8108 data
<< uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
8109 data
<< uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
8110 data
<< uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
8111 data
<< uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
8112 data
<< uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
8113 data
<< uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
8114 data
<< uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
8115 data
<< uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
8116 data
<< uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
8117 data
<< uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
8118 // and some more ... unknown
8121 case 3483: // Hellfire Peninsula
8122 data
<< uint32(0x9ba) << uint32(0x1); // 10
8123 data
<< uint32(0x9b9) << uint32(0x1); // 11
8124 data
<< uint32(0x9b5) << uint32(0x0); // 12
8125 data
<< uint32(0x9b4) << uint32(0x1); // 13
8126 data
<< uint32(0x9b3) << uint32(0x0); // 14
8127 data
<< uint32(0x9b2) << uint32(0x0); // 15
8128 data
<< uint32(0x9b1) << uint32(0x1); // 16
8129 data
<< uint32(0x9b0) << uint32(0x0); // 17
8130 data
<< uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
8131 data
<< uint32(0x9ac) << uint32(0x0); // 19
8132 data
<< uint32(0x9a8) << uint32(0x0); // 20
8133 data
<< uint32(0x9a7) << uint32(0x0); // 21
8134 data
<< uint32(0x9a6) << uint32(0x1); // 22
8136 case 3519: // Terokkar Forest
8137 data
<< uint32(0xa41) << uint32(0x0); // 10
8138 data
<< uint32(0xa40) << uint32(0x14); // 11
8139 data
<< uint32(0xa3f) << uint32(0x0); // 12
8140 data
<< uint32(0xa3e) << uint32(0x0); // 13
8141 data
<< uint32(0xa3d) << uint32(0x5); // 14
8142 data
<< uint32(0xa3c) << uint32(0x0); // 15
8143 data
<< uint32(0xa87) << uint32(0x0); // 16
8144 data
<< uint32(0xa86) << uint32(0x0); // 17
8145 data
<< uint32(0xa85) << uint32(0x0); // 18
8146 data
<< uint32(0xa84) << uint32(0x0); // 19
8147 data
<< uint32(0xa83) << uint32(0x0); // 20
8148 data
<< uint32(0xa82) << uint32(0x0); // 21
8149 data
<< uint32(0xa81) << uint32(0x0); // 22
8150 data
<< uint32(0xa80) << uint32(0x0); // 23
8151 data
<< uint32(0xa7e) << uint32(0x0); // 24
8152 data
<< uint32(0xa7d) << uint32(0x0); // 25
8153 data
<< uint32(0xa7c) << uint32(0x0); // 26
8154 data
<< uint32(0xa7b) << uint32(0x0); // 27
8155 data
<< uint32(0xa7a) << uint32(0x0); // 28
8156 data
<< uint32(0xa79) << uint32(0x0); // 29
8157 data
<< uint32(0x9d0) << uint32(0x5); // 30
8158 data
<< uint32(0x9ce) << uint32(0x0); // 31
8159 data
<< uint32(0x9cd) << uint32(0x0); // 32
8160 data
<< uint32(0x9cc) << uint32(0x0); // 33
8161 data
<< uint32(0xa88) << uint32(0x0); // 34
8162 data
<< uint32(0xad0) << uint32(0x0); // 35
8163 data
<< uint32(0xacf) << uint32(0x1); // 36
8165 case 3521: // Zangarmarsh
8166 data
<< uint32(0x9e1) << uint32(0x0); // 10
8167 data
<< uint32(0x9e0) << uint32(0x0); // 11
8168 data
<< uint32(0x9df) << uint32(0x0); // 12
8169 data
<< uint32(0xa5d) << uint32(0x1); // 13
8170 data
<< uint32(0xa5c) << uint32(0x0); // 14
8171 data
<< uint32(0xa5b) << uint32(0x1); // 15
8172 data
<< uint32(0xa5a) << uint32(0x0); // 16
8173 data
<< uint32(0xa59) << uint32(0x1); // 17
8174 data
<< uint32(0xa58) << uint32(0x0); // 18
8175 data
<< uint32(0xa57) << uint32(0x0); // 19
8176 data
<< uint32(0xa56) << uint32(0x0); // 20
8177 data
<< uint32(0xa55) << uint32(0x1); // 21
8178 data
<< uint32(0xa54) << uint32(0x0); // 22
8179 data
<< uint32(0x9e7) << uint32(0x0); // 23
8180 data
<< uint32(0x9e6) << uint32(0x0); // 24
8181 data
<< uint32(0x9e5) << uint32(0x0); // 25
8182 data
<< uint32(0xa00) << uint32(0x0); // 26
8183 data
<< uint32(0x9ff) << uint32(0x1); // 27
8184 data
<< uint32(0x9fe) << uint32(0x0); // 28
8185 data
<< uint32(0x9fd) << uint32(0x0); // 29
8186 data
<< uint32(0x9fc) << uint32(0x1); // 30
8187 data
<< uint32(0x9fb) << uint32(0x0); // 31
8188 data
<< uint32(0xa62) << uint32(0x0); // 32
8189 data
<< uint32(0xa61) << uint32(0x1); // 33
8190 data
<< uint32(0xa60) << uint32(0x1); // 34
8191 data
<< uint32(0xa5f) << uint32(0x0); // 35
8193 case 3698: // Nagrand Arena
8194 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_NA
)
8195 bg
->FillInitialWorldStates(data
);
8198 data
<< uint32(0xa0f) << uint32(0x0); // 7
8199 data
<< uint32(0xa10) << uint32(0x0); // 8
8200 data
<< uint32(0xa11) << uint32(0x0); // 9 show
8203 case 3702: // Blade's Edge Arena
8204 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_BE
)
8205 bg
->FillInitialWorldStates(data
);
8208 data
<< uint32(0x9f0) << uint32(0x0); // 7 gold
8209 data
<< uint32(0x9f1) << uint32(0x0); // 8 green
8210 data
<< uint32(0x9f3) << uint32(0x0); // 9 show
8213 case 3968: // Ruins of Lordaeron
8214 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_RL
)
8215 bg
->FillInitialWorldStates(data
);
8218 data
<< uint32(0xbb8) << uint32(0x0); // 7 gold
8219 data
<< uint32(0xbb9) << uint32(0x0); // 8 green
8220 data
<< uint32(0xbba) << uint32(0x0); // 9 show
8223 case 3703: // Shattrath City
8226 data
<< uint32(0x914) << uint32(0x0); // 7
8227 data
<< uint32(0x913) << uint32(0x0); // 8
8228 data
<< uint32(0x912) << uint32(0x0); // 9
8229 data
<< uint32(0x915) << uint32(0x0); // 10
8232 GetSession()->SendPacket(&data
);
8235 uint32
Player::GetXPRestBonus(uint32 xp
)
8237 uint32 rested_bonus
= (uint32
)GetRestBonus(); // xp for each rested bonus
8239 if(rested_bonus
> xp
) // max rested_bonus == xp or (r+x) = 200% xp
8242 SetRestBonus( GetRestBonus() - rested_bonus
);
8244 sLog
.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp
+rested_bonus
,rested_bonus
,GetRestBonus());
8245 return rested_bonus
;
8248 void Player::SetBindPoint(uint64 guid
)
8250 WorldPacket
data(SMSG_BINDER_CONFIRM
, 8);
8251 data
<< uint64(guid
);
8252 GetSession()->SendPacket( &data
);
8255 void Player::SendTalentWipeConfirm(uint64 guid
)
8257 WorldPacket
data(MSG_TALENT_WIPE_CONFIRM
, (8+4));
8258 data
<< uint64(guid
);
8259 data
<< uint32(resetTalentsCost());
8260 GetSession()->SendPacket( &data
);
8263 void Player::SendPetSkillWipeConfirm()
8265 Pet
* pet
= GetPet();
8268 WorldPacket
data(SMSG_PET_UNLEARN_CONFIRM
, (8+4));
8269 data
<< pet
->GetGUID();
8270 data
<< uint32(pet
->resetTalentsCost());
8271 GetSession()->SendPacket( &data
);
8274 /*********************************************************/
8275 /*** STORAGE SYSTEM ***/
8276 /*********************************************************/
8278 void Player::SetVirtualItemSlot( uint8 i
, Item
* item
)
8283 if(!item
->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT
))
8285 uint32 charges
= item
->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
);
8289 item
->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
,charges
-1);
8290 else if(charges
<= 1)
8292 ApplyEnchantment(item
,TEMP_ENCHANTMENT_SLOT
,false);
8293 item
->ClearEnchantment(TEMP_ENCHANTMENT_SLOT
);
8298 void Player::SetSheath( SheathState sheathed
)
8302 case SHEATH_STATE_UNARMED
: // no prepared weapon
8303 SetVirtualItemSlot(0,NULL
);
8304 SetVirtualItemSlot(1,NULL
);
8305 SetVirtualItemSlot(2,NULL
);
8307 case SHEATH_STATE_MELEE
: // prepared melee weapon
8309 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK
,true,true));
8310 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK
,true,true));
8311 SetVirtualItemSlot(2,NULL
);
8313 case SHEATH_STATE_RANGED
: // prepared ranged weapon
8314 SetVirtualItemSlot(0,NULL
);
8315 SetVirtualItemSlot(1,NULL
);
8316 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK
,true,true));
8319 SetVirtualItemSlot(0,NULL
);
8320 SetVirtualItemSlot(1,NULL
);
8321 SetVirtualItemSlot(2,NULL
);
8324 Unit::SetSheath(sheathed
); // this must visualize Sheath changing for other players...
8327 uint8
Player::FindEquipSlot( ItemPrototype
const* proto
, uint32 slot
, bool swap
) const
8329 uint8 pClass
= getClass();
8332 slots
[0] = NULL_SLOT
;
8333 slots
[1] = NULL_SLOT
;
8334 slots
[2] = NULL_SLOT
;
8335 slots
[3] = NULL_SLOT
;
8336 switch( proto
->InventoryType
)
8339 slots
[0] = EQUIPMENT_SLOT_HEAD
;
8342 slots
[0] = EQUIPMENT_SLOT_NECK
;
8344 case INVTYPE_SHOULDERS
:
8345 slots
[0] = EQUIPMENT_SLOT_SHOULDERS
;
8348 slots
[0] = EQUIPMENT_SLOT_BODY
;
8351 slots
[0] = EQUIPMENT_SLOT_CHEST
;
8354 slots
[0] = EQUIPMENT_SLOT_CHEST
;
8357 slots
[0] = EQUIPMENT_SLOT_WAIST
;
8360 slots
[0] = EQUIPMENT_SLOT_LEGS
;
8363 slots
[0] = EQUIPMENT_SLOT_FEET
;
8365 case INVTYPE_WRISTS
:
8366 slots
[0] = EQUIPMENT_SLOT_WRISTS
;
8369 slots
[0] = EQUIPMENT_SLOT_HANDS
;
8371 case INVTYPE_FINGER
:
8372 slots
[0] = EQUIPMENT_SLOT_FINGER1
;
8373 slots
[1] = EQUIPMENT_SLOT_FINGER2
;
8375 case INVTYPE_TRINKET
:
8376 slots
[0] = EQUIPMENT_SLOT_TRINKET1
;
8377 slots
[1] = EQUIPMENT_SLOT_TRINKET2
;
8380 slots
[0] = EQUIPMENT_SLOT_BACK
;
8382 case INVTYPE_WEAPON
:
8384 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8386 // suggest offhand slot only if know dual wielding
8387 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8389 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
8392 case INVTYPE_SHIELD
:
8393 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8395 case INVTYPE_RANGED
:
8396 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8398 case INVTYPE_2HWEAPON
:
8399 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8400 if (CanDualWield() && CanTitanGrip())
8401 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
8403 case INVTYPE_TABARD
:
8404 slots
[0] = EQUIPMENT_SLOT_TABARD
;
8406 case INVTYPE_WEAPONMAINHAND
:
8407 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8409 case INVTYPE_WEAPONOFFHAND
:
8410 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8412 case INVTYPE_HOLDABLE
:
8413 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8415 case INVTYPE_THROWN
:
8416 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8418 case INVTYPE_RANGEDRIGHT
:
8419 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8422 slots
[0] = INVENTORY_SLOT_BAG_START
+ 0;
8423 slots
[1] = INVENTORY_SLOT_BAG_START
+ 1;
8424 slots
[2] = INVENTORY_SLOT_BAG_START
+ 2;
8425 slots
[3] = INVENTORY_SLOT_BAG_START
+ 3;
8429 switch(proto
->SubClass
)
8431 case ITEM_SUBCLASS_ARMOR_LIBRAM
:
8432 if (pClass
== CLASS_PALADIN
)
8433 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8435 case ITEM_SUBCLASS_ARMOR_IDOL
:
8436 if (pClass
== CLASS_DRUID
)
8437 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8439 case ITEM_SUBCLASS_ARMOR_TOTEM
:
8440 if (pClass
== CLASS_SHAMAN
)
8441 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8443 case ITEM_SUBCLASS_ARMOR_MISC
:
8444 if (pClass
== CLASS_WARLOCK
)
8445 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8447 case ITEM_SUBCLASS_ARMOR_SIGIL
:
8448 if (pClass
== CLASS_DEATH_KNIGHT
)
8449 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8458 if( slot
!= NULL_SLOT
)
8460 if( swap
|| !GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
) )
8462 for (int i
= 0; i
< 4; ++i
)
8464 if ( slots
[i
] == slot
)
8471 // search free slot at first
8472 for (int i
= 0; i
< 4; ++i
)
8474 if ( slots
[i
] != NULL_SLOT
&& !GetItemByPos( INVENTORY_SLOT_BAG_0
, slots
[i
] ) )
8476 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8477 if(slots
[i
]!=EQUIPMENT_SLOT_OFFHAND
|| !IsTwoHandUsed())
8482 // if not found free and can swap return first appropriate from used
8483 for (int i
= 0; i
< 4; ++i
)
8485 if ( slots
[i
] != NULL_SLOT
&& swap
)
8494 uint8
Player::CanUnequipItems( uint32 item
, uint32 count
) const
8497 uint32 tempcount
= 0;
8499 uint8 res
= EQUIP_ERR_OK
;
8501 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8503 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8504 if( pItem
&& pItem
->GetEntry() == item
)
8506 uint8 ires
= CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
, false);
8507 if(ires
==EQUIP_ERR_OK
)
8509 tempcount
+= pItem
->GetCount();
8510 if( tempcount
>= count
)
8511 return EQUIP_ERR_OK
;
8517 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_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
;
8527 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
8529 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8530 if( pItem
&& pItem
->GetEntry() == item
)
8532 tempcount
+= pItem
->GetCount();
8533 if( tempcount
>= count
)
8534 return EQUIP_ERR_OK
;
8538 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8540 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8543 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8545 pItem
= GetItemByPos( i
, j
);
8546 if( pItem
&& pItem
->GetEntry() == item
)
8548 tempcount
+= pItem
->GetCount();
8549 if( tempcount
>= count
)
8550 return EQUIP_ERR_OK
;
8556 // not found req. item count and have unequippable items
8560 uint32
Player::GetItemCount( uint32 item
, bool inBankAlso
, Item
* skipItem
) const
8563 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8565 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8566 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8567 count
+= pItem
->GetCount();
8569 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
8571 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8572 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8573 count
+= pItem
->GetCount();
8575 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8577 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8579 count
+= pBag
->GetItemCount(item
,skipItem
);
8582 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8584 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8586 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8587 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8588 count
+= pItem
->GetGemCountWithID(item
);
8594 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; ++i
)
8596 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8597 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8598 count
+= pItem
->GetCount();
8600 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
8602 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8604 count
+= pBag
->GetItemCount(item
,skipItem
);
8607 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8609 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; ++i
)
8611 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8612 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8613 count
+= pItem
->GetGemCountWithID(item
);
8621 uint32
Player::GetItemCountWithLimitCategory( uint32 limitCategory
) const
8624 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8625 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8626 if (pItem
->GetProto()->ItemLimitCategory
== limitCategory
)
8627 count
+= pItem
->GetCount();
8629 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
8630 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8631 if (pItem
->GetProto()->ItemLimitCategory
== limitCategory
)
8632 count
+= pItem
->GetCount();
8634 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8635 if (Bag
* pBag
= (Bag
*)GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8636 count
+= pBag
->GetItemCountWithLimitCategory(limitCategory
);
8638 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; ++i
)
8639 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8640 if (pItem
->GetProto()->ItemLimitCategory
== limitCategory
)
8641 count
+= pItem
->GetCount();
8643 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
8644 if (Bag
* pBag
= (Bag
*)GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8645 count
+= pBag
->GetItemCountWithLimitCategory(limitCategory
);
8650 Item
* Player::GetItemByEntry( uint32 item
) const
8652 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8653 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8654 if (pItem
->GetEntry() == item
)
8657 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
8658 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8659 if (pItem
->GetEntry() == item
)
8662 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8663 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8664 if (Item
* itemPtr
= pBag
->GetItemByEntry(item
))
8670 Item
* Player::GetItemByLimitedCategory(uint32 limitedCategory
) const
8672 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8673 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8674 if (pItem
->GetProto()->ItemLimitCategory
== limitedCategory
)
8677 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
8678 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8679 if (pItem
->GetProto()->ItemLimitCategory
== limitedCategory
)
8682 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8683 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8684 if (Item
* itemPtr
= pBag
->GetItemByLimitedCategory(limitedCategory
))
8690 Item
* Player::GetItemByGuid(ObjectGuid guid
) const
8692 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8693 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8694 if (pItem
->GetObjectGuid() == guid
)
8697 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
8698 if (Item
*pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8699 if (pItem
->GetObjectGuid() == guid
)
8702 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8703 if (Bag
*pBag
= (Bag
*)GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8704 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8705 if (Item
* pItem
= pBag
->GetItemByPos(j
))
8706 if (pItem
->GetObjectGuid() == guid
)
8709 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
8710 if (Bag
*pBag
= (Bag
*)GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
8711 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8712 if (Item
* pItem
= pBag
->GetItemByPos(j
))
8713 if (pItem
->GetObjectGuid() == guid
)
8719 Item
* Player::GetItemByPos( uint16 pos
) const
8721 uint8 bag
= pos
>> 8;
8722 uint8 slot
= pos
& 255;
8723 return GetItemByPos( bag
, slot
);
8726 Item
* Player::GetItemByPos( uint8 bag
, uint8 slot
) const
8728 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< BANK_SLOT_BAG_END
|| (slot
>= KEYRING_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)) )
8729 return m_items
[slot
];
8730 else if ((bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8731 || (bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
) )
8733 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8735 return pBag
->GetItemByPos(slot
);
8740 Item
* Player::GetWeaponForAttack(WeaponAttackType attackType
, bool nonbroken
, bool useable
) const
8745 case BASE_ATTACK
: slot
= EQUIPMENT_SLOT_MAINHAND
; break;
8746 case OFF_ATTACK
: slot
= EQUIPMENT_SLOT_OFFHAND
; break;
8747 case RANGED_ATTACK
: slot
= EQUIPMENT_SLOT_RANGED
; break;
8748 default: return NULL
;
8751 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, slot
);
8752 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_WEAPON
)
8755 if (useable
&& !IsUseEquipedWeapon(attackType
==BASE_ATTACK
))
8758 if (nonbroken
&& item
->IsBroken())
8764 Item
* Player::GetShield(bool useable
) const
8766 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
8767 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_ARMOR
)
8773 if( item
->IsBroken())
8779 uint32
Player::GetAttackBySlot( uint8 slot
)
8783 case EQUIPMENT_SLOT_MAINHAND
: return BASE_ATTACK
;
8784 case EQUIPMENT_SLOT_OFFHAND
: return OFF_ATTACK
;
8785 case EQUIPMENT_SLOT_RANGED
: return RANGED_ATTACK
;
8786 default: return MAX_ATTACK
;
8790 bool Player::IsInventoryPos( uint8 bag
, uint8 slot
)
8792 if( bag
== INVENTORY_SLOT_BAG_0
&& slot
== NULL_SLOT
)
8794 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
) )
8796 if( bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8798 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= KEYRING_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
) )
8803 bool Player::IsEquipmentPos( uint8 bag
, uint8 slot
)
8805 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< EQUIPMENT_SLOT_END
) )
8807 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8812 bool Player::IsBankPos( uint8 bag
, uint8 slot
)
8814 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
) )
8816 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8818 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8823 bool Player::IsBagPos( uint16 pos
)
8825 uint8 bag
= pos
>> 8;
8826 uint8 slot
= pos
& 255;
8827 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8829 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8834 bool Player::IsValidPos( uint8 bag
, uint8 slot
, bool explicit_pos
) const
8837 if(bag
== NULL_BAG
&& !explicit_pos
)
8840 if (bag
== INVENTORY_SLOT_BAG_0
)
8842 // any post selected
8843 if (slot
== NULL_SLOT
&& !explicit_pos
)
8847 if (slot
< EQUIPMENT_SLOT_END
)
8851 if (slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
)
8855 if (slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
)
8859 if (slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_END
)
8863 if (slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
)
8867 if (slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
8873 // bag content slots
8874 if (bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8876 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8880 // any post selected
8881 if (slot
== NULL_SLOT
&& !explicit_pos
)
8884 return slot
< pBag
->GetBagSize();
8887 // bank bag content slots
8888 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8890 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8894 // any post selected
8895 if (slot
== NULL_SLOT
&& !explicit_pos
)
8898 return slot
< pBag
->GetBagSize();
8906 bool Player::HasItemCount( uint32 item
, uint32 count
, bool inBankAlso
) const
8908 uint32 tempcount
= 0;
8909 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_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
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
8921 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8922 if( pItem
&& pItem
->GetEntry() == item
)
8924 tempcount
+= pItem
->GetCount();
8925 if( tempcount
>= count
)
8929 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8931 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8933 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8935 Item
* pItem
= GetItemByPos( i
, j
);
8936 if( pItem
&& pItem
->GetEntry() == item
)
8938 tempcount
+= pItem
->GetCount();
8939 if( tempcount
>= count
)
8948 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; ++i
)
8950 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8951 if( pItem
&& pItem
->GetEntry() == item
)
8953 tempcount
+= pItem
->GetCount();
8954 if( tempcount
>= count
)
8958 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
8960 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8962 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8964 Item
* pItem
= GetItemByPos( i
, j
);
8965 if( pItem
&& pItem
->GetEntry() == item
)
8967 tempcount
+= pItem
->GetCount();
8968 if( tempcount
>= count
)
8979 bool Player::HasItemOrGemWithIdEquipped( uint32 item
, uint32 count
, uint8 except_slot
) const
8981 uint32 tempcount
= 0;
8982 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
8984 if(i
==int(except_slot
))
8987 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8988 if( pItem
&& pItem
->GetEntry() == item
)
8990 tempcount
+= pItem
->GetCount();
8991 if( tempcount
>= count
)
8996 ItemPrototype
const *pProto
= ObjectMgr::GetItemPrototype(item
);
8997 if (pProto
&& pProto
->GemProperties
)
8999 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
9001 if(i
==int(except_slot
))
9004 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9005 if( pItem
&& pItem
->GetProto()->Socket
[0].Color
)
9007 tempcount
+= pItem
->GetGemCountWithID(item
);
9008 if( tempcount
>= count
)
9017 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory
, uint32 count
, uint8 except_slot
) const
9019 uint32 tempcount
= 0;
9020 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
9022 if(i
==int(except_slot
))
9025 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9029 ItemPrototype
const *pProto
= pItem
->GetProto();
9033 if (pProto
->ItemLimitCategory
== limitCategory
)
9035 tempcount
+= pItem
->GetCount();
9036 if( tempcount
>= count
)
9040 if( pProto
->Socket
[0].Color
)
9042 tempcount
+= pItem
->GetGemCountWithLimitCategory(limitCategory
);
9043 if( tempcount
>= count
)
9051 uint8
Player::_CanTakeMoreSimilarItems(uint32 entry
, uint32 count
, Item
* pItem
, uint32
* no_space_count
) const
9053 ItemPrototype
const *pProto
= ObjectMgr::GetItemPrototype(entry
);
9057 *no_space_count
= count
;
9058 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9062 if(pProto
->MaxCount
> 0)
9064 uint32 curcount
= GetItemCount(pProto
->ItemId
,true,pItem
);
9066 if (curcount
+ count
> uint32(pProto
->MaxCount
))
9069 *no_space_count
= count
+curcount
- pProto
->MaxCount
;
9070 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9074 // check unique-equipped limit
9075 if (pProto
->ItemLimitCategory
)
9077 ItemLimitCategoryEntry
const* limitEntry
= sItemLimitCategoryStore
.LookupEntry(pProto
->ItemLimitCategory
);
9081 *no_space_count
= count
;
9082 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9085 if (limitEntry
->mode
== ITEM_LIMIT_CATEGORY_MODE_HAVE
)
9087 uint32 curcount
= GetItemCountWithLimitCategory(pProto
->ItemLimitCategory
);
9089 if (curcount
+ count
> uint32(limitEntry
->maxCount
))
9092 *no_space_count
= count
+ curcount
- limitEntry
->maxCount
;
9093 return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS
;
9098 return EQUIP_ERR_OK
;
9101 bool Player::HasItemTotemCategory( uint32 TotemCategory
) const
9104 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
9106 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9107 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
9110 for(uint8 i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
9112 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9113 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
9116 for(uint8 i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9118 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
9120 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9122 pItem
= GetItemByPos( i
, j
);
9123 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
9131 uint8
Player::_CanStoreItem_InSpecificSlot( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, ItemPrototype
const *pProto
, uint32
& count
, bool swap
, Item
* pSrcItem
) const
9133 Item
* pItem2
= GetItemByPos( bag
, slot
);
9135 // ignore move item (this slot will be empty at move)
9136 if (pItem2
==pSrcItem
)
9141 // empty specific slot - check item fit to slot
9142 if (!pItem2
|| swap
)
9144 if (bag
== INVENTORY_SLOT_BAG_0
)
9147 if (slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_START
+GetMaxKeyringSize() && !(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
))
9148 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9150 // currencytoken case
9151 if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
&& !(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
))
9152 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9155 if (slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
|| slot
>= PLAYER_SLOT_END
)
9156 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9160 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
9162 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9164 ItemPrototype
const* pBagProto
= pBag
->GetProto();
9166 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9168 if (slot
>= pBagProto
->ContainerSlots
)
9169 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9171 if (!ItemCanGoIntoBag(pProto
,pBagProto
))
9172 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9175 // non empty stack with space
9176 need_space
= pProto
->GetMaxStackSize();
9178 // non empty slot, check item type
9181 // can be merged at least partly
9182 uint8 res
= pItem2
->CanBeMergedPartlyWith(pProto
);
9183 if (res
!= EQUIP_ERR_OK
)
9186 // free stack space or infinity
9187 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
9190 if (need_space
> count
)
9193 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | slot
, need_space
);
9194 if (!newPosition
.isContainedIn(dest
))
9196 dest
.push_back(newPosition
);
9197 count
-= need_space
;
9199 return EQUIP_ERR_OK
;
9202 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
9204 // skip specific bag already processed in first called _CanStoreItem_InBag
9206 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9208 // skip not existed bag or self targeted bag
9209 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
9210 if (!pBag
|| pBag
==pSrcItem
)
9211 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9213 ItemPrototype
const* pBagProto
= pBag
->GetProto();
9215 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9217 // specialized bag mode or non-specilized
9218 if (non_specialized
!= (pBagProto
->Class
== ITEM_CLASS_CONTAINER
&& pBagProto
->SubClass
== ITEM_SUBCLASS_CONTAINER
))
9219 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9221 if (!ItemCanGoIntoBag(pProto
,pBagProto
))
9222 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9224 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9226 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9230 Item
* pItem2
= GetItemByPos( bag
, j
);
9232 // ignore move item (this slot will be empty at move)
9233 if (pItem2
== pSrcItem
)
9236 // if merge skip empty, if !merge skip non-empty
9237 if ((pItem2
!= NULL
) != merge
)
9240 uint32 need_space
= pProto
->GetMaxStackSize();
9244 // can be merged at least partly
9245 uint8 res
= pItem2
->CanBeMergedPartlyWith(pProto
);
9246 if (res
!= EQUIP_ERR_OK
)
9249 // descrease at current stacksize
9250 need_space
-= pItem2
->GetCount();
9253 if (need_space
> count
)
9256 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
9257 if (!newPosition
.isContainedIn(dest
))
9259 dest
.push_back(newPosition
);
9260 count
-= need_space
;
9263 return EQUIP_ERR_OK
;
9266 return EQUIP_ERR_OK
;
9269 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
9271 for(uint32 j
= slot_begin
; j
< slot_end
; ++j
)
9273 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9274 if (INVENTORY_SLOT_BAG_0
==skip_bag
&& j
==skip_slot
)
9277 Item
* pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, j
);
9279 // ignore move item (this slot will be empty at move)
9280 if (pItem2
==pSrcItem
)
9283 // if merge skip empty, if !merge skip non-empty
9284 if ((pItem2
!= NULL
) != merge
)
9287 uint32 need_space
= pProto
->GetMaxStackSize();
9291 // can be merged at least partly
9292 uint8 res
= pItem2
->CanBeMergedPartlyWith(pProto
);
9293 if (res
!= EQUIP_ERR_OK
)
9296 // descrease at current stacksize
9297 need_space
-= pItem2
->GetCount();
9300 if (need_space
> count
)
9303 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
9304 if (!newPosition
.isContainedIn(dest
))
9306 dest
.push_back(newPosition
);
9307 count
-= need_space
;
9310 return EQUIP_ERR_OK
;
9313 return EQUIP_ERR_OK
;
9316 uint8
Player::_CanStoreItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, uint32 entry
, uint32 count
, Item
*pItem
, bool swap
, uint32
* no_space_count
) const
9318 sLog
.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, entry
, count
);
9320 ItemPrototype
const *pProto
= ObjectMgr::GetItemPrototype(entry
);
9324 *no_space_count
= count
;
9325 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
:EQUIP_ERR_ITEM_NOT_FOUND
;
9331 if(pItem
->m_lootGenerated
)
9334 *no_space_count
= count
;
9335 return EQUIP_ERR_ALREADY_LOOTED
;
9338 if (pItem
->IsBindedNotWith(this))
9341 *no_space_count
= count
;
9342 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9346 // check count of items (skip for auto move for same player from bank)
9347 uint32 no_similar_count
= 0; // can't store this amount similar items
9348 uint8 res
= _CanTakeMoreSimilarItems(entry
,count
,pItem
,&no_similar_count
);
9349 if (res
!=EQUIP_ERR_OK
)
9351 if (count
==no_similar_count
)
9354 *no_space_count
= no_similar_count
;
9357 count
-= no_similar_count
;
9361 if (bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
9363 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
9364 if (res
!=EQUIP_ERR_OK
)
9367 *no_space_count
= count
+ no_similar_count
;
9373 if (no_similar_count
==0)
9374 return EQUIP_ERR_OK
;
9377 *no_space_count
= count
+ no_similar_count
;
9378 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9382 // not specific slot or have space for partly store only in specific slot
9385 if (bag
!= NULL_BAG
)
9387 // search stack in bag for merge to
9388 if (pProto
->Stackable
!= 1)
9390 if (bag
== INVENTORY_SLOT_BAG_0
) // inventory
9392 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9393 if (res
!=EQUIP_ERR_OK
)
9396 *no_space_count
= count
+ no_similar_count
;
9402 if (no_similar_count
==0)
9403 return EQUIP_ERR_OK
;
9406 *no_space_count
= count
+ no_similar_count
;
9407 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9410 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9411 if (res
!=EQUIP_ERR_OK
)
9414 *no_space_count
= count
+ no_similar_count
;
9420 if (no_similar_count
==0)
9421 return EQUIP_ERR_OK
;
9424 *no_space_count
= count
+ no_similar_count
;
9425 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9428 else // equipped bag
9430 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
9431 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
9432 if (res
!=EQUIP_ERR_OK
)
9433 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
9435 if (res
!=EQUIP_ERR_OK
)
9438 *no_space_count
= count
+ no_similar_count
;
9444 if (no_similar_count
==0)
9445 return EQUIP_ERR_OK
;
9448 *no_space_count
= count
+ no_similar_count
;
9449 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9454 // search free slot in bag for place to
9455 if(bag
== INVENTORY_SLOT_BAG_0
) // inventory
9457 // search free slot - keyring case
9458 if (pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9460 uint32 keyringSize
= GetMaxKeyringSize();
9461 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9462 if (res
!=EQUIP_ERR_OK
)
9465 *no_space_count
= count
+ no_similar_count
;
9471 if (no_similar_count
==0)
9472 return EQUIP_ERR_OK
;
9475 *no_space_count
= count
+ no_similar_count
;
9476 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9479 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9480 if (res
!=EQUIP_ERR_OK
)
9483 *no_space_count
= count
+ no_similar_count
;
9489 if (no_similar_count
==0)
9490 return EQUIP_ERR_OK
;
9493 *no_space_count
= count
+ no_similar_count
;
9494 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9497 else if (pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
9499 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9500 if (res
!=EQUIP_ERR_OK
)
9503 *no_space_count
= count
+ no_similar_count
;
9509 if (no_similar_count
==0)
9510 return EQUIP_ERR_OK
;
9513 *no_space_count
= count
+ no_similar_count
;
9514 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9518 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9519 if (res
!=EQUIP_ERR_OK
)
9522 *no_space_count
= count
+ no_similar_count
;
9528 if (no_similar_count
==0)
9529 return EQUIP_ERR_OK
;
9532 *no_space_count
= count
+ no_similar_count
;
9533 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9536 else // equipped bag
9538 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
9539 if (res
!=EQUIP_ERR_OK
)
9540 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
9542 if (res
!=EQUIP_ERR_OK
)
9545 *no_space_count
= count
+ no_similar_count
;
9551 if (no_similar_count
==0)
9552 return EQUIP_ERR_OK
;
9555 *no_space_count
= count
+ no_similar_count
;
9556 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9561 // not specific bag or have space for partly store only in specific bag
9563 // search stack for merge to
9564 if (pProto
->Stackable
!= 1)
9566 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9567 if (res
!=EQUIP_ERR_OK
)
9570 *no_space_count
= count
+ no_similar_count
;
9576 if (no_similar_count
==0)
9577 return EQUIP_ERR_OK
;
9580 *no_space_count
= count
+ no_similar_count
;
9581 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9584 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9585 if (res
!=EQUIP_ERR_OK
)
9588 *no_space_count
= count
+ no_similar_count
;
9594 if (no_similar_count
==0)
9595 return EQUIP_ERR_OK
;
9598 *no_space_count
= count
+ no_similar_count
;
9599 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9602 if (pProto
->BagFamily
)
9604 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9606 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
9607 if (res
!=EQUIP_ERR_OK
)
9612 if (no_similar_count
==0)
9613 return EQUIP_ERR_OK
;
9616 *no_space_count
= count
+ no_similar_count
;
9617 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9622 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9624 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
9625 if (res
!=EQUIP_ERR_OK
)
9630 if (no_similar_count
==0)
9631 return EQUIP_ERR_OK
;
9634 *no_space_count
= count
+ no_similar_count
;
9635 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9640 // search free slot - special bag case
9641 if (pProto
->BagFamily
)
9643 if (pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9645 uint32 keyringSize
= GetMaxKeyringSize();
9646 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9647 if (res
!=EQUIP_ERR_OK
)
9650 *no_space_count
= count
+ no_similar_count
;
9656 if (no_similar_count
==0)
9657 return EQUIP_ERR_OK
;
9660 *no_space_count
= count
+ no_similar_count
;
9661 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9664 else if (pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
9666 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9667 if (res
!=EQUIP_ERR_OK
)
9670 *no_space_count
= count
+ no_similar_count
;
9676 if (no_similar_count
==0)
9677 return EQUIP_ERR_OK
;
9680 *no_space_count
= count
+ no_similar_count
;
9681 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9685 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9687 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
9688 if (res
!=EQUIP_ERR_OK
)
9693 if (no_similar_count
==0)
9694 return EQUIP_ERR_OK
;
9697 *no_space_count
= count
+ no_similar_count
;
9698 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9704 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9705 if (res
!=EQUIP_ERR_OK
)
9708 *no_space_count
= count
+ no_similar_count
;
9714 if (no_similar_count
==0)
9715 return EQUIP_ERR_OK
;
9718 *no_space_count
= count
+ no_similar_count
;
9719 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9722 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9724 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
9725 if (res
!=EQUIP_ERR_OK
)
9730 if (no_similar_count
==0)
9731 return EQUIP_ERR_OK
;
9734 *no_space_count
= count
+ no_similar_count
;
9735 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9740 *no_space_count
= count
+ no_similar_count
;
9742 return EQUIP_ERR_INVENTORY_FULL
;
9745 //////////////////////////////////////////////////////////////////////////
9746 uint8
Player::CanStoreItems( Item
**pItems
,int count
) const
9751 int inv_slot_items
[INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
];
9752 int inv_bags
[INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
][MAX_BAG_SIZE
];
9753 int inv_keys
[KEYRING_SLOT_END
-KEYRING_SLOT_START
];
9754 int inv_tokens
[CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
];
9756 memset(inv_slot_items
,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
));
9757 memset(inv_bags
,0,sizeof(int)*(INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
)*MAX_BAG_SIZE
);
9758 memset(inv_keys
,0,sizeof(int)*(KEYRING_SLOT_END
-KEYRING_SLOT_START
));
9759 memset(inv_tokens
,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
));
9761 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
9763 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9765 if (pItem2
&& !pItem2
->IsInTrade())
9767 inv_slot_items
[i
-INVENTORY_SLOT_ITEM_START
] = pItem2
->GetCount();
9771 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; ++i
)
9773 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9775 if (pItem2
&& !pItem2
->IsInTrade())
9777 inv_keys
[i
-KEYRING_SLOT_START
] = pItem2
->GetCount();
9781 for(int i
= CURRENCYTOKEN_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
9783 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9785 if (pItem2
&& !pItem2
->IsInTrade())
9787 inv_tokens
[i
-CURRENCYTOKEN_SLOT_START
] = pItem2
->GetCount();
9791 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9793 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
9795 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9797 pItem2
= GetItemByPos( i
, j
);
9798 if (pItem2
&& !pItem2
->IsInTrade())
9800 inv_bags
[i
-INVENTORY_SLOT_BAG_START
][j
] = pItem2
->GetCount();
9806 // check free space for all items
9807 for (int k
= 0; k
< count
; ++k
)
9809 Item
*pItem
= pItems
[k
];
9812 if (!pItem
) continue;
9814 sLog
.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k
+1, pItem
->GetEntry(), pItem
->GetCount());
9815 ItemPrototype
const *pProto
= pItem
->GetProto();
9819 return EQUIP_ERR_ITEM_NOT_FOUND
;
9822 if(pItem
->m_lootGenerated
)
9823 return EQUIP_ERR_ALREADY_LOOTED
;
9826 if(pItem
->IsBindedNotWith(this))
9827 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9830 ItemPrototype
const *pBagProto
;
9832 // item is 'one item only'
9833 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9834 if(res
!= EQUIP_ERR_OK
)
9837 // search stack for merge to
9838 if( pProto
->Stackable
!= 1 )
9840 bool b_found
= false;
9842 for(int t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_END
; ++t
)
9844 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9845 if( pItem2
&& pItem2
->CanBeMergedPartlyWith(pProto
) == EQUIP_ERR_OK
&& inv_keys
[t
-KEYRING_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9847 inv_keys
[t
-KEYRING_SLOT_START
] += pItem
->GetCount();
9852 if (b_found
) continue;
9854 for(int t
= CURRENCYTOKEN_SLOT_START
; t
< CURRENCYTOKEN_SLOT_END
; ++t
)
9856 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9857 if( pItem2
&& pItem2
->CanBeMergedPartlyWith(pProto
) == EQUIP_ERR_OK
&& inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9859 inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] += pItem
->GetCount();
9864 if (b_found
) continue;
9866 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; ++t
)
9868 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9869 if( pItem2
&& pItem2
->CanBeMergedPartlyWith(pProto
) == EQUIP_ERR_OK
&& inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9871 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] += pItem
->GetCount();
9876 if (b_found
) continue;
9878 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; ++t
)
9880 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9883 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9885 pItem2
= GetItemByPos( t
, j
);
9886 if( pItem2
&& pItem2
->CanBeMergedPartlyWith(pProto
) == EQUIP_ERR_OK
&& inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9888 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] += pItem
->GetCount();
9895 if (b_found
) continue;
9899 if( pProto
->BagFamily
)
9901 bool b_found
= false;
9902 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9904 uint32 keyringSize
= GetMaxKeyringSize();
9905 for(uint32 t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_START
+keyringSize
; ++t
)
9907 if( inv_keys
[t
-KEYRING_SLOT_START
] == 0 )
9909 inv_keys
[t
-KEYRING_SLOT_START
] = 1;
9916 if (b_found
) continue;
9918 if(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
9920 for(uint32 t
= CURRENCYTOKEN_SLOT_START
; t
< CURRENCYTOKEN_SLOT_END
; ++t
)
9922 if( inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] == 0 )
9924 inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] = 1;
9931 if (b_found
) continue;
9933 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; ++t
)
9935 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9938 pBagProto
= pBag
->GetProto();
9940 // not plain container check
9941 if( pBagProto
&& (pBagProto
->Class
!= ITEM_CLASS_CONTAINER
|| pBagProto
->SubClass
!= ITEM_SUBCLASS_CONTAINER
) &&
9942 ItemCanGoIntoBag(pProto
,pBagProto
) )
9944 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9946 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9948 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9956 if (b_found
) continue;
9960 bool b_found
= false;
9961 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; ++t
)
9963 if( inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] == 0 )
9965 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] = 1;
9970 if (b_found
) continue;
9972 // search free slot in bags
9973 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; ++t
)
9975 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9978 pBagProto
= pBag
->GetProto();
9980 // special bag already checked
9981 if( pBagProto
&& (pBagProto
->Class
!= ITEM_CLASS_CONTAINER
|| pBagProto
->SubClass
!= ITEM_SUBCLASS_CONTAINER
))
9984 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9986 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9988 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9996 // no free slot found?
9998 return EQUIP_ERR_INVENTORY_FULL
;
10001 return EQUIP_ERR_OK
;
10004 //////////////////////////////////////////////////////////////////////////
10005 uint8
Player::CanEquipNewItem( uint8 slot
, uint16
&dest
, uint32 item
, bool swap
) const
10008 Item
*pItem
= Item::CreateItem( item
, 1, this );
10011 uint8 result
= CanEquipItem(slot
, dest
, pItem
, swap
);
10016 return EQUIP_ERR_ITEM_NOT_FOUND
;
10019 uint8
Player::CanEquipItem( uint8 slot
, uint16
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
10024 sLog
.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot
, pItem
->GetEntry(), pItem
->GetCount());
10025 ItemPrototype
const *pProto
= pItem
->GetProto();
10029 if(pItem
->m_lootGenerated
)
10030 return EQUIP_ERR_ALREADY_LOOTED
;
10032 if(pItem
->IsBindedNotWith(this))
10033 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
10035 // check count of items (skip for auto move for same player from bank)
10036 uint8 res
= CanTakeMoreSimilarItems(pItem
);
10037 if(res
!= EQUIP_ERR_OK
)
10040 // check this only in game
10043 // May be here should be more stronger checks; STUNNED checked
10044 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
10045 if (hasUnitState(UNIT_STAT_STUNNED
))
10046 return EQUIP_ERR_YOU_ARE_STUNNED
;
10048 // do not allow equipping gear except weapons, offhands, projectiles, relics in
10050 // - in-progress arenas
10051 if( !pProto
->CanChangeEquipStateInCombat() )
10054 return EQUIP_ERR_NOT_IN_COMBAT
;
10056 if(BattleGround
* bg
= GetBattleGround())
10057 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
10058 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
10061 if(isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
!= 0)
10062 return EQUIP_ERR_CANT_DO_RIGHT_NOW
; // maybe exist better err
10064 if(IsNonMeleeSpellCasted(false))
10065 return EQUIP_ERR_CANT_DO_RIGHT_NOW
;
10068 ScalingStatDistributionEntry
const *ssd
= pProto
->ScalingStatDistribution
? sScalingStatDistributionStore
.LookupEntry(pProto
->ScalingStatDistribution
) : 0;
10069 // 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)
10070 if (ssd
&& ssd
->MaxLevel
< DEFAULT_MAX_LEVEL
&& ssd
->MaxLevel
< getLevel())
10071 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
10073 uint8 eslot
= FindEquipSlot( pProto
, slot
, swap
);
10074 if (eslot
== NULL_SLOT
)
10075 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
10077 uint8 msg
= CanUseItem(pItem
, not_loading
);
10078 if (msg
!= EQUIP_ERR_OK
)
10080 if (!swap
&& GetItemByPos(INVENTORY_SLOT_BAG_0
, eslot
))
10081 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE
;
10083 // if swap ignore item (equipped also)
10084 if (uint8 res2
= CanEquipUniqueItem(pItem
, swap
? eslot
: NULL_SLOT
))
10087 // check unique-equipped special item classes
10088 if (pProto
->Class
== ITEM_CLASS_QUIVER
)
10090 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
10092 if (Item
* pBag
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
10096 if (ItemPrototype
const* pBagProto
= pBag
->GetProto())
10098 if (pBagProto
->Class
==pProto
->Class
&& (!swap
|| pBag
->GetSlot() != eslot
))
10099 return (pBagProto
->SubClass
== ITEM_SUBCLASS_AMMO_POUCH
)
10100 ? EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
10101 : EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER
;
10108 uint32 type
= pProto
->InventoryType
;
10110 if (eslot
== EQUIPMENT_SLOT_OFFHAND
)
10112 if (type
== INVTYPE_WEAPON
|| type
== INVTYPE_WEAPONOFFHAND
)
10114 if (!CanDualWield())
10115 return EQUIP_ERR_CANT_DUAL_WIELD
;
10117 else if (type
== INVTYPE_2HWEAPON
)
10119 if (!CanDualWield() || !CanTitanGrip())
10120 return EQUIP_ERR_CANT_DUAL_WIELD
;
10123 if (IsTwoHandUsed())
10124 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED
;
10127 // equip two-hand weapon case (with possible unequip 2 items)
10128 if (type
== INVTYPE_2HWEAPON
)
10130 if (eslot
== EQUIPMENT_SLOT_OFFHAND
)
10132 if (!CanTitanGrip())
10133 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
10135 else if (eslot
!= EQUIPMENT_SLOT_MAINHAND
)
10136 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
10138 if (!CanTitanGrip())
10140 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
10141 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
10142 ItemPosCountVec off_dest
;
10143 if (offItem
&& (!not_loading
||
10144 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0
) << 8 | EQUIPMENT_SLOT_OFFHAND
,false) != EQUIP_ERR_OK
||
10145 CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false ) != EQUIP_ERR_OK
))
10146 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_INVENTORY_FULL
;
10149 dest
= ((INVENTORY_SLOT_BAG_0
<< 8) | eslot
);
10150 return EQUIP_ERR_OK
;
10154 return !swap
? EQUIP_ERR_ITEM_NOT_FOUND
: EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
;
10157 uint8
Player::CanUnequipItem( uint16 pos
, bool swap
) const
10159 // Applied only to equipped items and bank bags
10160 if(!IsEquipmentPos(pos
) && !IsBagPos(pos
))
10161 return EQUIP_ERR_OK
;
10163 Item
* pItem
= GetItemByPos(pos
);
10165 // Applied only to existed equipped item
10167 return EQUIP_ERR_OK
;
10169 sLog
.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos
, pItem
->GetEntry(), pItem
->GetCount());
10171 ItemPrototype
const *pProto
= pItem
->GetProto();
10173 return EQUIP_ERR_ITEM_NOT_FOUND
;
10176 if(pItem
->m_lootGenerated
)
10177 return EQUIP_ERR_ALREADY_LOOTED
;
10179 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
10181 // - in-progress arenas
10182 if( !pProto
->CanChangeEquipStateInCombat() )
10185 return EQUIP_ERR_NOT_IN_COMBAT
;
10187 if(BattleGround
* bg
= GetBattleGround())
10188 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
10189 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
10192 if(!swap
&& pItem
->IsBag() && !((Bag
*)pItem
)->IsEmpty())
10193 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS
;
10195 return EQUIP_ERR_OK
;
10198 uint8
Player::CanBankItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
10201 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
10203 uint32 count
= pItem
->GetCount();
10205 sLog
.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), pItem
->GetCount());
10206 ItemPrototype
const *pProto
= pItem
->GetProto();
10208 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
10211 if(pItem
->m_lootGenerated
)
10212 return EQUIP_ERR_ALREADY_LOOTED
;
10214 if (pItem
->IsBindedNotWith(this))
10215 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
10217 // check count of items (skip for auto move for same player from bank)
10218 uint8 res
= CanTakeMoreSimilarItems(pItem
);
10219 if (res
!= EQUIP_ERR_OK
)
10222 // in specific slot
10223 if (bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
10225 if (slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
10227 if (!pItem
->IsBag())
10228 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
;
10230 if (slot
- BANK_SLOT_BAG_START
>= GetBankBagSlotCount())
10231 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT
;
10233 if (uint8 cantuse
= CanUseItem( pItem
, not_loading
) != EQUIP_ERR_OK
)
10237 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
10238 if (res
!=EQUIP_ERR_OK
)
10242 return EQUIP_ERR_OK
;
10245 // not specific slot or have space for partly store only in specific slot
10248 if( bag
!= NULL_BAG
)
10250 if( pProto
->InventoryType
== INVTYPE_BAG
)
10252 Bag
*pBag
= (Bag
*)pItem
;
10253 if( pBag
&& !pBag
->IsEmpty() )
10254 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
;
10257 // search stack in bag for merge to
10258 if( pProto
->Stackable
!= 1 )
10260 if( bag
== INVENTORY_SLOT_BAG_0
)
10262 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
10263 if(res
!=EQUIP_ERR_OK
)
10267 return EQUIP_ERR_OK
;
10271 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
10272 if(res
!=EQUIP_ERR_OK
)
10273 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
10275 if(res
!=EQUIP_ERR_OK
)
10279 return EQUIP_ERR_OK
;
10283 // search free slot in bag
10284 if( bag
== INVENTORY_SLOT_BAG_0
)
10286 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
10287 if(res
!=EQUIP_ERR_OK
)
10291 return EQUIP_ERR_OK
;
10295 res
= _CanStoreItem_InBag(bag
, dest
, pProto
, count
, false, false, pItem
, NULL_BAG
, slot
);
10296 if(res
!= EQUIP_ERR_OK
)
10297 res
= _CanStoreItem_InBag(bag
, dest
, pProto
, count
, false, true, pItem
, NULL_BAG
, slot
);
10299 if(res
!= EQUIP_ERR_OK
)
10303 return EQUIP_ERR_OK
;
10307 // not specific bag or have space for partly store only in specific bag
10309 // search stack for merge to
10310 if( pProto
->Stackable
!= 1 )
10313 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
10314 if(res
!= EQUIP_ERR_OK
)
10318 return EQUIP_ERR_OK
;
10321 if( pProto
->BagFamily
)
10323 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
10325 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
10326 if(res
!=EQUIP_ERR_OK
)
10330 return EQUIP_ERR_OK
;
10334 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
10336 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
10337 if(res
!=EQUIP_ERR_OK
)
10341 return EQUIP_ERR_OK
;
10345 // search free place in special bag
10346 if( pProto
->BagFamily
)
10348 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
10350 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
10351 if(res
!=EQUIP_ERR_OK
)
10355 return EQUIP_ERR_OK
;
10359 // search free space
10360 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
10361 if(res
!=EQUIP_ERR_OK
)
10365 return EQUIP_ERR_OK
;
10367 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
10369 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
10370 if(res
!=EQUIP_ERR_OK
)
10374 return EQUIP_ERR_OK
;
10376 return EQUIP_ERR_BANK_FULL
;
10379 uint8
Player::CanUseItem( Item
*pItem
, bool not_loading
) const
10383 sLog
.outDebug( "STORAGE: CanUseItem item = %u", pItem
->GetEntry());
10385 if (!isAlive() && not_loading
)
10386 return EQUIP_ERR_YOU_ARE_DEAD
;
10389 // return EQUIP_ERR_YOU_ARE_STUNNED;
10391 ItemPrototype
const *pProto
= pItem
->GetProto();
10394 if (pItem
->IsBindedNotWith(this))
10395 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
10397 if ((pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0)
10398 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
10400 if (uint32 item_use_skill
= pItem
->GetSkill())
10402 if (GetSkillValue(item_use_skill
) == 0)
10404 // armor items with scaling stats can downgrade armor skill reqs if related class can learn armor use at some level
10405 if (pProto
->Class
!= ITEM_CLASS_ARMOR
)
10406 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10408 ScalingStatDistributionEntry
const *ssd
= pProto
->ScalingStatDistribution
? sScalingStatDistributionStore
.LookupEntry(pProto
->ScalingStatDistribution
) : NULL
;
10410 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10412 bool allowScaleSkill
= false;
10413 for (uint32 i
= 0; i
< sSkillLineAbilityStore
.GetNumRows(); ++i
)
10415 SkillLineAbilityEntry
const *skillInfo
= sSkillLineAbilityStore
.LookupEntry(i
);
10419 if (skillInfo
->skillId
!= item_use_skill
)
10423 if (skillInfo
->classmask
&& (skillInfo
->classmask
& getClassMask()) == 0)
10426 if (skillInfo
->racemask
&& (skillInfo
->racemask
& getRaceMask()) == 0)
10429 allowScaleSkill
= true;
10433 if (!allowScaleSkill
)
10434 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10438 if (pProto
->RequiredSkill
!= 0)
10440 if (GetSkillValue( pProto
->RequiredSkill
) == 0)
10441 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10443 if (GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10444 return EQUIP_ERR_CANT_EQUIP_SKILL
;
10447 if (pProto
->RequiredSpell
!= 0 && !HasSpell(pProto
->RequiredSpell
))
10448 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10450 if (pProto
->RequiredReputationFaction
&& uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
10451 return EQUIP_ERR_CANT_EQUIP_REPUTATION
;
10453 if (getLevel() < pProto
->RequiredLevel
)
10454 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
10456 return EQUIP_ERR_OK
;
10459 return EQUIP_ERR_ITEM_NOT_FOUND
;
10462 bool Player::CanUseItem( ItemPrototype
const *pProto
)
10464 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10468 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
10470 if( pProto
->RequiredSkill
!= 0 )
10472 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
10474 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10477 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
10479 if( getLevel() < pProto
->RequiredLevel
)
10486 uint8
Player::CanUseAmmo( uint32 item
) const
10488 sLog
.outDebug( "STORAGE: CanUseAmmo item = %u", item
);
10490 return EQUIP_ERR_YOU_ARE_DEAD
;
10491 //if( isStunned() )
10492 // return EQUIP_ERR_YOU_ARE_STUNNED;
10493 ItemPrototype
const *pProto
= ObjectMgr::GetItemPrototype( item
);
10496 if( pProto
->InventoryType
!= INVTYPE_AMMO
)
10497 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE
;
10498 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
10499 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
10500 if( pProto
->RequiredSkill
!= 0 )
10502 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
10503 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10504 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10505 return EQUIP_ERR_CANT_EQUIP_SKILL
;
10507 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
10508 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10509 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
10510 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10512 if( getLevel() < pProto
->RequiredLevel
)
10513 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
10515 // Requires No Ammo
10516 if(GetDummyAura(46699))
10517 return EQUIP_ERR_BAG_FULL6
;
10519 return EQUIP_ERR_OK
;
10521 return EQUIP_ERR_ITEM_NOT_FOUND
;
10524 void Player::SetAmmo( uint32 item
)
10530 if( GetUInt32Value(PLAYER_AMMO_ID
) == item
)
10536 uint8 msg
= CanUseAmmo( item
);
10537 if (msg
!= EQUIP_ERR_OK
)
10539 SendEquipError(msg
, NULL
, NULL
, item
);
10544 SetUInt32Value(PLAYER_AMMO_ID
, item
);
10546 _ApplyAmmoBonuses();
10549 void Player::RemoveAmmo()
10551 SetUInt32Value(PLAYER_AMMO_ID
, 0);
10555 if (CanModifyStats())
10556 UpdateDamagePhysical(RANGED_ATTACK
);
10559 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10560 Item
* Player::StoreNewItem( ItemPosCountVec
const& dest
, uint32 item
, bool update
,int32 randomPropertyId
)
10563 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); ++itr
)
10564 count
+= itr
->count
;
10566 Item
*pItem
= Item::CreateItem( item
, count
, this );
10569 ItemAddedQuestCheck( item
, count
);
10570 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM
, item
, count
);
10571 if(randomPropertyId
)
10572 pItem
->SetItemRandomProperties(randomPropertyId
);
10573 pItem
= StoreItem( dest
, pItem
, update
);
10578 Item
* Player::StoreItem( ItemPosCountVec
const& dest
, Item
* pItem
, bool update
)
10583 Item
* lastItem
= pItem
;
10584 uint32 entry
= pItem
->GetEntry();
10585 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); )
10587 uint16 pos
= itr
->pos
;
10588 uint32 count
= itr
->count
;
10592 if(itr
== dest
.end())
10594 lastItem
= _StoreItem(pos
,pItem
,count
,false,update
);
10598 lastItem
= _StoreItem(pos
,pItem
,count
,true,update
);
10600 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM
, entry
);
10604 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10605 Item
* Player::_StoreItem( uint16 pos
, Item
*pItem
, uint32 count
, bool clone
, bool update
)
10610 uint8 bag
= pos
>> 8;
10611 uint8 slot
= pos
& 255;
10613 sLog
.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), count
);
10615 Item
*pItem2
= GetItemByPos( bag
, slot
);
10620 pItem
= pItem
->CloneItem(count
, this);
10622 pItem
->SetCount(count
);
10627 if (pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10628 pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10629 (pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
)))
10630 pItem
->SetBinding( true );
10632 if (bag
== INVENTORY_SLOT_BAG_0
)
10634 m_items
[slot
] = pItem
;
10635 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2), pItem
->GetGUID() );
10636 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10637 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10639 pItem
->SetSlot( slot
);
10640 pItem
->SetContainer( NULL
);
10642 // need update known currency
10643 if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)
10644 UpdateKnownCurrencies(pItem
->GetEntry(), true);
10646 if (IsInWorld() && update
)
10648 pItem
->AddToWorld();
10649 pItem
->SendCreateUpdateToPlayer( this );
10652 pItem
->SetState(ITEM_CHANGED
, this);
10654 else if (Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
))
10656 pBag
->StoreItem( slot
, pItem
, update
);
10657 if( IsInWorld() && update
)
10659 pItem
->AddToWorld();
10660 pItem
->SendCreateUpdateToPlayer( this );
10662 pItem
->SetState(ITEM_CHANGED
, this);
10663 pBag
->SetState(ITEM_CHANGED
, this);
10666 AddEnchantmentDurations(pItem
);
10667 AddItemDurations(pItem
);
10673 if (pItem2
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10674 pItem2
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10675 (pItem2
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
)))
10676 pItem2
->SetBinding( true );
10678 pItem2
->SetCount( pItem2
->GetCount() + count
);
10679 if (IsInWorld() && update
)
10680 pItem2
->SendCreateUpdateToPlayer( this );
10684 // delete item (it not in any slot currently)
10685 if (IsInWorld() && update
)
10687 pItem
->RemoveFromWorld();
10688 pItem
->DestroyForPlayer( this );
10691 RemoveEnchantmentDurations(pItem
);
10692 RemoveItemDurations(pItem
);
10694 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10695 pItem
->SetState(ITEM_REMOVED
, this);
10698 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10699 AddEnchantmentDurations(pItem2
);
10701 pItem2
->SetState(ITEM_CHANGED
, this);
10707 Item
* Player::EquipNewItem( uint16 pos
, uint32 item
, bool update
)
10709 if (Item
*pItem
= Item::CreateItem( item
, 1, this ))
10711 ItemAddedQuestCheck( item
, 1 );
10712 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM
, item
, 1);
10713 return EquipItem( pos
, pItem
, update
);
10719 Item
* Player::EquipItem( uint16 pos
, Item
*pItem
, bool update
)
10721 AddEnchantmentDurations(pItem
);
10722 AddItemDurations(pItem
);
10724 uint8 bag
= pos
>> 8;
10725 uint8 slot
= pos
& 255;
10727 Item
*pItem2
= GetItemByPos( bag
, slot
);
10731 VisualizeItem( slot
, pItem
);
10735 ItemPrototype
const *pProto
= pItem
->GetProto();
10737 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10738 if(pProto
&& pProto
->ItemSet
)
10739 AddItemsSetItem(this, pItem
);
10741 _ApplyItemMods(pItem
, slot
, true);
10743 if(pProto
&& isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
== 0)
10745 uint32 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s
;
10747 if (getClass() == CLASS_ROGUE
)
10748 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s
;
10750 SpellEntry
const* spellProto
= sSpellStore
.LookupEntry(cooldownSpell
);
10753 sLog
.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell
);
10756 m_weaponChangeTimer
= spellProto
->StartRecoveryTime
;
10758 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+4);
10759 data
<< uint64(GetGUID());
10761 data
<< uint32(cooldownSpell
);
10763 GetSession()->SendPacket(&data
);
10768 if( IsInWorld() && update
)
10770 pItem
->AddToWorld();
10771 pItem
->SendCreateUpdateToPlayer( this );
10774 ApplyEquipCooldown(pItem
);
10776 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
10778 UpdateExpertise(BASE_ATTACK
);
10779 UpdateArmorPenetration();
10781 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10783 UpdateExpertise(OFF_ATTACK
);
10784 UpdateArmorPenetration();
10789 pItem2
->SetCount( pItem2
->GetCount() + pItem
->GetCount() );
10790 if( IsInWorld() && update
)
10791 pItem2
->SendCreateUpdateToPlayer( this );
10793 // delete item (it not in any slot currently)
10794 //pItem->DeleteFromDB();
10795 if( IsInWorld() && update
)
10797 pItem
->RemoveFromWorld();
10798 pItem
->DestroyForPlayer( this );
10801 RemoveEnchantmentDurations(pItem
);
10802 RemoveItemDurations(pItem
);
10804 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10805 pItem
->SetState(ITEM_REMOVED
, this);
10806 pItem2
->SetState(ITEM_CHANGED
, this);
10808 ApplyEquipCooldown(pItem2
);
10813 // only for full equip instead adding to stack
10814 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM
, pItem
->GetEntry());
10815 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM
, slot
+1);
10820 void Player::QuickEquipItem( uint16 pos
, Item
*pItem
)
10824 AddEnchantmentDurations(pItem
);
10825 AddItemDurations(pItem
);
10827 uint8 slot
= pos
& 255;
10828 VisualizeItem( slot
, pItem
);
10832 pItem
->AddToWorld();
10833 pItem
->SendCreateUpdateToPlayer( this );
10836 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM
, pItem
->GetEntry());
10837 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM
, slot
+1);
10841 void Player::SetVisibleItemSlot(uint8 slot
, Item
*pItem
)
10845 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID
+ (slot
* 2), pItem
->GetEntry());
10846 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT
+ (slot
* 2), 0, pItem
->GetEnchantmentId(PERM_ENCHANTMENT_SLOT
));
10847 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT
+ (slot
* 2), 1, pItem
->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT
));
10851 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID
+ (slot
* 2), 0);
10852 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT
+ (slot
* 2), 0);
10856 void Player::VisualizeItem( uint8 slot
, Item
*pItem
)
10861 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10862 if( pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
|| pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
|| pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
)
10863 pItem
->SetBinding( true );
10865 sLog
.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot
, pItem
->GetEntry());
10867 m_items
[slot
] = pItem
;
10868 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2), pItem
->GetGUID() );
10869 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10870 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10871 pItem
->SetSlot( slot
);
10872 pItem
->SetContainer( NULL
);
10874 if( slot
< EQUIPMENT_SLOT_END
)
10875 SetVisibleItemSlot(slot
, pItem
);
10877 pItem
->SetState(ITEM_CHANGED
, this);
10880 void Player::RemoveItem( uint8 bag
, uint8 slot
, bool update
)
10882 // note: removeitem does not actually change the item
10883 // it only takes the item out of storage temporarily
10884 // note2: if removeitem is to be used for delinking
10885 // the item must be removed from the player's updatequeue
10887 Item
*pItem
= GetItemByPos( bag
, slot
);
10890 sLog
.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10892 RemoveEnchantmentDurations(pItem
);
10893 RemoveItemDurations(pItem
);
10895 if( bag
== INVENTORY_SLOT_BAG_0
)
10897 if ( slot
< INVENTORY_SLOT_BAG_END
)
10899 ItemPrototype
const *pProto
= pItem
->GetProto();
10900 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10902 if(pProto
&& pProto
->ItemSet
)
10903 RemoveItemsSetItem(this, pProto
);
10905 _ApplyItemMods(pItem
, slot
, false);
10907 // remove item dependent auras and casts (only weapon and armor slots)
10908 if(slot
< EQUIPMENT_SLOT_END
)
10910 RemoveItemDependentAurasAndCasts(pItem
);
10912 // remove held enchantments, update expertise
10913 if ( slot
== EQUIPMENT_SLOT_MAINHAND
)
10915 if (pItem
->GetItemSuffixFactor())
10917 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3
);
10918 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4
);
10922 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0
);
10923 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1
);
10926 UpdateExpertise(BASE_ATTACK
);
10927 UpdateArmorPenetration();
10929 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10931 UpdateExpertise(OFF_ATTACK
);
10932 UpdateArmorPenetration();
10936 // need update known currency
10937 else if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)
10938 UpdateKnownCurrencies(pItem
->GetEntry(), false);
10940 m_items
[slot
] = NULL
;
10941 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2), 0);
10943 if ( slot
< EQUIPMENT_SLOT_END
)
10944 SetVisibleItemSlot(slot
, NULL
);
10948 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
10950 pBag
->RemoveItem(slot
, update
);
10952 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10953 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10954 pItem
->SetSlot( NULL_SLOT
);
10955 if( IsInWorld() && update
)
10956 pItem
->SendCreateUpdateToPlayer( this );
10960 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10961 void Player::MoveItemFromInventory(uint8 bag
, uint8 slot
, bool update
)
10963 if(Item
* it
= GetItemByPos(bag
,slot
))
10965 ItemRemovedQuestCheck(it
->GetEntry(), it
->GetCount());
10966 RemoveItem(bag
, slot
, update
);
10967 it
->RemoveFromUpdateQueueOf(this);
10968 if(it
->IsInWorld())
10970 it
->RemoveFromWorld();
10971 it
->DestroyForPlayer( this );
10976 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10977 void Player::MoveItemToInventory(ItemPosCountVec
const& dest
, Item
* pItem
, bool update
, bool in_characterInventoryDB
)
10979 // update quest counters
10980 ItemAddedQuestCheck(pItem
->GetEntry(), pItem
->GetCount());
10981 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM
, pItem
->GetEntry(), pItem
->GetCount());
10984 Item
* pLastItem
= StoreItem(dest
, pItem
, update
);
10986 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10987 if(pLastItem
== pItem
)
10989 // update owner for last item (this can be original item with wrong owner
10990 if(pLastItem
->GetOwnerGUID() != GetGUID())
10991 pLastItem
->SetOwnerGUID(GetGUID());
10993 // if this original item then it need create record in inventory
10994 // in case trade we already have item in other player inventory
10995 pLastItem
->SetState(in_characterInventoryDB
? ITEM_CHANGED
: ITEM_NEW
, this);
10999 void Player::DestroyItem( uint8 bag
, uint8 slot
, bool update
)
11001 Item
*pItem
= GetItemByPos( bag
, slot
);
11004 sLog
.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
11006 // start from destroy contained items (only equipped bag can have its)
11007 if (pItem
->IsBag() && pItem
->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
11009 for (int i
= 0; i
< MAX_BAG_SIZE
; ++i
)
11010 DestroyItem(slot
, i
, update
);
11013 if(pItem
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_WRAPPED
))
11014 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem
->GetGUIDLow());
11016 RemoveEnchantmentDurations(pItem
);
11017 RemoveItemDurations(pItem
);
11019 ItemRemovedQuestCheck( pItem
->GetEntry(), pItem
->GetCount() );
11021 if( bag
== INVENTORY_SLOT_BAG_0
)
11023 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2), 0);
11025 // equipment and equipped bags can have applied bonuses
11026 if ( slot
< INVENTORY_SLOT_BAG_END
)
11028 ItemPrototype
const *pProto
= pItem
->GetProto();
11030 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
11031 if(pProto
&& pProto
->ItemSet
)
11032 RemoveItemsSetItem(this, pProto
);
11034 _ApplyItemMods(pItem
, slot
, false);
11037 if ( slot
< EQUIPMENT_SLOT_END
)
11039 // remove item dependent auras and casts (only weapon and armor slots)
11040 RemoveItemDependentAurasAndCasts(pItem
);
11042 // update expertise
11043 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
11045 UpdateExpertise(BASE_ATTACK
);
11046 UpdateArmorPenetration();
11048 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
11050 UpdateExpertise(OFF_ATTACK
);
11051 UpdateArmorPenetration();
11054 // equipment visual show
11055 SetVisibleItemSlot(slot
, NULL
);
11057 // need update known currency
11058 else if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)
11059 UpdateKnownCurrencies(pItem
->GetEntry(), false);
11061 m_items
[slot
] = NULL
;
11063 else if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
))
11064 pBag
->RemoveItem(slot
, update
);
11066 if( IsInWorld() && update
)
11068 pItem
->RemoveFromWorld();
11069 pItem
->DestroyForPlayer(this);
11072 //pItem->SetOwnerGUID(0);
11073 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
11074 pItem
->SetSlot( NULL_SLOT
);
11075 pItem
->SetState(ITEM_REMOVED
, this);
11079 void Player::DestroyItemCount( uint32 item
, uint32 count
, bool update
, bool unequip_check
)
11081 sLog
.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item
, count
);
11082 uint32 remcount
= 0;
11085 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
11087 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11089 if (pItem
->GetEntry() == item
)
11091 if (pItem
->GetCount() + remcount
<= count
)
11093 // all items in inventory can unequipped
11094 remcount
+= pItem
->GetCount();
11095 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11097 if (remcount
>= count
)
11102 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
11103 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
11104 if (IsInWorld() & update
)
11105 pItem
->SendCreateUpdateToPlayer( this );
11106 pItem
->SetState(ITEM_CHANGED
, this);
11113 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
11115 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11117 if (pItem
->GetEntry() == item
)
11119 if (pItem
->GetCount() + remcount
<= count
)
11121 // all keys can be unequipped
11122 remcount
+= pItem
->GetCount();
11123 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11125 if (remcount
>= count
)
11130 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
11131 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
11132 if (IsInWorld() & update
)
11133 pItem
->SendCreateUpdateToPlayer( this );
11134 pItem
->SetState(ITEM_CHANGED
, this);
11141 // in inventory bags
11142 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
11144 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11146 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
11148 if(Item
* pItem
= pBag
->GetItemByPos(j
))
11150 if (pItem
->GetEntry() == item
)
11152 // all items in bags can be unequipped
11153 if (pItem
->GetCount() + remcount
<= count
)
11155 remcount
+= pItem
->GetCount();
11156 DestroyItem( i
, j
, update
);
11158 if (remcount
>= count
)
11163 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
11164 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
11165 if (IsInWorld() && update
)
11166 pItem
->SendCreateUpdateToPlayer( this );
11167 pItem
->SetState(ITEM_CHANGED
, this);
11176 // in equipment and bag list
11177 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
11179 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11181 if (pItem
&& pItem
->GetEntry() == item
)
11183 if (pItem
->GetCount() + remcount
<= count
)
11185 if (!unequip_check
|| CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
, false) == EQUIP_ERR_OK
)
11187 remcount
+= pItem
->GetCount();
11188 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11190 if (remcount
>= count
)
11196 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
11197 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
11198 if (IsInWorld() & update
)
11199 pItem
->SendCreateUpdateToPlayer( this );
11200 pItem
->SetState(ITEM_CHANGED
, this);
11208 void Player::DestroyZoneLimitedItem( bool update
, uint32 new_zone
)
11210 sLog
.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone
);
11213 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
11214 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11215 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone
))
11216 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11218 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
11219 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11220 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone
))
11221 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11223 // in inventory bags
11224 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
11225 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11226 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
11227 if (Item
* pItem
= pBag
->GetItemByPos(j
))
11228 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone
))
11229 DestroyItem(i
, j
, update
);
11231 // in equipment and bag list
11232 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
11233 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11234 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone
))
11235 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11238 void Player::DestroyConjuredItems( bool update
)
11240 // used when entering arena
11241 // destroys all conjured items
11242 sLog
.outDebug( "STORAGE: DestroyConjuredItems" );
11245 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
11246 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11247 if (pItem
->IsConjuredConsumable())
11248 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11250 // in inventory bags
11251 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
11252 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11253 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
11254 if (Item
* pItem
= pBag
->GetItemByPos(j
))
11255 if (pItem
->IsConjuredConsumable())
11256 DestroyItem( i
, j
, update
);
11258 // in equipment and bag list
11259 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
11260 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11261 if (pItem
->IsConjuredConsumable())
11262 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11265 void Player::DestroyItemCount( Item
* pItem
, uint32
&count
, bool update
)
11270 sLog
.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem
->GetGUIDLow(),pItem
->GetEntry(), count
);
11272 if( pItem
->GetCount() <= count
)
11274 count
-= pItem
->GetCount();
11276 DestroyItem( pItem
->GetBagSlot(),pItem
->GetSlot(), update
);
11280 ItemRemovedQuestCheck( pItem
->GetEntry(), count
);
11281 pItem
->SetCount( pItem
->GetCount() - count
);
11283 if( IsInWorld() & update
)
11284 pItem
->SendCreateUpdateToPlayer( this );
11285 pItem
->SetState(ITEM_CHANGED
, this);
11289 void Player::SplitItem( uint16 src
, uint16 dst
, uint32 count
)
11291 uint8 srcbag
= src
>> 8;
11292 uint8 srcslot
= src
& 255;
11294 uint8 dstbag
= dst
>> 8;
11295 uint8 dstslot
= dst
& 255;
11297 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
11300 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
11304 if(pSrcItem
->m_lootGenerated
) // prevent split looting item (item
11306 //best error message found for attempting to split while looting
11307 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
11311 // not let split all items (can be only at cheating)
11312 if(pSrcItem
->GetCount() == count
)
11314 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
11318 // not let split more existed items (can be only at cheating)
11319 if(pSrcItem
->GetCount() < count
)
11321 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT
, pSrcItem
, NULL
);
11325 sLog
.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag
, dstslot
, pSrcItem
->GetEntry(), count
);
11326 Item
*pNewItem
= pSrcItem
->CloneItem( count
, this );
11329 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
11333 if( IsInventoryPos( dst
) )
11335 // change item amount before check (for unique max count check)
11336 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11338 ItemPosCountVec dest
;
11339 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pNewItem
, false );
11340 if( msg
!= EQUIP_ERR_OK
)
11343 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11344 SendEquipError( msg
, pSrcItem
, NULL
);
11349 pSrcItem
->SendCreateUpdateToPlayer( this );
11350 pSrcItem
->SetState(ITEM_CHANGED
, this);
11351 StoreItem( dest
, pNewItem
, true);
11353 else if( IsBankPos ( dst
) )
11355 // change item amount before check (for unique max count check)
11356 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11358 ItemPosCountVec dest
;
11359 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pNewItem
, false );
11360 if( msg
!= EQUIP_ERR_OK
)
11363 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11364 SendEquipError( msg
, pSrcItem
, NULL
);
11369 pSrcItem
->SendCreateUpdateToPlayer( this );
11370 pSrcItem
->SetState(ITEM_CHANGED
, this);
11371 BankItem( dest
, pNewItem
, true);
11373 else if( IsEquipmentPos ( dst
) )
11375 // change item amount before check (for unique max count check), provide space for splitted items
11376 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11379 uint8 msg
= CanEquipItem( dstslot
, dest
, pNewItem
, false );
11380 if( msg
!= EQUIP_ERR_OK
)
11383 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11384 SendEquipError( msg
, pSrcItem
, NULL
);
11389 pSrcItem
->SendCreateUpdateToPlayer( this );
11390 pSrcItem
->SetState(ITEM_CHANGED
, this);
11391 EquipItem( dest
, pNewItem
, true);
11392 AutoUnequipOffhandIfNeed();
11396 void Player::SwapItem( uint16 src
, uint16 dst
)
11398 uint8 srcbag
= src
>> 8;
11399 uint8 srcslot
= src
& 255;
11401 uint8 dstbag
= dst
>> 8;
11402 uint8 dstslot
= dst
& 255;
11404 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
11405 Item
*pDstItem
= GetItemByPos( dstbag
, dstslot
);
11410 sLog
.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag
, dstslot
, pSrcItem
->GetEntry());
11414 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD
, pSrcItem
, pDstItem
);
11420 // check unequip potability for equipped items and bank bags
11421 if (IsEquipmentPos(src
) || IsBagPos(src
))
11423 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11424 uint8 msg
= CanUnequipItem( src
, !IsBagPos ( src
) || IsBagPos ( dst
) || (pDstItem
&& pDstItem
->IsBag() && ((Bag
*)pDstItem
)->IsEmpty()));
11425 if (msg
!= EQUIP_ERR_OK
)
11427 SendEquipError( msg
, pSrcItem
, pDstItem
);
11432 // prevent put equipped/bank bag in self
11433 if (IsBagPos(src
) && srcslot
== dstbag
)
11435 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
11439 // prevent put equipped/bank bag in self
11440 if (IsBagPos(dst
) && dstslot
== srcbag
)
11442 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pDstItem
, pSrcItem
);
11450 // check unequip potability for equipped items and bank bags
11451 if(IsEquipmentPos ( dst
) || IsBagPos ( dst
))
11453 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11454 uint8 msg
= CanUnequipItem( dst
, !IsBagPos ( dst
) || IsBagPos ( src
) || (pSrcItem
->IsBag() && ((Bag
*)pSrcItem
)->IsEmpty()));
11455 if(msg
!= EQUIP_ERR_OK
)
11457 SendEquipError( msg
, pSrcItem
, pDstItem
);
11463 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
11464 // or swap empty bag with another empty or not empty bag (with items exchange)
11469 if( IsInventoryPos( dst
) )
11471 ItemPosCountVec dest
;
11472 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pSrcItem
, false );
11473 if( msg
!= EQUIP_ERR_OK
)
11475 SendEquipError( msg
, pSrcItem
, NULL
);
11479 RemoveItem(srcbag
, srcslot
, true);
11480 StoreItem( dest
, pSrcItem
, true);
11482 else if( IsBankPos ( dst
) )
11484 ItemPosCountVec dest
;
11485 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pSrcItem
, false);
11486 if( msg
!= EQUIP_ERR_OK
)
11488 SendEquipError( msg
, pSrcItem
, NULL
);
11492 RemoveItem(srcbag
, srcslot
, true);
11493 BankItem( dest
, pSrcItem
, true);
11495 else if( IsEquipmentPos ( dst
) )
11498 uint8 msg
= CanEquipItem( dstslot
, dest
, pSrcItem
, false );
11499 if( msg
!= EQUIP_ERR_OK
)
11501 SendEquipError( msg
, pSrcItem
, NULL
);
11505 RemoveItem(srcbag
, srcslot
, true);
11506 EquipItem(dest
, pSrcItem
, true);
11507 AutoUnequipOffhandIfNeed();
11513 // attempt merge to / fill target item
11514 if(!pSrcItem
->IsBag() && !pDstItem
->IsBag())
11517 ItemPosCountVec sDest
;
11519 if( IsInventoryPos( dst
) )
11520 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
11521 else if( IsBankPos ( dst
) )
11522 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
11523 else if( IsEquipmentPos ( dst
) )
11524 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, false );
11528 // can be merge/fill
11529 if(msg
== EQUIP_ERR_OK
)
11531 if( pSrcItem
->GetCount() + pDstItem
->GetCount() <= pSrcItem
->GetProto()->GetMaxStackSize())
11533 RemoveItem(srcbag
, srcslot
, true);
11535 if( IsInventoryPos( dst
) )
11536 StoreItem( sDest
, pSrcItem
, true);
11537 else if( IsBankPos ( dst
) )
11538 BankItem( sDest
, pSrcItem
, true);
11539 else if( IsEquipmentPos ( dst
) )
11541 EquipItem( eDest
, pSrcItem
, true);
11542 AutoUnequipOffhandIfNeed();
11547 pSrcItem
->SetCount( pSrcItem
->GetCount() + pDstItem
->GetCount() - pSrcItem
->GetProto()->GetMaxStackSize());
11548 pDstItem
->SetCount( pSrcItem
->GetProto()->GetMaxStackSize());
11549 pSrcItem
->SetState(ITEM_CHANGED
, this);
11550 pDstItem
->SetState(ITEM_CHANGED
, this);
11553 pSrcItem
->SendCreateUpdateToPlayer( this );
11554 pDstItem
->SendCreateUpdateToPlayer( this );
11561 // impossible merge/fill, do real swap
11564 // check src->dest move possibility
11565 ItemPosCountVec sDest
;
11567 if( IsInventoryPos( dst
) )
11568 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
11569 else if( IsBankPos( dst
) )
11570 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
11571 else if( IsEquipmentPos( dst
) )
11573 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, true );
11574 if( msg
== EQUIP_ERR_OK
)
11575 msg
= CanUnequipItem( eDest
, true );
11578 if( msg
!= EQUIP_ERR_OK
)
11580 SendEquipError( msg
, pSrcItem
, pDstItem
);
11584 // check dest->src move possibility
11585 ItemPosCountVec sDest2
;
11587 if( IsInventoryPos( src
) )
11588 msg
= CanStoreItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11589 else if( IsBankPos( src
) )
11590 msg
= CanBankItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11591 else if( IsEquipmentPos( src
) )
11593 msg
= CanEquipItem( srcslot
, eDest2
, pDstItem
, true);
11594 if( msg
== EQUIP_ERR_OK
)
11595 msg
= CanUnequipItem( eDest2
, true);
11598 if( msg
!= EQUIP_ERR_OK
)
11600 SendEquipError( msg
, pDstItem
, pSrcItem
);
11604 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11605 if(pSrcItem
->IsBag() && pDstItem
->IsBag())
11607 Bag
* emptyBag
= NULL
;
11608 Bag
* fullBag
= NULL
;
11609 if(((Bag
*)pSrcItem
)->IsEmpty() && !IsBagPos(src
))
11611 emptyBag
= (Bag
*)pSrcItem
;
11612 fullBag
= (Bag
*)pDstItem
;
11614 else if(((Bag
*)pDstItem
)->IsEmpty() && !IsBagPos(dst
))
11616 emptyBag
= (Bag
*)pDstItem
;
11617 fullBag
= (Bag
*)pSrcItem
;
11620 // bag swap (with items exchange) case
11621 if(emptyBag
&& fullBag
)
11623 ItemPrototype
const* emotyProto
= emptyBag
->GetProto();
11627 for(uint32 i
=0; i
< fullBag
->GetBagSize(); ++i
)
11629 Item
*bagItem
= fullBag
->GetItemByPos(i
);
11633 ItemPrototype
const* bagItemProto
= bagItem
->GetProto();
11634 if (!bagItemProto
|| !ItemCanGoIntoBag(bagItemProto
, emotyProto
))
11636 // one from items not go to empty target bag
11637 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
11645 if (count
> emptyBag
->GetBagSize())
11647 // too small targeted bag
11648 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
, pSrcItem
, pDstItem
);
11653 count
= 0; // will pos in new bag
11654 for(uint32 i
= 0; i
< fullBag
->GetBagSize(); ++i
)
11656 Item
*bagItem
= fullBag
->GetItemByPos(i
);
11660 fullBag
->RemoveItem(i
, true);
11661 emptyBag
->StoreItem(count
, bagItem
, true);
11662 bagItem
->SetState(ITEM_CHANGED
, this);
11669 // now do moves, remove...
11670 RemoveItem(dstbag
, dstslot
, false);
11671 RemoveItem(srcbag
, srcslot
, false);
11674 if (IsInventoryPos(dst
))
11675 StoreItem(sDest
, pSrcItem
, true);
11676 else if (IsBankPos(dst
))
11677 BankItem(sDest
, pSrcItem
, true);
11678 else if (IsEquipmentPos(dst
))
11679 EquipItem(eDest
, pSrcItem
, true);
11682 if (IsInventoryPos(src
))
11683 StoreItem(sDest2
, pDstItem
, true);
11684 else if (IsBankPos(src
))
11685 BankItem(sDest2
, pDstItem
, true);
11686 else if (IsEquipmentPos(src
))
11687 EquipItem(eDest2
, pDstItem
, true);
11689 AutoUnequipOffhandIfNeed();
11692 void Player::AddItemToBuyBackSlot( Item
*pItem
)
11696 uint32 slot
= m_currentBuybackSlot
;
11697 // if current back slot non-empty search oldest or free
11700 uint32 oldest_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
);
11701 uint32 oldest_slot
= BUYBACK_SLOT_START
;
11703 for(uint32 i
= BUYBACK_SLOT_START
+1; i
< BUYBACK_SLOT_END
; ++i
)
11712 uint32 i_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ i
- BUYBACK_SLOT_START
);
11714 if (oldest_time
> i_time
)
11716 oldest_time
= i_time
;
11722 slot
= oldest_slot
;
11725 RemoveItemFromBuyBackSlot( slot
, true );
11726 sLog
.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem
->GetEntry(), slot
);
11728 m_items
[slot
] = pItem
;
11729 time_t base
= time(NULL
);
11730 uint32 etime
= uint32(base
- m_logintime
+ (30 * 3600));
11731 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11733 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ (eslot
* 2), pItem
->GetGUID() );
11734 if (ItemPrototype
const *pProto
= pItem
->GetProto())
11735 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, pProto
->SellPrice
* pItem
->GetCount() );
11737 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11738 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, (uint32
)etime
);
11740 // move to next (for non filled list is move most optimized choice)
11741 if (m_currentBuybackSlot
< BUYBACK_SLOT_END
- 1)
11742 ++m_currentBuybackSlot
;
11746 Item
* Player::GetItemFromBuyBackSlot( uint32 slot
)
11748 sLog
.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot
);
11749 if (slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11750 return m_items
[slot
];
11754 void Player::RemoveItemFromBuyBackSlot( uint32 slot
, bool del
)
11756 sLog
.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot
);
11757 if (slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11759 Item
*pItem
= m_items
[slot
];
11762 pItem
->RemoveFromWorld();
11763 if(del
) pItem
->SetState(ITEM_REMOVED
, this);
11766 m_items
[slot
] = NULL
;
11768 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11769 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ (eslot
* 2), 0 );
11770 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11771 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, 0 );
11773 // if current backslot is filled set to now free slot
11774 if (m_items
[m_currentBuybackSlot
])
11775 m_currentBuybackSlot
= slot
;
11779 void Player::SendEquipError( uint8 msg
, Item
* pItem
, Item
*pItem2
, uint32 itemid
/*= 0*/ )
11781 sLog
.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg
);
11782 WorldPacket
data(SMSG_INVENTORY_CHANGE_FAILURE
, 1+8+8+1);
11783 data
<< uint8(msg
);
11785 if (msg
!= EQUIP_ERR_OK
)
11787 data
<< uint64(pItem
? pItem
->GetGUID() : 0);
11788 data
<< uint64(pItem2
? pItem2
->GetGUID() : 0);
11789 data
<< uint8(0); // bag type subclass, used with EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM and EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG2
11793 case EQUIP_ERR_CANT_EQUIP_LEVEL_I
:
11794 case EQUIP_ERR_PURCHASE_LEVEL_TOO_LOW
:
11796 ItemPrototype
const* proto
= pItem
? pItem
->GetProto() : sObjectMgr
.GetItemPrototype(itemid
);
11797 data
<< uint32(proto
? proto
->RequiredLevel
: 0);
11800 case EQUIP_ERR_EVENT_AUTOEQUIP_BIND_CONFIRM
: // no idea about this one...
11807 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_COUNT_EXCEEDED_IS
:
11808 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_SOCKETED_EXCEEDED_IS
:
11809 case EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS
:
11811 ItemPrototype
const* proto
= pItem
? pItem
->GetProto() : sObjectMgr
.GetItemPrototype(itemid
);
11812 data
<< uint32(proto
? proto
->ItemLimitCategory
: 0);
11819 GetSession()->SendPacket(&data
);
11822 void Player::SendBuyError( uint8 msg
, Creature
* pCreature
, uint32 item
, uint32 param
)
11824 sLog
.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11825 WorldPacket
data( SMSG_BUY_FAILED
, (8+4+4+1) );
11826 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11827 data
<< uint32(item
);
11829 data
<< uint32(param
);
11830 data
<< uint8(msg
);
11831 GetSession()->SendPacket(&data
);
11834 void Player::SendSellError( uint8 msg
, Creature
* pCreature
, uint64 guid
, uint32 param
)
11836 sLog
.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11837 WorldPacket
data( SMSG_SELL_ITEM
,(8+8+(param
?4:0)+1)); // last check 2.0.10
11838 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11839 data
<< uint64(guid
);
11841 data
<< uint32(param
);
11842 data
<< uint8(msg
);
11843 GetSession()->SendPacket(&data
);
11846 void Player::ClearTrade()
11849 acceptTrade
= false;
11850 for(int i
= 0; i
< TRADE_SLOT_COUNT
; ++i
)
11851 tradeItems
[i
] = NULL_SLOT
;
11854 void Player::TradeCancel(bool sendback
)
11858 // send yellow "Trade canceled" message to both traders
11862 ws
->SendCancelTrade();
11863 ws
= pTrader
->GetSession();
11864 if (!ws
->PlayerLogout())
11865 ws
->SendCancelTrade();
11869 pTrader
->ClearTrade();
11870 // prevent loss of reference
11871 pTrader
->pTrader
= NULL
;
11876 void Player::UpdateItemDuration(uint32 time
, bool realtimeonly
)
11878 if (m_itemDuration
.empty())
11881 sLog
.outDebug("Player::UpdateItemDuration(%u,%u)", time
, realtimeonly
);
11883 for(ItemDurationList::const_iterator itr
= m_itemDuration
.begin(); itr
!= m_itemDuration
.end(); )
11886 ++itr
; // current element can be erased in UpdateDuration
11888 if ((realtimeonly
&& item
->GetProto()->Duration
< 0) || !realtimeonly
)
11889 item
->UpdateDuration(this,time
);
11893 void Player::UpdateEnchantTime(uint32 time
)
11895 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11899 if (!itr
->item
->GetEnchantmentId(itr
->slot
))
11901 next
= m_enchantDuration
.erase(itr
);
11903 else if (itr
->leftduration
<= time
)
11905 ApplyEnchantment(itr
->item
, itr
->slot
, false, false);
11906 itr
->item
->ClearEnchantment(itr
->slot
);
11907 next
= m_enchantDuration
.erase(itr
);
11909 else if (itr
->leftduration
> time
)
11911 itr
->leftduration
-= time
;
11917 void Player::AddEnchantmentDurations(Item
*item
)
11919 for(int x
= 0; x
< MAX_ENCHANTMENT_SLOT
; ++x
)
11921 if (!item
->GetEnchantmentId(EnchantmentSlot(x
)))
11924 uint32 duration
= item
->GetEnchantmentDuration(EnchantmentSlot(x
));
11926 AddEnchantmentDuration(item
, EnchantmentSlot(x
), duration
);
11930 void Player::RemoveEnchantmentDurations(Item
*item
)
11932 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(); itr
!= m_enchantDuration
.end();)
11934 if (itr
->item
== item
)
11936 // save duration in item
11937 item
->SetEnchantmentDuration(EnchantmentSlot(itr
->slot
), itr
->leftduration
);
11938 itr
= m_enchantDuration
.erase(itr
);
11945 void Player::RemoveAllEnchantments(EnchantmentSlot slot
)
11947 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11948 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(), next
; itr
!= m_enchantDuration
.end(); itr
= next
)
11951 if (itr
->slot
== slot
)
11953 if (itr
->item
&& itr
->item
->GetEnchantmentId(slot
))
11955 // remove from stats
11956 ApplyEnchantment(itr
->item
, slot
, false, false);
11958 itr
->item
->ClearEnchantment(slot
);
11960 // remove from update list
11961 next
= m_enchantDuration
.erase(itr
);
11967 // remove enchants from inventory items
11968 // NOTE: no need to remove these from stats, since these aren't equipped
11970 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
11971 if (Item
* pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
11972 if (pItem
->GetEnchantmentId(slot
))
11973 pItem
->ClearEnchantment(slot
);
11975 // in inventory bags
11976 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
11977 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11978 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
11979 if (Item
* pItem
= pBag
->GetItemByPos(j
))
11980 if (pItem
->GetEnchantmentId(slot
))
11981 pItem
->ClearEnchantment(slot
);
11984 // duration == 0 will remove item enchant
11985 void Player::AddEnchantmentDuration(Item
*item
,EnchantmentSlot slot
,uint32 duration
)
11990 if (slot
>= MAX_ENCHANTMENT_SLOT
)
11993 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(); itr
!= m_enchantDuration
.end(); ++itr
)
11995 if (itr
->item
== item
&& itr
->slot
== slot
)
11997 itr
->item
->SetEnchantmentDuration(itr
->slot
, itr
->leftduration
);
11998 m_enchantDuration
.erase(itr
);
12002 if (item
&& duration
> 0 )
12004 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item
->GetGUID(), slot
, uint32(duration
/1000));
12005 m_enchantDuration
.push_back(EnchantDuration(item
, slot
, duration
));
12009 void Player::ApplyEnchantment(Item
*item
,bool apply
)
12011 for(uint32 slot
= 0; slot
< MAX_ENCHANTMENT_SLOT
; ++slot
)
12012 ApplyEnchantment(item
, EnchantmentSlot(slot
), apply
);
12015 void Player::ApplyEnchantment(Item
*item
, EnchantmentSlot slot
, bool apply
, bool apply_dur
, bool ignore_condition
)
12020 if (!item
->IsEquipped())
12023 if (slot
>= MAX_ENCHANTMENT_SLOT
)
12026 uint32 enchant_id
= item
->GetEnchantmentId(slot
);
12030 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
12034 if (!ignore_condition
&& pEnchant
->EnchantmentCondition
&& !((Player
*)this)->EnchantmentFitsRequirements(pEnchant
->EnchantmentCondition
, -1))
12037 if (!item
->IsBroken())
12039 for (int s
= 0; s
< 3; ++s
)
12041 uint32 enchant_display_type
= pEnchant
->type
[s
];
12042 uint32 enchant_amount
= pEnchant
->amount
[s
];
12043 uint32 enchant_spell_id
= pEnchant
->spellid
[s
];
12045 switch(enchant_display_type
)
12047 case ITEM_ENCHANTMENT_TYPE_NONE
:
12049 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
:
12050 // processed in Player::CastItemCombatSpell
12052 case ITEM_ENCHANTMENT_TYPE_DAMAGE
:
12053 if (item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
12054 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12055 else if (item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
12056 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12057 else if (item
->GetSlot() == EQUIPMENT_SLOT_RANGED
)
12058 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12060 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL
:
12061 if (enchant_spell_id
)
12065 int32 basepoints
= 0;
12066 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
12067 if (item
->GetItemRandomPropertyId())
12069 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
12072 // Search enchant_amount
12073 for (int k
= 0; k
< 3; ++k
)
12075 if(item_rand
->enchant_id
[k
] == enchant_id
)
12077 basepoints
= int32((item_rand
->prefix
[k
] * item
->GetItemSuffixFactor()) / 10000 );
12083 // Cast custom spell vs all equal basepoints getted from enchant_amount
12085 CastCustomSpell(this, enchant_spell_id
, &basepoints
, &basepoints
, &basepoints
, true, item
);
12087 CastSpell(this, enchant_spell_id
, true, item
);
12090 RemoveAurasDueToItemSpell(item
, enchant_spell_id
);
12093 case ITEM_ENCHANTMENT_TYPE_RESISTANCE
:
12094 if (!enchant_amount
)
12096 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
12099 for (int k
= 0; k
< 3; ++k
)
12101 if(item_rand
->enchant_id
[k
] == enchant_id
)
12103 enchant_amount
= uint32((item_rand
->prefix
[k
] * item
->GetItemSuffixFactor()) / 10000 );
12110 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START
+ enchant_spell_id
), TOTAL_VALUE
, float(enchant_amount
), apply
);
12112 case ITEM_ENCHANTMENT_TYPE_STAT
:
12114 if (!enchant_amount
)
12116 ItemRandomSuffixEntry
const *item_rand_suffix
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
12117 if(item_rand_suffix
)
12119 for (int k
= 0; k
< 3; ++k
)
12121 if(item_rand_suffix
->enchant_id
[k
] == enchant_id
)
12123 enchant_amount
= uint32((item_rand_suffix
->prefix
[k
] * item
->GetItemSuffixFactor()) / 10000 );
12130 sLog
.outDebug("Adding %u to stat nb %u",enchant_amount
,enchant_spell_id
);
12131 switch (enchant_spell_id
)
12133 case ITEM_MOD_MANA
:
12134 sLog
.outDebug("+ %u MANA",enchant_amount
);
12135 HandleStatModifier(UNIT_MOD_MANA
, BASE_VALUE
, float(enchant_amount
), apply
);
12137 case ITEM_MOD_HEALTH
:
12138 sLog
.outDebug("+ %u HEALTH",enchant_amount
);
12139 HandleStatModifier(UNIT_MOD_HEALTH
, BASE_VALUE
, float(enchant_amount
), apply
);
12141 case ITEM_MOD_AGILITY
:
12142 sLog
.outDebug("+ %u AGILITY",enchant_amount
);
12143 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12144 ApplyStatBuffMod(STAT_AGILITY
, float(enchant_amount
), apply
);
12146 case ITEM_MOD_STRENGTH
:
12147 sLog
.outDebug("+ %u STRENGTH",enchant_amount
);
12148 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12149 ApplyStatBuffMod(STAT_STRENGTH
, float(enchant_amount
), apply
);
12151 case ITEM_MOD_INTELLECT
:
12152 sLog
.outDebug("+ %u INTELLECT",enchant_amount
);
12153 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12154 ApplyStatBuffMod(STAT_INTELLECT
, float(enchant_amount
), apply
);
12156 case ITEM_MOD_SPIRIT
:
12157 sLog
.outDebug("+ %u SPIRIT",enchant_amount
);
12158 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12159 ApplyStatBuffMod(STAT_SPIRIT
, float(enchant_amount
), apply
);
12161 case ITEM_MOD_STAMINA
:
12162 sLog
.outDebug("+ %u STAMINA",enchant_amount
);
12163 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12164 ApplyStatBuffMod(STAT_STAMINA
, float(enchant_amount
), apply
);
12166 case ITEM_MOD_DEFENSE_SKILL_RATING
:
12167 ((Player
*)this)->ApplyRatingMod(CR_DEFENSE_SKILL
, enchant_amount
, apply
);
12168 sLog
.outDebug("+ %u DEFENCE", enchant_amount
);
12170 case ITEM_MOD_DODGE_RATING
:
12171 ((Player
*)this)->ApplyRatingMod(CR_DODGE
, enchant_amount
, apply
);
12172 sLog
.outDebug("+ %u DODGE", enchant_amount
);
12174 case ITEM_MOD_PARRY_RATING
:
12175 ((Player
*)this)->ApplyRatingMod(CR_PARRY
, enchant_amount
, apply
);
12176 sLog
.outDebug("+ %u PARRY", enchant_amount
);
12178 case ITEM_MOD_BLOCK_RATING
:
12179 ((Player
*)this)->ApplyRatingMod(CR_BLOCK
, enchant_amount
, apply
);
12180 sLog
.outDebug("+ %u SHIELD_BLOCK", enchant_amount
);
12182 case ITEM_MOD_HIT_MELEE_RATING
:
12183 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
12184 sLog
.outDebug("+ %u MELEE_HIT", enchant_amount
);
12186 case ITEM_MOD_HIT_RANGED_RATING
:
12187 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
12188 sLog
.outDebug("+ %u RANGED_HIT", enchant_amount
);
12190 case ITEM_MOD_HIT_SPELL_RATING
:
12191 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
12192 sLog
.outDebug("+ %u SPELL_HIT", enchant_amount
);
12194 case ITEM_MOD_CRIT_MELEE_RATING
:
12195 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
12196 sLog
.outDebug("+ %u MELEE_CRIT", enchant_amount
);
12198 case ITEM_MOD_CRIT_RANGED_RATING
:
12199 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
12200 sLog
.outDebug("+ %u RANGED_CRIT", enchant_amount
);
12202 case ITEM_MOD_CRIT_SPELL_RATING
:
12203 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
12204 sLog
.outDebug("+ %u SPELL_CRIT", enchant_amount
);
12206 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
12208 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
12209 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12211 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
12212 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12214 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
12215 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12217 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
12218 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12220 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
12221 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12223 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
12224 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12226 // case ITEM_MOD_HASTE_MELEE_RATING:
12227 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12229 // case ITEM_MOD_HASTE_RANGED_RATING:
12230 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12232 case ITEM_MOD_HASTE_SPELL_RATING
:
12233 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
12235 case ITEM_MOD_HIT_RATING
:
12236 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
12237 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
12238 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
12239 sLog
.outDebug("+ %u HIT", enchant_amount
);
12241 case ITEM_MOD_CRIT_RATING
:
12242 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
12243 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
12244 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
12245 sLog
.outDebug("+ %u CRITICAL", enchant_amount
);
12247 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
12248 // case ITEM_MOD_HIT_TAKEN_RATING:
12249 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12250 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12251 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12253 // case ITEM_MOD_CRIT_TAKEN_RATING:
12254 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12255 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12256 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12258 case ITEM_MOD_RESILIENCE_RATING
:
12259 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, enchant_amount
, apply
);
12260 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, enchant_amount
, apply
);
12261 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, enchant_amount
, apply
);
12262 sLog
.outDebug("+ %u RESILIENCE", enchant_amount
);
12264 case ITEM_MOD_HASTE_RATING
:
12265 ((Player
*)this)->ApplyRatingMod(CR_HASTE_MELEE
, enchant_amount
, apply
);
12266 ((Player
*)this)->ApplyRatingMod(CR_HASTE_RANGED
, enchant_amount
, apply
);
12267 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
12268 sLog
.outDebug("+ %u HASTE", enchant_amount
);
12270 case ITEM_MOD_EXPERTISE_RATING
:
12271 ((Player
*)this)->ApplyRatingMod(CR_EXPERTISE
, enchant_amount
, apply
);
12272 sLog
.outDebug("+ %u EXPERTISE", enchant_amount
);
12274 case ITEM_MOD_ATTACK_POWER
:
12275 HandleStatModifier(UNIT_MOD_ATTACK_POWER
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12276 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12277 sLog
.outDebug("+ %u ATTACK_POWER", enchant_amount
);
12279 case ITEM_MOD_RANGED_ATTACK_POWER
:
12280 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12281 sLog
.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount
);
12283 case ITEM_MOD_MANA_REGENERATION
:
12284 ((Player
*)this)->ApplyManaRegenBonus(enchant_amount
, apply
);
12285 sLog
.outDebug("+ %u MANA_REGENERATION", enchant_amount
);
12287 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
12288 ((Player
*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION
, enchant_amount
, apply
);
12289 sLog
.outDebug("+ %u ARMOR PENETRATION", enchant_amount
);
12291 case ITEM_MOD_SPELL_POWER
:
12292 ((Player
*)this)->ApplySpellPowerBonus(enchant_amount
, apply
);
12293 sLog
.outDebug("+ %u SPELL_POWER", enchant_amount
);
12295 case ITEM_MOD_FERAL_ATTACK_POWER
:
12296 case ITEM_MOD_SPELL_HEALING_DONE
: // deprecated
12297 case ITEM_MOD_SPELL_DAMAGE_DONE
: // deprecated
12303 case ITEM_ENCHANTMENT_TYPE_TOTEM
: // Shaman Rockbiter Weapon
12305 if(getClass() == CLASS_SHAMAN
)
12307 float addValue
= 0.0f
;
12308 if(item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
12310 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/ 1000.0f
);
12311 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, addValue
, apply
);
12313 else if(item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
12315 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/ 1000.0f
);
12316 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, addValue
, apply
);
12321 case ITEM_ENCHANTMENT_TYPE_USE_SPELL
:
12322 // processed in Player::CastItemUseSpell
12324 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET
:
12328 sLog
.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id
, enchant_display_type
);
12330 } /*switch(enchant_display_type)*/
12334 // visualize enchantment at player and equipped items
12335 if(slot
== PERM_ENCHANTMENT_SLOT
)
12336 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT
+ (item
->GetSlot() * 2), 0, apply
? item
->GetEnchantmentId(slot
) : 0);
12338 if(slot
== TEMP_ENCHANTMENT_SLOT
)
12339 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT
+ (item
->GetSlot() * 2), 1, apply
? item
->GetEnchantmentId(slot
) : 0);
12347 uint32 duration
= item
->GetEnchantmentDuration(slot
);
12349 AddEnchantmentDuration(item
, slot
, duration
);
12353 // duration == 0 will remove EnchantDuration
12354 AddEnchantmentDuration(item
, slot
, 0);
12359 void Player::SendEnchantmentDurations()
12361 for(EnchantDurationList::const_iterator itr
= m_enchantDuration
.begin(); itr
!= m_enchantDuration
.end(); ++itr
)
12363 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr
->item
->GetGUID(), itr
->slot
, uint32(itr
->leftduration
) / 1000);
12367 void Player::SendItemDurations()
12369 for(ItemDurationList::const_iterator itr
= m_itemDuration
.begin(); itr
!= m_itemDuration
.end(); ++itr
)
12371 (*itr
)->SendTimeUpdate(this);
12375 void Player::SendNewItem(Item
*item
, uint32 count
, bool received
, bool created
, bool broadcast
)
12377 if(!item
) // prevent crash
12380 // last check 2.0.10
12381 WorldPacket
data( SMSG_ITEM_PUSH_RESULT
, (8+4+4+4+1+4+4+4+4+4) );
12382 data
<< uint64(GetGUID()); // player GUID
12383 data
<< uint32(received
); // 0=looted, 1=from npc
12384 data
<< uint32(created
); // 0=received, 1=created
12385 data
<< uint32(1); // always 0x01 (probably meant to be count of listed items)
12386 data
<< uint8(item
->GetBagSlot()); // bagslot
12387 // item slot, but when added to stack: 0xFFFFFFFF
12388 data
<< uint32((item
->GetCount() == count
) ? item
->GetSlot() : -1);
12389 data
<< uint32(item
->GetEntry()); // item id
12390 data
<< uint32(item
->GetItemSuffixFactor()); // SuffixFactor
12391 data
<< uint32(item
->GetItemRandomPropertyId()); // random item property id
12392 data
<< uint32(count
); // count of items
12393 data
<< uint32(GetItemCount(item
->GetEntry())); // count of items in inventory
12395 if (broadcast
&& GetGroup())
12396 GetGroup()->BroadcastPacket(&data
, true);
12398 GetSession()->SendPacket(&data
);
12401 /*********************************************************/
12402 /*** GOSSIP SYSTEM ***/
12403 /*********************************************************/
12405 void Player::PrepareGossipMenu(WorldObject
*pSource
, uint32 menuId
)
12407 PlayerMenu
* pMenu
= PlayerTalkClass
;
12408 pMenu
->ClearMenus();
12410 pMenu
->GetGossipMenu().SetMenuId(menuId
);
12412 GossipMenuItemsMapBounds pMenuItemBounds
= sObjectMgr
.GetGossipMenuItemsMapBounds(menuId
);
12414 // if default menuId and no menu options exist for this, use options from default options
12415 if (pMenuItemBounds
.first
== pMenuItemBounds
.second
&& menuId
== GetDefaultGossipMenuForSource(pSource
))
12416 pMenuItemBounds
= sObjectMgr
.GetGossipMenuItemsMapBounds(0);
12418 for(GossipMenuItemsMap::const_iterator itr
= pMenuItemBounds
.first
; itr
!= pMenuItemBounds
.second
; ++itr
)
12420 bool bCanTalk
= true;
12422 if (itr
->second
.cond_1
&& !sObjectMgr
.IsPlayerMeetToCondition(this, itr
->second
.cond_1
))
12425 if (itr
->second
.cond_2
&& !sObjectMgr
.IsPlayerMeetToCondition(this, itr
->second
.cond_2
))
12428 if (itr
->second
.cond_3
&& !sObjectMgr
.IsPlayerMeetToCondition(this, itr
->second
.cond_3
))
12431 if (pSource
->GetTypeId() == TYPEID_UNIT
)
12433 Creature
*pCreature
= (Creature
*)pSource
;
12435 uint32 npcflags
= pCreature
->GetUInt32Value(UNIT_NPC_FLAGS
);
12437 if (!(itr
->second
.npc_option_npcflag
& npcflags
))
12440 switch(itr
->second
.option_id
)
12442 case GOSSIP_OPTION_QUESTGIVER
:
12443 PrepareQuestMenu(pSource
->GetGUID());
12446 case GOSSIP_OPTION_ARMORER
:
12447 bCanTalk
= false; // added in special mode
12449 case GOSSIP_OPTION_SPIRITHEALER
:
12453 case GOSSIP_OPTION_VENDOR
:
12455 VendorItemData
const* vItems
= pCreature
->GetVendorItems();
12456 if (!vItems
|| vItems
->Empty())
12458 sLog
.outErrorDb("Creature %u (Entry: %u) have UNIT_NPC_FLAG_VENDOR but have empty trading item list.", pCreature
->GetGUIDLow(), pCreature
->GetEntry());
12463 case GOSSIP_OPTION_TRAINER
:
12464 if (!pCreature
->isCanTrainingOf(this, false))
12467 case GOSSIP_OPTION_UNLEARNTALENTS
:
12468 if (!pCreature
->isCanTrainingAndResetTalentsOf(this))
12471 case GOSSIP_OPTION_UNLEARNPETSKILLS
:
12472 if (!GetPet() || GetPet()->getPetType() != HUNTER_PET
|| GetPet()->m_spells
.size() <= 1 || pCreature
->GetCreatureInfo()->trainer_type
!= TRAINER_TYPE_PETS
|| pCreature
->GetCreatureInfo()->trainer_class
!= CLASS_HUNTER
)
12475 case GOSSIP_OPTION_TAXIVENDOR
:
12476 if (GetSession()->SendLearnNewTaxiNode(pCreature
))
12479 case GOSSIP_OPTION_BATTLEFIELD
:
12480 if (!pCreature
->isCanInteractWithBattleMaster(this, false))
12483 case GOSSIP_OPTION_STABLEPET
:
12484 if (getClass() != CLASS_HUNTER
)
12487 case GOSSIP_OPTION_GOSSIP
:
12488 case GOSSIP_OPTION_SPIRITGUIDE
:
12489 case GOSSIP_OPTION_INNKEEPER
:
12490 case GOSSIP_OPTION_BANKER
:
12491 case GOSSIP_OPTION_PETITIONER
:
12492 case GOSSIP_OPTION_TABARDDESIGNER
:
12493 case GOSSIP_OPTION_AUCTIONEER
:
12494 break; // no checks
12496 sLog
.outErrorDb("Creature entry %u have unknown gossip option %u for menu %u", pCreature
->GetEntry(), itr
->second
.option_id
, itr
->second
.menu_id
);
12501 else if (pSource
->GetTypeId() == TYPEID_GAMEOBJECT
)
12503 GameObject
*pGo
= (GameObject
*)pSource
;
12505 switch(itr
->second
.option_id
)
12507 case GOSSIP_OPTION_QUESTGIVER
:
12508 if (pGo
->GetGoType() == GAMEOBJECT_TYPE_QUESTGIVER
)
12509 PrepareQuestMenu(pSource
->GetGUID());
12512 case GOSSIP_OPTION_GOSSIP
:
12513 if (pGo
->GetGoType() != GAMEOBJECT_TYPE_QUESTGIVER
&& pGo
->GetGoType() != GAMEOBJECT_TYPE_GOOBER
)
12524 std::string strOptionText
= itr
->second
.option_text
;
12525 std::string strBoxText
= itr
->second
.box_text
;
12527 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
12531 uint32 idxEntry
= MAKE_PAIR32(menuId
, itr
->second
.id
);
12533 if (GossipMenuItemsLocale
const *no
= sObjectMgr
.GetGossipMenuItemsLocale(idxEntry
))
12535 if (no
->OptionText
.size() > (size_t)loc_idx
&& !no
->OptionText
[loc_idx
].empty())
12536 strOptionText
= no
->OptionText
[loc_idx
];
12538 if (no
->BoxText
.size() > (size_t)loc_idx
&& !no
->BoxText
[loc_idx
].empty())
12539 strBoxText
= no
->BoxText
[loc_idx
];
12543 pMenu
->GetGossipMenu().AddMenuItem(itr
->second
.option_icon
, strOptionText
, 0, itr
->second
.option_id
, strBoxText
, itr
->second
.box_money
, itr
->second
.box_coded
);
12544 pMenu
->GetGossipMenu().AddGossipMenuItemData(itr
->second
.action_menu_id
, itr
->second
.action_poi_id
, itr
->second
.action_script_id
);
12548 // some gossips aren't handled in normal way ... so we need to do it this way .. TODO: handle it in normal way ;-)
12549 /*if (pMenu->Empty())
12551 if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_TRAINER))
12553 // output error message if need
12554 pCreature->isCanTrainingOf(this, true);
12557 if (pCreature->HasFlag(UNIT_NPC_FLAGS,UNIT_NPC_FLAG_BATTLEMASTER))
12559 // output error message if need
12560 pCreature->isCanInteractWithBattleMaster(this, true);
12565 void Player::SendPreparedGossip(WorldObject
*pSource
)
12570 if (pSource
->GetTypeId() == TYPEID_UNIT
)
12572 // in case no gossip flag and quest menu not empty, open quest menu (client expect gossip menu with this flag)
12573 if (!((Creature
*)pSource
)->HasFlag(UNIT_NPC_FLAGS
,UNIT_NPC_FLAG_GOSSIP
) && !PlayerTalkClass
->GetQuestMenu().Empty())
12575 SendPreparedQuest(pSource
->GetGUID());
12579 else if (pSource
->GetTypeId() == TYPEID_GAMEOBJECT
)
12581 // probably need to find a better way here
12582 if (!PlayerTalkClass
->GetGossipMenu().GetMenuId() && !PlayerTalkClass
->GetQuestMenu().Empty())
12584 SendPreparedQuest(pSource
->GetGUID());
12589 // in case non empty gossip menu (that not included quests list size) show it
12590 // (quest entries from quest menu will be included in list)
12592 uint32 textId
= GetGossipTextId(pSource
);
12594 if (uint32 menuId
= PlayerTalkClass
->GetGossipMenu().GetMenuId())
12595 textId
= GetGossipTextId(menuId
);
12597 PlayerTalkClass
->SendGossipMenu(textId
, pSource
->GetGUID());
12600 void Player::OnGossipSelect(WorldObject
* pSource
, uint32 gossipListId
, uint32 menuId
)
12602 GossipMenu
& gossipmenu
= PlayerTalkClass
->GetGossipMenu();
12604 if (gossipListId
>= gossipmenu
.MenuItemCount())
12607 // if not same, then something funky is going on
12608 if (menuId
!= gossipmenu
.GetMenuId())
12611 uint32 gossipOptionId
= gossipmenu
.GetItem(gossipListId
).m_gOptionId
;
12612 uint64 guid
= pSource
->GetGUID();
12614 if (pSource
->GetTypeId() == TYPEID_GAMEOBJECT
)
12616 if (gossipOptionId
> GOSSIP_OPTION_QUESTGIVER
)
12618 sLog
.outError("Player guid %u request invalid gossip option for GameObject entry %u", GetGUIDLow(), pSource
->GetEntry());
12623 GossipMenuItemData pMenuData
= gossipmenu
.GetItemData(gossipListId
);
12625 switch(gossipOptionId
)
12627 case GOSSIP_OPTION_GOSSIP
:
12629 if (pMenuData
.m_gAction_poi
)
12630 PlayerTalkClass
->SendPointOfInterest(pMenuData
.m_gAction_poi
);
12632 if (pMenuData
.m_gAction_menu
)
12634 PrepareGossipMenu(pSource
, pMenuData
.m_gAction_menu
);
12635 SendPreparedGossip(pSource
);
12638 if (pMenuData
.m_gAction_script
)
12640 if (pSource
->GetTypeId() == TYPEID_GAMEOBJECT
)
12641 GetMap()->ScriptsStart(sGossipScripts
, pMenuData
.m_gAction_script
, this, pSource
);
12642 else if (pSource
->GetTypeId() == TYPEID_UNIT
)
12643 GetMap()->ScriptsStart(sGossipScripts
, pMenuData
.m_gAction_script
, pSource
, this);
12648 case GOSSIP_OPTION_SPIRITHEALER
:
12650 ((Creature
*)pSource
)->CastSpell(((Creature
*)pSource
),17251,true,NULL
,NULL
,GetGUID());
12652 case GOSSIP_OPTION_QUESTGIVER
:
12653 PrepareQuestMenu(guid
);
12654 SendPreparedQuest(guid
);
12656 case GOSSIP_OPTION_VENDOR
:
12657 case GOSSIP_OPTION_ARMORER
:
12658 GetSession()->SendListInventory(guid
);
12660 case GOSSIP_OPTION_STABLEPET
:
12661 GetSession()->SendStablePet(guid
);
12663 case GOSSIP_OPTION_TRAINER
:
12664 GetSession()->SendTrainerList(guid
);
12666 case GOSSIP_OPTION_UNLEARNTALENTS
:
12667 PlayerTalkClass
->CloseGossip();
12668 SendTalentWipeConfirm(guid
);
12670 case GOSSIP_OPTION_UNLEARNPETSKILLS
:
12671 PlayerTalkClass
->CloseGossip();
12672 SendPetSkillWipeConfirm();
12674 case GOSSIP_OPTION_TAXIVENDOR
:
12675 GetSession()->SendTaxiMenu(((Creature
*)pSource
));
12677 case GOSSIP_OPTION_INNKEEPER
:
12678 PlayerTalkClass
->CloseGossip();
12679 SetBindPoint(guid
);
12681 case GOSSIP_OPTION_BANKER
:
12682 GetSession()->SendShowBank(guid
);
12684 case GOSSIP_OPTION_PETITIONER
:
12685 PlayerTalkClass
->CloseGossip();
12686 GetSession()->SendPetitionShowList(guid
);
12688 case GOSSIP_OPTION_TABARDDESIGNER
:
12689 PlayerTalkClass
->CloseGossip();
12690 GetSession()->SendTabardVendorActivate(guid
);
12692 case GOSSIP_OPTION_AUCTIONEER
:
12693 GetSession()->SendAuctionHello(guid
, ((Creature
*)pSource
));
12695 case GOSSIP_OPTION_SPIRITGUIDE
:
12696 PrepareGossipMenu(pSource
);
12697 SendPreparedGossip(pSource
);
12699 case GOSSIP_OPTION_BATTLEFIELD
:
12701 BattleGroundTypeId bgTypeId
= sBattleGroundMgr
.GetBattleMasterBG(pSource
->GetEntry());
12703 if (bgTypeId
== BATTLEGROUND_TYPE_NONE
)
12705 sLog
.outError("a user (guid %u) requested battlegroundlist from a npc who is no battlemaster", GetGUIDLow());
12709 GetSession()->SendBattlegGroundList(guid
, bgTypeId
);
12715 uint32
Player::GetGossipTextId(WorldObject
*pSource
)
12717 if (!pSource
|| pSource
->GetTypeId() != TYPEID_UNIT
|| !((Creature
*)pSource
)->GetDBTableGUIDLow())
12718 return DEFAULT_GOSSIP_MESSAGE
;
12720 if (uint32 pos
= sObjectMgr
.GetNpcGossip(((Creature
*)pSource
)->GetDBTableGUIDLow()))
12723 return DEFAULT_GOSSIP_MESSAGE
;
12726 uint32
Player::GetGossipTextId(uint32 menuId
)
12728 uint32 textId
= DEFAULT_GOSSIP_MESSAGE
;
12733 GossipMenusMapBounds pMenuBounds
= sObjectMgr
.GetGossipMenusMapBounds(menuId
);
12735 for(GossipMenusMap::const_iterator itr
= pMenuBounds
.first
; itr
!= pMenuBounds
.second
; ++itr
)
12737 if (sObjectMgr
.IsPlayerMeetToCondition(this, itr
->second
.cond_1
) && sObjectMgr
.IsPlayerMeetToCondition(this, itr
->second
.cond_2
))
12738 textId
= itr
->second
.text_id
;
12744 uint32
Player::GetDefaultGossipMenuForSource(WorldObject
*pSource
)
12746 if (pSource
->GetTypeId() == TYPEID_UNIT
)
12747 return ((Creature
*)pSource
)->GetCreatureInfo()->GossipMenuId
;
12748 else if (pSource
->GetTypeId() == TYPEID_GAMEOBJECT
)
12749 return((GameObject
*)pSource
)->GetGOInfo()->GetGossipMenuId();
12754 /*********************************************************/
12755 /*** QUEST SYSTEM ***/
12756 /*********************************************************/
12758 void Player::PrepareQuestMenu( uint64 guid
)
12761 QuestRelations
* pObjectQR
;
12762 QuestRelations
* pObjectQIR
;
12764 // pets also can have quests
12765 if (Creature
*pCreature
= GetMap()->GetCreatureOrPetOrVehicle(guid
))
12767 pObject
= (Object
*)pCreature
;
12768 pObjectQR
= &sObjectMgr
.mCreatureQuestRelations
;
12769 pObjectQIR
= &sObjectMgr
.mCreatureQuestInvolvedRelations
;
12773 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12774 //only for quests which cast teleport spells on player
12775 Map
* _map
= IsInWorld() ? GetMap() : sMapMgr
.FindMap(GetMapId(), GetInstanceId());
12777 GameObject
*pGameObject
= _map
->GetGameObject(guid
);
12780 pObject
= (Object
*)pGameObject
;
12781 pObjectQR
= &sObjectMgr
.mGOQuestRelations
;
12782 pObjectQIR
= &sObjectMgr
.mGOQuestInvolvedRelations
;
12788 QuestMenu
&qm
= PlayerTalkClass
->GetQuestMenu();
12791 for(QuestRelations::const_iterator i
= pObjectQIR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQIR
->upper_bound(pObject
->GetEntry()); ++i
)
12793 uint32 quest_id
= i
->second
;
12794 QuestStatus status
= GetQuestStatus( quest_id
);
12795 if ( status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus( quest_id
) )
12796 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_UNK2
);
12797 else if ( status
== QUEST_STATUS_INCOMPLETE
)
12798 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_UNK2
);
12799 else if (status
== QUEST_STATUS_AVAILABLE
)
12800 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_CHAT
);
12803 for(QuestRelations::const_iterator i
= pObjectQR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++i
)
12805 uint32 quest_id
= i
->second
;
12806 Quest
const* pQuest
= sObjectMgr
.GetQuestTemplate(quest_id
);
12807 if(!pQuest
) continue;
12809 QuestStatus status
= GetQuestStatus( quest_id
);
12811 if (pQuest
->IsAutoComplete() && CanTakeQuest(pQuest
, false))
12812 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_UNK2
);
12813 else if ( status
== QUEST_STATUS_NONE
&& CanTakeQuest( pQuest
, false ) )
12814 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_CHAT
);
12818 void Player::SendPreparedQuest(uint64 guid
)
12820 QuestMenu
& questMenu
= PlayerTalkClass
->GetQuestMenu();
12822 if (questMenu
.Empty())
12825 QuestMenuItem
const& qmi0
= questMenu
.GetItem(0);
12827 uint32 status
= qmi0
.m_qIcon
;
12829 // single element case
12830 if (questMenu
.MenuItemCount() == 1)
12832 // Auto open -- maybe also should verify there is no greeting
12833 uint32 quest_id
= qmi0
.m_qId
;
12834 Quest
const* pQuest
= sObjectMgr
.GetQuestTemplate(quest_id
);
12838 if (status
== DIALOG_STATUS_UNK2
&& !GetQuestRewardStatus(quest_id
))
12839 PlayerTalkClass
->SendQuestGiverRequestItems(pQuest
, guid
, CanRewardQuest(pQuest
, false), true);
12840 else if (status
== DIALOG_STATUS_UNK2
)
12841 PlayerTalkClass
->SendQuestGiverRequestItems(pQuest
, guid
, CanRewardQuest(pQuest
, false), true);
12842 // Send completable on repeatable and autoCompletable quest if player don't have quest
12843 // TODO: verify if check for !pQuest->IsDaily() is really correct (possibly not)
12844 else if (pQuest
->IsAutoComplete() && pQuest
->IsRepeatable() && !pQuest
->IsDaily())
12845 PlayerTalkClass
->SendQuestGiverRequestItems(pQuest
, guid
, CanCompleteRepeatableQuest(pQuest
), true);
12847 PlayerTalkClass
->SendQuestGiverQuestDetails(pQuest
, guid
, true);
12850 // multiply entries
12856 std::string title
= "";
12858 // need pet case for some quests
12859 if (Creature
*pCreature
= GetMap()->GetCreatureOrPetOrVehicle(guid
))
12861 uint32 textid
= GetGossipTextId(pCreature
);
12863 GossipText
const* gossiptext
= sObjectMgr
.GetGossipText(textid
);
12866 qe
._Delay
= 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12867 qe
._Emote
= 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12872 qe
= gossiptext
->Options
[0].Emotes
[0];
12874 if(!gossiptext
->Options
[0].Text_0
.empty())
12876 title
= gossiptext
->Options
[0].Text_0
;
12878 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
12881 NpcTextLocale
const *nl
= sObjectMgr
.GetNpcTextLocale(textid
);
12884 if ((int32
)nl
->Text_0
[0].size() > loc_idx
&& !nl
->Text_0
[0][loc_idx
].empty())
12885 title
= nl
->Text_0
[0][loc_idx
];
12891 title
= gossiptext
->Options
[0].Text_1
;
12893 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
12896 NpcTextLocale
const *nl
= sObjectMgr
.GetNpcTextLocale(textid
);
12899 if ((int32
)nl
->Text_1
[0].size() > loc_idx
&& !nl
->Text_1
[0][loc_idx
].empty())
12900 title
= nl
->Text_1
[0][loc_idx
];
12906 PlayerTalkClass
->SendQuestGiverQuestList(qe
, title
, guid
);
12910 bool Player::IsActiveQuest( uint32 quest_id
) const
12912 QuestStatusMap::const_iterator itr
= mQuestStatus
.find(quest_id
);
12914 return itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
;
12917 Quest
const * Player::GetNextQuest( uint64 guid
, Quest
const *pQuest
)
12920 QuestRelations
* pObjectQR
;
12921 QuestRelations
* pObjectQIR
;
12923 if (Creature
*pCreature
= GetMap()->GetCreatureOrPetOrVehicle(guid
))
12925 pObject
= (Object
*)pCreature
;
12926 pObjectQR
= &sObjectMgr
.mCreatureQuestRelations
;
12927 pObjectQIR
= &sObjectMgr
.mCreatureQuestInvolvedRelations
;
12931 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12932 //only for quests which cast teleport spells on player
12933 Map
* _map
= IsInWorld() ? GetMap() : sMapMgr
.FindMap(GetMapId(), GetInstanceId());
12935 GameObject
*pGameObject
= _map
->GetGameObject(guid
);
12938 pObject
= (Object
*)pGameObject
;
12939 pObjectQR
= &sObjectMgr
.mGOQuestRelations
;
12940 pObjectQIR
= &sObjectMgr
.mGOQuestInvolvedRelations
;
12946 uint32 nextQuestID
= pQuest
->GetNextQuestInChain();
12947 for(QuestRelations::const_iterator itr
= pObjectQR
->lower_bound(pObject
->GetEntry()); itr
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++itr
)
12949 if (itr
->second
== nextQuestID
)
12950 return sObjectMgr
.GetQuestTemplate(nextQuestID
);
12956 bool Player::CanSeeStartQuest( Quest
const *pQuest
)
12958 if( SatisfyQuestRace( pQuest
, false ) && SatisfyQuestSkillOrClass( pQuest
, false ) &&
12959 SatisfyQuestExclusiveGroup( pQuest
, false ) && SatisfyQuestReputation( pQuest
, false ) &&
12960 SatisfyQuestPreviousQuest( pQuest
, false ) && SatisfyQuestNextChain( pQuest
, false ) &&
12961 SatisfyQuestPrevChain( pQuest
, false ) && SatisfyQuestDay( pQuest
, false ) )
12963 return getLevel() + sWorld
.getConfig(CONFIG_UINT32_QUEST_HIGH_LEVEL_HIDE_DIFF
) >= pQuest
->GetMinLevel();
12969 bool Player::CanTakeQuest( Quest
const *pQuest
, bool msg
)
12971 return SatisfyQuestStatus( pQuest
, msg
) && SatisfyQuestExclusiveGroup( pQuest
, msg
)
12972 && SatisfyQuestRace( pQuest
, msg
) && SatisfyQuestLevel( pQuest
, msg
)
12973 && SatisfyQuestSkillOrClass( pQuest
, msg
) && SatisfyQuestReputation( pQuest
, msg
)
12974 && SatisfyQuestPreviousQuest( pQuest
, msg
) && SatisfyQuestTimed( pQuest
, msg
)
12975 && SatisfyQuestNextChain( pQuest
, msg
) && SatisfyQuestPrevChain( pQuest
, msg
)
12976 && SatisfyQuestDay( pQuest
, msg
);
12979 bool Player::CanAddQuest( Quest
const *pQuest
, bool msg
)
12981 if( !SatisfyQuestLog( msg
) )
12984 uint32 srcitem
= pQuest
->GetSrcItemId();
12987 uint32 count
= pQuest
->GetSrcItemCount();
12988 ItemPosCountVec dest
;
12989 uint8 msg2
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
12991 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12992 if( msg2
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
12994 else if( msg2
!= EQUIP_ERR_OK
)
12996 SendEquipError(msg2
, NULL
, NULL
, srcitem
);
13003 bool Player::CanCompleteQuest( uint32 quest_id
)
13007 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
13008 if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
13009 return false; // not allow re-complete quest
13011 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(quest_id
);
13016 // auto complete quest
13017 if (qInfo
->IsAutoComplete() && CanTakeQuest(qInfo
, false))
13020 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13023 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13025 for(int i
= 0; i
< QUEST_ITEM_OBJECTIVES_COUNT
; ++i
)
13027 if( qInfo
->ReqItemCount
[i
] != 0 && q_status
.m_itemcount
[i
] < qInfo
->ReqItemCount
[i
] )
13032 if ( qInfo
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
13034 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
13036 if( qInfo
->ReqCreatureOrGOId
[i
] == 0 )
13039 if( qInfo
->ReqCreatureOrGOCount
[i
] != 0 && q_status
.m_creatureOrGOcount
[i
] < qInfo
->ReqCreatureOrGOCount
[i
] )
13044 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT
) && !q_status
.m_explored
)
13047 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && q_status
.m_timer
== 0 )
13050 if ( qInfo
->GetRewOrReqMoney() < 0 )
13052 if ( GetMoney() < uint32(-qInfo
->GetRewOrReqMoney()) )
13056 uint32 repFacId
= qInfo
->GetRepObjectiveFaction();
13057 if ( repFacId
&& GetReputationMgr().GetReputation(repFacId
) < qInfo
->GetRepObjectiveValue() )
13066 bool Player::CanCompleteRepeatableQuest( Quest
const *pQuest
)
13068 // Solve problem that player don't have the quest and try complete it.
13069 // if repeatable she must be able to complete event if player don't have it.
13070 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
13071 if( !CanTakeQuest(pQuest
, false) )
13074 if (pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13075 for(int i
= 0; i
< QUEST_ITEM_OBJECTIVES_COUNT
; ++i
)
13076 if( pQuest
->ReqItemId
[i
] && pQuest
->ReqItemCount
[i
] && !HasItemCount(pQuest
->ReqItemId
[i
], pQuest
->ReqItemCount
[i
]) )
13079 if( !CanRewardQuest(pQuest
, false) )
13085 bool Player::CanRewardQuest( Quest
const *pQuest
, bool msg
)
13087 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
13088 if(!pQuest
->IsAutoComplete() && GetQuestStatus(pQuest
->GetQuestId()) != QUEST_STATUS_COMPLETE
)
13091 // daily quest can't be rewarded (25 daily quest already completed)
13092 if(!SatisfyQuestDay(pQuest
,true))
13095 // rewarded and not repeatable quest (only cheating case, then ignore without message)
13096 if(GetQuestRewardStatus(pQuest
->GetQuestId()))
13099 // prevent receive reward with quest items in bank
13100 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13102 for(int i
= 0; i
< QUEST_ITEM_OBJECTIVES_COUNT
; ++i
)
13104 if( pQuest
->ReqItemCount
[i
] != 0 &&
13105 GetItemCount(pQuest
->ReqItemId
[i
]) < pQuest
->ReqItemCount
[i
] )
13108 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, NULL
, NULL
, pQuest
->ReqItemId
[i
]);
13114 // prevent receive reward with low money and GetRewOrReqMoney() < 0
13115 if(pQuest
->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest
->GetRewOrReqMoney()) )
13121 bool Player::CanRewardQuest( Quest
const *pQuest
, uint32 reward
, bool msg
)
13123 // prevent receive reward with quest items in bank or for not completed quest
13124 if(!CanRewardQuest(pQuest
,msg
))
13127 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
13129 if( pQuest
->RewChoiceItemId
[reward
] )
13131 ItemPosCountVec dest
;
13132 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] );
13133 if( res
!= EQUIP_ERR_OK
)
13135 SendEquipError( res
, NULL
, NULL
, pQuest
->RewChoiceItemId
[reward
] );
13141 if ( pQuest
->GetRewItemsCount() > 0 )
13143 for (uint32 i
= 0; i
< pQuest
->GetRewItemsCount(); ++i
)
13145 if( pQuest
->RewItemId
[i
] )
13147 ItemPosCountVec dest
;
13148 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] );
13149 if( res
!= EQUIP_ERR_OK
)
13151 SendEquipError( res
, NULL
, NULL
);
13161 void Player::SendPetTameFailure(PetTameFailureReason reason
)
13163 WorldPacket
data(SMSG_PET_TAME_FAILURE
, 1);
13164 data
<< uint8(reason
);
13165 GetSession()->SendPacket(&data
);
13168 void Player::AddQuest( Quest
const *pQuest
, Object
*questGiver
)
13170 uint16 log_slot
= FindQuestSlot( 0 );
13171 assert(log_slot
< MAX_QUEST_LOG_SIZE
);
13173 uint32 quest_id
= pQuest
->GetQuestId();
13175 // if not exist then created with set uState==NEW and rewarded=false
13176 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
13178 // check for repeatable quests status reset
13179 questStatusData
.m_status
= QUEST_STATUS_INCOMPLETE
;
13180 questStatusData
.m_explored
= false;
13182 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13184 for(int i
= 0; i
< QUEST_ITEM_OBJECTIVES_COUNT
; ++i
)
13185 questStatusData
.m_itemcount
[i
] = 0;
13188 if ( pQuest
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
13190 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
13191 questStatusData
.m_creatureOrGOcount
[i
] = 0;
13194 GiveQuestSourceItem( pQuest
);
13195 AdjustQuestReqItemCount( pQuest
, questStatusData
);
13197 if( pQuest
->GetRepObjectiveFaction() )
13198 if(FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(pQuest
->GetRepObjectiveFaction()))
13199 GetReputationMgr().SetVisible(factionEntry
);
13202 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
13204 uint32 limittime
= pQuest
->GetLimitTime();
13206 // shared timed quest
13207 if(questGiver
&& questGiver
->GetTypeId()==TYPEID_PLAYER
)
13208 limittime
= ((Player
*)questGiver
)->getQuestStatusMap()[quest_id
].m_timer
/ IN_MILISECONDS
;
13210 AddTimedQuest( quest_id
);
13211 questStatusData
.m_timer
= limittime
* IN_MILISECONDS
;
13212 qtime
= static_cast<uint32
>(time(NULL
)) + limittime
;
13215 questStatusData
.m_timer
= 0;
13217 SetQuestSlot(log_slot
, quest_id
, qtime
);
13219 if (questStatusData
.uState
!= QUEST_NEW
)
13220 questStatusData
.uState
= QUEST_CHANGED
;
13222 //starting initial quest script
13223 if(questGiver
&& pQuest
->GetQuestStartScript()!=0)
13224 GetMap()->ScriptsStart(sQuestStartScripts
, pQuest
->GetQuestStartScript(), questGiver
, this);
13226 // Some spells applied at quest activation
13227 SpellAreaForQuestMapBounds saBounds
= sSpellMgr
.GetSpellAreaForQuestMapBounds(quest_id
,true);
13228 if(saBounds
.first
!= saBounds
.second
)
13231 GetZoneAndAreaId(zone
,area
);
13233 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
13234 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,zone
,area
))
13235 if (!HasAura(itr
->second
->spellId
, EFFECT_INDEX_0
) )
13236 CastSpell(this,itr
->second
->spellId
,true);
13239 UpdateForQuestWorldObjects();
13242 void Player::CompleteQuest( uint32 quest_id
)
13246 SetQuestStatus( quest_id
, QUEST_STATUS_COMPLETE
);
13248 uint16 log_slot
= FindQuestSlot( quest_id
);
13249 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13250 SetQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
13252 if(Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(quest_id
))
13254 if( qInfo
->HasFlag(QUEST_FLAGS_AUTO_REWARDED
) )
13255 RewardQuest(qInfo
,0,this,false);
13257 SendQuestComplete( quest_id
);
13262 void Player::IncompleteQuest( uint32 quest_id
)
13266 SetQuestStatus( quest_id
, QUEST_STATUS_INCOMPLETE
);
13268 uint16 log_slot
= FindQuestSlot( quest_id
);
13269 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13270 RemoveQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
13274 void Player::RewardQuest( Quest
const *pQuest
, uint32 reward
, Object
* questGiver
, bool announce
)
13276 //this THING should be here to protect code from quest, which cast on player far teleport as a reward
13277 //should work fine, cause far teleport will be executed in Player::Update()
13278 SetCanDelayTeleport(true);
13280 uint32 quest_id
= pQuest
->GetQuestId();
13282 for (int i
= 0; i
< QUEST_ITEM_OBJECTIVES_COUNT
; ++i
)
13284 if (pQuest
->ReqItemId
[i
])
13285 DestroyItemCount( pQuest
->ReqItemId
[i
], pQuest
->ReqItemCount
[i
], true);
13288 RemoveTimedQuest(quest_id
);
13290 if (BattleGround
* bg
= GetBattleGround())
13291 if (bg
->GetTypeID() == BATTLEGROUND_AV
)
13292 ((BattleGroundAV
*)bg
)->HandleQuestComplete(pQuest
->GetQuestId(), this);
13294 if (pQuest
->GetRewChoiceItemsCount() > 0)
13296 if (uint32 itemId
= pQuest
->RewChoiceItemId
[reward
])
13298 ItemPosCountVec dest
;
13299 if (CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, itemId
, pQuest
->RewChoiceItemCount
[reward
] ) == EQUIP_ERR_OK
)
13301 Item
* item
= StoreNewItem( dest
, itemId
, true, Item::GenerateItemRandomPropertyId(itemId
));
13302 SendNewItem(item
, pQuest
->RewChoiceItemCount
[reward
], true, false);
13307 if (pQuest
->GetRewItemsCount() > 0)
13309 for (uint32 i
=0; i
< pQuest
->GetRewItemsCount(); ++i
)
13311 if (uint32 itemId
= pQuest
->RewItemId
[i
])
13313 ItemPosCountVec dest
;
13314 if (CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, itemId
, pQuest
->RewItemCount
[i
] ) == EQUIP_ERR_OK
)
13316 Item
* item
= StoreNewItem( dest
, itemId
, true, Item::GenerateItemRandomPropertyId(itemId
));
13317 SendNewItem(item
, pQuest
->RewItemCount
[i
], true, false);
13323 RewardReputation( pQuest
);
13325 uint16 log_slot
= FindQuestSlot( quest_id
);
13326 if (log_slot
< MAX_QUEST_LOG_SIZE
)
13327 SetQuestSlot(log_slot
,0);
13329 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
13331 // Not give XP in case already completed once repeatable quest
13332 uint32 XP
= q_status
.m_rewarded
? 0 : uint32(pQuest
->XPValue( this )*sWorld
.getConfig(CONFIG_FLOAT_RATE_XP_QUEST
));
13334 if (getLevel() < sWorld
.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL
))
13335 GiveXP( XP
, NULL
);
13338 uint32 money
= uint32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY
));
13339 ModifyMoney( money
);
13340 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD
, money
);
13343 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
13344 if (pQuest
->GetRewOrReqMoney())
13346 ModifyMoney( pQuest
->GetRewOrReqMoney() );
13348 if (pQuest
->GetRewOrReqMoney() > 0)
13349 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD
, pQuest
->GetRewOrReqMoney());
13353 if (pQuest
->GetRewHonorAddition())
13354 RewardHonor(NULL
, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorAddition()));
13357 if (pQuest
->GetCharTitleId())
13359 if (CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
13360 SetTitle(titleEntry
);
13363 if (pQuest
->GetBonusTalents())
13365 m_questRewardTalentCount
+=pQuest
->GetBonusTalents();
13366 InitTalentForLevel();
13369 // Send reward mail
13370 if (uint32 mail_template_id
= pQuest
->GetRewMailTemplateId())
13371 MailDraft(mail_template_id
).SendMailTo(this, questGiver
, MAIL_CHECK_MASK_NONE
, pQuest
->GetRewMailDelaySecs());
13373 if (pQuest
->IsDaily())
13375 SetDailyQuestStatus(quest_id
);
13376 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST
, 1);
13379 if (!pQuest
->IsRepeatable())
13380 SetQuestStatus(quest_id
, QUEST_STATUS_COMPLETE
);
13382 SetQuestStatus(quest_id
, QUEST_STATUS_NONE
);
13384 q_status
.m_rewarded
= true;
13385 if (q_status
.uState
!= QUEST_NEW
)
13386 q_status
.uState
= QUEST_CHANGED
;
13389 SendQuestReward( pQuest
, XP
, questGiver
);
13391 // cast spells after mark quest complete (some spells have quest completed state reqyurements in spell_area data)
13392 if (pQuest
->GetRewSpellCast() > 0)
13393 CastSpell( this, pQuest
->GetRewSpellCast(), true);
13394 else if ( pQuest
->GetRewSpell() > 0)
13395 CastSpell( this, pQuest
->GetRewSpell(), true);
13397 if (pQuest
->GetZoneOrSort() > 0)
13398 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE
, pQuest
->GetZoneOrSort());
13399 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT
);
13400 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST
, pQuest
->GetQuestId());
13405 // remove auras from spells with quest reward state limitations
13406 SpellAreaForQuestMapBounds saEndBounds
= sSpellMgr
.GetSpellAreaForQuestEndMapBounds(quest_id
);
13407 if(saEndBounds
.first
!= saEndBounds
.second
)
13409 GetZoneAndAreaId(zone
,area
);
13411 for(SpellAreaForAreaMap::const_iterator itr
= saEndBounds
.first
; itr
!= saEndBounds
.second
; ++itr
)
13412 if(!itr
->second
->IsFitToRequirements(this,zone
,area
))
13413 RemoveAurasDueToSpell(itr
->second
->spellId
);
13416 // Some spells applied at quest reward
13417 SpellAreaForQuestMapBounds saBounds
= sSpellMgr
.GetSpellAreaForQuestMapBounds(quest_id
,false);
13418 if(saBounds
.first
!= saBounds
.second
)
13421 GetZoneAndAreaId(zone
,area
);
13423 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
13424 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,zone
,area
))
13425 if (!HasAura(itr
->second
->spellId
, EFFECT_INDEX_0
))
13426 CastSpell(this,itr
->second
->spellId
,true);
13429 //lets remove flag for delayed teleports
13430 SetCanDelayTeleport(false);
13433 void Player::FailQuest(uint32 questId
)
13435 if (Quest
const* pQuest
= sObjectMgr
.GetQuestTemplate(questId
))
13437 SetQuestStatus(questId
, QUEST_STATUS_FAILED
);
13439 uint16 log_slot
= FindQuestSlot(questId
);
13441 if (log_slot
< MAX_QUEST_LOG_SIZE
)
13443 SetQuestSlotTimer(log_slot
, 1);
13444 SetQuestSlotState(log_slot
, QUEST_STATE_FAIL
);
13447 if (pQuest
->HasFlag(QUEST_MANGOS_FLAGS_TIMED
))
13449 QuestStatusData
& q_status
= mQuestStatus
[questId
];
13451 RemoveTimedQuest(questId
);
13452 q_status
.m_timer
= 0;
13454 SendQuestTimerFailed(questId
);
13457 SendQuestFailed(questId
);
13461 bool Player::SatisfyQuestSkillOrClass( Quest
const* qInfo
, bool msg
)
13463 int32 zoneOrSort
= qInfo
->GetZoneOrSort();
13464 int32 skillOrClass
= qInfo
->GetSkillOrClass();
13466 // skip zone zoneOrSort and 0 case skillOrClass
13467 if( zoneOrSort
>= 0 && skillOrClass
== 0 )
13470 int32 questSort
= -zoneOrSort
;
13471 uint8 reqSortClass
= ClassByQuestSort(questSort
);
13473 // check class sort cases in zoneOrSort
13474 if( reqSortClass
!= 0 && getClass() != reqSortClass
)
13477 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13482 if( skillOrClass
< 0 )
13484 uint8 reqClass
= -int32(skillOrClass
);
13485 if(getClass() != reqClass
)
13488 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13493 else if( skillOrClass
> 0 )
13495 uint32 reqSkill
= skillOrClass
;
13496 if( GetSkillValue( reqSkill
) < qInfo
->GetRequiredSkillValue() )
13499 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13507 bool Player::SatisfyQuestLevel( Quest
const* qInfo
, bool msg
)
13509 if( getLevel() < qInfo
->GetMinLevel() )
13512 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13518 bool Player::SatisfyQuestLog( bool msg
)
13521 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE
)
13526 WorldPacket
data( SMSG_QUESTLOG_FULL
, 0 );
13527 GetSession()->SendPacket( &data
);
13528 sLog
.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
13533 bool Player::SatisfyQuestPreviousQuest( Quest
const* qInfo
, bool msg
)
13535 // No previous quest (might be first quest in a series)
13536 if( qInfo
->prevQuests
.empty())
13539 for(Quest::PrevQuests::const_iterator iter
= qInfo
->prevQuests
.begin(); iter
!= qInfo
->prevQuests
.end(); ++iter
)
13541 uint32 prevId
= abs(*iter
);
13543 QuestStatusMap::const_iterator i_prevstatus
= mQuestStatus
.find( prevId
);
13544 Quest
const* qPrevInfo
= sObjectMgr
.GetQuestTemplate(prevId
);
13546 if( qPrevInfo
&& i_prevstatus
!= mQuestStatus
.end() )
13548 // If any of the positive previous quests completed, return true
13549 if( *iter
> 0 && i_prevstatus
->second
.m_rewarded
)
13551 // skip one-from-all exclusive group
13552 if(qPrevInfo
->GetExclusiveGroup() >= 0)
13555 // each-from-all exclusive group ( < 0)
13556 // can be start if only all quests in prev quest exclusive group completed and rewarded
13557 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2
= sObjectMgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
13558 ObjectMgr::ExclusiveQuestGroups::const_iterator end
= sObjectMgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
13560 assert(iter2
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
13562 for(; iter2
!= end
; ++iter2
)
13564 uint32 exclude_Id
= iter2
->second
;
13566 // skip checked quest id, only state of other quests in group is interesting
13567 if(exclude_Id
== prevId
)
13570 QuestStatusMap::const_iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
13572 // alternative quest from group also must be completed and rewarded(reported)
13573 if( i_exstatus
== mQuestStatus
.end() || !i_exstatus
->second
.m_rewarded
)
13576 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13582 // If any of the negative previous quests active, return true
13583 if( *iter
< 0 && (i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
13584 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
))))
13586 // skip one-from-all exclusive group
13587 if(qPrevInfo
->GetExclusiveGroup() >= 0)
13590 // each-from-all exclusive group ( < 0)
13591 // can be start if only all quests in prev quest exclusive group active
13592 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2
= sObjectMgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
13593 ObjectMgr::ExclusiveQuestGroups::const_iterator end
= sObjectMgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
13595 assert(iter2
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
13597 for(; iter2
!= end
; ++iter2
)
13599 uint32 exclude_Id
= iter2
->second
;
13601 // skip checked quest id, only state of other quests in group is interesting
13602 if(exclude_Id
== prevId
)
13605 QuestStatusMap::const_iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
13607 // alternative quest from group also must be active
13608 if( i_exstatus
== mQuestStatus
.end() ||
13609 i_exstatus
->second
.m_status
!= QUEST_STATUS_INCOMPLETE
&&
13610 (i_prevstatus
->second
.m_status
!= QUEST_STATUS_COMPLETE
|| GetQuestRewardStatus(prevId
)) )
13613 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13622 // Has only positive prev. quests in non-rewarded state
13623 // and negative prev. quests in non-active state
13625 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13630 bool Player::SatisfyQuestRace( Quest
const* qInfo
, bool msg
)
13632 uint32 reqraces
= qInfo
->GetRequiredRaces();
13633 if ( reqraces
== 0 )
13635 if( (reqraces
& getRaceMask()) == 0 )
13638 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE
);
13644 bool Player::SatisfyQuestReputation( Quest
const* qInfo
, bool msg
)
13646 uint32 fIdMin
= qInfo
->GetRequiredMinRepFaction(); //Min required rep
13647 if(fIdMin
&& GetReputationMgr().GetReputation(fIdMin
) < qInfo
->GetRequiredMinRepValue())
13650 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13654 uint32 fIdMax
= qInfo
->GetRequiredMaxRepFaction(); //Max required rep
13655 if(fIdMax
&& GetReputationMgr().GetReputation(fIdMax
) >= qInfo
->GetRequiredMaxRepValue())
13658 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13665 bool Player::SatisfyQuestStatus( Quest
const* qInfo
, bool msg
)
13667 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( qInfo
->GetQuestId() );
13668 if ( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
)
13671 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON
);
13677 bool Player::SatisfyQuestTimed(Quest
const* qInfo
, bool msg
)
13679 if (!m_timedquests
.empty() && qInfo
->HasFlag(QUEST_MANGOS_FLAGS_TIMED
))
13682 SendCanTakeQuestResponse(INVALIDREASON_QUEST_ONLY_ONE_TIMED
);
13689 bool Player::SatisfyQuestExclusiveGroup( Quest
const* qInfo
, bool msg
)
13691 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
13692 if(qInfo
->GetExclusiveGroup() <= 0)
13695 ObjectMgr::ExclusiveQuestGroups::const_iterator iter
= sObjectMgr
.mExclusiveQuestGroups
.lower_bound(qInfo
->GetExclusiveGroup());
13696 ObjectMgr::ExclusiveQuestGroups::const_iterator end
= sObjectMgr
.mExclusiveQuestGroups
.upper_bound(qInfo
->GetExclusiveGroup());
13698 assert(iter
!=end
); // always must be found if qInfo->ExclusiveGroup != 0
13700 for(; iter
!= end
; ++iter
)
13702 uint32 exclude_Id
= iter
->second
;
13704 // skip checked quest id, only state of other quests in group is interesting
13705 if(exclude_Id
== qInfo
->GetQuestId())
13708 // not allow have daily quest if daily quest from exclusive group already recently completed
13709 Quest
const* Nquest
= sObjectMgr
.GetQuestTemplate(exclude_Id
);
13710 if( !SatisfyQuestDay(Nquest
, false) )
13713 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13717 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
13719 // alternative quest already started or completed
13720 if( i_exstatus
!= mQuestStatus
.end()
13721 && (i_exstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
|| i_exstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
13724 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13731 bool Player::SatisfyQuestNextChain( Quest
const* qInfo
, bool msg
)
13733 if(!qInfo
->GetNextQuestInChain())
13736 // next quest in chain already started or completed
13737 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( qInfo
->GetNextQuestInChain() );
13738 if( itr
!= mQuestStatus
.end()
13739 && (itr
->second
.m_status
== QUEST_STATUS_COMPLETE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
13742 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13746 // check for all quests further up the chain
13747 // only necessary if there are quest chains with more than one quest that can be skipped
13748 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
13752 bool Player::SatisfyQuestPrevChain( Quest
const* qInfo
, bool msg
)
13754 // No previous quest in chain
13755 if( qInfo
->prevChainQuests
.empty())
13758 for(Quest::PrevChainQuests::const_iterator iter
= qInfo
->prevChainQuests
.begin(); iter
!= qInfo
->prevChainQuests
.end(); ++iter
)
13760 uint32 prevId
= *iter
;
13762 QuestStatusMap::const_iterator i_prevstatus
= mQuestStatus
.find( prevId
);
13764 if( i_prevstatus
!= mQuestStatus
.end() )
13766 // If any of the previous quests in chain active, return false
13767 if( i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
13768 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
)))
13771 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13776 // check for all quests further down the chain
13777 // only necessary if there are quest chains with more than one quest that can be skipped
13778 //if( !SatisfyQuestPrevChain( prevId, msg ) )
13782 // No previous quest in chain active
13786 bool Player::SatisfyQuestDay( Quest
const* qInfo
, bool msg
)
13788 if(!qInfo
->IsDaily())
13791 bool have_slot
= false;
13792 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
13794 uint32 id
= GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
);
13795 if(qInfo
->GetQuestId()==id
)
13805 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING
);
13812 bool Player::GiveQuestSourceItem( Quest
const *pQuest
)
13814 uint32 srcitem
= pQuest
->GetSrcItemId();
13817 uint32 count
= pQuest
->GetSrcItemCount();
13821 ItemPosCountVec dest
;
13822 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
13823 if( msg
== EQUIP_ERR_OK
)
13825 Item
* item
= StoreNewItem(dest
, srcitem
, true);
13826 SendNewItem(item
, count
, true, false);
13829 // player already have max amount required item, just report success
13830 else if( msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
13833 SendEquipError( msg
, NULL
, NULL
, srcitem
);
13840 bool Player::TakeQuestSourceItem( uint32 quest_id
, bool msg
)
13842 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(quest_id
);
13845 uint32 srcitem
= qInfo
->GetSrcItemId();
13848 uint32 count
= qInfo
->GetSrcItemCount();
13852 // exist one case when destroy source quest item not possible:
13853 // non un-equippable item (equipped non-empty bag, for example)
13854 uint8 res
= CanUnequipItems(srcitem
,count
);
13855 if(res
!= EQUIP_ERR_OK
)
13858 SendEquipError( res
, NULL
, NULL
, srcitem
);
13862 DestroyItemCount(srcitem
, count
, true, true);
13868 bool Player::GetQuestRewardStatus( uint32 quest_id
) const
13870 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(quest_id
);
13873 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13874 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13875 if( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
13876 && !qInfo
->IsRepeatable() )
13877 return itr
->second
.m_rewarded
;
13884 QuestStatus
Player::GetQuestStatus( uint32 quest_id
) const
13888 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13889 if( itr
!= mQuestStatus
.end() )
13890 return itr
->second
.m_status
;
13892 return QUEST_STATUS_NONE
;
13895 bool Player::CanShareQuest(uint32 quest_id
) const
13897 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(quest_id
);
13898 if( qInfo
&& qInfo
->HasFlag(QUEST_FLAGS_SHARABLE
) )
13900 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13901 if( itr
!= mQuestStatus
.end() )
13902 return itr
->second
.m_status
== QUEST_STATUS_NONE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
;
13907 void Player::SetQuestStatus(uint32 quest_id
, QuestStatus status
)
13909 if (sObjectMgr
.GetQuestTemplate(quest_id
))
13911 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
13913 q_status
.m_status
= status
;
13915 if (q_status
.uState
!= QUEST_NEW
)
13916 q_status
.uState
= QUEST_CHANGED
;
13919 UpdateForQuestWorldObjects();
13922 // not used in MaNGOS, but used in scripting code
13923 uint32
Player::GetReqKillOrCastCurrentCount(uint32 quest_id
, int32 entry
)
13925 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(quest_id
);
13929 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13930 if ( qInfo
->ReqCreatureOrGOId
[j
] == entry
)
13931 return mQuestStatus
[quest_id
].m_creatureOrGOcount
[j
];
13936 void Player::AdjustQuestReqItemCount( Quest
const* pQuest
, QuestStatusData
& questStatusData
)
13938 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13940 for(int i
= 0; i
< QUEST_ITEM_OBJECTIVES_COUNT
; ++i
)
13942 uint32 reqitemcount
= pQuest
->ReqItemCount
[i
];
13943 if( reqitemcount
!= 0 )
13945 uint32 curitemcount
= GetItemCount(pQuest
->ReqItemId
[i
], true);
13947 questStatusData
.m_itemcount
[i
] = std::min(curitemcount
, reqitemcount
);
13948 if (questStatusData
.uState
!= QUEST_NEW
) questStatusData
.uState
= QUEST_CHANGED
;
13954 uint16
Player::FindQuestSlot( uint32 quest_id
) const
13956 for ( uint16 i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13957 if ( GetQuestSlotQuestId(i
) == quest_id
)
13960 return MAX_QUEST_LOG_SIZE
;
13963 void Player::AreaExploredOrEventHappens( uint32 questId
)
13967 uint16 log_slot
= FindQuestSlot( questId
);
13968 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13970 QuestStatusData
& q_status
= mQuestStatus
[questId
];
13972 if(!q_status
.m_explored
)
13974 q_status
.m_explored
= true;
13975 if (q_status
.uState
!= QUEST_NEW
)
13976 q_status
.uState
= QUEST_CHANGED
;
13979 if( CanCompleteQuest( questId
) )
13980 CompleteQuest( questId
);
13984 //not used in mangosd, function for external script library
13985 void Player::GroupEventHappens( uint32 questId
, WorldObject
const* pEventObject
)
13987 if( Group
*pGroup
= GetGroup() )
13989 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
13991 Player
*pGroupGuy
= itr
->getSource();
13993 // for any leave or dead (with not released body) group member at appropriate distance
13994 if( pGroupGuy
&& pGroupGuy
->IsAtGroupRewardDistance(pEventObject
) && !pGroupGuy
->GetCorpse() )
13995 pGroupGuy
->AreaExploredOrEventHappens(questId
);
13999 AreaExploredOrEventHappens(questId
);
14002 void Player::ItemAddedQuestCheck( uint32 entry
, uint32 count
)
14004 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14006 uint32 questid
= GetQuestSlotQuestId(i
);
14007 if ( questid
== 0 )
14010 QuestStatusData
& q_status
= mQuestStatus
[questid
];
14012 if ( q_status
.m_status
!= QUEST_STATUS_INCOMPLETE
)
14015 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(questid
);
14016 if( !qInfo
|| !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
14019 for (int j
= 0; j
< QUEST_ITEM_OBJECTIVES_COUNT
; ++j
)
14021 uint32 reqitem
= qInfo
->ReqItemId
[j
];
14022 if ( reqitem
== entry
)
14024 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
14025 uint32 curitemcount
= q_status
.m_itemcount
[j
];
14026 if ( curitemcount
< reqitemcount
)
14028 uint32 additemcount
= ( curitemcount
+ count
<= reqitemcount
? count
: reqitemcount
- curitemcount
);
14029 q_status
.m_itemcount
[j
] += additemcount
;
14030 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
14032 SendQuestUpdateAddItem( qInfo
, j
, additemcount
);
14034 if ( CanCompleteQuest( questid
) )
14035 CompleteQuest( questid
);
14040 UpdateForQuestWorldObjects();
14043 void Player::ItemRemovedQuestCheck( uint32 entry
, uint32 count
)
14045 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14047 uint32 questid
= GetQuestSlotQuestId(i
);
14050 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(questid
);
14053 if( !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
14056 for (int j
= 0; j
< QUEST_ITEM_OBJECTIVES_COUNT
; ++j
)
14058 uint32 reqitem
= qInfo
->ReqItemId
[j
];
14059 if ( reqitem
== entry
)
14061 QuestStatusData
& q_status
= mQuestStatus
[questid
];
14063 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
14064 uint32 curitemcount
;
14065 if( q_status
.m_status
!= QUEST_STATUS_COMPLETE
)
14066 curitemcount
= q_status
.m_itemcount
[j
];
14068 curitemcount
= GetItemCount(entry
, true);
14069 if ( curitemcount
< reqitemcount
+ count
)
14071 uint32 remitemcount
= ( curitemcount
<= reqitemcount
? count
: count
+ reqitemcount
- curitemcount
);
14072 q_status
.m_itemcount
[j
] = curitemcount
- remitemcount
;
14073 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
14075 IncompleteQuest( questid
);
14081 UpdateForQuestWorldObjects();
14084 void Player::KilledMonster( CreatureInfo
const* cInfo
, uint64 guid
)
14087 KilledMonsterCredit(cInfo
->Entry
,guid
);
14089 for(int i
= 0; i
< MAX_KILL_CREDIT
; ++i
)
14090 if(cInfo
->KillCredit
[i
])
14091 KilledMonsterCredit(cInfo
->KillCredit
[i
],guid
);
14094 void Player::KilledMonsterCredit( uint32 entry
, uint64 guid
)
14096 uint32 addkillcount
= 1;
14097 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE
, entry
, addkillcount
);
14098 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14100 uint32 questid
= GetQuestSlotQuestId(i
);
14104 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(questid
);
14107 // just if !ingroup || !noraidgroup || raidgroup
14108 QuestStatusData
& q_status
= mQuestStatus
[questid
];
14109 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
&& (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo
->GetType() == QUEST_TYPE_RAID
))
14111 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
14113 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
14115 // skip GO activate objective or none
14116 if(qInfo
->ReqCreatureOrGOId
[j
] <=0)
14119 // skip Cast at creature objective
14120 if(qInfo
->ReqSpell
[j
] !=0 )
14123 uint32 reqkill
= qInfo
->ReqCreatureOrGOId
[j
];
14125 if ( reqkill
== entry
)
14127 uint32 reqkillcount
= qInfo
->ReqCreatureOrGOCount
[j
];
14128 uint32 curkillcount
= q_status
.m_creatureOrGOcount
[j
];
14129 if ( curkillcount
< reqkillcount
)
14131 q_status
.m_creatureOrGOcount
[j
] = curkillcount
+ addkillcount
;
14132 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
14134 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curkillcount
, addkillcount
);
14136 if ( CanCompleteQuest( questid
) )
14137 CompleteQuest( questid
);
14139 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
14148 void Player::CastedCreatureOrGO( uint32 entry
, uint64 guid
, uint32 spell_id
)
14150 bool isCreature
= IS_CREATURE_GUID(guid
);
14152 uint32 addCastCount
= 1;
14153 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14155 uint32 questid
= GetQuestSlotQuestId(i
);
14159 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(questid
);
14163 QuestStatusData
& q_status
= mQuestStatus
[questid
];
14165 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
14167 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
14169 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
14171 // skip kill creature objective (0) or wrong spell casts
14172 if(qInfo
->ReqSpell
[j
] != spell_id
)
14175 uint32 reqTarget
= 0;
14179 // creature activate objectives
14180 if(qInfo
->ReqCreatureOrGOId
[j
] > 0)
14181 // checked at quest_template loading
14182 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
14186 // GO activate objective
14187 if(qInfo
->ReqCreatureOrGOId
[j
] < 0)
14188 // checked at quest_template loading
14189 reqTarget
= - qInfo
->ReqCreatureOrGOId
[j
];
14192 // other not this creature/GO related objectives
14193 if( reqTarget
!= entry
)
14196 uint32 reqCastCount
= qInfo
->ReqCreatureOrGOCount
[j
];
14197 uint32 curCastCount
= q_status
.m_creatureOrGOcount
[j
];
14198 if ( curCastCount
< reqCastCount
)
14200 q_status
.m_creatureOrGOcount
[j
] = curCastCount
+ addCastCount
;
14201 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
14203 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curCastCount
, addCastCount
);
14206 if ( CanCompleteQuest( questid
) )
14207 CompleteQuest( questid
);
14209 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
14217 void Player::TalkedToCreature( uint32 entry
, uint64 guid
)
14219 uint32 addTalkCount
= 1;
14220 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14222 uint32 questid
= GetQuestSlotQuestId(i
);
14226 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(questid
);
14230 QuestStatusData
& q_status
= mQuestStatus
[questid
];
14232 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
14234 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
14236 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
14238 // skip spell casts and Gameobject objectives
14239 if(qInfo
->ReqSpell
[j
] > 0 || qInfo
->ReqCreatureOrGOId
[j
] < 0)
14242 uint32 reqTarget
= 0;
14244 if(qInfo
->ReqCreatureOrGOId
[j
] > 0) // creature activate objectives
14245 // checked at quest_template loading
14246 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
14250 if ( reqTarget
== entry
)
14252 uint32 reqTalkCount
= qInfo
->ReqCreatureOrGOCount
[j
];
14253 uint32 curTalkCount
= q_status
.m_creatureOrGOcount
[j
];
14254 if ( curTalkCount
< reqTalkCount
)
14256 q_status
.m_creatureOrGOcount
[j
] = curTalkCount
+ addTalkCount
;
14257 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
14259 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curTalkCount
, addTalkCount
);
14261 if ( CanCompleteQuest( questid
) )
14262 CompleteQuest( questid
);
14264 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
14273 void Player::MoneyChanged( uint32 count
)
14275 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14277 uint32 questid
= GetQuestSlotQuestId(i
);
14281 Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(questid
);
14282 if( qInfo
&& qInfo
->GetRewOrReqMoney() < 0 )
14284 QuestStatusData
& q_status
= mQuestStatus
[questid
];
14286 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
14288 if(int32(count
) >= -qInfo
->GetRewOrReqMoney())
14290 if ( CanCompleteQuest( questid
) )
14291 CompleteQuest( questid
);
14294 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
14296 if(int32(count
) < -qInfo
->GetRewOrReqMoney())
14297 IncompleteQuest( questid
);
14303 void Player::ReputationChanged(FactionEntry
const* factionEntry
)
14305 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14307 if(uint32 questid
= GetQuestSlotQuestId(i
))
14309 if(Quest
const* qInfo
= sObjectMgr
.GetQuestTemplate(questid
))
14311 if(qInfo
->GetRepObjectiveFaction() == factionEntry
->ID
)
14313 QuestStatusData
& q_status
= mQuestStatus
[questid
];
14314 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
14316 if(GetReputationMgr().GetReputation(factionEntry
) >= qInfo
->GetRepObjectiveValue())
14317 if ( CanCompleteQuest( questid
) )
14318 CompleteQuest( questid
);
14320 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
14322 if(GetReputationMgr().GetReputation(factionEntry
) < qInfo
->GetRepObjectiveValue())
14323 IncompleteQuest( questid
);
14331 bool Player::HasQuestForItem( uint32 itemid
) const
14333 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14335 uint32 questid
= GetQuestSlotQuestId(i
);
14336 if ( questid
== 0 )
14339 QuestStatusMap::const_iterator qs_itr
= mQuestStatus
.find(questid
);
14340 if(qs_itr
== mQuestStatus
.end())
14343 QuestStatusData
const& q_status
= qs_itr
->second
;
14345 if (q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
14347 Quest
const* qinfo
= sObjectMgr
.GetQuestTemplate(questid
);
14351 // hide quest if player is in raid-group and quest is no raid quest
14352 if (GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
14353 && !InBattleGround())
14356 // There should be no mixed ReqItem/ReqSource drop
14357 // This part for ReqItem drop
14358 for (int j
= 0; j
< QUEST_ITEM_OBJECTIVES_COUNT
; ++j
)
14360 if(itemid
== qinfo
->ReqItemId
[j
] && q_status
.m_itemcount
[j
] < qinfo
->ReqItemCount
[j
] )
14363 // This part - for ReqSource
14364 for (int j
= 0; j
< QUEST_SOURCE_ITEM_IDS_COUNT
; ++j
)
14366 // examined item is a source item
14367 if (qinfo
->ReqSourceId
[j
] == itemid
)
14369 ItemPrototype
const *pProto
= ObjectMgr::GetItemPrototype(itemid
);
14372 if (pProto
->MaxCount
&& (int32
)GetItemCount(itemid
,true) < pProto
->MaxCount
)
14375 // allows custom amount drop when not 0
14376 if (qinfo
->ReqSourceCount
[j
])
14378 if (GetItemCount(itemid
,true) < qinfo
->ReqSourceCount
[j
])
14380 } else if ((int32
)GetItemCount(itemid
,true) < pProto
->Stackable
)
14389 void Player::SendQuestComplete( uint32 quest_id
)
14393 WorldPacket
data( SMSG_QUESTUPDATE_COMPLETE
, 4 );
14394 data
<< uint32(quest_id
);
14395 GetSession()->SendPacket( &data
);
14396 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id
);
14400 void Player::SendQuestReward( Quest
const *pQuest
, uint32 XP
, Object
* questGiver
)
14402 uint32 questid
= pQuest
->GetQuestId();
14403 sLog
.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid
);
14404 WorldPacket
data( SMSG_QUESTGIVER_QUEST_COMPLETE
, (4+4+4+4+4) );
14405 data
<< uint32(questid
);
14407 if ( getLevel() < sWorld
.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL
) )
14409 data
<< uint32(XP
);
14410 data
<< uint32(pQuest
->GetRewOrReqMoney());
14415 data
<< uint32(pQuest
->GetRewOrReqMoney() + int32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getConfig(CONFIG_FLOAT_RATE_DROP_MONEY
)));
14418 data
<< uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorAddition()));
14419 data
<< uint32(pQuest
->GetBonusTalents()); // bonus talents
14421 GetSession()->SendPacket( &data
);
14423 if (pQuest
->GetQuestCompleteScript() != 0)
14424 GetMap()->ScriptsStart(sQuestEndScripts
, pQuest
->GetQuestCompleteScript(), questGiver
, this);
14427 void Player::SendQuestFailed( uint32 quest_id
)
14431 WorldPacket
data( SMSG_QUESTGIVER_QUEST_FAILED
, 4+4 );
14432 data
<< uint32(quest_id
);
14433 data
<< uint32(0); // failed reason (4 for inventory is full)
14434 GetSession()->SendPacket( &data
);
14435 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
14439 void Player::SendQuestTimerFailed( uint32 quest_id
)
14443 WorldPacket
data( SMSG_QUESTUPDATE_FAILEDTIMER
, 4 );
14444 data
<< uint32(quest_id
);
14445 GetSession()->SendPacket( &data
);
14446 sLog
.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
14450 void Player::SendCanTakeQuestResponse( uint32 msg
)
14452 WorldPacket
data( SMSG_QUESTGIVER_QUEST_INVALID
, 4 );
14453 data
<< uint32(msg
);
14454 GetSession()->SendPacket( &data
);
14455 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
14458 void Player::SendQuestConfirmAccept(const Quest
* pQuest
, Player
* pReceiver
)
14462 std::string strTitle
= pQuest
->GetTitle();
14464 int loc_idx
= pReceiver
->GetSession()->GetSessionDbLocaleIndex();
14468 if (const QuestLocale
* pLocale
= sObjectMgr
.GetQuestLocale(pQuest
->GetQuestId()))
14470 if ((int32
)pLocale
->Title
.size() > loc_idx
&& !pLocale
->Title
[loc_idx
].empty())
14471 strTitle
= pLocale
->Title
[loc_idx
];
14475 WorldPacket
data(SMSG_QUEST_CONFIRM_ACCEPT
, (4 + strTitle
.size() + 8));
14476 data
<< uint32(pQuest
->GetQuestId());
14478 data
<< uint64(GetGUID());
14479 pReceiver
->GetSession()->SendPacket(&data
);
14481 sLog
.outDebug("WORLD: Sent SMSG_QUEST_CONFIRM_ACCEPT");
14485 void Player::SendPushToPartyResponse( Player
*pPlayer
, uint32 msg
)
14489 WorldPacket
data( MSG_QUEST_PUSH_RESULT
, (8+1) );
14490 data
<< uint64(pPlayer
->GetGUID());
14491 data
<< uint8(msg
); // valid values: 0-8
14492 GetSession()->SendPacket( &data
);
14493 sLog
.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
14497 void Player::SendQuestUpdateAddItem( Quest
const* /*pQuest*/, uint32
/*item_idx*/, uint32
/*count*/ )
14499 WorldPacket
data( SMSG_QUESTUPDATE_ADD_ITEM
, 0 );
14500 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
14501 //data << pQuest->ReqItemId[item_idx];
14503 GetSession()->SendPacket( &data
);
14506 void Player::SendQuestUpdateAddCreatureOrGo( Quest
const* pQuest
, uint64 guid
, uint32 creatureOrGO_idx
, uint32 old_count
, uint32 add_count
)
14508 assert(old_count
+ add_count
< 65536 && "mob/GO count store in 16 bits 2^16 = 65536 (0..65536)");
14510 int32 entry
= pQuest
->ReqCreatureOrGOId
[ creatureOrGO_idx
];
14512 // client expected gameobject template id in form (id|0x80000000)
14513 entry
= (-entry
) | 0x80000000;
14515 WorldPacket
data( SMSG_QUESTUPDATE_ADD_KILL
, (4*4+8) );
14516 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
14517 data
<< uint32(pQuest
->GetQuestId());
14518 data
<< uint32(entry
);
14519 data
<< uint32(old_count
+ add_count
);
14520 data
<< uint32(pQuest
->ReqCreatureOrGOCount
[ creatureOrGO_idx
]);
14521 data
<< uint64(guid
);
14522 GetSession()->SendPacket(&data
);
14524 uint16 log_slot
= FindQuestSlot( pQuest
->GetQuestId() );
14525 if( log_slot
< MAX_QUEST_LOG_SIZE
)
14526 SetQuestSlotCounter(log_slot
,creatureOrGO_idx
,GetQuestSlotCounter(log_slot
,creatureOrGO_idx
)+add_count
);
14529 /*********************************************************/
14530 /*** LOAD SYSTEM ***/
14531 /*********************************************************/
14533 void Player::_LoadDeclinedNames(QueryResult
* result
)
14539 delete m_declinedname
;
14541 m_declinedname
= new DeclinedName
;
14542 Field
*fields
= result
->Fetch();
14543 for(int i
= 0; i
< MAX_DECLINED_NAME_CASES
; ++i
)
14544 m_declinedname
->name
[i
] = fields
[i
].GetCppString();
14549 void Player::_LoadArenaTeamInfo(QueryResult
*result
)
14551 // arenateamid, played_week, played_season, personal_rating
14552 memset((void*)&m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
], 0, sizeof(uint32
) * MAX_ARENA_SLOT
* ARENA_TEAM_END
);
14558 Field
*fields
= result
->Fetch();
14560 uint32 arenateamid
= fields
[0].GetUInt32();
14561 uint32 played_week
= fields
[1].GetUInt32();
14562 uint32 played_season
= fields
[2].GetUInt32();
14563 uint32 wons_season
= fields
[3].GetUInt32();
14564 uint32 personal_rating
= fields
[4].GetUInt32();
14566 ArenaTeam
* aTeam
= sObjectMgr
.GetArenaTeamById(arenateamid
);
14569 sLog
.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u", arenateamid
);
14572 uint8 arenaSlot
= aTeam
->GetSlot();
14574 SetArenaTeamInfoField(arenaSlot
, ARENA_TEAM_ID
, arenateamid
);
14575 SetArenaTeamInfoField(arenaSlot
, ARENA_TEAM_TYPE
, aTeam
->GetType());
14576 SetArenaTeamInfoField(arenaSlot
, ARENA_TEAM_MEMBER
, (aTeam
->GetCaptain() == GetGUID()) ? 0 : 1);
14577 SetArenaTeamInfoField(arenaSlot
, ARENA_TEAM_GAMES_WEEK
, played_week
);
14578 SetArenaTeamInfoField(arenaSlot
, ARENA_TEAM_GAMES_SEASON
, played_season
);
14579 SetArenaTeamInfoField(arenaSlot
, ARENA_TEAM_WINS_SEASON
, wons_season
);
14580 SetArenaTeamInfoField(arenaSlot
, ARENA_TEAM_PERSONAL_RATING
, personal_rating
);
14582 } while (result
->NextRow());
14586 void Player::_LoadEquipmentSets(QueryResult
*result
)
14588 // 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));
14595 Field
*fields
= result
->Fetch();
14597 EquipmentSet eqSet
;
14599 eqSet
.Guid
= fields
[0].GetUInt64();
14600 uint32 index
= fields
[1].GetUInt32();
14601 eqSet
.Name
= fields
[2].GetCppString();
14602 eqSet
.IconName
= fields
[3].GetCppString();
14603 eqSet
.state
= EQUIPMENT_SET_UNCHANGED
;
14605 for(uint32 i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
14606 eqSet
.Items
[i
] = fields
[4+i
].GetUInt32();
14608 m_EquipmentSets
[index
] = eqSet
;
14612 if(count
>= MAX_EQUIPMENT_SET_INDEX
) // client limit
14614 } while (result
->NextRow());
14618 void Player::_LoadBGData(QueryResult
* result
)
14623 // Expecting only one row
14624 Field
*fields
= result
->Fetch();
14625 /* bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
14626 m_bgData
.bgInstanceID
= fields
[0].GetUInt32();
14627 m_bgData
.bgTeam
= fields
[1].GetUInt32();
14628 m_bgData
.joinPos
= WorldLocation(fields
[6].GetUInt32(), // Map
14629 fields
[2].GetFloat(), // X
14630 fields
[3].GetFloat(), // Y
14631 fields
[4].GetFloat(), // Z
14632 fields
[5].GetFloat()); // Orientation
14633 m_bgData
.taxiPath
[0] = fields
[7].GetUInt32();
14634 m_bgData
.taxiPath
[1] = fields
[8].GetUInt32();
14635 m_bgData
.mountSpell
= fields
[9].GetUInt32();
14640 bool Player::LoadPositionFromDB(uint32
& mapid
, float& x
,float& y
,float& z
,float& o
, bool& in_flight
, uint64 guid
)
14642 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid
));
14646 Field
*fields
= result
->Fetch();
14648 x
= fields
[0].GetFloat();
14649 y
= fields
[1].GetFloat();
14650 z
= fields
[2].GetFloat();
14651 o
= fields
[3].GetFloat();
14652 mapid
= fields
[4].GetUInt32();
14653 in_flight
= !fields
[5].GetCppString().empty();
14659 bool Player::LoadValuesArrayFromDB(Tokens
& data
, uint64 guid
)
14661 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid
));
14665 Field
*fields
= result
->Fetch();
14667 data
= StrSplit(fields
[0].GetCppString(), " ");
14674 uint32
Player::GetUInt32ValueFromArray(Tokens
const& data
, uint16 index
)
14676 if(index
>= data
.size())
14679 return (uint32
)atoi(data
[index
].c_str());
14682 float Player::GetFloatValueFromArray(Tokens
const& data
, uint16 index
)
14685 uint32 temp
= Player::GetUInt32ValueFromArray(data
,index
);
14686 memcpy(&result
, &temp
, sizeof(result
));
14691 uint32
Player::GetUInt32ValueFromDB(uint16 index
, uint64 guid
)
14694 if(!LoadValuesArrayFromDB(data
,guid
))
14697 return GetUInt32ValueFromArray(data
,index
);
14700 float Player::GetFloatValueFromDB(uint16 index
, uint64 guid
)
14703 uint32 temp
= Player::GetUInt32ValueFromDB(index
, guid
);
14704 memcpy(&result
, &temp
, sizeof(result
));
14709 bool Player::LoadFromDB( uint32 guid
, SqlQueryHolder
*holder
)
14711 // 0 1 2 3 4 5 6 7 8 9 10 11 12
14712 //SELECT guid, account, data, name, race, class, gender, level, xp, money, playerBytes, playerBytes2, playerFlags,"
14713 // 13 14 15 16 17 18 19 20 21 22 23 24 25
14714 //"position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost,"
14715 // 26 27 28 29 30 31 32 33 34 35 36 37 38 39
14716 //"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,"
14717 // 40 41 42 43 44 45 46 47 48 49 50
14718 //"arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk,"
14719 // 51 52 53 54 55 56 57 58 59 60
14720 //"health, power1, power2, power3, power4, power5, power6, power7, specCount, activeSpec FROM characters WHERE guid = '%u'", GUID_LOPART(m_guid));
14721 QueryResult
*result
= holder
->GetResult(PLAYER_LOGIN_QUERY_LOADFROM
);
14725 sLog
.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid
);
14729 Field
*fields
= result
->Fetch();
14731 uint32 dbAccountId
= fields
[1].GetUInt32();
14733 // check if the character's account in the db and the logged in account match.
14734 // player should be able to load/delete character only with correct account!
14735 if( dbAccountId
!= GetSession()->GetAccountId() )
14737 sLog
.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid
,GetSession()->GetAccountId(),dbAccountId
);
14742 Object::_Create( guid
, 0, HIGHGUID_PLAYER
);
14744 m_name
= fields
[3].GetCppString();
14746 // check name limitations
14747 if (ObjectMgr::CheckPlayerName(m_name
) != CHAR_NAME_SUCCESS
||
14748 (GetSession()->GetSecurity() == SEC_PLAYER
&& sObjectMgr
.IsReservedName(m_name
)))
14751 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME
),guid
);
14755 if(!LoadValues( fields
[2].GetString()))
14757 sLog
.outError("Player #%d have broken data in `data` field. Can't be loaded.", GUID_LOPART(guid
));
14762 // overwrite possible wrong/corrupted guid
14763 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
14765 // overwrite some data fields
14766 uint32 bytes0
= GetUInt32Value(UNIT_FIELD_BYTES_0
) & 0xFF000000;
14767 bytes0
|= fields
[4].GetUInt8(); // race
14768 bytes0
|= fields
[5].GetUInt8() << 8; // class
14769 bytes0
|= fields
[6].GetUInt8() << 16; // gender
14770 SetUInt32Value(UNIT_FIELD_BYTES_0
, bytes0
);
14772 SetUInt32Value(UNIT_FIELD_LEVEL
, fields
[7].GetUInt8());
14773 SetUInt32Value(PLAYER_XP
, fields
[8].GetUInt32());
14775 uint32 money
= fields
[9].GetUInt32();
14776 if(money
> MAX_MONEY_AMOUNT
)
14777 money
= MAX_MONEY_AMOUNT
;
14780 SetUInt32Value(PLAYER_BYTES
, fields
[10].GetUInt32());
14781 SetUInt32Value(PLAYER_BYTES_2
, fields
[11].GetUInt32());
14782 SetUInt32Value(PLAYER_BYTES_3
, (fields
[50].GetUInt16() & 0xFFFE) | fields
[6].GetUInt8());
14783 SetUInt32Value(PLAYER_FLAGS
, fields
[12].GetUInt32());
14784 SetInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX
, fields
[49].GetInt32());
14786 SetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES
, fields
[48].GetUInt64());
14791 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
14792 for(uint8 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
14794 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2), 0 );
14795 SetVisibleItemSlot(slot
, NULL
);
14799 delete m_items
[slot
];
14800 m_items
[slot
] = NULL
;
14804 sLog
.outDebug("Load Basic value of player %s is: ", m_name
.c_str());
14807 //Need to call it to initialize m_team (m_team can be calculated from race)
14808 //Other way is to saves m_team into characters table.
14809 setFactionForRace(getRace());
14812 // load home bind and check in same time class/race pair, it used later for restore broken positions
14813 if(!_LoadHomeBind(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND
)))
14819 InitPrimaryProfessions(); // to max set before any spell loaded
14821 // init saved position, and fix it later if problematic
14822 uint32 transGUID
= fields
[31].GetUInt32();
14823 Relocate(fields
[13].GetFloat(),fields
[14].GetFloat(),fields
[15].GetFloat(),fields
[17].GetFloat());
14824 SetLocationMapId(fields
[16].GetUInt32());
14826 uint32 difficulty
= fields
[39].GetUInt32();
14827 if(difficulty
>= MAX_DUNGEON_DIFFICULTY
)
14828 difficulty
= DUNGEON_DIFFICULTY_NORMAL
;
14829 SetDungeonDifficulty(Difficulty(difficulty
)); // may be changed in _LoadGroup
14831 _LoadGroup(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP
));
14833 _LoadArenaTeamInfo(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO
));
14835 uint32 arena_currency
= fields
[40].GetUInt32();
14836 if (arena_currency
> sWorld
.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS
))
14837 arena_currency
= sWorld
.getConfig(CONFIG_UINT32_MAX_ARENA_POINTS
);
14839 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, arena_currency
);
14841 // check arena teams integrity
14842 for(uint32 arena_slot
= 0; arena_slot
< MAX_ARENA_SLOT
; ++arena_slot
)
14844 uint32 arena_team_id
= GetArenaTeamId(arena_slot
);
14848 if(ArenaTeam
* at
= sObjectMgr
.GetArenaTeamById(arena_team_id
))
14849 if(at
->HaveMember(GetGUID()))
14852 // arena team not exist or not member, cleanup fields
14853 for(int j
= 0; j
< ARENA_TEAM_END
; ++j
)
14854 SetArenaTeamInfoField(arena_slot
, ArenaTeamInfoType(j
), 0);
14857 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, fields
[41].GetUInt32());
14858 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, fields
[42].GetUInt32());
14859 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, fields
[43].GetUInt32());
14860 SetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, fields
[44].GetUInt32());
14861 SetUInt16Value(PLAYER_FIELD_KILLS
, 0, fields
[45].GetUInt16());
14862 SetUInt16Value(PLAYER_FIELD_KILLS
, 1, fields
[46].GetUInt16());
14864 _LoadBoundInstances(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES
));
14866 if(!IsPositionValid())
14868 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());
14869 RelocateToHomebind();
14873 m_movementInfo
.SetTransportData(0, 0.0f
, 0.0f
, 0.0f
, 0.0f
, 0, -1);
14876 _LoadBGData(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADBGDATA
));
14878 if(m_bgData
.bgInstanceID
) //saved in BattleGround
14880 BattleGround
*currentBg
= sBattleGroundMgr
.GetBattleGround(m_bgData
.bgInstanceID
, BATTLEGROUND_TYPE_NONE
);
14882 bool player_at_bg
= currentBg
&& currentBg
->IsPlayerInBattleGround(GetGUID());
14884 if(player_at_bg
&& currentBg
->GetStatus() != STATUS_WAIT_LEAVE
)
14886 BattleGroundQueueTypeId bgQueueTypeId
= BattleGroundMgr::BGQueueTypeId(currentBg
->GetTypeID(), currentBg
->GetArenaType());
14887 AddBattleGroundQueueId(bgQueueTypeId
);
14889 m_bgData
.bgTypeID
= currentBg
->GetTypeID();
14891 //join player to battleground group
14892 currentBg
->EventPlayerLoggedIn(this, GetGUID());
14893 currentBg
->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), m_bgData
.bgTeam
);
14895 SetInviteForBattleGroundQueueType(bgQueueTypeId
,currentBg
->GetInstanceID());
14901 currentBg
->RemovePlayerAtLeave(GetGUID(), false, true);
14903 // move to bg enter point
14904 const WorldLocation
& _loc
= GetBattleGroundEntryPoint();
14905 SetLocationMapId(_loc
.mapid
);
14906 Relocate(_loc
.coord_x
, _loc
.coord_y
, _loc
.coord_z
, _loc
.orientation
);
14908 // We are not in BG anymore
14909 m_bgData
.bgInstanceID
= 0;
14914 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(GetMapId());
14915 // if server restart after player save in BG or area
14916 // player can have current coordinates in to BG/Arena map, fix this
14917 if(!mapEntry
|| mapEntry
->IsBattleGroundOrArena())
14919 const WorldLocation
& _loc
= GetBattleGroundEntryPoint();
14920 SetLocationMapId(_loc
.mapid
);
14921 Relocate(_loc
.coord_x
, _loc
.coord_y
, _loc
.coord_z
, _loc
.orientation
);
14925 if (transGUID
!= 0)
14927 m_movementInfo
.SetTransportData(transGUID
, fields
[27].GetFloat(), fields
[28].GetFloat(), fields
[29].GetFloat(), fields
[30].GetFloat(), 0, -1);
14929 if( !MaNGOS::IsValidMapCoord(
14930 GetPositionX() + m_movementInfo
.GetTransportPos()->x
, GetPositionY() + m_movementInfo
.GetTransportPos()->y
,
14931 GetPositionZ() + m_movementInfo
.GetTransportPos()->z
, GetOrientation() + m_movementInfo
.GetTransportPos()->o
) ||
14932 // transport size limited
14933 m_movementInfo
.GetTransportPos()->x
> 50 || m_movementInfo
.GetTransportPos()->y
> 50 || m_movementInfo
.GetTransportPos()->z
> 50 )
14935 sLog
.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
14936 guid
, GetPositionX() + m_movementInfo
.GetTransportPos()->x
, GetPositionY() + m_movementInfo
.GetTransportPos()->y
,
14937 GetPositionZ() + m_movementInfo
.GetTransportPos()->z
, GetOrientation() + m_movementInfo
.GetTransportPos()->o
);
14939 RelocateToHomebind();
14941 m_movementInfo
.SetTransportData(0, 0.0f
, 0.0f
, 0.0f
, 0.0f
, 0, -1);
14947 if (transGUID
!= 0)
14949 for (MapManager::TransportSet::const_iterator iter
= sMapMgr
.m_Transports
.begin(); iter
!= sMapMgr
.m_Transports
.end(); ++iter
)
14951 if( (*iter
)->GetGUIDLow() == transGUID
)
14953 MapEntry
const* transMapEntry
= sMapStore
.LookupEntry((*iter
)->GetMapId());
14954 // client without expansion support
14955 if(GetSession()->Expansion() < transMapEntry
->Expansion())
14957 sLog
.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter
)->GetMapId());
14961 m_transport
= *iter
;
14962 m_transport
->AddPassenger(this);
14963 SetLocationMapId(m_transport
->GetMapId());
14970 sLog
.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
14973 RelocateToHomebind();
14975 m_movementInfo
.SetTransportData(0, 0.0f
, 0.0f
, 0.0f
, 0.0f
, 0, -1);
14980 else // not transport case
14982 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(GetMapId());
14983 // client without expansion support
14984 if(GetSession()->Expansion() < mapEntry
->Expansion())
14986 sLog
.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
14987 RelocateToHomebind();
14991 // NOW player must have valid map
14992 // load the player's map here if it's not already loaded
14993 SetMap(sMapMgr
.CreateMap(GetMapId(), this));
14995 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14996 if(GetInstanceId() && !sInstanceSaveMgr
.GetInstanceSave(GetInstanceId()))
14998 AreaTrigger
const* at
= sObjectMgr
.GetMapEntranceTrigger(GetMapId());
15000 Relocate(at
->target_X
, at
->target_Y
, at
->target_Z
, at
->target_Orientation
);
15002 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());
15005 SaveRecallPosition();
15007 time_t now
= time(NULL
);
15008 time_t logoutTime
= time_t(fields
[23].GetUInt64());
15010 // since last logout (in seconds)
15011 uint32 time_diff
= uint32(now
- logoutTime
);
15013 // set value, including drunk invisibility detection
15014 // calculate sobering. after 15 minutes logged out, the player will be sober again
15016 if(time_diff
> 15*MINUTE
)
15019 soberFactor
= 1-time_diff
/(15.0f
*MINUTE
);
15020 uint16 newDrunkenValue
= uint16(soberFactor
*(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFE));
15021 SetDrunkValue(newDrunkenValue
);
15023 m_rest_bonus
= fields
[22].GetFloat();
15024 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
15025 float bubble0
= 0.031f
;
15026 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
15027 float bubble1
= 0.125f
;
15031 float bubble
= fields
[24].GetUInt32() > 0
15032 ? bubble1
*sWorld
.getConfig(CONFIG_FLOAT_RATE_REST_OFFLINE_IN_TAVERN_OR_CITY
)
15033 : bubble0
*sWorld
.getConfig(CONFIG_FLOAT_RATE_REST_OFFLINE_IN_WILDERNESS
);
15035 SetRestBonus(GetRestBonus()+ time_diff
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
15038 m_cinematic
= fields
[19].GetUInt32();
15039 m_Played_time
[PLAYED_TIME_TOTAL
]= fields
[20].GetUInt32();
15040 m_Played_time
[PLAYED_TIME_LEVEL
]= fields
[21].GetUInt32();
15042 m_resetTalentsCost
= fields
[25].GetUInt32();
15043 m_resetTalentsTime
= time_t(fields
[26].GetUInt64());
15045 // reserve some flags
15046 uint32 old_safe_flags
= GetUInt32Value(PLAYER_FLAGS
) & ( PLAYER_FLAGS_HIDE_CLOAK
| PLAYER_FLAGS_HIDE_HELM
);
15048 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
) )
15049 SetUInt32Value(PLAYER_FLAGS
, 0 | old_safe_flags
);
15051 m_taxi
.LoadTaxiMask( fields
[18].GetString() ); // must be before InitTaxiNodesForLevel
15053 uint32 extraflags
= fields
[32].GetUInt32();
15055 m_stableSlots
= fields
[33].GetUInt32();
15056 if(m_stableSlots
> MAX_PET_STABLES
)
15058 sLog
.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES
,uint32(m_stableSlots
));
15059 m_stableSlots
= MAX_PET_STABLES
;
15062 m_atLoginFlags
= fields
[34].GetUInt32();
15065 // Update Honor kills data
15066 m_lastHonorUpdateTime
= logoutTime
;
15067 UpdateHonorFields();
15069 m_deathExpireTime
= (time_t)fields
[37].GetUInt64();
15070 if(m_deathExpireTime
> now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
)
15071 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
-1;
15073 std::string taxi_nodes
= fields
[38].GetCppString();
15075 // clear channel spell data (if saved at channel spell casting)
15076 SetChannelObjectGUID(0);
15077 SetUInt32Value(UNIT_CHANNEL_SPELL
,0);
15079 // clear charm/summon related fields
15083 SetChannelObjectGUID(0);
15088 // reset some aura modifiers before aura apply
15089 SetFarSightGUID(0);
15090 SetUInt32Value(PLAYER_TRACK_CREATURES
, 0 );
15091 SetUInt32Value(PLAYER_TRACK_RESOURCES
, 0 );
15093 // cleanup aura list explicitly before skill load wher some spells can be applied
15096 // make sure the unit is considered out of combat for proper loading
15099 // make sure the unit is considered not in duel for proper loading
15100 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
15101 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
15103 // reset stats before loading any modifiers
15104 InitStatsForLevel();
15105 InitGlyphsForLevel();
15106 InitTaxiNodesForLevel();
15109 // load skills after InitStatsForLevel because it triggering aura apply also
15110 _LoadSkills(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSKILLS
));
15112 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
15116 UpdateNextMailTimeAndUnreads();
15118 m_specsCount
= fields
[59].GetUInt8();
15119 m_activeSpec
= fields
[60].GetUInt8();
15121 _LoadGlyphs(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADGLYPHS
));
15123 _LoadAuras(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS
), time_diff
);
15126 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
15127 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
15128 m_deathState
= DEAD
;
15130 _LoadSpells(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS
));
15132 // after spell load, learn rewarded spell if need also
15133 _LoadQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS
));
15134 _LoadDailyQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS
));
15136 // after spell and quest load
15137 InitTalentForLevel();
15138 learnDefaultSpells();
15140 // must be before inventory (some items required reputation check)
15141 m_reputationMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION
));
15143 _LoadInventory(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY
), time_diff
);
15145 // update items with duration and realtime
15146 UpdateItemDuration(time_diff
, true);
15148 _LoadActions(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS
));
15150 m_social
= sSocialMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST
), GetGUIDLow());
15152 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
15153 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
15154 uint32 curTitle
= fields
[47].GetUInt32();
15155 if (curTitle
&& !HasTitle(curTitle
))
15158 SetUInt32Value(PLAYER_CHOSEN_TITLE
, curTitle
);
15160 // Not finish taxi flight path
15161 if(m_bgData
.HasTaxiPath())
15163 m_taxi
.ClearTaxiDestinations();
15164 for (int i
= 0; i
< 2; ++i
)
15165 m_taxi
.AddTaxiDestination(m_bgData
.taxiPath
[i
]);
15167 else if(!m_taxi
.LoadTaxiDestinationsFromString(taxi_nodes
,GetTeam()))
15169 // problems with taxi path loading
15170 TaxiNodesEntry
const* nodeEntry
= NULL
;
15171 if(uint32 node_id
= m_taxi
.GetTaxiSource())
15172 nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
15174 if(!nodeEntry
) // don't know taxi start node, to homebind
15176 sLog
.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
15177 RelocateToHomebind();
15179 else // have start node, to it
15181 sLog
.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
15182 SetLocationMapId(nodeEntry
->map_id
);
15183 Relocate(nodeEntry
->x
, nodeEntry
->y
, nodeEntry
->z
,0.0f
);
15186 //we can be relocated from taxi and still have an outdated Map pointer!
15187 //so we need to get a new Map pointer!
15188 SetMap(sMapMgr
.CreateMap(GetMapId(), this));
15189 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
15191 m_taxi
.ClearTaxiDestinations();
15194 if(uint32 node_id
= m_taxi
.GetTaxiSource())
15196 // save source node as recall coord to prevent recall and fall from sky
15197 TaxiNodesEntry
const* nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
15198 assert(nodeEntry
); // checked in m_taxi.LoadTaxiDestinationsFromString
15199 m_recallMap
= nodeEntry
->map_id
;
15200 m_recallX
= nodeEntry
->x
;
15201 m_recallY
= nodeEntry
->y
;
15202 m_recallZ
= nodeEntry
->z
;
15204 // flight will started later
15207 // has to be called after last Relocate() in Player::LoadFromDB
15208 SetFallInformation(0, GetPositionZ());
15210 _LoadSpellCooldowns(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS
));
15212 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
15213 // Do now before stats re-calculation cleanup for ghost state unexpected auras
15215 RemoveAllAurasOnDeath();
15217 //apply all stat bonuses from items and auras
15218 SetCanModifyStats(true);
15221 // restore remembered power/health values (but not more max values)
15222 uint32 savedhealth
= fields
[51].GetUInt32();
15223 SetHealth(savedhealth
> GetMaxHealth() ? GetMaxHealth() : savedhealth
);
15224 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
15226 uint32 savedpower
= fields
[52+i
].GetUInt32();
15227 SetPower(Powers(i
),savedpower
> GetMaxPower(Powers(i
)) ? GetMaxPower(Powers(i
)) : savedpower
);
15230 sLog
.outDebug("The value of player %s after load item and aura is: ", m_name
.c_str());
15237 if(GetSession()->GetSecurity() > SEC_PLAYER
)
15239 switch(sWorld
.getConfig(CONFIG_UINT32_GM_LOGIN_STATE
))
15242 case 0: break; // disable
15243 case 1: SetGameMaster(true); break; // enable
15244 case 2: // save state
15245 if(extraflags
& PLAYER_EXTRA_GM_ON
)
15246 SetGameMaster(true);
15250 switch(sWorld
.getConfig(CONFIG_UINT32_GM_VISIBLE_STATE
))
15253 case 0: SetGMVisible(false); break; // invisible
15254 case 1: break; // visible
15255 case 2: // save state
15256 if(extraflags
& PLAYER_EXTRA_GM_INVISIBLE
)
15257 SetGMVisible(false);
15261 switch(sWorld
.getConfig(CONFIG_UINT32_GM_ACCEPT_TICKETS
))
15264 case 0: break; // disable
15265 case 1: SetAcceptTicket(true); break; // enable
15266 case 2: // save state
15267 if(extraflags
& PLAYER_EXTRA_GM_ACCEPT_TICKETS
)
15268 SetAcceptTicket(true);
15272 switch(sWorld
.getConfig(CONFIG_UINT32_GM_CHAT
))
15275 case 0: break; // disable
15276 case 1: SetGMChat(true); break; // enable
15277 case 2: // save state
15278 if(extraflags
& PLAYER_EXTRA_GM_CHAT
)
15283 switch(sWorld
.getConfig(CONFIG_UINT32_GM_WISPERING_TO
))
15286 case 0: break; // disable
15287 case 1: SetAcceptWhispers(true); break; // enable
15288 case 2: // save state
15289 if(extraflags
& PLAYER_EXTRA_ACCEPT_WHISPERS
)
15290 SetAcceptWhispers(true);
15295 _LoadDeclinedNames(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES
));
15297 m_achievementMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS
), holder
->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS
));
15298 m_achievementMgr
.CheckAllAchievementCriteria();
15300 _LoadEquipmentSets(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS
));
15305 bool Player::isAllowedToLoot(Creature
* creature
)
15307 if(Player
* recipient
= creature
->GetLootRecipient())
15309 if (recipient
== this)
15311 if( Group
* otherGroup
= recipient
->GetGroup())
15313 Group
* thisGroup
= GetGroup();
15316 return thisGroup
== otherGroup
;
15321 // prevent other players from looting if the recipient got disconnected
15322 return !creature
->hasLootRecipient();
15325 void Player::_LoadActions(QueryResult
*result
)
15327 for(int i
= 0; i
< MAX_TALENT_SPEC_COUNT
; ++i
)
15328 m_actionButtons
[i
].clear();
15330 //QueryResult *result = CharacterDatabase.PQuery("SELECT spec, button,action,type FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
15336 Field
*fields
= result
->Fetch();
15338 uint8 spec
= fields
[0].GetUInt8();
15339 uint8 button
= fields
[1].GetUInt8();
15340 uint32 action
= fields
[2].GetUInt32();
15341 uint8 type
= fields
[3].GetUInt8();
15343 if(ActionButton
* ab
= addActionButton(spec
, button
, action
, type
))
15344 ab
->uState
= ACTIONBUTTON_UNCHANGED
;
15347 sLog
.outError( " ...at loading, and will deleted in DB also");
15349 // Will deleted in DB at next save (it can create data until save but marked as deleted)
15350 m_actionButtons
[spec
][button
].uState
= ACTIONBUTTON_DELETED
;
15353 while( result
->NextRow() );
15359 void Player::_LoadAuras(QueryResult
*result
, uint32 timediff
)
15361 //RemoveAllAuras(); -- some spells casted before aura load, for example in LoadSkills, aura list explcitly cleaned early
15363 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15369 Field
*fields
= result
->Fetch();
15370 uint64 caster_guid
= fields
[0].GetUInt64();
15371 uint32 spellid
= fields
[1].GetUInt32();
15372 SpellEffectIndex effindex
= SpellEffectIndex(fields
[2].GetUInt32());
15373 uint32 stackcount
= fields
[3].GetUInt32();
15374 int32 damage
= fields
[4].GetInt32();
15375 int32 maxduration
= fields
[5].GetInt32();
15376 int32 remaintime
= fields
[6].GetInt32();
15377 int32 remaincharges
= fields
[7].GetInt32();
15379 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellid
);
15382 sLog
.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid
,effindex
);
15386 if (effindex
>= MAX_EFFECT_INDEX
)
15388 sLog
.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid
,effindex
);
15392 // negative effects should continue counting down after logout
15393 if (remaintime
!= -1 && !IsPositiveEffect(spellid
, effindex
))
15395 if (remaintime
/IN_MILISECONDS
<= int32(timediff
))
15398 remaintime
-= timediff
*IN_MILISECONDS
;
15401 // prevent wrong values of remaincharges
15402 if (spellproto
->procCharges
)
15404 if (remaincharges
<= 0 || remaincharges
> (int32
)spellproto
->procCharges
)
15405 remaincharges
= spellproto
->procCharges
;
15411 for(uint32 i
= 0; i
< stackcount
; ++i
)
15413 Aura
* aura
= CreateAura(spellproto
, effindex
, NULL
, this, NULL
);
15415 damage
= aura
->GetModifier()->m_amount
;
15417 // reset stolen single target auras
15418 if (caster_guid
!= GetGUID() && aura
->IsSingleTarget())
15419 aura
->SetIsSingleTarget(false);
15421 aura
->SetLoadedState(caster_guid
,damage
,maxduration
,remaintime
,remaincharges
);
15423 sLog
.outDetail("Added aura spellid %u, effect %u", spellproto
->Id
, effindex
);
15426 while( result
->NextRow() );
15431 if(getClass() == CLASS_WARRIOR
&& !HasAuraType(SPELL_AURA_MOD_SHAPESHIFT
))
15432 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
15435 void Player::_LoadGlyphs(QueryResult
*result
)
15441 // "SELECT spec, slot, glyph FROM character_glyphs WHERE guid='%u'"
15445 Field
*fields
= result
->Fetch();
15446 uint8 spec
= fields
[0].GetUInt8();
15447 uint8 slot
= fields
[1].GetUInt8();
15448 uint32 glyph
= fields
[2].GetUInt32();
15450 GlyphPropertiesEntry
const *gp
= sGlyphPropertiesStore
.LookupEntry(glyph
);
15453 sLog
.outError("Player %s has not existing glyph entry %u on index %u, spec %u", m_name
.c_str(), glyph
, slot
, spec
);
15457 GlyphSlotEntry
const *gs
= sGlyphSlotStore
.LookupEntry(GetGlyphSlot(slot
));
15460 sLog
.outError("Player %s has not existing glyph slot entry %u on index %u, spec %u", m_name
.c_str(), GetGlyphSlot(slot
), slot
, spec
);
15464 if(gp
->TypeFlags
!= gs
->TypeFlags
)
15466 sLog
.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name
.c_str(), gp
->TypeFlags
, gs
->TypeFlags
);
15470 m_glyphs
[spec
][slot
].id
= glyph
;
15472 } while( result
->NextRow() );
15479 void Player::LoadCorpse()
15483 sObjectAccessor
.ConvertCorpseForPlayer(GetGUID());
15487 if(Corpse
*corpse
= GetCorpse())
15489 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, corpse
&& !sMapStore
.LookupEntry(corpse
->GetMapId())->Instanceable() );
15493 //Prevent Dead Player login without corpse
15494 ResurrectPlayer(0.5f
);
15499 void Player::_LoadInventory(QueryResult
*result
, uint32 timediff
)
15501 //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());
15502 std::map
<uint64
, Bag
*> bagMap
; // fast guid lookup for bags
15503 //NOTE: the "order by `bag`" is important because it makes sure
15504 //the bagMap is filled before items in the bags are loaded
15505 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
15506 //expected to be equipped before offhand items (TODO: fixme)
15508 uint32 zone
= GetZoneId();
15512 std::list
<Item
*> problematicItems
;
15514 // prevent items from being added to the queue when stored
15515 m_itemUpdateQueueBlocked
= true;
15518 Field
*fields
= result
->Fetch();
15519 uint32 bag_guid
= fields
[1].GetUInt32();
15520 uint8 slot
= fields
[2].GetUInt8();
15521 uint32 item_guid
= fields
[3].GetUInt32();
15522 uint32 item_id
= fields
[4].GetUInt32();
15524 ItemPrototype
const * proto
= ObjectMgr::GetItemPrototype(item_id
);
15528 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
15529 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid
);
15530 sLog
.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id
);
15534 Item
*item
= NewItemOrBag(proto
);
15536 if(!item
->LoadFromDB(item_guid
, GetGUID(), result
))
15538 sLog
.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id
);
15539 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
15540 item
->FSetState(ITEM_REMOVED
);
15541 item
->SaveToDB(); // it also deletes item object !
15545 // not allow have in alive state item limited to another map/zone
15546 if(isAlive() && item
->IsLimitedToAnotherMapOrZone(GetMapId(),zone
) )
15548 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
15549 item
->FSetState(ITEM_REMOVED
);
15550 item
->SaveToDB(); // it also deletes item object !
15554 // "Conjured items disappear if you are logged out for more than 15 minutes"
15555 if (timediff
> 15*MINUTE
&& item
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_CONJURED
))
15557 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
15558 item
->FSetState(ITEM_REMOVED
);
15559 item
->SaveToDB(); // it also deletes item object !
15563 bool success
= true;
15565 // the item/bag is not in a bag
15568 item
->SetContainer( NULL
);
15569 item
->SetSlot(slot
);
15571 if( IsInventoryPos( INVENTORY_SLOT_BAG_0
, slot
) )
15573 ItemPosCountVec dest
;
15574 if( CanStoreItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false ) == EQUIP_ERR_OK
)
15575 item
= StoreItem(dest
, item
, true);
15579 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0
, slot
) )
15582 if( CanEquipItem( slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
15583 QuickEquipItem(dest
, item
);
15587 else if( IsBankPos( INVENTORY_SLOT_BAG_0
, slot
) )
15589 ItemPosCountVec dest
;
15590 if( CanBankItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
15591 item
= BankItem(dest
, item
, true);
15598 // store bags that may contain items in them
15599 if(item
->IsBag() && IsBagPos(item
->GetPos()))
15600 bagMap
[item_guid
] = (Bag
*)item
;
15603 // the item/bag in a bag
15606 item
->SetSlot(NULL_SLOT
);
15607 // the item is in a bag, find the bag
15608 std::map
<uint64
, Bag
*>::const_iterator itr
= bagMap
.find(bag_guid
);
15609 if(itr
!= bagMap
.end() && slot
< itr
->second
->GetBagSize())
15611 ItemPosCountVec dest
;
15612 if( CanStoreItem( itr
->second
->GetSlot(), slot
, dest
, item
, false ) == EQUIP_ERR_OK
)
15613 item
= StoreItem(dest
, item
, true);
15621 // item's state may have changed after stored
15624 item
->SetState(ITEM_UNCHANGED
, this);
15626 // recharged mana gem
15627 if (timediff
> 15*MINUTE
&& proto
->ItemLimitCategory
==ITEM_LIMIT_CATEGORY_MANA_GEM
)
15628 item
->RestoreCharges();
15632 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
);
15633 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
15634 problematicItems
.push_back(item
);
15636 } while (result
->NextRow());
15639 m_itemUpdateQueueBlocked
= false;
15641 // send by mail problematic items
15642 while(!problematicItems
.empty())
15644 std::string subject
= GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM
);
15647 MailDraft
draft(subject
);
15649 for(int i
= 0; !problematicItems
.empty() && i
< MAX_MAIL_ITEMS
; ++i
)
15651 Item
* item
= problematicItems
.front();
15652 problematicItems
.pop_front();
15654 draft
.AddItem(item
);
15657 draft
.SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM
));
15661 _ApplyAllItemMods();
15664 // load mailed item which should receive current player
15665 void Player::_LoadMailedItems(Mail
*mail
)
15667 // data needs to be at first place for Item::LoadFromDB
15668 QueryResult
* result
= CharacterDatabase
.PQuery("SELECT data, item_guid, item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE mail_id='%u'", mail
->messageID
);
15674 Field
*fields
= result
->Fetch();
15675 uint32 item_guid_low
= fields
[1].GetUInt32();
15676 uint32 item_template
= fields
[2].GetUInt32();
15678 mail
->AddItem(item_guid_low
, item_template
);
15680 ItemPrototype
const *proto
= ObjectMgr::GetItemPrototype(item_template
);
15684 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
);
15685 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
15686 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low
);
15690 Item
*item
= NewItemOrBag(proto
);
15692 if(!item
->LoadFromDB(item_guid_low
, 0, result
))
15694 sLog
.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail
->messageID
, item_guid_low
);
15695 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
15696 item
->FSetState(ITEM_REMOVED
);
15697 item
->SaveToDB(); // it also deletes item object !
15702 } while (result
->NextRow());
15707 void Player::_LoadMail()
15710 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
15711 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT id,messageType,sender,receiver,subject,itemTextId,has_items,expire_time,deliver_time,money,cod,checked,stationery,mailTemplateId FROM mail WHERE receiver = '%u' ORDER BY id DESC",GetGUIDLow());
15716 Field
*fields
= result
->Fetch();
15717 Mail
*m
= new Mail
;
15718 m
->messageID
= fields
[0].GetUInt32();
15719 m
->messageType
= fields
[1].GetUInt8();
15720 m
->sender
= fields
[2].GetUInt32();
15721 m
->receiver
= fields
[3].GetUInt32();
15722 m
->subject
= fields
[4].GetCppString();
15723 m
->itemTextId
= fields
[5].GetUInt32();
15724 bool has_items
= fields
[6].GetBool();
15725 m
->expire_time
= (time_t)fields
[7].GetUInt64();
15726 m
->deliver_time
= (time_t)fields
[8].GetUInt64();
15727 m
->money
= fields
[9].GetUInt32();
15728 m
->COD
= fields
[10].GetUInt32();
15729 m
->checked
= fields
[11].GetUInt32();
15730 m
->stationery
= fields
[12].GetUInt8();
15731 m
->mailTemplateId
= fields
[13].GetInt16();
15733 if(m
->mailTemplateId
&& !sMailTemplateStore
.LookupEntry(m
->mailTemplateId
))
15735 sLog
.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m
->messageID
, m
->mailTemplateId
);
15736 m
->mailTemplateId
= 0;
15739 m
->state
= MAIL_STATE_UNCHANGED
;
15742 _LoadMailedItems(m
);
15744 m_mail
.push_back(m
);
15745 } while( result
->NextRow() );
15750 void Player::LoadPet()
15752 //fixme: the pet should still be loaded if the player is not in world
15753 // just not added to the map
15756 Pet
*pet
= new Pet
;
15757 if(!pet
->LoadPetFromDB(this,0,0,true))
15762 void Player::_LoadQuestStatus(QueryResult
*result
)
15764 mQuestStatus
.clear();
15768 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
15769 //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());
15775 Field
*fields
= result
->Fetch();
15777 uint32 quest_id
= fields
[0].GetUInt32();
15778 // used to be new, no delete?
15779 Quest
const* pQuest
= sObjectMgr
.GetQuestTemplate(quest_id
);
15783 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
15785 uint32 qstatus
= fields
[1].GetUInt32();
15786 if(qstatus
< MAX_QUEST_STATUS
)
15787 questStatusData
.m_status
= QuestStatus(qstatus
);
15790 questStatusData
.m_status
= QUEST_STATUS_NONE
;
15791 sLog
.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id
,qstatus
);
15794 questStatusData
.m_rewarded
= ( fields
[2].GetUInt8() > 0 );
15795 questStatusData
.m_explored
= ( fields
[3].GetUInt8() > 0 );
15797 time_t quest_time
= time_t(fields
[4].GetUInt64());
15799 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && !GetQuestRewardStatus(quest_id
) && questStatusData
.m_status
!= QUEST_STATUS_NONE
)
15801 AddTimedQuest( quest_id
);
15803 if (quest_time
<= sWorld
.GetGameTime())
15804 questStatusData
.m_timer
= 1;
15806 questStatusData
.m_timer
= uint32(quest_time
- sWorld
.GetGameTime()) * IN_MILISECONDS
;
15811 questStatusData
.m_creatureOrGOcount
[0] = fields
[5].GetUInt32();
15812 questStatusData
.m_creatureOrGOcount
[1] = fields
[6].GetUInt32();
15813 questStatusData
.m_creatureOrGOcount
[2] = fields
[7].GetUInt32();
15814 questStatusData
.m_creatureOrGOcount
[3] = fields
[8].GetUInt32();
15815 questStatusData
.m_itemcount
[0] = fields
[9].GetUInt32();
15816 questStatusData
.m_itemcount
[1] = fields
[10].GetUInt32();
15817 questStatusData
.m_itemcount
[2] = fields
[11].GetUInt32();
15818 questStatusData
.m_itemcount
[3] = fields
[12].GetUInt32();
15820 questStatusData
.uState
= QUEST_UNCHANGED
;
15822 // add to quest log
15823 if (slot
< MAX_QUEST_LOG_SIZE
&&
15824 ((questStatusData
.m_status
== QUEST_STATUS_INCOMPLETE
||
15825 questStatusData
.m_status
== QUEST_STATUS_COMPLETE
||
15826 questStatusData
.m_status
== QUEST_STATUS_FAILED
) &&
15827 (!questStatusData
.m_rewarded
|| pQuest
->IsRepeatable())))
15829 SetQuestSlot(slot
, quest_id
, uint32(quest_time
));
15831 if (questStatusData
.m_status
== QUEST_STATUS_COMPLETE
)
15832 SetQuestSlotState(slot
, QUEST_STATE_COMPLETE
);
15834 if (questStatusData
.m_status
== QUEST_STATUS_FAILED
)
15835 SetQuestSlotState(slot
, QUEST_STATE_FAIL
);
15837 for(uint8 idx
= 0; idx
< QUEST_OBJECTIVES_COUNT
; ++idx
)
15838 if(questStatusData
.m_creatureOrGOcount
[idx
])
15839 SetQuestSlotCounter(slot
, idx
, questStatusData
.m_creatureOrGOcount
[idx
]);
15844 if(questStatusData
.m_rewarded
)
15846 // learn rewarded spell if unknown
15847 learnQuestRewardedSpells(pQuest
);
15849 // set rewarded title if any
15850 if(pQuest
->GetCharTitleId())
15852 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
15853 SetTitle(titleEntry
);
15856 if(pQuest
->GetBonusTalents())
15857 m_questRewardTalentCount
+= pQuest
->GetBonusTalents();
15860 sLog
.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData
.m_status
, quest_id
, GetGUIDLow());
15863 while( result
->NextRow() );
15868 // clear quest log tail
15869 for ( uint16 i
= slot
; i
< MAX_QUEST_LOG_SIZE
; ++i
)
15870 SetQuestSlot(i
, 0);
15873 void Player::_LoadDailyQuestStatus(QueryResult
*result
)
15875 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
15876 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
15878 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
15882 uint32 quest_daily_idx
= 0;
15886 if(quest_daily_idx
>= PLAYER_MAX_DAILY_QUESTS
) // max amount with exist data in query
15888 sLog
.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15892 Field
*fields
= result
->Fetch();
15894 uint32 quest_id
= fields
[0].GetUInt32();
15896 // save _any_ from daily quest times (it must be after last reset anyway)
15897 m_lastDailyQuestTime
= (time_t)fields
[1].GetUInt64();
15899 Quest
const* pQuest
= sObjectMgr
.GetQuestTemplate(quest_id
);
15903 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
15906 sLog
.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id
, GetGUIDLow());
15908 while( result
->NextRow() );
15913 m_DailyQuestChanged
= false;
15916 void Player::_LoadSpells(QueryResult
*result
)
15918 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
15924 Field
*fields
= result
->Fetch();
15926 addSpell(fields
[0].GetUInt32(), fields
[1].GetBool(), false, false, fields
[2].GetBool());
15928 while( result
->NextRow() );
15934 void Player::_LoadGroup(QueryResult
*result
)
15936 //QueryResult *result = CharacterDatabase.PQuery("SELECT groupId FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
15939 uint32 groupId
= (*result
)[0].GetUInt32();
15942 if (Group
* group
= sObjectMgr
.GetGroupById(groupId
))
15944 uint8 subgroup
= group
->GetMemberGroup(GetGUID());
15945 SetGroup(group
, subgroup
);
15946 if (getLevel() >= LEVELREQUIREMENT_HEROIC
)
15948 // the group leader may change the instance difficulty while the player is offline
15949 SetDungeonDifficulty(group
->GetDungeonDifficulty());
15950 SetRaidDifficulty(group
->GetRaidDifficulty());
15956 void Player::_LoadBoundInstances(QueryResult
*result
)
15958 for(uint8 i
= 0; i
< MAX_DIFFICULTY
; ++i
)
15959 m_boundInstances
[i
].clear();
15961 Group
*group
= GetGroup();
15963 //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));
15968 Field
*fields
= result
->Fetch();
15969 bool perm
= fields
[1].GetBool();
15970 uint32 mapId
= fields
[2].GetUInt32();
15971 uint32 instanceId
= fields
[0].GetUInt32();
15972 uint8 difficulty
= fields
[3].GetUInt8();
15974 time_t resetTime
= (time_t)fields
[4].GetUInt64();
15975 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15976 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15977 // and in that case it is not used
15979 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(mapId
);
15980 if(!mapEntry
|| !mapEntry
->IsDungeon())
15982 sLog
.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId
);
15983 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
15987 if(difficulty
>= MAX_DIFFICULTY
)
15989 sLog
.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty
, mapId
);
15990 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
15994 MapDifficulty
const* mapDiff
= GetMapDifficultyData(mapId
,Difficulty(difficulty
));
15997 sLog
.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty
, mapId
);
15998 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
16004 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
);
16005 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
16009 // since non permanent binds are always solo bind, they can always be reset
16010 InstanceSave
*save
= sInstanceSaveMgr
.AddInstanceSave(mapId
, instanceId
, Difficulty(difficulty
), resetTime
, !perm
, true);
16011 if(save
) BindToInstance(save
, perm
, true);
16012 } while(result
->NextRow());
16017 InstancePlayerBind
* Player::GetBoundInstance(uint32 mapid
, Difficulty difficulty
)
16019 // some instances only have one difficulty
16020 MapDifficulty
const* mapDiff
= GetMapDifficultyData(mapid
,difficulty
);
16024 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
16025 if(itr
!= m_boundInstances
[difficulty
].end())
16026 return &itr
->second
;
16031 void Player::UnbindInstance(uint32 mapid
, Difficulty difficulty
, bool unload
)
16033 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
16034 UnbindInstance(itr
, difficulty
, unload
);
16037 void Player::UnbindInstance(BoundInstancesMap::iterator
&itr
, Difficulty difficulty
, bool unload
)
16039 if(itr
!= m_boundInstances
[difficulty
].end())
16041 if(!unload
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr
->second
.save
->GetInstanceId());
16042 itr
->second
.save
->RemovePlayer(this); // save can become invalid
16043 m_boundInstances
[difficulty
].erase(itr
++);
16047 InstancePlayerBind
* Player::BindToInstance(InstanceSave
*save
, bool permanent
, bool load
)
16051 InstancePlayerBind
& bind
= m_boundInstances
[save
->GetDifficulty()][save
->GetMapId()];
16054 // update the save when the group kills a boss
16055 if(permanent
!= bind
.perm
|| save
!= bind
.save
)
16056 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());
16059 if(!load
) CharacterDatabase
.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save
->GetInstanceId(), permanent
);
16061 if(bind
.save
!= save
)
16063 if(bind
.save
) bind
.save
->RemovePlayer(this);
16064 save
->AddPlayer(this);
16067 if(permanent
) save
->SetCanReset(false);
16070 bind
.perm
= permanent
;
16071 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());
16078 void Player::SendRaidInfo()
16080 uint32 counter
= 0;
16082 WorldPacket
data(SMSG_RAID_INSTANCE_INFO
, 4);
16084 size_t p_counter
= data
.wpos();
16085 data
<< uint32(counter
); // placeholder
16087 time_t now
= time(NULL
);
16089 for(int i
= 0; i
< MAX_DIFFICULTY
; ++i
)
16091 for (BoundInstancesMap::const_iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
16093 if(itr
->second
.perm
)
16095 InstanceSave
*save
= itr
->second
.save
;
16096 data
<< uint32(save
->GetMapId()); // map id
16097 data
<< uint32(save
->GetDifficulty()); // difficulty
16098 data
<< uint64(save
->GetInstanceId()); // instance id
16099 data
<< uint8(1); // expired = 0
16100 data
<< uint8(0); // extended = 1
16101 data
<< uint32(save
->GetResetTime() - now
); // reset time
16106 data
.put
<uint32
>(p_counter
, counter
);
16107 GetSession()->SendPacket(&data
);
16111 - called on every successful teleportation to a map
16113 void Player::SendSavedInstances()
16115 bool hasBeenSaved
= false;
16118 for(uint8 i
= 0; i
< MAX_DIFFICULTY
; ++i
)
16120 for (BoundInstancesMap::const_iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
16122 if(itr
->second
.perm
) // only permanent binds are sent
16124 hasBeenSaved
= true;
16130 //Send opcode 811. true or false means, whether you have current raid/heroic instances
16131 data
.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP
);
16132 data
<< uint32(hasBeenSaved
);
16133 GetSession()->SendPacket(&data
);
16138 for(uint8 i
= 0; i
< MAX_DIFFICULTY
; ++i
)
16140 for (BoundInstancesMap::const_iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
16142 if(itr
->second
.perm
)
16144 data
.Initialize(SMSG_UPDATE_LAST_INSTANCE
);
16145 data
<< uint32(itr
->second
.save
->GetMapId());
16146 GetSession()->SendPacket(&data
);
16152 /// convert the player's binds to the group
16153 void Player::ConvertInstancesToGroup(Player
*player
, Group
*group
, uint64 player_guid
)
16155 bool has_binds
= false;
16156 bool has_solo
= false;
16158 if(player
) { player_guid
= player
->GetGUID(); if(!group
) group
= player
->GetGroup(); }
16159 assert(player_guid
);
16161 // copy all binds to the group, when changing leader it's assumed the character
16162 // will not have any solo binds
16166 for(uint8 i
= 0; i
< MAX_DIFFICULTY
; ++i
)
16168 for (BoundInstancesMap::iterator itr
= player
->m_boundInstances
[i
].begin(); itr
!= player
->m_boundInstances
[i
].end();)
16171 if(group
) group
->BindToInstance(itr
->second
.save
, itr
->second
.perm
, true);
16172 // permanent binds are not removed
16173 if(!itr
->second
.perm
)
16175 // increments itr in call
16176 player
->UnbindInstance(itr
, Difficulty(i
), true);
16185 // if the player's not online we don't know what binds it has
16186 if(!player
|| !group
|| has_binds
)
16187 CharacterDatabase
.PExecute("INSERT INTO group_instance SELECT guid, instance, permanent FROM character_instance WHERE guid = '%u'", GUID_LOPART(player_guid
));
16189 // the following should not get executed when changing leaders
16190 if(!player
|| has_solo
)
16191 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid
));
16194 bool Player::_LoadHomeBind(QueryResult
*result
)
16196 PlayerInfo
const *info
= sObjectMgr
.GetPlayerInfo(getRace(), getClass());
16199 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
16204 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
16207 Field
*fields
= result
->Fetch();
16208 m_homebindMapId
= fields
[0].GetUInt32();
16209 m_homebindAreaId
= fields
[1].GetUInt16();
16210 m_homebindX
= fields
[2].GetFloat();
16211 m_homebindY
= fields
[3].GetFloat();
16212 m_homebindZ
= fields
[4].GetFloat();
16215 MapEntry
const* bindMapEntry
= sMapStore
.LookupEntry(m_homebindMapId
);
16217 // accept saved data only for valid position (and non instanceable), and accessable
16218 if( MapManager::IsValidMapCoord(m_homebindMapId
,m_homebindX
,m_homebindY
,m_homebindZ
) &&
16219 !bindMapEntry
->Instanceable() && GetSession()->Expansion() >= bindMapEntry
->Expansion())
16224 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
16229 m_homebindMapId
= info
->mapId
;
16230 m_homebindAreaId
= info
->areaId
;
16231 m_homebindX
= info
->positionX
;
16232 m_homebindY
= info
->positionY
;
16233 m_homebindZ
= info
->positionZ
;
16235 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
);
16238 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
16239 m_homebindMapId
, m_homebindAreaId
, m_homebindX
, m_homebindY
, m_homebindZ
);
16244 /*********************************************************/
16245 /*** SAVE SYSTEM ***/
16246 /*********************************************************/
16248 void Player::SaveToDB()
16250 // we should assure this: assert((m_nextSave != sWorld.getConfig(CONFIG_UINT32_INTERVAL_SAVE)));
16251 // delay auto save at any saves (manual, in code, or autosave)
16252 m_nextSave
= sWorld
.getConfig(CONFIG_UINT32_INTERVAL_SAVE
);
16254 //lets allow only players in world to be saved
16255 if(IsBeingTeleportedFar())
16257 ScheduleDelayedOperation(DELAYED_SAVE_PLAYER
);
16261 // first save/honor gain after midnight will also update the player's honor fields
16262 UpdateHonorFields();
16264 sLog
.outDebug("The value of player %s at save: ", m_name
.c_str());
16267 CharacterDatabase
.BeginTransaction();
16269 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
16271 std::string sql_name
= m_name
;
16272 CharacterDatabase
.escape_string(sql_name
);
16274 std::ostringstream ss
;
16275 ss
<< "INSERT INTO characters (guid,account,name,race,class,gender,level,xp,money,playerBytes,playerBytes2,playerFlags,"
16276 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
16277 "taximask, online, cinematic, "
16278 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
16279 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
16280 "death_expire_time, taxi_path, arenaPoints, totalHonorPoints, todayHonorPoints, yesterdayHonorPoints, totalKills, "
16281 "todayKills, yesterdayKills, chosenTitle, knownCurrencies, watchedFaction, drunk, health, power1, power2, power3, "
16282 "power4, power5, power6, power7, specCount, activeSpec) VALUES ("
16283 << GetGUIDLow() << ", "
16284 << GetSession()->GetAccountId() << ", '"
16285 << sql_name
<< "', "
16286 << (uint32
)getRace() << ", "
16287 << (uint32
)getClass() << ", "
16288 << (uint32
)getGender() << ", "
16289 << getLevel() << ", "
16290 << GetUInt32Value(PLAYER_XP
) << ", "
16291 << GetMoney() << ", "
16292 << GetUInt32Value(PLAYER_BYTES
) << ", "
16293 << GetUInt32Value(PLAYER_BYTES_2
) << ", "
16294 << GetUInt32Value(PLAYER_FLAGS
) << ", ";
16296 if(!IsBeingTeleported())
16298 ss
<< GetMapId() << ", "
16299 << (uint32
)GetDungeonDifficulty() << ", "
16300 << finiteAlways(GetPositionX()) << ", "
16301 << finiteAlways(GetPositionY()) << ", "
16302 << finiteAlways(GetPositionZ()) << ", "
16303 << finiteAlways(GetOrientation()) << ", '";
16307 ss
<< GetTeleportDest().mapid
<< ", "
16308 << (uint32
)GetDungeonDifficulty() << ", "
16309 << finiteAlways(GetTeleportDest().coord_x
) << ", "
16310 << finiteAlways(GetTeleportDest().coord_y
) << ", "
16311 << finiteAlways(GetTeleportDest().coord_z
) << ", "
16312 << finiteAlways(GetTeleportDest().orientation
) << ", '";
16316 for( i
= 0; i
< m_valuesCount
; ++i
)
16318 ss
<< GetUInt32Value(i
) << " ";
16323 ss
<< m_taxi
<< ", "; // string with TaxiMaskSize numbers
16325 ss
<< (IsInWorld() ? 1 : 0) << ", ";
16327 ss
<< m_cinematic
<< ", ";
16329 ss
<< m_Played_time
[PLAYED_TIME_TOTAL
] << ", ";
16330 ss
<< m_Played_time
[PLAYED_TIME_LEVEL
] << ", ";
16332 ss
<< finiteAlways(m_rest_bonus
) << ", ";
16333 ss
<< (uint64
)time(NULL
) << ", ";
16334 ss
<< (HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
) ? 1 : 0) << ", ";
16335 //save, far from tavern/city
16336 //save, but in tavern/city
16337 ss
<< m_resetTalentsCost
<< ", ";
16338 ss
<< (uint64
)m_resetTalentsTime
<< ", ";
16340 ss
<< finiteAlways(m_movementInfo
.GetTransportPos()->x
) << ", ";
16341 ss
<< finiteAlways(m_movementInfo
.GetTransportPos()->y
) << ", ";
16342 ss
<< finiteAlways(m_movementInfo
.GetTransportPos()->z
) << ", ";
16343 ss
<< finiteAlways(m_movementInfo
.GetTransportPos()->o
) << ", ";
16345 ss
<< m_transport
->GetGUIDLow();
16350 ss
<< m_ExtraFlags
<< ", ";
16352 ss
<< uint32(m_stableSlots
) << ", "; // to prevent save uint8 as char
16354 ss
<< uint32(m_atLoginFlags
) << ", ";
16356 ss
<< GetZoneId() << ", ";
16358 ss
<< (uint64
)m_deathExpireTime
<< ", '";
16360 ss
<< m_taxi
.SaveTaxiDestinationsToString() << "', ";
16362 ss
<< GetArenaPoints() << ", ";
16364 ss
<< GetHonorPoints() << ", ";
16366 ss
<< GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
) << ", ";
16368 ss
<< GetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
) << ", ";
16370 ss
<< GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
) << ", ";
16372 ss
<< GetUInt16Value(PLAYER_FIELD_KILLS
, 0) << ", ";
16374 ss
<< GetUInt16Value(PLAYER_FIELD_KILLS
, 1) << ", ";
16376 ss
<< GetUInt32Value(PLAYER_CHOSEN_TITLE
) << ", ";
16378 ss
<< GetUInt64Value(PLAYER_FIELD_KNOWN_CURRENCIES
) << ", ";
16380 // FIXME: at this moment send to DB as unsigned, including unit32(-1)
16381 ss
<< GetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX
) << ", ";
16383 ss
<< (uint16
)(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFE) << ", ";
16387 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
16388 ss
<< "," << GetPower(Powers(i
));
16391 ss
<< uint32(m_specsCount
) << ", ";
16392 ss
<< uint32(m_activeSpec
);
16396 CharacterDatabase
.Execute( ss
.str().c_str() );
16398 if(m_mailsUpdated
) //save mails only when needed
16403 _SaveQuestStatus();
16404 _SaveDailyQuestStatus();
16406 _SaveSpellCooldowns();
16410 m_achievementMgr
.SaveToDB();
16411 m_reputationMgr
.SaveToDB();
16412 _SaveEquipmentSets();
16413 GetSession()->SaveTutorialsData(); // changed only while character in game
16416 CharacterDatabase
.CommitTransaction();
16418 // save pet (hunter pet level and experience and all type pets health/mana).
16419 if(Pet
* pet
= GetPet())
16420 pet
->SavePetToDB(PET_SAVE_AS_CURRENT
);
16423 // fast save function for item/money cheating preventing - save only inventory and money state
16424 void Player::SaveInventoryAndGoldToDB()
16430 void Player::SaveGoldToDB()
16432 CharacterDatabase
.PExecute("UPDATE characters SET money = '%u' WHERE guid = '%u'", GetMoney(), GetGUIDLow());
16435 void Player::_SaveActions()
16437 for(int i
= 0; i
< MAX_TALENT_SPEC_COUNT
; ++i
)
16439 for(ActionButtonList::iterator itr
= m_actionButtons
[i
].begin(); itr
!= m_actionButtons
[i
].end(); )
16441 switch (itr
->second
.uState
)
16443 case ACTIONBUTTON_NEW
:
16444 CharacterDatabase
.PExecute("INSERT INTO character_action (guid,spec, button,action,type) VALUES ('%u', '%u', '%u', '%u', '%u')",
16445 GetGUIDLow(), i
, (uint32
)itr
->first
, (uint32
)itr
->second
.GetAction(), (uint32
)itr
->second
.GetType() );
16446 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
16449 case ACTIONBUTTON_CHANGED
:
16450 CharacterDatabase
.PExecute("UPDATE character_action SET action = '%u', type = '%u' WHERE guid= '%u' AND button= '%u' AND spec = '%u'",
16451 (uint32
)itr
->second
.GetAction(), (uint32
)itr
->second
.GetType(), GetGUIDLow(), (uint32
)itr
->first
, i
);
16452 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
16455 case ACTIONBUTTON_DELETED
:
16456 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u' AND button = '%u' AND spec = '%u'", GetGUIDLow(), (uint32
)itr
->first
, i
);
16457 m_actionButtons
[i
].erase(itr
++);
16467 void Player::_SaveAuras()
16469 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
16471 AuraMap
const& auras
= GetAuras();
16476 spellEffectPair lastEffectPair
= auras
.begin()->first
;
16477 uint32 stackCounter
= 1;
16479 /* copied following sql-code partly from achievementmgr */
16480 bool first_round
= true;
16481 std::ostringstream ss
;
16482 for(AuraMap::const_iterator itr
= auras
.begin(); ; ++itr
)
16484 if(itr
== auras
.end() || lastEffectPair
!= itr
->first
)
16486 AuraMap::const_iterator itr2
= itr
;
16487 // save previous spellEffectPair to db
16490 //skip all auras from spells that are passive
16491 //do not save single target auras (unless they were cast by the player)
16492 if (!itr2
->second
->IsPassive() && (itr2
->second
->GetCasterGUID() == GetGUID() || !itr2
->second
->IsSingleTarget()))
16496 ss
<< "INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges)VALUES ";
16497 first_round
= false;
16499 // next new/changed record prefix
16503 ss
<< "("<< GetGUIDLow() << "," << itr2
->second
->GetCasterGUID() << ","
16504 << (uint32
)itr2
->second
->GetId() << "," << (uint32
)itr2
->second
->GetEffIndex() << ","
16505 << stackCounter
<< "," << itr2
->second
->GetModifier()->m_amount
<< ","
16506 <<int(itr2
->second
->GetAuraMaxDuration()) << "," << int(itr2
->second
->GetAuraDuration()) << ","
16507 << int(itr2
->second
->GetAuraCharges()) << ")";
16510 if(itr
== auras
.end())
16514 if (lastEffectPair
== itr
->first
)
16518 lastEffectPair
= itr
->first
;
16523 // if something changed execute
16525 CharacterDatabase
.Execute( ss
.str().c_str() );
16528 void Player::_SaveGlyphs()
16531 for (uint8 spec
= 0; spec
< m_specsCount
; ++spec
)
16533 for (uint8 slot
= 0; slot
< MAX_GLYPH_SLOT_INDEX
; ++slot
)
16535 switch(m_glyphs
[spec
][slot
].uState
)
16538 CharacterDatabase
.PExecute("INSERT INTO character_glyphs (guid, spec, slot, glyph) VALUES ('%u', '%u', '%u', '%u')", GetGUIDLow(), spec
, slot
, m_glyphs
[spec
][slot
].GetId());
16540 case GLYPH_CHANGED
:
16541 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
);
16543 case GLYPH_DELETED
:
16544 CharacterDatabase
.PExecute("DELETE FROM character_glyphs WHERE guid='%u' AND spec = '%u' AND slot = '%u'",GetGUIDLow(), spec
, slot
);
16546 case GLYPH_UNCHANGED
:
16549 m_glyphs
[spec
][slot
].uState
= GLYPH_UNCHANGED
;
16554 void Player::_SaveInventory()
16556 // force items in buyback slots to new state
16557 // and remove those that aren't already
16558 for (uint8 i
= BUYBACK_SLOT_START
; i
< BUYBACK_SLOT_END
; ++i
)
16560 Item
*item
= m_items
[i
];
16561 if (!item
|| item
->GetState() == ITEM_NEW
) continue;
16562 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
16563 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item
->GetGUIDLow());
16564 m_items
[i
]->FSetState(ITEM_NEW
);
16567 // update enchantment durations
16568 for(EnchantDurationList::const_iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
16570 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
16574 if (m_itemUpdateQueue
.empty()) return;
16576 // do not save if the update queue is corrupt
16577 bool error
= false;
16578 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); ++i
)
16580 Item
*item
= m_itemUpdateQueue
[i
];
16581 if(!item
|| item
->GetState() == ITEM_REMOVED
) continue;
16582 Item
*test
= GetItemByPos( item
->GetBagSlot(), item
->GetSlot());
16586 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());
16589 else if (test
!= item
)
16591 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());
16598 sLog
.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
16599 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED
);
16603 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); ++i
)
16605 Item
*item
= m_itemUpdateQueue
[i
];
16606 if(!item
) continue;
16608 Bag
*container
= item
->GetContainer();
16609 uint32 bag_guid
= container
? container
->GetGUIDLow() : 0;
16611 switch(item
->GetState())
16614 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());
16617 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());
16620 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
16622 case ITEM_UNCHANGED
:
16626 item
->SaveToDB(); // item have unchanged inventory record and can be save standalone
16628 m_itemUpdateQueue
.clear();
16631 void Player::_SaveMail()
16633 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
16636 if (m
->state
== MAIL_STATE_CHANGED
)
16638 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'",
16639 m
->itemTextId
, m
->HasItems() ? 1 : 0, (uint64
)m
->expire_time
, (uint64
)m
->deliver_time
, m
->money
, m
->COD
, m
->checked
, m
->messageID
);
16640 if(m
->removedItems
.size())
16642 for(std::vector
<uint32
>::const_iterator itr2
= m
->removedItems
.begin(); itr2
!= m
->removedItems
.end(); ++itr2
)
16643 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2
);
16644 m
->removedItems
.clear();
16646 m
->state
= MAIL_STATE_UNCHANGED
;
16648 else if (m
->state
== MAIL_STATE_DELETED
)
16651 for(std::vector
<MailItemInfo
>::const_iterator itr2
= m
->items
.begin(); itr2
!= m
->items
.end(); ++itr2
)
16652 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2
->item_guid
);
16654 CharacterDatabase
.PExecute("DELETE FROM item_text WHERE id = '%u'", m
->itemTextId
);
16655 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", m
->messageID
);
16656 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m
->messageID
);
16660 //deallocate deleted mails...
16661 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); )
16663 if ((*itr
)->state
== MAIL_STATE_DELETED
)
16668 itr
= m_mail
.begin();
16674 m_mailsUpdated
= false;
16677 void Player::_SaveQuestStatus()
16679 // we don't need transactions here.
16680 for( QuestStatusMap::iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
16682 switch (i
->second
.uState
)
16685 CharacterDatabase
.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
16686 "VALUES ('%u', '%u', '%u', '%u', '%u', '" UI64FMTD
"', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
16687 GetGUIDLow(), i
->first
, i
->second
.m_status
, i
->second
.m_rewarded
, i
->second
.m_explored
, uint64(i
->second
.m_timer
/ IN_MILISECONDS
+ sWorld
.GetGameTime()), i
->second
.m_creatureOrGOcount
[0], i
->second
.m_creatureOrGOcount
[1], i
->second
.m_creatureOrGOcount
[2], i
->second
.m_creatureOrGOcount
[3], i
->second
.m_itemcount
[0], i
->second
.m_itemcount
[1], i
->second
.m_itemcount
[2], i
->second
.m_itemcount
[3]);
16689 case QUEST_CHANGED
:
16690 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' ",
16691 i
->second
.m_status
, i
->second
.m_rewarded
, i
->second
.m_explored
, uint64(i
->second
.m_timer
/ IN_MILISECONDS
+ sWorld
.GetGameTime()), i
->second
.m_creatureOrGOcount
[0], i
->second
.m_creatureOrGOcount
[1], i
->second
.m_creatureOrGOcount
[2], i
->second
.m_creatureOrGOcount
[3], i
->second
.m_itemcount
[0], i
->second
.m_itemcount
[1], i
->second
.m_itemcount
[2], i
->second
.m_itemcount
[3], GetGUIDLow(), i
->first
);
16693 case QUEST_UNCHANGED
:
16696 i
->second
.uState
= QUEST_UNCHANGED
;
16700 void Player::_SaveDailyQuestStatus()
16702 if(!m_DailyQuestChanged
)
16705 m_DailyQuestChanged
= false;
16707 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
16709 // we don't need transactions here.
16710 CharacterDatabase
.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
16711 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
16712 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
16713 CharacterDatabase
.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" UI64FMTD
"')",
16714 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
),uint64(m_lastDailyQuestTime
));
16718 void Player::_SaveSkills()
16720 // we don't need transactions here.
16721 for( SkillStatusMap::iterator itr
= mSkillStatus
.begin(); itr
!= mSkillStatus
.end(); )
16723 if(itr
->second
.uState
== SKILL_UNCHANGED
)
16729 if(itr
->second
.uState
== SKILL_DELETED
)
16731 CharacterDatabase
.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), itr
->first
);
16732 mSkillStatus
.erase(itr
++);
16736 uint32 valueData
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(itr
->second
.pos
));
16737 uint16 value
= SKILL_VALUE(valueData
);
16738 uint16 max
= SKILL_MAX(valueData
);
16740 switch (itr
->second
.uState
)
16743 CharacterDatabase
.PExecute("INSERT INTO character_skills (guid, skill, value, max) VALUES ('%u', '%u', '%u', '%u')",
16744 GetGUIDLow(), itr
->first
, value
, max
);
16746 case SKILL_CHANGED
:
16747 CharacterDatabase
.PExecute("UPDATE character_skills SET value = '%u',max = '%u'WHERE guid = '%u' AND skill = '%u' ",
16748 value
, max
, GetGUIDLow(), itr
->first
);
16751 itr
->second
.uState
= SKILL_UNCHANGED
;
16757 void Player::_SaveSpells()
16759 for (PlayerSpellMap::iterator itr
= m_spells
.begin(), next
= m_spells
.begin(); itr
!= m_spells
.end();)
16761 if (itr
->second
.state
== PLAYERSPELL_REMOVED
|| itr
->second
.state
== PLAYERSPELL_CHANGED
)
16762 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr
->first
);
16764 // add only changed/new not dependent spells
16765 if (!itr
->second
.dependent
&& (itr
->second
.state
== PLAYERSPELL_NEW
|| itr
->second
.state
== PLAYERSPELL_CHANGED
))
16766 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);
16768 if (itr
->second
.state
== PLAYERSPELL_REMOVED
)
16769 m_spells
.erase(itr
++);
16772 itr
->second
.state
= PLAYERSPELL_UNCHANGED
;
16779 void Player::outDebugValues() const
16781 if(!sLog
.IsOutDebug()) // optimize disabled debug output
16784 sLog
.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA
));
16785 sLog
.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY
), GetStat(STAT_STRENGTH
));
16786 sLog
.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT
), GetStat(STAT_SPIRIT
));
16787 sLog
.outDebug("STAMINA is: \t\t%f",GetStat(STAT_STAMINA
));
16788 sLog
.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE
));
16789 sLog
.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY
), GetResistance(SPELL_SCHOOL_FIRE
));
16790 sLog
.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE
), GetResistance(SPELL_SCHOOL_FROST
));
16791 sLog
.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW
), GetResistance(SPELL_SCHOOL_ARCANE
));
16792 sLog
.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE
), GetFloatValue(UNIT_FIELD_MAXDAMAGE
));
16793 sLog
.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
));
16794 sLog
.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
));
16795 sLog
.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK
), GetAttackTime(RANGED_ATTACK
));
16798 /*********************************************************/
16799 /*** FLOOD FILTER SYSTEM ***/
16800 /*********************************************************/
16802 void Player::UpdateSpeakTime()
16804 // ignore chat spam protection for GMs in any mode
16805 if(GetSession()->GetSecurity() > SEC_PLAYER
)
16808 time_t current
= time (NULL
);
16809 if(m_speakTime
> current
)
16811 uint32 max_count
= sWorld
.getConfig(CONFIG_UINT32_CHATFLOOD_MESSAGE_COUNT
);
16816 if(m_speakCount
>= max_count
)
16818 // prevent overwrite mute time, if message send just before mutes set, for example.
16819 time_t new_mute
= current
+ sWorld
.getConfig(CONFIG_UINT32_CHATFLOOD_MUTE_TIME
);
16820 if(GetSession()->m_muteTime
< new_mute
)
16821 GetSession()->m_muteTime
= new_mute
;
16829 m_speakTime
= current
+ sWorld
.getConfig(CONFIG_UINT32_CHATFLOOD_MESSAGE_DELAY
);
16832 bool Player::CanSpeak() const
16834 return GetSession()->m_muteTime
<= time (NULL
);
16837 /*********************************************************/
16838 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
16839 /*********************************************************/
16841 void Player::SendAttackSwingNotInRange()
16843 WorldPacket
data(SMSG_ATTACKSWING_NOTINRANGE
, 0);
16844 GetSession()->SendPacket( &data
);
16847 void Player::SavePositionInDB(uint32 mapid
, float x
,float y
,float z
,float o
,uint32 zone
,uint64 guid
)
16849 std::ostringstream ss
;
16850 ss
<< "UPDATE characters SET position_x='"<<x
<<"',position_y='"<<y
16851 << "',position_z='"<<z
<<"',orientation='"<<o
<<"',map='"<<mapid
16852 << "',zone='"<<zone
<<"',trans_x='0',trans_y='0',trans_z='0',"
16853 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
16854 sLog
.outDebug("%s", ss
.str().c_str());
16855 CharacterDatabase
.Execute(ss
.str().c_str());
16858 void Player::SaveDataFieldToDB()
16860 std::ostringstream ss
;
16861 ss
<<"UPDATE characters SET data='";
16863 for(uint16 i
= 0; i
< m_valuesCount
; ++i
)
16865 ss
<< GetUInt32Value(i
) << " ";
16867 ss
<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
16869 CharacterDatabase
.Execute(ss
.str().c_str());
16872 bool Player::SaveValuesArrayInDB(Tokens
const& tokens
, uint64 guid
)
16874 std::ostringstream ss2
;
16875 ss2
<< "UPDATE characters SET data='";
16877 for (Tokens::const_iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
, ++i
)
16879 ss2
<< tokens
[i
] << " ";
16881 ss2
<< "' WHERE guid='" << GUID_LOPART(guid
) << "'";
16883 return CharacterDatabase
.Execute(ss2
.str().c_str());
16886 void Player::SetUInt32ValueInArray(Tokens
& tokens
,uint16 index
, uint32 value
)
16889 snprintf(buf
,11,"%u",value
);
16891 if(index
>= tokens
.size())
16894 tokens
[index
] = buf
;
16897 void Player::SetUInt32ValueInDB(uint16 index
, uint32 value
, uint64 guid
)
16900 if(!LoadValuesArrayFromDB(tokens
,guid
))
16903 if(index
>= tokens
.size())
16907 snprintf(buf
,11,"%u",value
);
16908 tokens
[index
] = buf
;
16910 SaveValuesArrayInDB(tokens
,guid
);
16913 void Player::SetFloatValueInDB(uint16 index
, float value
, uint64 guid
)
16916 memcpy(&temp
, &value
, sizeof(value
));
16917 Player::SetUInt32ValueInDB(index
, temp
, guid
);
16920 void Player::Customize(uint64 guid
, uint8 gender
, uint8 skin
, uint8 face
, uint8 hairStyle
, uint8 hairColor
, uint8 facialHair
)
16923 QueryResult
* result
= CharacterDatabase
.PQuery("SELECT playerBytes2 FROM characters WHERE guid = '%u'", GUID_LOPART(guid
));
16927 Field
* fields
= result
->Fetch();
16929 uint32 player_bytes2
= fields
[0].GetUInt32();
16930 player_bytes2
&= ~0xFF;
16931 player_bytes2
|= facialHair
;
16933 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
));
16938 void Player::SendAttackSwingDeadTarget()
16940 WorldPacket
data(SMSG_ATTACKSWING_DEADTARGET
, 0);
16941 GetSession()->SendPacket( &data
);
16944 void Player::SendAttackSwingCantAttack()
16946 WorldPacket
data(SMSG_ATTACKSWING_CANT_ATTACK
, 0);
16947 GetSession()->SendPacket( &data
);
16950 void Player::SendAttackSwingCancelAttack()
16952 WorldPacket
data(SMSG_CANCEL_COMBAT
, 0);
16953 GetSession()->SendPacket( &data
);
16956 void Player::SendAttackSwingBadFacingAttack()
16958 WorldPacket
data(SMSG_ATTACKSWING_BADFACING
, 0);
16959 GetSession()->SendPacket( &data
);
16962 void Player::SendAutoRepeatCancel(Unit
*target
)
16964 WorldPacket
data(SMSG_CANCEL_AUTO_REPEAT
, target
->GetPackGUID().size());
16965 data
<< target
->GetPackGUID(); // may be it's target guid
16966 GetSession()->SendPacket( &data
);
16969 void Player::SendExplorationExperience(uint32 Area
, uint32 Experience
)
16971 WorldPacket
data( SMSG_EXPLORATION_EXPERIENCE
, 8 );
16972 data
<< uint32(Area
);
16973 data
<< uint32(Experience
);
16974 GetSession()->SendPacket(&data
);
16977 void Player::SendDungeonDifficulty(bool IsInGroup
)
16979 uint8 val
= 0x00000001;
16980 WorldPacket
data(MSG_SET_DUNGEON_DIFFICULTY
, 12);
16981 data
<< uint32(GetDungeonDifficulty());
16982 data
<< uint32(val
);
16983 data
<< uint32(IsInGroup
);
16984 GetSession()->SendPacket(&data
);
16987 void Player::SendRaidDifficulty(bool IsInGroup
)
16989 uint8 val
= 0x00000001;
16990 WorldPacket
data(MSG_SET_RAID_DIFFICULTY
, 12);
16991 data
<< uint32(GetRaidDifficulty());
16992 data
<< uint32(val
);
16993 data
<< uint32(IsInGroup
);
16994 GetSession()->SendPacket(&data
);
16997 void Player::SendResetFailedNotify(uint32 mapid
)
16999 WorldPacket
data(SMSG_RESET_FAILED_NOTIFY
, 4);
17000 data
<< uint32(mapid
);
17001 GetSession()->SendPacket(&data
);
17004 /// Reset all solo instances and optionally send a message on success for each
17005 void Player::ResetInstances(uint8 method
, bool isRaid
)
17007 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
17009 // we assume that when the difficulty changes, all instances that can be reset will be
17010 Difficulty diff
= GetDifficulty(isRaid
);
17012 for (BoundInstancesMap::iterator itr
= m_boundInstances
[diff
].begin(); itr
!= m_boundInstances
[diff
].end();)
17014 InstanceSave
*p
= itr
->second
.save
;
17015 const MapEntry
*entry
= sMapStore
.LookupEntry(itr
->first
);
17016 if(!entry
|| entry
->IsRaid() != isRaid
|| !p
->CanReset())
17022 if(method
== INSTANCE_RESET_ALL
)
17024 // the "reset all instances" method can only reset normal maps
17025 if(entry
->map_type
== MAP_RAID
|| diff
== DUNGEON_DIFFICULTY_HEROIC
)
17032 // if the map is loaded, reset it
17033 Map
*map
= sMapMgr
.FindMap(p
->GetMapId(), p
->GetInstanceId());
17034 if(map
&& map
->IsDungeon())
17035 ((InstanceMap
*)map
)->Reset(method
);
17037 // since this is a solo instance there should not be any players inside
17038 if(method
== INSTANCE_RESET_ALL
|| method
== INSTANCE_RESET_CHANGE_DIFFICULTY
)
17039 SendResetInstanceSuccess(p
->GetMapId());
17042 m_boundInstances
[diff
].erase(itr
++);
17044 // the following should remove the instance save from the manager and delete it as well
17045 p
->RemovePlayer(this);
17049 void Player::SendResetInstanceSuccess(uint32 MapId
)
17051 WorldPacket
data(SMSG_INSTANCE_RESET
, 4);
17052 data
<< uint32(MapId
);
17053 GetSession()->SendPacket(&data
);
17056 void Player::SendResetInstanceFailed(uint32 reason
, uint32 MapId
)
17058 // TODO: find what other fail reasons there are besides players in the instance
17059 WorldPacket
data(SMSG_INSTANCE_RESET_FAILED
, 4);
17060 data
<< uint32(reason
);
17061 data
<< uint32(MapId
);
17062 GetSession()->SendPacket(&data
);
17065 /*********************************************************/
17066 /*** Update timers ***/
17067 /*********************************************************/
17069 ///checks the 15 afk reports per 5 minutes limit
17070 void Player::UpdateAfkReport(time_t currTime
)
17072 if(m_bgData
.bgAfkReportedTimer
<= currTime
)
17074 m_bgData
.bgAfkReportedCount
= 0;
17075 m_bgData
.bgAfkReportedTimer
= currTime
+5*MINUTE
;
17079 void Player::UpdateContestedPvP(uint32 diff
)
17081 if(!m_contestedPvPTimer
||isInCombat())
17083 if(m_contestedPvPTimer
<= diff
)
17085 ResetContestedPvP();
17088 m_contestedPvPTimer
-= diff
;
17091 void Player::UpdatePvPFlag(time_t currTime
)
17095 if(pvpInfo
.endTimer
== 0 || currTime
< (pvpInfo
.endTimer
+ 300))
17101 void Player::UpdateDuelFlag(time_t currTime
)
17103 if(!duel
|| duel
->startTimer
== 0 ||currTime
< duel
->startTimer
+ 3)
17106 SetUInt32Value(PLAYER_DUEL_TEAM
, 1);
17107 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 2);
17109 duel
->startTimer
= 0;
17110 duel
->startTime
= currTime
;
17111 duel
->opponent
->duel
->startTimer
= 0;
17112 duel
->opponent
->duel
->startTime
= currTime
;
17115 void Player::RemovePet(Pet
* pet
, PetSaveMode mode
, bool returnreagent
)
17120 if(!pet
|| pet
->GetOwnerGUID()!=GetGUID())
17123 // not save secondary permanent pet as current
17124 if (pet
&& m_temporaryUnsummonedPetNumber
!= pet
->GetCharmInfo()->GetPetNumber() && mode
== PET_SAVE_AS_CURRENT
)
17125 mode
= PET_SAVE_NOT_IN_SLOT
;
17127 if(returnreagent
&& pet
&& mode
!= PET_SAVE_AS_CURRENT
)
17129 //returning of reagents only for players, so best done here
17130 uint32 spellId
= pet
? pet
->GetUInt32Value(UNIT_CREATED_BY_SPELL
) : m_oldpetspell
;
17131 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellId
);
17135 for(uint32 i
= 0; i
< 7; ++i
)
17137 if(spellInfo
->Reagent
[i
] > 0)
17139 ItemPosCountVec dest
; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
17140 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, spellInfo
->Reagent
[i
], spellInfo
->ReagentCount
[i
] );
17141 if( msg
== EQUIP_ERR_OK
)
17143 Item
* item
= StoreNewItem( dest
, spellInfo
->Reagent
[i
], true);
17145 SendNewItem(item
,spellInfo
->ReagentCount
[i
],true,false);
17152 // only if current pet in slot
17153 switch(pet
->getPetType())
17159 RemoveGuardian(pet
);
17162 if(GetPetGUID() == pet
->GetGUID())
17169 pet
->SavePetToDB(mode
);
17171 pet
->AddObjectToRemoveList();
17172 pet
->m_removed
= true;
17174 if(pet
->isControlled())
17176 RemovePetActionBar();
17179 SetGroupUpdateFlag(GROUP_UPDATE_PET
);
17183 void Player::RemoveMiniPet()
17185 if(Pet
* pet
= GetMiniPet())
17187 pet
->Remove(PET_SAVE_AS_DELETED
);
17192 Pet
* Player::GetMiniPet()
17196 return GetMap()->GetPet(m_miniPet
);
17199 void Player::BuildPlayerChat(WorldPacket
*data
, uint8 msgtype
, const std::string
& text
, uint32 language
) const
17201 *data
<< (uint8
)msgtype
;
17202 *data
<< (uint32
)language
;
17203 *data
<< (uint64
)GetGUID();
17204 *data
<< (uint32
)language
; //language 2.1.0 ?
17205 *data
<< (uint64
)GetGUID();
17206 *data
<< (uint32
)(text
.length()+1);
17208 *data
<< (uint8
)chatTag();
17211 void Player::Say(const std::string
& text
, const uint32 language
)
17213 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
17214 BuildPlayerChat(&data
, CHAT_MSG_SAY
, text
, language
);
17215 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_FLOAT_LISTEN_RANGE_SAY
),true);
17218 void Player::Yell(const std::string
& text
, const uint32 language
)
17220 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
17221 BuildPlayerChat(&data
, CHAT_MSG_YELL
, text
, language
);
17222 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_FLOAT_LISTEN_RANGE_YELL
),true);
17225 void Player::TextEmote(const std::string
& text
)
17227 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
17228 BuildPlayerChat(&data
, CHAT_MSG_EMOTE
, text
, LANG_UNIVERSAL
);
17229 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_FLOAT_LISTEN_RANGE_TEXTEMOTE
),true, !sWorld
.getConfig(CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_CHAT
) );
17232 void Player::Whisper(const std::string
& text
, uint32 language
,uint64 receiver
)
17234 if (language
!= LANG_ADDON
) // if not addon data
17235 language
= LANG_UNIVERSAL
; // whispers should always be readable
17237 Player
*rPlayer
= sObjectMgr
.GetPlayer(receiver
);
17239 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
17240 if(!rPlayer
->isDND() || isGameMaster())
17242 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
17243 BuildPlayerChat(&data
, CHAT_MSG_WHISPER
, text
, language
);
17244 rPlayer
->GetSession()->SendPacket(&data
);
17246 // not send confirmation for addon messages
17247 if (language
!= LANG_ADDON
)
17249 data
.Initialize(SMSG_MESSAGECHAT
, 200);
17250 rPlayer
->BuildPlayerChat(&data
, CHAT_MSG_WHISPER_INFORM
, text
, language
);
17251 GetSession()->SendPacket(&data
);
17256 // announce to player that player he is whispering to is dnd and cannot receive his message
17257 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND
, rPlayer
->GetName(), rPlayer
->dndMsg
.c_str());
17260 if(!isAcceptWhispers())
17262 SetAcceptWhispers(true);
17263 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON
);
17266 // announce to player that player he is whispering to is afk
17267 if(rPlayer
->isAFK())
17268 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK
, rPlayer
->GetName(), rPlayer
->afkMsg
.c_str());
17270 // if player whisper someone, auto turn of dnd to be able to receive an answer
17271 if(isDND() && !rPlayer
->isGameMaster())
17275 void Player::PetSpellInitialize()
17277 Pet
* pet
= GetPet();
17282 sLog
.outDebug("Pet Spells Groups");
17284 CharmInfo
*charmInfo
= pet
->GetCharmInfo();
17286 WorldPacket
data(SMSG_PET_SPELLS
, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX
+1+1);
17287 data
<< uint64(pet
->GetGUID());
17288 data
<< uint16(pet
->GetCreatureInfo()->family
); // creature family (required for pet talents)
17290 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState()) << uint16(0);
17293 charmInfo
->BuildActionBar(&data
);
17295 size_t spellsCountPos
= data
.wpos();
17299 data
<< uint8(addlist
); // placeholder
17301 if (pet
->IsPermanentPetFor(this))
17304 for (PetSpellMap::const_iterator itr
= pet
->m_spells
.begin(); itr
!= pet
->m_spells
.end(); ++itr
)
17306 if(itr
->second
.state
== PETSPELL_REMOVED
)
17309 data
<< uint32(MAKE_UNIT_ACTION_BUTTON(itr
->first
,itr
->second
.active
));
17314 data
.put
<uint8
>(spellsCountPos
, addlist
);
17316 uint8 cooldownsCount
= pet
->m_CreatureSpellCooldowns
.size() + pet
->m_CreatureCategoryCooldowns
.size();
17317 data
<< uint8(cooldownsCount
);
17319 time_t curTime
= time(NULL
);
17321 for(CreatureSpellCooldowns::const_iterator itr
= pet
->m_CreatureSpellCooldowns
.begin(); itr
!= pet
->m_CreatureSpellCooldowns
.end(); ++itr
)
17323 time_t cooldown
= (itr
->second
> curTime
) ? (itr
->second
- curTime
) * IN_MILISECONDS
: 0;
17325 data
<< uint32(itr
->first
); // spellid
17326 data
<< uint16(0); // spell category?
17327 data
<< uint32(cooldown
); // cooldown
17328 data
<< uint32(0); // category cooldown
17331 for(CreatureSpellCooldowns::const_iterator itr
= pet
->m_CreatureCategoryCooldowns
.begin(); itr
!= pet
->m_CreatureCategoryCooldowns
.end(); ++itr
)
17333 time_t cooldown
= (itr
->second
> curTime
) ? (itr
->second
- curTime
) * IN_MILISECONDS
: 0;
17335 data
<< uint32(itr
->first
); // spellid
17336 data
<< uint16(0); // spell category?
17337 data
<< uint32(0); // cooldown
17338 data
<< uint32(cooldown
); // category cooldown
17341 GetSession()->SendPacket(&data
);
17344 void Player::SendPetGUIDs()
17349 // Later this function might get modified for multiple guids
17350 WorldPacket
data(SMSG_PET_GUIDS
, 12);
17351 data
<< uint32(1); // count
17352 data
<< uint64(GetPetGUID());
17353 GetSession()->SendPacket(&data
);
17356 void Player::PossessSpellInitialize()
17358 Unit
* charm
= GetCharm();
17363 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
17367 sLog
.outError("Player::PossessSpellInitialize(): charm (GUID: %u TypeId: %u) has no charminfo!", charm
->GetGUIDLow(),charm
->GetTypeId());
17371 WorldPacket
data(SMSG_PET_SPELLS
, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX
+1+1);
17372 data
<< uint64(charm
->GetGUID());
17377 charmInfo
->BuildActionBar(&data
);
17379 data
<< uint8(0); // spells count
17380 data
<< uint8(0); // cooldowns count
17382 GetSession()->SendPacket(&data
);
17385 void Player::CharmSpellInitialize()
17387 Unit
* charm
= GetCharm();
17392 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
17395 sLog
.outError("Player::CharmSpellInitialize(): the player's charm (GUID: %u TypeId: %u) has no charminfo!", charm
->GetGUIDLow(),charm
->GetTypeId());
17401 if(charm
->GetTypeId() != TYPEID_PLAYER
)
17403 CreatureInfo
const *cinfo
= ((Creature
*)charm
)->GetCreatureInfo();
17405 if(cinfo
&& cinfo
->type
== CREATURE_TYPE_DEMON
&& getClass() == CLASS_WARLOCK
)
17407 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
17409 if(charmInfo
->GetCharmSpell(i
)->GetAction())
17415 WorldPacket
data(SMSG_PET_SPELLS
, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX
+1+4*addlist
+1);
17416 data
<< uint64(charm
->GetGUID());
17420 if(charm
->GetTypeId() != TYPEID_PLAYER
)
17421 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState()) << uint16(0);
17423 data
<< uint8(0) << uint8(0) << uint16(0);
17425 charmInfo
->BuildActionBar(&data
);
17427 data
<< uint8(addlist
);
17431 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
17433 CharmSpellEntry
*cspell
= charmInfo
->GetCharmSpell(i
);
17434 if(cspell
->GetAction())
17435 data
<< uint32(cspell
->packedData
);
17439 data
<< uint8(0); // cooldowns count
17441 GetSession()->SendPacket(&data
);
17444 void Player::RemovePetActionBar()
17446 WorldPacket
data(SMSG_PET_SPELLS
, 8);
17448 SendDirectMessage(&data
);
17451 bool Player::IsAffectedBySpellmod(SpellEntry
const *spellInfo
, SpellModifier
*mod
, Spell
const* spell
)
17453 if (!mod
|| !spellInfo
)
17456 if(mod
->charges
== -1 && mod
->lastAffected
) // marked as expired but locked until spell casting finish
17458 // prevent apply to any spell except spell that trigger expire
17461 if(mod
->lastAffected
!= spell
)
17464 else if(mod
->lastAffected
!= FindCurrentSpellBySpellId(spellInfo
->Id
))
17468 return mod
->isAffectedOnSpell(spellInfo
);
17471 void Player::AddSpellMod(SpellModifier
* mod
, bool apply
)
17473 uint16 Opcode
= (mod
->type
== SPELLMOD_FLAT
) ? SMSG_SET_FLAT_SPELL_MODIFIER
: SMSG_SET_PCT_SPELL_MODIFIER
;
17475 for(int eff
= 0; eff
< 96; ++eff
)
17481 _mask
= uint64(1) << (eff
- 0);
17483 _mask2
= uint32(1) << (eff
- 64);
17485 if ( mod
->mask
& _mask
|| mod
->mask2
& _mask2
)
17488 for (SpellModList::const_iterator itr
= m_spellMods
[mod
->op
].begin(); itr
!= m_spellMods
[mod
->op
].end(); ++itr
)
17490 if ((*itr
)->type
== mod
->type
&& ((*itr
)->mask
& _mask
|| (*itr
)->mask2
& _mask2
))
17491 val
+= (*itr
)->value
;
17493 val
+= apply
? mod
->value
: -(mod
->value
);
17494 WorldPacket
data(Opcode
, (1+1+4));
17495 data
<< uint8(eff
);
17496 data
<< uint8(mod
->op
);
17497 data
<< int32(val
);
17498 SendDirectMessage(&data
);
17503 m_spellMods
[mod
->op
].push_back(mod
);
17506 if (mod
->charges
== -1)
17507 --m_SpellModRemoveCount
;
17508 m_spellMods
[mod
->op
].remove(mod
);
17513 void Player::RemoveSpellMods(Spell
const* spell
)
17515 if(!spell
|| (m_SpellModRemoveCount
== 0))
17518 for(int i
=0;i
<MAX_SPELLMOD
;++i
)
17520 for (SpellModList::const_iterator itr
= m_spellMods
[i
].begin(); itr
!= m_spellMods
[i
].end();)
17522 SpellModifier
*mod
= *itr
;
17525 if (mod
&& mod
->charges
== -1 && (mod
->lastAffected
== spell
|| mod
->lastAffected
==NULL
))
17527 RemoveAurasDueToSpell(mod
->spellId
);
17528 if (m_spellMods
[i
].empty())
17531 itr
= m_spellMods
[i
].begin();
17537 // send Proficiency
17538 void Player::SendProficiency(uint8 pr1
, uint32 pr2
)
17540 WorldPacket
data(SMSG_SET_PROFICIENCY
, 8);
17541 data
<< uint8(pr1
) << uint32(pr2
);
17542 GetSession()->SendPacket (&data
);
17545 void Player::RemovePetitionsAndSigns(uint64 guid
, uint32 type
)
17547 QueryResult
*result
= NULL
;
17549 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
17551 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
17554 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.
17555 { // and SendPetitionQueryOpcode reads data from the DB
17556 Field
*fields
= result
->Fetch();
17557 uint64 ownerguid
= MAKE_NEW_GUID(fields
[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
17558 uint64 petitionguid
= MAKE_NEW_GUID(fields
[1].GetUInt32(), 0, HIGHGUID_ITEM
);
17560 // send update if charter owner in game
17561 Player
* owner
= sObjectMgr
.GetPlayer(ownerguid
);
17563 owner
->GetSession()->SendPetitionQueryOpcode(petitionguid
);
17565 } while ( result
->NextRow() );
17570 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
17572 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
17575 CharacterDatabase
.BeginTransaction();
17578 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid
));
17579 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid
));
17583 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
17584 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
17586 CharacterDatabase
.CommitTransaction();
17589 void Player::LeaveAllArenaTeams(uint64 guid
)
17591 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
));
17597 Field
*fields
= result
->Fetch();
17598 uint32 at_id
= fields
[0].GetUInt32();
17601 ArenaTeam
* at
= sObjectMgr
.GetArenaTeamById(at_id
);
17603 at
->DelMember(guid
);
17605 } while (result
->NextRow());
17610 void Player::SetRestBonus (float rest_bonus_new
)
17612 // Prevent resting on max level
17613 if(getLevel() >= sWorld
.getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL
))
17614 rest_bonus_new
= 0;
17616 if(rest_bonus_new
< 0)
17617 rest_bonus_new
= 0;
17619 float rest_bonus_max
= (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)*1.5f
/2.0f
;
17621 if(rest_bonus_new
> rest_bonus_max
)
17622 m_rest_bonus
= rest_bonus_max
;
17624 m_rest_bonus
= rest_bonus_new
;
17626 // update data for client
17627 if(m_rest_bonus
>10)
17628 SetByteValue(PLAYER_BYTES_2
, 3, 0x01); // Set Reststate = Rested
17629 else if(m_rest_bonus
<=1)
17630 SetByteValue(PLAYER_BYTES_2
, 3, 0x02); // Set Reststate = Normal
17633 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE
, uint32(m_rest_bonus
));
17636 void Player::HandleStealthedUnitsDetection()
17638 std::list
<Unit
*> stealthedUnits
;
17640 CellPair
p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
17642 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
17643 cell
.SetNoCreate();
17645 MaNGOS::AnyStealthedCheck u_check
;
17646 MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
> searcher(this,stealthedUnits
, u_check
);
17648 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, WorldTypeMapContainer
> world_unit_searcher(searcher
);
17649 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, GridTypeMapContainer
> grid_unit_searcher(searcher
);
17651 cell
.Visit(p
, world_unit_searcher
, *GetMap(), *this, MAX_PLAYER_STEALTH_DETECT_RANGE
);
17652 cell
.Visit(p
, grid_unit_searcher
, *GetMap(), *this, MAX_PLAYER_STEALTH_DETECT_RANGE
);
17654 WorldObject
const* viewPoint
= GetViewPoint();
17656 for (std::list
<Unit
*>::const_iterator i
= stealthedUnits
.begin(); i
!= stealthedUnits
.end(); ++i
)
17661 bool hasAtClient
= HaveAtClient((*i
));
17662 bool hasDetected
= (*i
)->isVisibleForOrDetect(this, viewPoint
, true);
17668 ObjectGuid i_guid
= (*i
)->GetGUID();
17669 (*i
)->SendCreateUpdateToPlayer(this);
17670 m_clientGUIDs
.insert(i_guid
);
17672 #ifdef MANGOS_DEBUG
17673 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17674 sLog
.outDebug("%s is detected in stealth by player %u. Distance = %f",i_guid
.GetString().c_str(),GetGUIDLow(),GetDistance(*i
));
17677 // target aura duration for caster show only if target exist at caster client
17678 // send data at target visibility change (adding to client)
17679 if((*i
)!=this && (*i
)->isType(TYPEMASK_UNIT
))
17680 SendAurasForTarget(*i
);
17687 (*i
)->DestroyForPlayer(this);
17688 m_clientGUIDs
.erase((*i
)->GetGUID());
17694 bool Player::ActivateTaxiPathTo(std::vector
<uint32
> const& nodes
, Creature
* npc
/*= NULL*/, uint32 spellid
/*= 0*/)
17696 if(nodes
.size() < 2)
17699 // 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
17700 if(GetSession()->isLogingOut() || isInCombat())
17702 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17703 data
<< uint32(ERR_TAXIPLAYERBUSY
);
17704 GetSession()->SendPacket(&data
);
17708 if(HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_DISABLE_MOVE
))
17714 // not let cheating with start flight mounted
17717 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17718 data
<< uint32(ERR_TAXIPLAYERALREADYMOUNTED
);
17719 GetSession()->SendPacket(&data
);
17723 if( m_ShapeShiftFormSpellId
&& m_form
!= FORM_BATTLESTANCE
&& m_form
!= FORM_BERSERKERSTANCE
&& m_form
!= FORM_DEFENSIVESTANCE
&& m_form
!= FORM_SHADOW
)
17725 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17726 data
<< uint32(ERR_TAXIPLAYERSHAPESHIFTED
);
17727 GetSession()->SendPacket(&data
);
17731 // 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
17732 if(IsNonMeleeSpellCasted(false))
17734 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17735 data
<< uint32(ERR_TAXIPLAYERBUSY
);
17736 GetSession()->SendPacket(&data
);
17740 // cast case or scripted call case
17743 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED
);
17745 if( m_ShapeShiftFormSpellId
&& m_form
!= FORM_BATTLESTANCE
&& m_form
!= FORM_BERSERKERSTANCE
&& m_form
!= FORM_DEFENSIVESTANCE
&& m_form
!= FORM_SHADOW
)
17746 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId
);
17748 if (Spell
* spell
= GetCurrentSpell(CURRENT_GENERIC_SPELL
))
17749 if (spell
->m_spellInfo
->Id
!= spellid
)
17750 InterruptSpell(CURRENT_GENERIC_SPELL
,false);
17752 InterruptSpell(CURRENT_AUTOREPEAT_SPELL
,false);
17754 if (Spell
* spell
= GetCurrentSpell(CURRENT_CHANNELED_SPELL
))
17755 if (spell
->m_spellInfo
->Id
!= spellid
)
17756 InterruptSpell(CURRENT_CHANNELED_SPELL
,true);
17759 uint32 sourcenode
= nodes
[0];
17761 // starting node too far away (cheat?)
17762 TaxiNodesEntry
const* node
= sTaxiNodesStore
.LookupEntry(sourcenode
);
17765 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17766 data
<< uint32(ERR_TAXINOSUCHPATH
);
17767 GetSession()->SendPacket(&data
);
17771 // check node starting pos data set case if provided
17772 if (node
->x
!= 0.0f
|| node
->y
!= 0.0f
|| node
->z
!= 0.0f
)
17774 if (node
->map_id
!= GetMapId() ||
17775 (node
->x
- GetPositionX())*(node
->x
- GetPositionX())+
17776 (node
->y
- GetPositionY())*(node
->y
- GetPositionY())+
17777 (node
->z
- GetPositionZ())*(node
->z
- GetPositionZ()) >
17778 (2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
))
17780 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17781 data
<< uint32(ERR_TAXITOOFARAWAY
);
17782 GetSession()->SendPacket(&data
);
17786 // node must have pos if taxi master case (npc != NULL)
17789 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17790 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
17791 GetSession()->SendPacket(&data
);
17795 // Prepare to flight start now
17797 // stop combat at start taxi flight if any
17800 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
17803 // clean not finished taxi path if any
17804 m_taxi
.ClearTaxiDestinations();
17806 // 0 element current node
17807 m_taxi
.AddTaxiDestination(sourcenode
);
17809 // fill destinations path tail
17810 uint32 sourcepath
= 0;
17811 uint32 totalcost
= 0;
17813 uint32 prevnode
= sourcenode
;
17814 uint32 lastnode
= 0;
17816 for(uint32 i
= 1; i
< nodes
.size(); ++i
)
17820 lastnode
= nodes
[i
];
17821 sObjectMgr
.GetTaxiPath(prevnode
, lastnode
, path
, cost
);
17825 m_taxi
.ClearTaxiDestinations();
17831 if(prevnode
== sourcenode
)
17834 m_taxi
.AddTaxiDestination(lastnode
);
17836 prevnode
= lastnode
;
17839 // get mount model (in case non taximaster (npc==NULL) allow more wide lookup)
17840 uint32 mount_display_id
= sObjectMgr
.GetTaxiMountDisplayId(sourcenode
, GetTeam(), npc
== NULL
);
17842 // in spell case allow 0 model
17843 if ((mount_display_id
== 0 && spellid
== 0) || sourcepath
== 0)
17845 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17846 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
17847 GetSession()->SendPacket(&data
);
17848 m_taxi
.ClearTaxiDestinations();
17852 uint32 money
= GetMoney();
17855 totalcost
= (uint32
)ceil(totalcost
*GetReputationPriceDiscount(npc
));
17857 if(money
< totalcost
)
17859 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17860 data
<< uint32(ERR_TAXINOTENOUGHMONEY
);
17861 GetSession()->SendPacket(&data
);
17862 m_taxi
.ClearTaxiDestinations();
17866 //Checks and preparations done, DO FLIGHT
17867 ModifyMoney(-(int32
)totalcost
);
17868 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING
, totalcost
);
17869 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN
, 1);
17871 // prevent stealth flight
17872 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH
);
17874 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17875 data
<< uint32(ERR_TAXIOK
);
17876 GetSession()->SendPacket(&data
);
17878 sLog
.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
17880 GetSession()->SendDoFlight(mount_display_id
, sourcepath
);
17885 bool Player::ActivateTaxiPathTo( uint32 taxi_path_id
, uint32 spellid
/*= 0*/ )
17887 TaxiPathEntry
const* entry
= sTaxiPathStore
.LookupEntry(taxi_path_id
);
17891 std::vector
<uint32
> nodes
;
17894 nodes
[0] = entry
->from
;
17895 nodes
[1] = entry
->to
;
17897 return ActivateTaxiPathTo(nodes
,NULL
,spellid
);
17900 void Player::ContinueTaxiFlight()
17902 uint32 sourceNode
= m_taxi
.GetTaxiSource();
17906 sLog
.outDebug( "WORLD: Restart character %u taxi flight", GetGUIDLow() );
17908 uint32 mountDisplayId
= sObjectMgr
.GetTaxiMountDisplayId(sourceNode
, GetTeam(),true);
17909 uint32 path
= m_taxi
.GetCurrentTaxiPath();
17911 // search appropriate start path node
17912 uint32 startNode
= 0;
17914 TaxiPathNodeList
const& nodeList
= sTaxiPathNodesByPath
[path
];
17916 float distPrev
= MAP_SIZE
*MAP_SIZE
;
17918 (nodeList
[0].x
-GetPositionX())*(nodeList
[0].x
-GetPositionX())+
17919 (nodeList
[0].y
-GetPositionY())*(nodeList
[0].y
-GetPositionY())+
17920 (nodeList
[0].z
-GetPositionZ())*(nodeList
[0].z
-GetPositionZ());
17922 for(uint32 i
= 1; i
< nodeList
.size(); ++i
)
17924 TaxiPathNode
const& node
= nodeList
[i
];
17925 TaxiPathNode
const& prevNode
= nodeList
[i
-1];
17927 // skip nodes at another map
17928 if(node
.mapid
!= GetMapId())
17931 distPrev
= distNext
;
17934 (node
.x
-GetPositionX())*(node
.x
-GetPositionX())+
17935 (node
.y
-GetPositionY())*(node
.y
-GetPositionY())+
17936 (node
.z
-GetPositionZ())*(node
.z
-GetPositionZ());
17939 (node
.x
-prevNode
.x
)*(node
.x
-prevNode
.x
)+
17940 (node
.y
-prevNode
.y
)*(node
.y
-prevNode
.y
)+
17941 (node
.z
-prevNode
.z
)*(node
.z
-prevNode
.z
);
17943 if(distNext
+ distPrev
< distNodes
)
17950 GetSession()->SendDoFlight(mountDisplayId
, path
, startNode
);
17953 void Player::ProhibitSpellSchool(SpellSchoolMask idSchoolMask
, uint32 unTimeMs
)
17955 // last check 2.0.10
17956 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+m_spells
.size()*8);
17957 data
<< uint64(GetGUID());
17958 data
<< uint8(0x0); // flags (0x1, 0x2)
17959 time_t curTime
= time(NULL
);
17960 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
17962 if (itr
->second
.state
== PLAYERSPELL_REMOVED
)
17964 uint32 unSpellId
= itr
->first
;
17965 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(unSpellId
);
17972 // Not send cooldown for this spells
17973 if (spellInfo
->Attributes
& SPELL_ATTR_DISABLED_WHILE_ACTIVE
)
17976 if((idSchoolMask
& GetSpellSchoolMask(spellInfo
)) && GetSpellCooldownDelay(unSpellId
) < unTimeMs
)
17978 data
<< uint32(unSpellId
);
17979 data
<< uint32(unTimeMs
); // in m.secs
17980 AddSpellCooldown(unSpellId
, 0, curTime
+ unTimeMs
/IN_MILISECONDS
);
17983 GetSession()->SendPacket(&data
);
17986 void Player::InitDataForForm(bool reapplyMods
)
17988 SpellShapeshiftEntry
const* ssEntry
= sSpellShapeshiftStore
.LookupEntry(m_form
);
17989 if(ssEntry
&& ssEntry
->attackSpeed
)
17991 SetAttackTime(BASE_ATTACK
,ssEntry
->attackSpeed
);
17992 SetAttackTime(OFF_ATTACK
,ssEntry
->attackSpeed
);
17993 SetAttackTime(RANGED_ATTACK
, BASE_ATTACK_TIME
);
17996 SetRegularAttackTime();
18002 if(getPowerType()!=POWER_ENERGY
)
18003 setPowerType(POWER_ENERGY
);
18007 case FORM_DIREBEAR
:
18009 if(getPowerType()!=POWER_RAGE
)
18010 setPowerType(POWER_RAGE
);
18013 default: // 0, for example
18015 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(getClass());
18016 if(cEntry
&& cEntry
->powerType
< MAX_POWERS
&& uint32(getPowerType()) != cEntry
->powerType
)
18017 setPowerType(Powers(cEntry
->powerType
));
18022 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
18024 UpdateEquipSpellsAtFormChange();
18026 UpdateAttackPowerAndDamage();
18027 UpdateAttackPowerAndDamage(true);
18030 void Player::InitDisplayIds()
18032 PlayerInfo
const *info
= sObjectMgr
.GetPlayerInfo(getRace(), getClass());
18035 sLog
.outError("Player %u has incorrect race/class pair. Can't init display ids.", GetGUIDLow());
18039 uint8 gender
= getGender();
18042 case GENDER_FEMALE
:
18043 SetDisplayId(info
->displayId_f
);
18044 SetNativeDisplayId(info
->displayId_f
);
18047 SetDisplayId(info
->displayId_m
);
18048 SetNativeDisplayId(info
->displayId_m
);
18051 sLog
.outError("Invalid gender %u for player",gender
);
18056 // Return true is the bought item has a max count to force refresh of window by caller
18057 bool Player::BuyItemFromVendor(uint64 vendorguid
, uint32 item
, uint8 count
, uint8 bag
, uint8 slot
)
18059 // cheating attempt
18060 if (count
< 1) count
= 1;
18065 ItemPrototype
const *pProto
= ObjectMgr::GetItemPrototype( item
);
18068 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, NULL
, item
, 0);
18072 Creature
*pCreature
= GetNPCIfCanInteractWith(vendorguid
,UNIT_NPC_FLAG_VENDOR
);
18075 sLog
.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid
)) );
18076 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR
, NULL
, item
, 0);
18080 VendorItemData
const* vItems
= pCreature
->GetVendorItems();
18081 if(!vItems
|| vItems
->Empty())
18083 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
18087 size_t vendor_slot
= vItems
->FindItemSlot(item
);
18088 if (vendor_slot
>= vItems
->GetItemCount())
18090 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
18094 VendorItem
const* crItem
= vItems
->m_items
[vendor_slot
];
18096 // check current item amount if it limited
18097 if (crItem
->maxcount
!= 0)
18099 if (pCreature
->GetVendorItemCurrentCount(crItem
) < pProto
->BuyCount
* count
)
18101 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD
, pCreature
, item
, 0);
18106 if (uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
18108 SendBuyError( BUY_ERR_REPUTATION_REQUIRE
, pCreature
, item
, 0);
18112 if (crItem
->ExtendedCost
)
18114 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
18117 sLog
.outError("Item %u have wrong ExtendedCost field value %u", pProto
->ItemId
, crItem
->ExtendedCost
);
18121 // honor points price
18122 if (GetHonorPoints() < (iece
->reqhonorpoints
* count
))
18124 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS
, NULL
, NULL
);
18128 // arena points price
18129 if (GetArenaPoints() < (iece
->reqarenapoints
* count
))
18131 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS
, NULL
, NULL
);
18136 for (uint8 i
= 0; i
< 5; ++i
)
18138 if(iece
->reqitem
[i
] && !HasItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
)))
18140 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS
, NULL
, NULL
);
18145 // check for personal arena rating requirement
18146 if( GetMaxPersonalArenaRatingRequirement(iece
->reqarenaslot
) < iece
->reqpersonalarenarating
)
18148 // probably not the proper equip err
18149 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK
,NULL
,NULL
);
18154 uint32 price
= pProto
->BuyPrice
* count
;
18156 // reputation discount
18157 price
= uint32(floor(price
* GetReputationPriceDiscount(pCreature
)));
18159 if (GetMoney() < price
)
18161 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, pCreature
, item
, 0);
18165 if ((bag
== NULL_BAG
&& slot
== NULL_SLOT
) || IsInventoryPos(bag
, slot
))
18167 ItemPosCountVec dest
;
18168 uint8 msg
= CanStoreNewItem( bag
, slot
, dest
, item
, pProto
->BuyCount
* count
);
18169 if (msg
!= EQUIP_ERR_OK
)
18171 SendEquipError( msg
, NULL
, NULL
, item
);
18175 ModifyMoney( -(int32
)price
);
18176 if (crItem
->ExtendedCost
) // case for new honor system
18178 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
18179 if (iece
->reqhonorpoints
)
18180 ModifyHonorPoints( - int32(iece
->reqhonorpoints
* count
));
18181 if (iece
->reqarenapoints
)
18182 ModifyArenaPoints( - int32(iece
->reqarenapoints
* count
));
18183 for (uint8 i
= 0; i
< 5; ++i
)
18185 if (iece
->reqitem
[i
])
18186 DestroyItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
), true);
18190 if (Item
*it
= StoreNewItem( dest
, item
, true ))
18192 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
18194 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
18195 data
<< uint64(pCreature
->GetGUID());
18196 data
<< uint32(vendor_slot
+1); // numbered from 1 at client
18197 data
<< uint32(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
18198 data
<< uint32(count
);
18199 GetSession()->SendPacket(&data
);
18201 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
18204 else if (IsEquipmentPos(bag
, slot
))
18206 if (pProto
->BuyCount
* count
!= 1)
18208 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
, NULL
, NULL
);
18213 uint8 msg
= CanEquipNewItem( slot
, dest
, item
, false );
18214 if (msg
!= EQUIP_ERR_OK
)
18216 SendEquipError( msg
, NULL
, NULL
, item
);
18220 ModifyMoney( -(int32
)price
);
18221 if (crItem
->ExtendedCost
) // case for new honor system
18223 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
18224 if (iece
->reqhonorpoints
)
18225 ModifyHonorPoints( - int32(iece
->reqhonorpoints
));
18226 if (iece
->reqarenapoints
)
18227 ModifyArenaPoints( - int32(iece
->reqarenapoints
));
18228 for (uint8 i
= 0; i
< 5; ++i
)
18230 if(iece
->reqitem
[i
])
18231 DestroyItemCount(iece
->reqitem
[i
], iece
->reqitemcount
[i
], true);
18235 if (Item
*it
= EquipNewItem( dest
, item
, true ))
18237 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
18239 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
18240 data
<< uint64(pCreature
->GetGUID());
18241 data
<< uint32(vendor_slot
+ 1); // numbered from 1 at client
18242 data
<< uint32(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
18243 data
<< uint32(count
);
18244 GetSession()->SendPacket(&data
);
18246 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
18248 AutoUnequipOffhandIfNeed();
18253 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
, NULL
, NULL
);
18257 return crItem
->maxcount
!= 0;
18260 uint32
Player::GetMaxPersonalArenaRatingRequirement(uint32 minarenaslot
)
18262 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
18263 // the personal rating of the arena team must match the required limit as well
18264 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
18265 uint32 max_personal_rating
= 0;
18266 for(int i
= minarenaslot
; i
< MAX_ARENA_SLOT
; ++i
)
18268 if(ArenaTeam
* at
= sObjectMgr
.GetArenaTeamById(GetArenaTeamId(i
)))
18270 uint32 p_rating
= GetArenaPersonalRating(i
);
18271 uint32 t_rating
= at
->GetRating();
18272 p_rating
= p_rating
< t_rating
? p_rating
: t_rating
;
18273 if(max_personal_rating
< p_rating
)
18274 max_personal_rating
= p_rating
;
18277 return max_personal_rating
;
18280 void Player::UpdateHomebindTime(uint32 time
)
18282 // GMs never get homebind timer online
18283 if (m_InstanceValid
|| isGameMaster())
18285 if(m_HomebindTimer
) // instance valid, but timer not reset
18288 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
18290 data
<< uint32(ERR_RAID_GROUP_NONE
); // error used only when timer = 0
18291 GetSession()->SendPacket(&data
);
18293 // instance is valid, reset homebind timer
18294 m_HomebindTimer
= 0;
18296 else if (m_HomebindTimer
> 0)
18298 if (time
>= m_HomebindTimer
)
18300 // teleport to nearest graveyard
18301 RepopAtGraveyard();
18304 m_HomebindTimer
-= time
;
18308 // instance is invalid, start homebind timer
18309 m_HomebindTimer
= 60000;
18310 // send message to player
18311 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
18312 data
<< uint32(m_HomebindTimer
);
18313 data
<< uint32(ERR_RAID_GROUP_NONE
); // error used only when timer = 0
18314 GetSession()->SendPacket(&data
);
18315 sLog
.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
18319 void Player::UpdatePvP(bool state
, bool ovrride
)
18321 if(!state
|| ovrride
)
18324 pvpInfo
.endTimer
= 0;
18328 if(pvpInfo
.endTimer
!= 0)
18329 pvpInfo
.endTimer
= time(NULL
);
18335 void Player::AddSpellAndCategoryCooldowns(SpellEntry
const* spellInfo
, uint32 itemId
, Spell
* spell
, bool infinityCooldown
)
18337 // init cooldown values
18342 // some special item spells without correct cooldown in SpellInfo
18343 // cooldown information stored in item prototype
18344 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
18348 if(ItemPrototype
const* proto
= ObjectMgr::GetItemPrototype(itemId
))
18350 for(int idx
= 0; idx
< 5; ++idx
)
18352 if(proto
->Spells
[idx
].SpellId
== spellInfo
->Id
)
18354 cat
= proto
->Spells
[idx
].SpellCategory
;
18355 rec
= proto
->Spells
[idx
].SpellCooldown
;
18356 catrec
= proto
->Spells
[idx
].SpellCategoryCooldown
;
18363 // if no cooldown found above then base at DBC data
18364 if(rec
< 0 && catrec
< 0)
18366 cat
= spellInfo
->Category
;
18367 rec
= spellInfo
->RecoveryTime
;
18368 catrec
= spellInfo
->CategoryRecoveryTime
;
18371 time_t curTime
= time(NULL
);
18376 // overwrite time for selected category
18377 if(infinityCooldown
)
18379 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
18380 // but not allow ignore until reset or re-login
18381 catrecTime
= catrec
> 0 ? curTime
+infinityCooldownDelay
: 0;
18382 recTime
= rec
> 0 ? curTime
+infinityCooldownDelay
: catrecTime
;
18386 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
18387 // prevent 0 cooldowns set by another way
18388 if (rec
<= 0 && catrec
<= 0 && (cat
== 76 || IsAutoRepeatRangedSpell(spellInfo
) && spellInfo
->Id
!= SPELL_ID_AUTOSHOT
))
18389 rec
= GetAttackTime(RANGED_ATTACK
);
18391 // Now we have cooldown data (if found any), time to apply mods
18393 ApplySpellMod(spellInfo
->Id
, SPELLMOD_COOLDOWN
, rec
, spell
);
18396 ApplySpellMod(spellInfo
->Id
, SPELLMOD_COOLDOWN
, catrec
, spell
);
18398 // replace negative cooldowns by 0
18399 if (rec
< 0) rec
= 0;
18400 if (catrec
< 0) catrec
= 0;
18402 // no cooldown after applying spell mods
18403 if( rec
== 0 && catrec
== 0)
18406 catrecTime
= catrec
? curTime
+catrec
/IN_MILISECONDS
: 0;
18407 recTime
= rec
? curTime
+rec
/IN_MILISECONDS
: catrecTime
;
18410 // self spell cooldown
18412 AddSpellCooldown(spellInfo
->Id
, itemId
, recTime
);
18415 if (cat
&& catrec
> 0)
18417 SpellCategoryStore::const_iterator i_scstore
= sSpellCategoryStore
.find(cat
);
18418 if(i_scstore
!= sSpellCategoryStore
.end())
18420 for(SpellCategorySet::const_iterator i_scset
= i_scstore
->second
.begin(); i_scset
!= i_scstore
->second
.end(); ++i_scset
)
18422 if(*i_scset
== spellInfo
->Id
) // skip main spell, already handled above
18425 AddSpellCooldown(*i_scset
, itemId
, catrecTime
);
18431 void Player::AddSpellCooldown(uint32 spellid
, uint32 itemid
, time_t end_time
)
18435 sc
.itemid
= itemid
;
18436 m_spellCooldowns
[spellid
] = sc
;
18439 void Player::SendCooldownEvent(SpellEntry
const *spellInfo
, uint32 itemId
, Spell
* spell
)
18441 // start cooldowns at server side, if any
18442 AddSpellAndCategoryCooldowns(spellInfo
, itemId
, spell
);
18444 // Send activate cooldown timer (possible 0) at client side
18445 WorldPacket
data(SMSG_COOLDOWN_EVENT
, (4+8));
18446 data
<< uint32(spellInfo
->Id
);
18447 data
<< uint64(GetGUID());
18448 SendDirectMessage(&data
);
18451 void Player::UpdatePotionCooldown(Spell
* spell
)
18453 // no potion used i combat or still in combat
18454 if(!m_lastPotionId
|| isInCombat())
18457 // Call not from spell cast, send cooldown event for item spells if no in combat
18460 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
18461 if(ItemPrototype
const* proto
= ObjectMgr::GetItemPrototype(m_lastPotionId
))
18462 for(int idx
= 0; idx
< 5; ++idx
)
18463 if(proto
->Spells
[idx
].SpellId
&& proto
->Spells
[idx
].SpellTrigger
== ITEM_SPELLTRIGGER_ON_USE
)
18464 if(SpellEntry
const* spellInfo
= sSpellStore
.LookupEntry(proto
->Spells
[idx
].SpellId
))
18465 SendCooldownEvent(spellInfo
,m_lastPotionId
);
18467 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
18469 SendCooldownEvent(spell
->m_spellInfo
,m_lastPotionId
,spell
);
18471 m_lastPotionId
= 0;
18474 //slot to be excluded while counting
18475 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition
, int8 slot
)
18477 if(!enchantmentcondition
)
18480 SpellItemEnchantmentConditionEntry
const *Condition
= sSpellItemEnchantmentConditionStore
.LookupEntry(enchantmentcondition
);
18485 uint8 curcount
[4] = {0, 0, 0, 0};
18487 //counting current equipped gem colors
18488 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
18492 Item
*pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
18493 if(pItem2
&& pItem2
->GetProto()->Socket
[0].Color
)
18495 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
18497 uint32 enchant_id
= pItem2
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
18501 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
18505 uint32 gemid
= enchantEntry
->GemID
;
18509 ItemPrototype
const* gemProto
= sItemStorage
.LookupEntry
<ItemPrototype
>(gemid
);
18513 GemPropertiesEntry
const* gemProperty
= sGemPropertiesStore
.LookupEntry(gemProto
->GemProperties
);
18517 uint8 GemColor
= gemProperty
->color
;
18519 for(uint8 b
= 0, tmpcolormask
= 1; b
< 4; b
++, tmpcolormask
<<= 1)
18521 if(tmpcolormask
& GemColor
)
18528 bool activate
= true;
18530 for(int i
= 0; i
< 5; ++i
)
18532 if(!Condition
->Color
[i
])
18535 uint32 _cur_gem
= curcount
[Condition
->Color
[i
] - 1];
18537 // if have <CompareColor> use them as count, else use <value> from Condition
18538 uint32 _cmp_gem
= Condition
->CompareColor
[i
] ? curcount
[Condition
->CompareColor
[i
] - 1]: Condition
->Value
[i
];
18540 switch(Condition
->Comparator
[i
])
18542 case 2: // requires less <color> than (<value> || <comparecolor>) gems
18543 activate
&= (_cur_gem
< _cmp_gem
) ? true : false;
18545 case 3: // requires more <color> than (<value> || <comparecolor>) gems
18546 activate
&= (_cur_gem
> _cmp_gem
) ? true : false;
18548 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
18549 activate
&= (_cur_gem
>= _cmp_gem
) ? true : false;
18554 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");
18559 void Player::CorrectMetaGemEnchants(uint8 exceptslot
, bool apply
)
18561 //cycle all equipped items
18562 for(uint32 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
18564 //enchants for the slot being socketed are handled by Player::ApplyItemMods
18565 if(slot
== exceptslot
)
18568 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
18570 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
)
18573 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
18575 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
18579 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
18583 uint32 condition
= enchantEntry
->EnchantmentCondition
;
18586 //was enchant active with/without item?
18587 bool wasactive
= EnchantmentFitsRequirements(condition
, apply
? exceptslot
: -1);
18588 //should it now be?
18589 if(wasactive
!= EnchantmentFitsRequirements(condition
, apply
? -1 : exceptslot
))
18591 // ignore item gem conditions
18592 //if state changed, (dis)apply enchant
18593 ApplyEnchantment(pItem
, EnchantmentSlot(enchant_slot
), !wasactive
, true, true);
18600 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
18601 void Player::ToggleMetaGemsActive(uint8 exceptslot
, bool apply
)
18603 //cycle all equipped items
18604 for(int slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
18606 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
18607 if(slot
== exceptslot
)
18610 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
18612 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
) //if item has no sockets or no item is equipped go to next item
18615 //cycle all (gem)enchants
18616 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
18618 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
18619 if(!enchant_id
) //if no enchant go to next enchant(slot)
18622 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
18626 //only metagems to be (de)activated, so only enchants with condition
18627 uint32 condition
= enchantEntry
->EnchantmentCondition
;
18629 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
), apply
);
18634 void Player::SetBattleGroundEntryPoint()
18637 if (!m_taxi
.empty())
18639 m_bgData
.mountSpell
= 0;
18640 m_bgData
.taxiPath
[0] = m_taxi
.GetTaxiSource();
18641 m_bgData
.taxiPath
[1] = m_taxi
.GetTaxiDestination();
18643 // On taxi we don't need check for dungeon
18644 m_bgData
.joinPos
= WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
18649 m_bgData
.ClearTaxiPath();
18651 // Mount spell id storing
18654 AuraList
const& auras
= GetAurasByType(SPELL_AURA_MOUNTED
);
18655 if (!auras
.empty())
18656 m_bgData
.mountSpell
= (*auras
.begin())->GetId();
18659 m_bgData
.mountSpell
= 0;
18661 // If map is dungeon find linked graveyard
18662 if(GetMap()->IsDungeon())
18664 if (const WorldSafeLocsEntry
* entry
= sObjectMgr
.GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam()))
18666 m_bgData
.joinPos
= WorldLocation(entry
->map_id
, entry
->x
, entry
->y
, entry
->z
, 0.0f
);
18670 sLog
.outError("SetBattleGroundEntryPoint: Dungeon map %u has no linked graveyard, setting home location as entry point.", GetMapId());
18672 // If new entry point is not BG or arena set it
18673 else if (!GetMap()->IsBattleGroundOrArena())
18675 m_bgData
.joinPos
= WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
18680 // In error cases use homebind position
18681 m_bgData
.joinPos
= WorldLocation(m_homebindMapId
, m_homebindX
, m_homebindY
, m_homebindZ
, 0.0f
);
18684 void Player::LeaveBattleground(bool teleportToEntryPoint
)
18686 if(BattleGround
*bg
= GetBattleGround())
18688 bg
->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint
, true);
18690 // call after remove to be sure that player resurrected for correct cast
18691 if( bg
->isBattleGround() && !isGameMaster() && sWorld
.getConfig(CONFIG_BOOL_BATTLEGROUND_CAST_DESERTER
) )
18693 if( bg
->GetStatus() == STATUS_IN_PROGRESS
|| bg
->GetStatus() == STATUS_WAIT_JOIN
)
18695 //lets check if player was teleported from BG and schedule delayed Deserter spell cast
18696 if(IsBeingTeleportedFar())
18698 ScheduleDelayedOperation(DELAYED_SPELL_CAST_DESERTER
);
18702 CastSpell(this, 26013, true); // Deserter
18708 bool Player::CanJoinToBattleground() const
18710 // check Deserter debuff
18711 if(GetDummyAura(26013))
18717 bool Player::CanReportAfkDueToLimit()
18719 // a player can complain about 15 people per 5 minutes
18720 if(m_bgData
.bgAfkReportedCount
++ >= 15)
18726 ///This player has been blamed to be inactive in a battleground
18727 void Player::ReportedAfkBy(Player
* reporter
)
18729 BattleGround
*bg
= GetBattleGround();
18730 if(!bg
|| bg
!= reporter
->GetBattleGround() || GetTeam() != reporter
->GetTeam())
18733 // check if player has 'Idle' or 'Inactive' debuff
18734 if(m_bgData
.bgAfkReporter
.find(reporter
->GetGUIDLow()) == m_bgData
.bgAfkReporter
.end() && !HasAura(43680, EFFECT_INDEX_0
) && !HasAura(43681, EFFECT_INDEX_0
) && reporter
->CanReportAfkDueToLimit())
18736 m_bgData
.bgAfkReporter
.insert(reporter
->GetGUIDLow());
18737 // 3 players have to complain to apply debuff
18738 if(m_bgData
.bgAfkReporter
.size() >= 3)
18740 // cast 'Idle' spell
18741 CastSpell(this, 43680, true);
18742 m_bgData
.bgAfkReporter
.clear();
18747 WorldObject
const* Player::GetViewPoint() const
18749 if(uint64 far_sight
= GetFarSight())
18751 WorldObject
const* viewPoint
= GetMap()->GetWorldObject(far_sight
);
18752 return viewPoint
? viewPoint
: this; // always expected not NULL
18758 bool Player::IsVisibleInGridForPlayer( Player
* pl
) const
18760 // gamemaster in GM mode see all, including ghosts
18761 if(pl
->isGameMaster() && GetSession()->GetSecurity() <= pl
->GetSession()->GetSecurity())
18764 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
18765 if (InBattleGround())
18767 if (!(isAlive() || m_deathTimer
> 0) && !IsFriendlyTo(pl
) )
18772 // Live player see live player or dead player with not realized corpse
18773 if(pl
->isAlive() || pl
->m_deathTimer
> 0)
18775 return isAlive() || m_deathTimer
> 0;
18778 // Ghost see other friendly ghosts, that's for sure
18779 if(!(isAlive() || m_deathTimer
> 0) && IsFriendlyTo(pl
))
18782 // Dead player see live players near own corpse
18785 Corpse
*corpse
= pl
->GetCorpse();
18788 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
18789 if(corpse
->IsWithinDistInMap(this,(20+25)*sWorld
.getConfig(CONFIG_FLOAT_RATE_CREATURE_AGGRO
)))
18794 // and not see any other
18798 bool Player::IsVisibleGloballyFor( Player
* u
) const
18803 // Always can see self
18807 // Visible units, always are visible for all players
18808 if (GetVisibility() == VISIBILITY_ON
)
18811 // GMs are visible for higher gms (or players are visible for gms)
18812 if (u
->GetSession()->GetSecurity() > SEC_PLAYER
)
18813 return GetSession()->GetSecurity() <= u
->GetSession()->GetSecurity();
18815 // non faction visibility non-breakable for non-GMs
18816 if (GetVisibility() == VISIBILITY_OFF
)
18819 // non-gm stealth/invisibility not hide from global player lists
18824 inline void BeforeVisibilityDestroy(T
* /*t*/, Player
* /*p*/)
18829 inline void BeforeVisibilityDestroy
<Creature
>(Creature
* t
, Player
* p
)
18831 if (p
->GetPetGUID()==t
->GetGUID() && ((Creature
*)t
)->isPet())
18832 ((Pet
*)t
)->Remove(PET_SAVE_NOT_IN_SLOT
, true);
18835 void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, WorldObject
* target
)
18837 if(HaveAtClient(target
))
18839 if(!target
->isVisibleForInState(this, viewPoint
, true))
18841 if (target
->GetTypeId()==TYPEID_UNIT
)
18842 BeforeVisibilityDestroy
<Creature
>((Creature
*)target
,this);
18844 ObjectGuid t_guid
= target
->GetGUID();
18846 target
->DestroyForPlayer(this);
18847 m_clientGUIDs
.erase(t_guid
);
18849 #ifdef MANGOS_DEBUG
18850 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
18851 sLog
.outDebug("%s out of range for player %u. Distance = %f",t_guid
.GetString().c_str(),GetGUIDLow(),GetDistance(target
));
18857 if(target
->isVisibleForInState(this, viewPoint
, false))
18859 target
->SendCreateUpdateToPlayer(this);
18860 if(target
->GetTypeId()!=TYPEID_GAMEOBJECT
||!((GameObject
*)target
)->IsTransport())
18861 m_clientGUIDs
.insert(target
->GetGUID());
18863 #ifdef MANGOS_DEBUG
18864 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
18865 sLog
.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
18868 // target aura duration for caster show only if target exist at caster client
18869 // send data at target visibility change (adding to client)
18870 if(target
!=this && target
->isType(TYPEMASK_UNIT
))
18871 SendAurasForTarget((Unit
*)target
);
18873 if(target
->GetTypeId()==TYPEID_UNIT
&& ((Creature
*)target
)->isAlive())
18874 ((Creature
*)target
)->SendMonsterMoveWithSpeedToCurrentDestination(this);
18880 inline void UpdateVisibilityOf_helper(ObjectGuidSet
& s64
, T
* target
)
18882 s64
.insert(target
->GetGUID());
18886 inline void UpdateVisibilityOf_helper(ObjectGuidSet
& s64
, GameObject
* target
)
18888 if(!target
->IsTransport())
18889 s64
.insert(target
->GetGUID());
18893 void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, T
* target
, UpdateData
& data
, UpdateDataMapType
& /*data_updates*/, std::set
<WorldObject
*>& visibleNow
)
18895 if(HaveAtClient(target
))
18897 if(!target
->isVisibleForInState(this,viewPoint
,true))
18899 BeforeVisibilityDestroy
<T
>(target
,this);
18901 ObjectGuid t_guid
= target
->GetGUID();
18903 target
->BuildOutOfRangeUpdateBlock(&data
);
18904 m_clientGUIDs
.erase(t_guid
);
18906 #ifdef MANGOS_DEBUG
18907 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
18908 sLog
.outDebug("%s is out of range for player %u. Distance = %f",t_guid
.GetString().c_str(),GetGUIDLow(),GetDistance(target
));
18914 if(target
->isVisibleForInState(this,viewPoint
,false))
18916 visibleNow
.insert(target
);
18917 target
->BuildCreateUpdateBlockForPlayer(&data
, this);
18918 UpdateVisibilityOf_helper(m_clientGUIDs
,target
);
18920 #ifdef MANGOS_DEBUG
18921 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
18922 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
));
18928 template void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, Player
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
18929 template void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, Creature
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
18930 template void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, Corpse
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
18931 template void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, GameObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
18932 template void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, DynamicObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
18934 void Player::InitPrimaryProfessions()
18936 SetFreePrimaryProfessions(sWorld
.getConfig(CONFIG_UINT32_MAX_PRIMARY_TRADE_SKILL
));
18939 void Player::SendComboPoints()
18941 Unit
*combotarget
= ObjectAccessor::GetUnit(*this, m_comboTarget
);
18944 WorldPacket
data(SMSG_UPDATE_COMBO_POINTS
, combotarget
->GetPackGUID().size()+1);
18945 data
<< combotarget
->GetPackGUID();
18946 data
<< uint8(m_comboPoints
);
18947 GetSession()->SendPacket(&data
);
18951 void Player::AddComboPoints(Unit
* target
, int8 count
)
18956 // without combo points lost (duration checked in aura)
18957 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
18959 if(target
->GetGUID() == m_comboTarget
)
18961 m_comboPoints
+= count
;
18966 if(Unit
* target2
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
18967 target2
->RemoveComboPointHolder(GetGUIDLow());
18969 m_comboTarget
= target
->GetGUID();
18970 m_comboPoints
= count
;
18972 target
->AddComboPointHolder(GetGUIDLow());
18975 if (m_comboPoints
> 5) m_comboPoints
= 5;
18976 if (m_comboPoints
< 0) m_comboPoints
= 0;
18981 void Player::ClearComboPoints()
18986 // without combopoints lost (duration checked in aura)
18987 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
18993 if(Unit
* target
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
18994 target
->RemoveComboPointHolder(GetGUIDLow());
18999 void Player::SetGroup(Group
*group
, int8 subgroup
)
19005 // never use SetGroup without a subgroup unless you specify NULL for group
19006 assert(subgroup
>= 0);
19007 m_group
.link(group
, this);
19008 m_group
.setSubGroup((uint8
)subgroup
);
19012 void Player::SendInitialPacketsBeforeAddToMap()
19014 GetSocial()->SendSocialList();
19017 WorldPacket
data(SMSG_BINDPOINTUPDATE
, 5*4);
19018 data
<< m_homebindX
<< m_homebindY
<< m_homebindZ
;
19019 data
<< (uint32
) m_homebindMapId
;
19020 data
<< (uint32
) m_homebindAreaId
;
19021 GetSession()->SendPacket(&data
);
19023 // SMSG_SET_PROFICIENCY
19024 // SMSG_SET_PCT_SPELL_MODIFIER
19025 // SMSG_SET_FLAT_SPELL_MODIFIER
19027 SendTalentsInfoData(false);
19029 data
.Initialize(SMSG_INSTANCE_DIFFICULTY
, 4+4);
19032 GetSession()->SendPacket(&data
);
19034 SendInitialSpells();
19036 data
.Initialize(SMSG_SEND_UNLEARN_SPELLS
, 4);
19037 data
<< uint32(0); // count, for(count) uint32;
19038 GetSession()->SendPacket(&data
);
19040 SendInitialActionButtons();
19041 m_reputationMgr
.SendInitialReputations();
19044 SendCorpseReclaimDelay(true);
19046 SendInitWorldStates(GetZoneId(), GetAreaId());
19048 SendEquipmentSetList();
19050 m_achievementMgr
.SendAllAchievementData();
19052 data
.Initialize(SMSG_LOGIN_SETTIMESPEED
, 4 + 4 + 4);
19053 data
<< uint32(secsToTimeBitFields(sWorld
.GetGameTime()));
19054 data
<< (float)0.01666667f
; // game speed
19055 data
<< uint32(0); // added in 3.1.2
19056 GetSession()->SendPacket( &data
);
19058 // SMSG_TALENTS_INFO x 2 for pet (unspent points and talents in separate packets...)
19060 // SMSG_POWER_UPDATE
19062 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
19063 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
) || HasAuraType(SPELL_AURA_FLY
) || isInFlight())
19064 m_movementInfo
.AddMovementFlag(MOVEFLAG_FLYING
);
19069 void Player::SendInitialPacketsAfterAddToMap()
19072 uint32 newzone
, newarea
;
19073 GetZoneAndAreaId(newzone
,newarea
);
19074 UpdateZone(newzone
,newarea
); // also call SendInitWorldStates();
19076 WorldPacket
data(SMSG_TIME_SYNC_REQ
, 4); // new 2.0.x, enable movement
19077 data
<< uint32(0x00000000); // on blizz it increments periodically
19078 GetSession()->SendPacket(&data
);
19080 CastSpell(this, 836, true); // LOGINEFFECT
19082 // set some aura effects that send packet to player client after add player to map
19083 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
19084 // same auras state lost at far teleport, send it one more time in this case also
19085 static const AuraType auratypes
[] =
19087 SPELL_AURA_MOD_FEAR
, SPELL_AURA_TRANSFORM
, SPELL_AURA_WATER_WALK
,
19088 SPELL_AURA_FEATHER_FALL
, SPELL_AURA_HOVER
, SPELL_AURA_SAFE_FALL
,
19089 SPELL_AURA_FLY
, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
, SPELL_AURA_NONE
19091 for(AuraType
const* itr
= &auratypes
[0]; itr
&& itr
[0] != SPELL_AURA_NONE
; ++itr
)
19093 Unit::AuraList
const& auraList
= GetAurasByType(*itr
);
19094 if(!auraList
.empty())
19095 auraList
.front()->ApplyModifier(true,true);
19098 if(HasAuraType(SPELL_AURA_MOD_STUN
))
19099 SetMovement(MOVE_ROOT
);
19101 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
19102 if(HasAuraType(SPELL_AURA_MOD_ROOT
))
19104 WorldPacket
data2(SMSG_FORCE_MOVE_ROOT
, 10);
19105 data2
<< GetPackGUID();
19106 data2
<< (uint32
)2;
19107 SendMessageToSet(&data2
,true);
19110 SendAurasForTarget(this);
19111 SendEnchantmentDurations(); // must be after add to map
19112 SendItemDurations(); // must be after add to map
19115 void Player::SendUpdateToOutOfRangeGroupMembers()
19117 if (m_groupUpdateMask
== GROUP_UPDATE_FLAG_NONE
)
19119 if(Group
* group
= GetGroup())
19120 group
->UpdatePlayerOutOfRange(this);
19122 m_groupUpdateMask
= GROUP_UPDATE_FLAG_NONE
;
19123 m_auraUpdateMask
= 0;
19124 if(Pet
*pet
= GetPet())
19125 pet
->ResetAuraUpdateMask();
19128 void Player::SendTransferAborted(uint32 mapid
, uint8 reason
, uint8 arg
)
19130 WorldPacket
data(SMSG_TRANSFER_ABORTED
, 4+2);
19131 data
<< uint32(mapid
);
19132 data
<< uint8(reason
); // transfer abort reason
19135 case TRANSFER_ABORT_INSUF_EXPAN_LVL
:
19136 case TRANSFER_ABORT_DIFFICULTY
:
19137 case TRANSFER_ABORT_UNIQUE_MESSAGE
:
19138 data
<< uint8(arg
);
19141 GetSession()->SendPacket(&data
);
19144 void Player::SendInstanceResetWarning( uint32 mapid
, Difficulty difficulty
, uint32 time
)
19146 // type of warning, based on the time remaining until reset
19149 type
= RAID_INSTANCE_WELCOME
;
19150 else if(time
> 900 && time
<= 3600)
19151 type
= RAID_INSTANCE_WARNING_HOURS
;
19152 else if(time
> 300 && time
<= 900)
19153 type
= RAID_INSTANCE_WARNING_MIN
;
19155 type
= RAID_INSTANCE_WARNING_MIN_SOON
;
19157 WorldPacket
data(SMSG_RAID_INSTANCE_MESSAGE
, 4+4+4+4);
19158 data
<< uint32(type
);
19159 data
<< uint32(mapid
);
19160 data
<< uint32(difficulty
); // difficulty
19161 data
<< uint32(time
);
19162 if(type
== RAID_INSTANCE_WELCOME
)
19164 data
<< uint8(0); // is your (1)
19165 data
<< uint8(0); // is extended (1), ignored if prev field is 0
19167 GetSession()->SendPacket(&data
);
19170 void Player::ApplyEquipCooldown( Item
* pItem
)
19172 for(int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
19174 _Spell
const& spellData
= pItem
->GetProto()->Spells
[i
];
19177 if( !spellData
.SpellId
)
19180 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
19181 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
)
19184 AddSpellCooldown(spellData
.SpellId
, pItem
->GetEntry(), time(NULL
) + 30);
19186 WorldPacket
data(SMSG_ITEM_COOLDOWN
, 12);
19187 data
<< pItem
->GetGUID();
19188 data
<< uint32(spellData
.SpellId
);
19189 GetSession()->SendPacket(&data
);
19193 void Player::resetSpells()
19195 // not need after this call
19196 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS
))
19197 RemoveAtLoginFlag(AT_LOGIN_RESET_SPELLS
,true);
19199 // make full copy of map (spells removed and marked as deleted at another spell remove
19200 // and we can't use original map for safe iterative with visit each spell at loop end
19201 PlayerSpellMap smap
= GetSpellMap();
19203 for(PlayerSpellMap::const_iterator iter
= smap
.begin();iter
!= smap
.end(); ++iter
)
19204 removeSpell(iter
->first
,false,false); // only iter->first can be accessed, object by iter->second can be deleted already
19206 learnDefaultSpells();
19207 learnQuestRewardedSpells();
19210 void Player::learnDefaultSpells()
19212 // learn default race/class spells
19213 PlayerInfo
const *info
= sObjectMgr
.GetPlayerInfo(getRace(),getClass());
19214 for (PlayerCreateInfoSpells::const_iterator itr
= info
->spell
.begin(); itr
!=info
->spell
.end(); ++itr
)
19216 uint32 tspell
= *itr
;
19217 sLog
.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell
);
19218 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
19219 addSpell(tspell
,true,true,true,false);
19220 else // but send in normal spell in game learn case
19221 learnSpell(tspell
,true);
19225 void Player::learnQuestRewardedSpells(Quest
const* quest
)
19227 uint32 spell_id
= quest
->GetRewSpellCast();
19229 // skip quests without rewarded spell
19233 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
19237 // check learned spells state
19238 bool found
= false;
19239 for(int i
=0; i
< MAX_EFFECT_INDEX
; ++i
)
19241 if(spellInfo
->Effect
[i
] == SPELL_EFFECT_LEARN_SPELL
&& !HasSpell(spellInfo
->EffectTriggerSpell
[i
]))
19248 // skip quests with not teaching spell or already known spell
19252 // prevent learn non first rank unknown profession and second specialization for same profession)
19253 uint32 learned_0
= spellInfo
->EffectTriggerSpell
[EFFECT_INDEX_0
];
19254 if( sSpellMgr
.GetSpellRank(learned_0
) > 1 && !HasSpell(learned_0
) )
19256 // not have first rank learned (unlearned prof?)
19257 uint32 first_spell
= sSpellMgr
.GetFirstSpellInChain(learned_0
);
19258 if( !HasSpell(first_spell
) )
19261 SpellEntry
const *learnedInfo
= sSpellStore
.LookupEntry(learned_0
);
19266 if (learnedInfo
->Effect
[EFFECT_INDEX_0
] == SPELL_EFFECT_TRADE_SKILL
&& learnedInfo
->Effect
[EFFECT_INDEX_1
] == 0)
19268 // search other specialization for same prof
19269 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
19271 if(itr
->second
.state
== PLAYERSPELL_REMOVED
|| itr
->first
==learned_0
)
19274 SpellEntry
const *itrInfo
= sSpellStore
.LookupEntry(itr
->first
);
19278 // compare only specializations
19279 if (itrInfo
->Effect
[EFFECT_INDEX_0
] != SPELL_EFFECT_TRADE_SKILL
|| itrInfo
->Effect
[EFFECT_INDEX_1
] != 0)
19282 // compare same chain spells
19283 if(sSpellMgr
.GetFirstSpellInChain(itr
->first
) != first_spell
)
19286 // now we have 2 specialization, learn possible only if found is lesser specialization rank
19287 if(!sSpellMgr
.IsHighRankOfSpell(learned_0
,itr
->first
))
19293 CastSpell( this, spell_id
, true);
19296 void Player::learnQuestRewardedSpells()
19298 // learn spells received from quest completing
19299 for(QuestStatusMap::const_iterator itr
= mQuestStatus
.begin(); itr
!= mQuestStatus
.end(); ++itr
)
19301 // skip no rewarded quests
19302 if(!itr
->second
.m_rewarded
)
19305 Quest
const* quest
= sObjectMgr
.GetQuestTemplate(itr
->first
);
19309 learnQuestRewardedSpells(quest
);
19313 void Player::learnSkillRewardedSpells(uint32 skill_id
, uint32 skill_value
)
19315 uint32 raceMask
= getRaceMask();
19316 uint32 classMask
= getClassMask();
19317 for (uint32 j
=0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
19319 SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
);
19320 if (!pAbility
|| pAbility
->skillId
!=skill_id
|| pAbility
->learnOnGetSkill
!= ABILITY_LEARNED_ON_GET_PROFESSION_SKILL
)
19322 // Check race if set
19323 if (pAbility
->racemask
&& !(pAbility
->racemask
& raceMask
))
19325 // Check class if set
19326 if (pAbility
->classmask
&& !(pAbility
->classmask
& classMask
))
19329 if (sSpellStore
.LookupEntry(pAbility
->spellId
))
19331 // need unlearn spell
19332 if (skill_value
< pAbility
->req_skill_value
)
19333 removeSpell(pAbility
->spellId
);
19335 else if (!IsInWorld())
19336 addSpell(pAbility
->spellId
,true,true,true,false);
19338 learnSpell(pAbility
->spellId
,true);
19343 void Player::SendAurasForTarget(Unit
*target
)
19345 if(target
->GetVisibleAuras()->empty()) // speedup things
19348 WorldPacket
data(SMSG_AURA_UPDATE_ALL
);
19349 data
<< target
->GetPackGUID();
19351 Unit::VisibleAuraMap
const *visibleAuras
= target
->GetVisibleAuras();
19352 for(Unit::VisibleAuraMap::const_iterator itr
= visibleAuras
->begin(); itr
!= visibleAuras
->end(); ++itr
)
19354 for(int j
= 0; j
< MAX_EFFECT_INDEX
; ++j
)
19356 if(Aura
*aura
= target
->GetAura(itr
->second
, SpellEffectIndex(j
)))
19358 data
<< uint8(aura
->GetAuraSlot());
19359 data
<< uint32(aura
->GetId());
19363 uint8 auraFlags
= aura
->GetAuraFlags();
19365 data
<< uint8(auraFlags
);
19367 data
<< uint8(aura
->GetAuraLevel());
19369 if (aura
->GetAuraCharges())
19370 data
<< uint8(aura
->GetAuraCharges() * aura
->GetStackAmount());
19372 data
<< uint8(aura
->GetStackAmount());
19374 if(!(auraFlags
& AFLAG_NOT_CASTER
))
19376 data
<< uint8(0); // packed GUID of someone (caster?)
19379 if(auraFlags
& AFLAG_DURATION
) // include aura duration
19381 data
<< uint32(aura
->GetAuraMaxDuration());
19382 data
<< uint32(aura
->GetAuraDuration());
19390 GetSession()->SendPacket(&data
);
19393 void Player::SetDailyQuestStatus( uint32 quest_id
)
19395 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
19397 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
19399 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
19400 m_lastDailyQuestTime
= time(NULL
); // last daily quest time
19401 m_DailyQuestChanged
= true;
19407 void Player::ResetDailyQuestStatus()
19409 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
19410 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
19412 // DB data deleted in caller
19413 m_DailyQuestChanged
= false;
19414 m_lastDailyQuestTime
= 0;
19417 BattleGround
* Player::GetBattleGround() const
19419 if(GetBattleGroundId()==0)
19422 return sBattleGroundMgr
.GetBattleGround(GetBattleGroundId(), m_bgData
.bgTypeID
);
19425 bool Player::InArena() const
19427 BattleGround
*bg
= GetBattleGround();
19428 if(!bg
|| !bg
->isArena())
19434 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId
) const
19436 // get a template bg instead of running one
19437 BattleGround
*bg
= sBattleGroundMgr
.GetBattleGroundTemplate(bgTypeId
);
19441 // limit check leel to dbc compatible level range
19442 uint32 level
= getLevel();
19443 if (level
> DEFAULT_MAX_LEVEL
)
19444 level
= DEFAULT_MAX_LEVEL
;
19446 if(level
< bg
->GetMinLevel() || level
> bg
->GetMaxLevel())
19452 float Player::GetReputationPriceDiscount( Creature
const* pCreature
) const
19454 FactionTemplateEntry
const* vendor_faction
= pCreature
->getFactionTemplateEntry();
19455 if(!vendor_faction
|| !vendor_faction
->faction
)
19458 ReputationRank rank
= GetReputationRank(vendor_faction
->faction
);
19459 if(rank
<= REP_NEUTRAL
)
19462 return 1.0f
- 0.05f
* (rank
- REP_NEUTRAL
);
19465 bool Player::IsSpellFitByClassAndRace( uint32 spell_id
) const
19467 uint32 racemask
= getRaceMask();
19468 uint32 classmask
= getClassMask();
19470 SkillLineAbilityMapBounds bounds
= sSpellMgr
.GetSkillLineAbilityMapBounds(spell_id
);
19471 if (bounds
.first
==bounds
.second
)
19474 for(SkillLineAbilityMap::const_iterator _spell_idx
= bounds
.first
; _spell_idx
!= bounds
.second
; ++_spell_idx
)
19476 // skip wrong race skills
19477 if (_spell_idx
->second
->racemask
&& (_spell_idx
->second
->racemask
& racemask
) == 0)
19480 // skip wrong class skills
19481 if (_spell_idx
->second
->classmask
&& (_spell_idx
->second
->classmask
& classmask
) == 0)
19490 bool Player::HasQuestForGO(int32 GOId
) const
19492 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
19494 uint32 questid
= GetQuestSlotQuestId(i
);
19495 if ( questid
== 0 )
19498 QuestStatusMap::const_iterator qs_itr
= mQuestStatus
.find(questid
);
19499 if(qs_itr
== mQuestStatus
.end())
19502 QuestStatusData
const& qs
= qs_itr
->second
;
19504 if (qs
.m_status
== QUEST_STATUS_INCOMPLETE
)
19506 Quest
const* qinfo
= sObjectMgr
.GetQuestTemplate(questid
);
19510 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
19513 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
19515 if (qinfo
->ReqCreatureOrGOId
[j
]>=0) //skip non GO case
19518 if((-1)*GOId
== qinfo
->ReqCreatureOrGOId
[j
] && qs
.m_creatureOrGOcount
[j
] < qinfo
->ReqCreatureOrGOCount
[j
])
19526 void Player::UpdateForQuestWorldObjects()
19528 if(m_clientGUIDs
.empty())
19532 WorldPacket packet
;
19533 for(ObjectGuidSet::const_iterator itr
=m_clientGUIDs
.begin(); itr
!=m_clientGUIDs
.end(); ++itr
)
19535 if (itr
->IsGameobject())
19537 if (GameObject
*obj
= GetMap()->GetGameObject(*itr
))
19538 obj
->BuildValuesUpdateBlockForPlayer(&udata
,this);
19540 else if (itr
->IsCreatureOrVehicle())
19542 Creature
*obj
= GetMap()->GetCreatureOrPetOrVehicle(*itr
);
19546 // check if this unit requires quest specific flags
19547 if(!obj
->HasFlag(UNIT_NPC_FLAGS
,UNIT_NPC_FLAG_SPELLCLICK
))
19550 SpellClickInfoMapBounds clickPair
= sObjectMgr
.GetSpellClickInfoMapBounds(obj
->GetEntry());
19551 for(SpellClickInfoMap::const_iterator _itr
= clickPair
.first
; _itr
!= clickPair
.second
; ++_itr
)
19553 if(_itr
->second
.questStart
|| _itr
->second
.questEnd
)
19555 obj
->BuildCreateUpdateBlockForPlayer(&udata
,this);
19561 udata
.BuildPacket(&packet
);
19562 GetSession()->SendPacket(&packet
);
19565 void Player::SummonIfPossible(bool agree
)
19569 m_summon_expire
= 0;
19573 // expire and auto declined
19574 if(m_summon_expire
< time(NULL
))
19577 // stop taxi flight at summon
19580 GetMotionMaster()->MovementExpired();
19581 m_taxi
.ClearTaxiDestinations();
19584 // drop flag at summon
19585 // 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
19586 if(BattleGround
*bg
= GetBattleGround())
19587 bg
->EventPlayerDroppedFlag(this);
19589 m_summon_expire
= 0;
19591 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS
, 1);
19593 TeleportTo(m_summon_mapid
, m_summon_x
, m_summon_y
, m_summon_z
,GetOrientation());
19596 void Player::RemoveItemDurations( Item
*item
)
19598 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); ++itr
)
19602 m_itemDuration
.erase(itr
);
19608 void Player::AddItemDurations( Item
*item
)
19610 if(item
->GetUInt32Value(ITEM_FIELD_DURATION
))
19612 m_itemDuration
.push_back(item
);
19613 item
->SendTimeUpdate(this);
19617 void Player::AutoUnequipOffhandIfNeed()
19619 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
19623 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
19624 if (CanTitanGrip() || (offItem
->GetProto()->InventoryType
!= INVTYPE_2HWEAPON
&& !IsTwoHandUsed()))
19627 ItemPosCountVec off_dest
;
19628 uint8 off_msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false );
19629 if( off_msg
== EQUIP_ERR_OK
)
19631 RemoveItem(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
, true);
19632 StoreItem( off_dest
, offItem
, true );
19636 MoveItemFromInventory(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
, true);
19637 CharacterDatabase
.BeginTransaction();
19638 offItem
->DeleteFromInventoryDB(); // deletes item from character's inventory
19639 offItem
->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
19640 CharacterDatabase
.CommitTransaction();
19642 std::string subject
= GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM
);
19643 MailDraft(subject
).AddItem(offItem
).SendMailTo(this, MailSender(this, MAIL_STATIONERY_GM
));
19647 bool Player::HasItemFitToSpellReqirements(SpellEntry
const* spellInfo
, Item
const* ignoreItem
)
19649 if(spellInfo
->EquippedItemClass
< 0)
19652 // scan other equipped items for same requirements (mostly 2 daggers/etc)
19653 // for optimize check 2 used cases only
19654 switch(spellInfo
->EquippedItemClass
)
19656 case ITEM_CLASS_WEAPON
:
19658 for(int i
= EQUIPMENT_SLOT_MAINHAND
; i
< EQUIPMENT_SLOT_TABARD
; ++i
)
19659 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
19660 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
19664 case ITEM_CLASS_ARMOR
:
19666 // tabard not have dependent spells
19667 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_MAINHAND
; ++i
)
19668 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
19669 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
19672 // shields can be equipped to offhand slot
19673 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
))
19674 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
19677 // ranged slot can have some armor subclasses
19678 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_RANGED
))
19679 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
19685 sLog
.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo
->EquippedItemClass
);
19692 bool Player::CanNoReagentCast(SpellEntry
const* spellInfo
) const
19694 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
19695 if (spellInfo
->AttributesEx5
& SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
&&
19696 HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PREPARATION
))
19699 // Check no reagent use mask
19700 uint64 noReagentMask_0_1
= GetUInt64Value(PLAYER_NO_REAGENT_COST_1
);
19701 uint32 noReagentMask_2
= GetUInt32Value(PLAYER_NO_REAGENT_COST_1
+2);
19702 if (spellInfo
->SpellFamilyFlags
& noReagentMask_0_1
||
19703 spellInfo
->SpellFamilyFlags2
& noReagentMask_2
)
19709 void Player::RemoveItemDependentAurasAndCasts( Item
* pItem
)
19711 AuraMap
& auras
= GetAuras();
19712 for(AuraMap::const_iterator itr
= auras
.begin(); itr
!= auras
.end(); )
19714 Aura
* aura
= itr
->second
;
19716 // skip passive (passive item dependent spells work in another way) and not self applied auras
19717 SpellEntry
const* spellInfo
= aura
->GetSpellProto();
19718 if(aura
->IsPassive() || aura
->GetCasterGUID()!=GetGUID())
19724 // skip if not item dependent or have alternative item
19725 if(HasItemFitToSpellReqirements(spellInfo
,pItem
))
19731 // no alt item, remove aura, restart check
19732 RemoveAurasDueToSpell(aura
->GetId());
19733 itr
= auras
.begin();
19736 // currently casted spells can be dependent from item
19737 for (uint32 i
= 0; i
< CURRENT_MAX_SPELL
; ++i
)
19738 if (Spell
* spell
= GetCurrentSpell(CurrentSpellTypes(i
)))
19739 if (spell
->getState()!=SPELL_STATE_DELAYED
&& !HasItemFitToSpellReqirements(spell
->m_spellInfo
,pItem
) )
19740 InterruptSpell(CurrentSpellTypes(i
));
19743 uint32
Player::GetResurrectionSpellId()
19745 // search priceless resurrection possibilities
19747 uint32 spell_id
= 0;
19748 AuraList
const& dummyAuras
= GetAurasByType(SPELL_AURA_DUMMY
);
19749 for(AuraList::const_iterator itr
= dummyAuras
.begin(); itr
!= dummyAuras
.end(); ++itr
)
19751 // Soulstone Resurrection // prio: 3 (max, non death persistent)
19752 if( prio
< 2 && (*itr
)->GetSpellProto()->SpellVisual
[0] == 99 && (*itr
)->GetSpellProto()->SpellIconID
== 92 )
19754 switch((*itr
)->GetId())
19756 case 20707: spell_id
= 3026; break; // rank 1
19757 case 20762: spell_id
= 20758; break; // rank 2
19758 case 20763: spell_id
= 20759; break; // rank 3
19759 case 20764: spell_id
= 20760; break; // rank 4
19760 case 20765: spell_id
= 20761; break; // rank 5
19761 case 27239: spell_id
= 27240; break; // rank 6
19762 case 47883: spell_id
= 47882; break; // rank 7
19764 sLog
.outError("Unhandled spell %u: S.Resurrection",(*itr
)->GetId());
19770 // Twisting Nether // prio: 2 (max)
19771 else if((*itr
)->GetId()==23701 && roll_chance_i(10))
19778 // Reincarnation (passive spell) // prio: 1
19779 // Glyph of Renewed Life remove reagent requiremnnt
19780 if (prio
< 1 && HasSpell(20608) && !HasSpellCooldown(21169) && (HasItemCount(17030,1) || HasAura(58059, EFFECT_INDEX_0
)))
19786 // Used in triggers for check "Only to targets that grant experience or honor" req
19787 bool Player::isHonorOrXPTarget(Unit
* pVictim
) const
19789 uint32 v_level
= pVictim
->getLevel();
19790 uint32 k_grey
= MaNGOS::XP::GetGrayLevel(getLevel());
19792 // Victim level less gray level
19793 if(v_level
<=k_grey
)
19796 if(pVictim
->GetTypeId() == TYPEID_UNIT
)
19798 if (((Creature
*)pVictim
)->isTotem() ||
19799 ((Creature
*)pVictim
)->isPet() ||
19800 ((Creature
*)pVictim
)->GetCreatureInfo()->flags_extra
& CREATURE_FLAG_EXTRA_NO_XP_AT_KILL
)
19806 bool Player::RewardPlayerAndGroupAtKill(Unit
* pVictim
)
19808 bool PvP
= pVictim
->isCharmedOwnedByPlayerOrPlayer();
19810 // prepare data for near group iteration (PvP and !PvP cases)
19812 bool honored_kill
= false;
19814 if(Group
*pGroup
= GetGroup())
19817 uint32 sum_level
= 0;
19818 Player
* member_with_max_level
= NULL
;
19819 Player
* not_gray_member_with_max_level
= NULL
;
19821 pGroup
->GetDataForXPAtKill(pVictim
,count
,sum_level
,member_with_max_level
,not_gray_member_with_max_level
);
19823 if(member_with_max_level
)
19825 /// not get Xp in PvP or no not gray players in group
19826 xp
= (PvP
|| !not_gray_member_with_max_level
) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level
, pVictim
);
19828 /// skip in check PvP case (for speed, not used)
19829 bool is_raid
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsRaid() && pGroup
->isRaidGroup();
19830 bool is_dungeon
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsDungeon();
19831 float group_rate
= MaNGOS::XP::xp_in_group_rate(count
,is_raid
);
19833 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
19835 Player
* pGroupGuy
= itr
->getSource();
19839 if(!pGroupGuy
->IsAtGroupRewardDistance(pVictim
))
19840 continue; // member (alive or dead) or his corpse at req. distance
19842 // honor can be in PvP and !PvP (racial leader) cases (for alive)
19843 if(pGroupGuy
->isAlive() && pGroupGuy
->RewardHonor(pVictim
,count
) && pGroupGuy
==this)
19844 honored_kill
= true;
19846 // xp and reputation only in !PvP case
19849 float rate
= group_rate
* float(pGroupGuy
->getLevel()) / sum_level
;
19851 // if is in dungeon then all receive full reputation at kill
19852 // rewarded any alive/dead/near_corpse group member
19853 pGroupGuy
->RewardReputation(pVictim
,is_dungeon
? 1.0f
: rate
);
19855 // XP updated only for alive group member
19856 if(pGroupGuy
->isAlive() && not_gray_member_with_max_level
&&
19857 pGroupGuy
->getLevel() <= not_gray_member_with_max_level
->getLevel())
19859 uint32 itr_xp
= (member_with_max_level
== not_gray_member_with_max_level
) ? uint32(xp
*rate
) : uint32((xp
*rate
/2)+1);
19861 pGroupGuy
->GiveXP(itr_xp
, pVictim
);
19862 if(Pet
* pet
= pGroupGuy
->GetPet())
19863 pet
->GivePetXP(itr_xp
/2);
19866 // quest objectives updated only for alive group member or dead but with not released body
19867 if(pGroupGuy
->isAlive()|| !pGroupGuy
->GetCorpse())
19869 // normal creature (not pet/etc) can be only in !PvP case
19870 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
19871 pGroupGuy
->KilledMonster(((Creature
*)pVictim
)->GetCreatureInfo(), pVictim
->GetGUID());
19877 else // if (!pGroup)
19879 xp
= PvP
? 0 : MaNGOS::XP::Gain(this, pVictim
);
19881 // honor can be in PvP and !PvP (racial leader) cases
19882 if(RewardHonor(pVictim
,1))
19883 honored_kill
= true;
19885 // xp and reputation only in !PvP case
19888 RewardReputation(pVictim
,1);
19889 GiveXP(xp
, pVictim
);
19891 if(Pet
* pet
= GetPet())
19892 pet
->GivePetXP(xp
);
19894 // normal creature (not pet/etc) can be only in !PvP case
19895 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
19896 KilledMonster(((Creature
*)pVictim
)->GetCreatureInfo(), pVictim
->GetGUID());
19899 return xp
|| honored_kill
;
19902 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id
, WorldObject
* pRewardSource
)
19904 uint64 creature_guid
= pRewardSource
->GetTypeId()==TYPEID_UNIT
? pRewardSource
->GetGUID() : uint64(0);
19906 // prepare data for near group iteration
19907 if(Group
*pGroup
= GetGroup())
19909 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
19911 Player
* pGroupGuy
= itr
->getSource();
19915 if(!pGroupGuy
->IsAtGroupRewardDistance(pRewardSource
))
19916 continue; // member (alive or dead) or his corpse at req. distance
19918 // quest objectives updated only for alive group member or dead but with not released body
19919 if(pGroupGuy
->isAlive()|| !pGroupGuy
->GetCorpse())
19920 pGroupGuy
->KilledMonsterCredit(creature_id
, creature_guid
);
19923 else // if (!pGroup)
19924 KilledMonsterCredit(creature_id
, creature_guid
);
19927 bool Player::IsAtGroupRewardDistance(WorldObject
const* pRewardSource
) const
19929 if (pRewardSource
->IsWithinDistInMap(this,sWorld
.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE
)))
19935 Corpse
* corpse
= GetCorpse();
19939 return pRewardSource
->IsWithinDistInMap(corpse
,sWorld
.getConfig(CONFIG_FLOAT_GROUP_XP_DISTANCE
));
19942 uint32
Player::GetBaseWeaponSkillValue (WeaponAttackType attType
) const
19944 Item
* item
= GetWeaponForAttack(attType
,true,true);
19946 // unarmed only with base attack
19947 if(attType
!= BASE_ATTACK
&& !item
)
19950 // weapon skill or (unarmed for base attack)
19951 uint32 skill
= item
? item
->GetSkill() : uint32(SKILL_UNARMED
);
19952 return GetBaseSkillValue(skill
);
19955 void Player::ResurectUsingRequestData()
19957 /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
19958 if(IS_PLAYER_GUID(m_resurrectGUID
))
19959 TeleportTo(m_resurrectMap
, m_resurrectX
, m_resurrectY
, m_resurrectZ
, GetOrientation());
19961 //we cannot resurrect player when we triggered far teleport
19962 //player will be resurrected upon teleportation
19963 if(IsBeingTeleportedFar())
19965 ScheduleDelayedOperation(DELAYED_RESURRECT_PLAYER
);
19969 ResurrectPlayer(0.0f
,false);
19971 if(GetMaxHealth() > m_resurrectHealth
)
19972 SetHealth( m_resurrectHealth
);
19974 SetHealth( GetMaxHealth() );
19976 if(GetMaxPower(POWER_MANA
) > m_resurrectMana
)
19977 SetPower(POWER_MANA
, m_resurrectMana
);
19979 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
) );
19981 SetPower(POWER_RAGE
, 0 );
19983 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
) );
19985 SpawnCorpseBones();
19988 void Player::SetClientControl(Unit
* target
, uint8 allowMove
)
19990 WorldPacket
data(SMSG_CLIENT_CONTROL_UPDATE
, target
->GetPackGUID().size()+1);
19991 data
<< target
->GetPackGUID();
19992 data
<< uint8(allowMove
);
19993 GetSession()->SendPacket(&data
);
19996 void Player::UpdateZoneDependentAuras( uint32 newZone
)
19998 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
19999 SpellAreaForAreaMapBounds saBounds
= sSpellMgr
.GetSpellAreaForAreaMapBounds(newZone
);
20000 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
20001 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,newZone
,0))
20002 if (!HasAura(itr
->second
->spellId
, EFFECT_INDEX_0
))
20003 CastSpell(this,itr
->second
->spellId
,true);
20006 void Player::UpdateAreaDependentAuras( uint32 newArea
)
20008 // remove auras from spells with area limitations
20009 for(AuraMap::iterator iter
= m_Auras
.begin(); iter
!= m_Auras
.end();)
20011 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
20012 if(sSpellMgr
.GetSpellAllowedInLocationError(iter
->second
->GetSpellProto(),GetMapId(),m_zoneUpdateId
,newArea
,this) != SPELL_CAST_OK
)
20018 // some auras applied at subzone enter
20019 SpellAreaForAreaMapBounds saBounds
= sSpellMgr
.GetSpellAreaForAreaMapBounds(newArea
);
20020 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
20021 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,m_zoneUpdateId
,newArea
))
20022 if (!HasAura(itr
->second
->spellId
, EFFECT_INDEX_0
))
20023 CastSpell(this,itr
->second
->spellId
,true);
20026 uint32
Player::GetCorpseReclaimDelay(bool pvp
) const
20028 if ((pvp
&& !sWorld
.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP
)) ||
20029 (!pvp
&& !sWorld
.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE
) ))
20031 return copseReclaimDelay
[0];
20034 time_t now
= time(NULL
);
20035 // 0..2 full period
20036 uint32 count
= (now
< m_deathExpireTime
) ? uint32((m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
) : 0;
20037 return copseReclaimDelay
[count
];
20040 void Player::UpdateCorpseReclaimDelay()
20042 bool pvp
= m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
;
20044 if ((pvp
&& !sWorld
.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP
)) ||
20045 (!pvp
&& !sWorld
.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE
) ))
20048 time_t now
= time(NULL
);
20049 if(now
< m_deathExpireTime
)
20051 // full and partly periods 1..3
20052 uint32 count
= uint32((m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
+1);
20053 if(count
< MAX_DEATH_COUNT
)
20054 m_deathExpireTime
= now
+(count
+1)*DEATH_EXPIRE_STEP
;
20056 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
;
20059 m_deathExpireTime
= now
+DEATH_EXPIRE_STEP
;
20062 void Player::SendCorpseReclaimDelay(bool load
)
20064 Corpse
* corpse
= GetCorpse();
20071 if(corpse
->GetGhostTime() > m_deathExpireTime
)
20074 bool pvp
= corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
;
20077 if( pvp
&& sWorld
.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
20078 !pvp
&& sWorld
.getConfig(CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
20080 count
= uint32(m_deathExpireTime
-corpse
->GetGhostTime())/DEATH_EXPIRE_STEP
;
20081 if(count
>=MAX_DEATH_COUNT
)
20082 count
= MAX_DEATH_COUNT
-1;
20087 time_t expected_time
= corpse
->GetGhostTime()+copseReclaimDelay
[count
];
20089 time_t now
= time(NULL
);
20090 if(now
>= expected_time
)
20093 delay
= uint32(expected_time
-now
);
20096 delay
= GetCorpseReclaimDelay(corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
);
20098 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
20099 WorldPacket
data(SMSG_CORPSE_RECLAIM_DELAY
, 4);
20100 data
<< uint32(delay
*IN_MILISECONDS
);
20101 GetSession()->SendPacket( &data
);
20104 Player
* Player::GetNextRandomRaidMember(float radius
)
20106 Group
*pGroup
= GetGroup();
20110 std::vector
<Player
*> nearMembers
;
20111 nearMembers
.reserve(pGroup
->GetMembersCount());
20113 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
20115 Player
* Target
= itr
->getSource();
20117 // IsHostileTo check duel and controlled by enemy
20118 if( Target
&& Target
!= this && IsWithinDistInMap(Target
, radius
) &&
20119 !Target
->HasInvisibilityAura() && !IsHostileTo(Target
) )
20120 nearMembers
.push_back(Target
);
20123 if (nearMembers
.empty())
20126 uint32 randTarget
= urand(0,nearMembers
.size()-1);
20127 return nearMembers
[randTarget
];
20130 PartyResult
Player::CanUninviteFromGroup() const
20132 const Group
* grp
= GetGroup();
20134 return PARTY_RESULT_YOU_NOT_IN_GROUP
;
20136 if(!grp
->IsLeader(GetGUID()) && !grp
->IsAssistant(GetGUID()))
20137 return PARTY_RESULT_YOU_NOT_LEADER
;
20139 if(InBattleGround())
20140 return PARTY_RESULT_INVITE_RESTRICTED
;
20142 return PARTY_RESULT_OK
;
20145 void Player::SetBattleGroundRaid(Group
* group
, int8 subgroup
)
20147 //we must move references from m_group to m_originalGroup
20148 SetOriginalGroup(GetGroup(), GetSubGroup());
20151 m_group
.link(group
, this);
20152 m_group
.setSubGroup((uint8
)subgroup
);
20155 void Player::RemoveFromBattleGroundRaid()
20157 //remove existing reference
20159 if( Group
* group
= GetOriginalGroup() )
20161 m_group
.link(group
, this);
20162 m_group
.setSubGroup(GetOriginalSubGroup());
20164 SetOriginalGroup(NULL
);
20167 void Player::SetOriginalGroup(Group
*group
, int8 subgroup
)
20169 if( group
== NULL
)
20170 m_originalGroup
.unlink();
20173 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
20174 assert(subgroup
>= 0);
20175 m_originalGroup
.link(group
, this);
20176 m_originalGroup
.setSubGroup((uint8
)subgroup
);
20180 void Player::UpdateUnderwaterState( Map
* m
, float x
, float y
, float z
)
20182 LiquidData liquid_status
;
20183 ZLiquidStatus res
= m
->getLiquidStatus(x
, y
, z
, MAP_ALL_LIQUIDS
, &liquid_status
);
20186 m_MirrorTimerFlags
&= ~(UNDERWATER_INWATER
|UNDERWATER_INLAVA
|UNDERWATER_INSLIME
|UNDERWARER_INDARKWATER
);
20187 // Small hack for enable breath in WMO
20189 m_MirrorTimerFlags
|=UNDERWATER_INWATER
;
20193 // All liquids type - check under water position
20194 if (liquid_status
.type
&(MAP_LIQUID_TYPE_WATER
|MAP_LIQUID_TYPE_OCEAN
|MAP_LIQUID_TYPE_MAGMA
|MAP_LIQUID_TYPE_SLIME
))
20196 if ( res
& LIQUID_MAP_UNDER_WATER
)
20197 m_MirrorTimerFlags
|= UNDERWATER_INWATER
;
20199 m_MirrorTimerFlags
&= ~UNDERWATER_INWATER
;
20202 // Allow travel in dark water on taxi or transport
20203 if ((liquid_status
.type
& MAP_LIQUID_TYPE_DARK_WATER
) && !isInFlight() && !GetTransport())
20204 m_MirrorTimerFlags
|= UNDERWARER_INDARKWATER
;
20206 m_MirrorTimerFlags
&= ~UNDERWARER_INDARKWATER
;
20208 // in lava check, anywhere in lava level
20209 if (liquid_status
.type
&MAP_LIQUID_TYPE_MAGMA
)
20211 if (res
& (LIQUID_MAP_UNDER_WATER
|LIQUID_MAP_IN_WATER
|LIQUID_MAP_WATER_WALK
))
20212 m_MirrorTimerFlags
|= UNDERWATER_INLAVA
;
20214 m_MirrorTimerFlags
&= ~UNDERWATER_INLAVA
;
20216 // in slime check, anywhere in slime level
20217 if (liquid_status
.type
&MAP_LIQUID_TYPE_SLIME
)
20219 if (res
& (LIQUID_MAP_UNDER_WATER
|LIQUID_MAP_IN_WATER
|LIQUID_MAP_WATER_WALK
))
20220 m_MirrorTimerFlags
|= UNDERWATER_INSLIME
;
20222 m_MirrorTimerFlags
&= ~UNDERWATER_INSLIME
;
20226 void Player::SetCanParry( bool value
)
20228 if(m_canParry
==value
)
20231 m_canParry
= value
;
20232 UpdateParryPercentage();
20235 void Player::SetCanBlock( bool value
)
20237 if(m_canBlock
==value
)
20240 m_canBlock
= value
;
20241 UpdateBlockPercentage();
20244 bool ItemPosCount::isContainedIn(ItemPosCountVec
const& vec
) const
20246 for(ItemPosCountVec::const_iterator itr
= vec
.begin(); itr
!= vec
.end();++itr
)
20247 if(itr
->pos
== pos
)
20253 bool Player::CanUseBattleGroundObject()
20255 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
20256 // maybe gameobject code should handle that ForceReaction usage
20257 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
20258 return ( //InBattleGround() && // in battleground - not need, check in other cases
20259 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
20260 //player cannot use object when he is invulnerable (immune)
20261 !isTotalImmune() && // not totally immune
20262 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
20263 !HasStealthAura() && // not stealthed
20264 !HasInvisibilityAura() && // not invisible
20265 !HasAura(SPELL_RECENTLY_DROPPED_FLAG
, EFFECT_INDEX_0
) &&// can't pickup
20266 isAlive() // live player
20270 bool Player::CanCaptureTowerPoint()
20272 return ( !HasStealthAura() && // not stealthed
20273 !HasInvisibilityAura() && // not invisible
20274 isAlive() // live player
20278 uint32
Player::GetBarberShopCost(uint8 newhairstyle
, uint8 newhaircolor
, uint8 newfacialhair
)
20280 uint32 level
= getLevel();
20282 if(level
> GT_MAX_LEVEL
)
20283 level
= GT_MAX_LEVEL
; // max level in this dbc
20285 uint8 hairstyle
= GetByteValue(PLAYER_BYTES
, 2);
20286 uint8 haircolor
= GetByteValue(PLAYER_BYTES
, 3);
20287 uint8 facialhair
= GetByteValue(PLAYER_BYTES_2
, 0);
20289 if((hairstyle
== newhairstyle
) && (haircolor
== newhaircolor
) && (facialhair
== newfacialhair
))
20292 GtBarberShopCostBaseEntry
const *bsc
= sGtBarberShopCostBaseStore
.LookupEntry(level
- 1);
20294 if(!bsc
) // shouldn't happen
20299 if(hairstyle
!= newhairstyle
)
20300 cost
+= bsc
->cost
; // full price
20302 if((haircolor
!= newhaircolor
) && (hairstyle
== newhairstyle
))
20303 cost
+= bsc
->cost
* 0.5f
; // +1/2 of price
20305 if(facialhair
!= newfacialhair
)
20306 cost
+= bsc
->cost
* 0.75f
; // +3/4 of price
20308 return uint32(cost
);
20311 void Player::InitGlyphsForLevel()
20313 for(uint32 i
= 0; i
< sGlyphSlotStore
.GetNumRows(); ++i
)
20314 if(GlyphSlotEntry
const * gs
= sGlyphSlotStore
.LookupEntry(i
))
20316 SetGlyphSlot(gs
->Order
- 1, gs
->Id
);
20318 uint32 level
= getLevel();
20321 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
20323 value
|= (0x01 | 0x02);
20333 SetUInt32Value(PLAYER_GLYPHS_ENABLED
, value
);
20336 void Player::ApplyGlyph(uint8 slot
, bool apply
)
20338 if (uint32 glyph
= GetGlyph(slot
))
20340 if(GlyphPropertiesEntry
const *gp
= sGlyphPropertiesStore
.LookupEntry(glyph
))
20344 CastSpell(this, gp
->SpellId
, true);
20345 SetUInt32Value(PLAYER_FIELD_GLYPHS_1
+ slot
, glyph
);
20349 RemoveAurasDueToSpell(gp
->SpellId
);
20350 SetUInt32Value(PLAYER_FIELD_GLYPHS_1
+ slot
, 0);
20356 void Player::ApplyGlyphs(bool apply
)
20358 for (uint8 i
= 0; i
< MAX_GLYPH_SLOT_INDEX
; ++i
)
20359 ApplyGlyph(i
,apply
);
20362 void Player::EnterVehicle(Vehicle
*vehicle
)
20364 VehicleEntry
const *ve
= sVehicleStore
.LookupEntry(vehicle
->GetVehicleId());
20368 VehicleSeatEntry
const *veSeat
= sVehicleSeatStore
.LookupEntry(ve
->m_seatID
[0]);
20372 vehicle
->SetCharmerGUID(GetGUID());
20373 vehicle
->RemoveFlag(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_SPELLCLICK
);
20374 vehicle
->SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PLAYER_CONTROLLED
);
20375 vehicle
->setFaction(getFaction());
20377 SetCharm(vehicle
); // charm
20378 SetFarSightGUID(vehicle
->GetGUID()); // set view
20380 SetClientControl(vehicle
, 1); // redirect controls to vehicle
20383 WorldPacket
data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA
, 0);
20384 GetSession()->SendPacket(&data
);
20386 data
.Initialize(MSG_MOVE_TELEPORT_ACK
, 30);
20387 data
<< GetPackGUID();
20388 data
<< uint32(0); // counter?
20389 data
<< uint32(MOVEFLAG_ONTRANSPORT
); // transport
20390 data
<< uint16(0); // special flags
20391 data
<< uint32(getMSTime()); // time
20392 data
<< vehicle
->GetPositionX(); // x
20393 data
<< vehicle
->GetPositionY(); // y
20394 data
<< vehicle
->GetPositionZ(); // z
20395 data
<< vehicle
->GetOrientation(); // o
20396 // transport part, TODO: load/calculate seat offsets
20397 data
<< uint64(vehicle
->GetGUID()); // transport guid
20398 data
<< float(veSeat
->m_attachmentOffsetX
); // transport offsetX
20399 data
<< float(veSeat
->m_attachmentOffsetY
); // transport offsetY
20400 data
<< float(veSeat
->m_attachmentOffsetZ
); // transport offsetZ
20401 data
<< float(0); // transport orientation
20402 data
<< uint32(getMSTime()); // transport time
20403 data
<< uint8(0); // seat
20404 // end of transport part
20405 data
<< uint32(0); // fall time
20406 GetSession()->SendPacket(&data
);
20408 data
.Initialize(SMSG_PET_SPELLS
, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX
+1+1);
20409 data
<< uint64(vehicle
->GetGUID());
20412 data
<< uint32(0x00000101);
20414 for(uint32 i
= 0; i
< 10; ++i
)
20415 data
<< uint16(0) << uint8(0) << uint8(i
+8);
20419 GetSession()->SendPacket(&data
);
20422 void Player::ExitVehicle(Vehicle
*vehicle
)
20424 vehicle
->SetCharmerGUID(0);
20425 vehicle
->SetFlag(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_SPELLCLICK
);
20426 vehicle
->RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PLAYER_CONTROLLED
);
20427 vehicle
->setFaction((GetTeam() == ALLIANCE
) ? vehicle
->GetCreatureInfo()->faction_A
: vehicle
->GetCreatureInfo()->faction_H
);
20430 SetFarSightGUID(0);
20432 SetClientControl(vehicle
, 0);
20435 WorldPacket
data(MSG_MOVE_TELEPORT_ACK
, 30);
20436 data
<< GetPackGUID();
20437 data
<< uint32(0); // counter?
20438 data
<< uint32(MOVEFLAG_ROOT
); // fly unk
20439 data
<< uint16(MOVEFLAG2_UNK4
); // special flags
20440 data
<< uint32(getMSTime()); // time
20441 data
<< vehicle
->GetPositionX(); // x
20442 data
<< vehicle
->GetPositionY(); // y
20443 data
<< vehicle
->GetPositionZ(); // z
20444 data
<< vehicle
->GetOrientation(); // o
20445 data
<< uint32(0); // fall time
20446 GetSession()->SendPacket(&data
);
20448 RemovePetActionBar();
20450 // maybe called at dummy aura remove?
20451 // CastSpell(this, 45472, true); // Parachute
20454 bool Player::isTotalImmune()
20456 AuraList
const& immune
= GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY
);
20458 uint32 immuneMask
= 0;
20459 for(AuraList::const_iterator itr
= immune
.begin(); itr
!= immune
.end(); ++itr
)
20461 immuneMask
|= (*itr
)->GetModifier()->m_miscvalue
;
20462 if( immuneMask
& SPELL_SCHOOL_MASK_ALL
) // total immunity
20468 bool Player::HasTitle(uint32 bitIndex
)
20470 if (bitIndex
> MAX_TITLE_INDEX
)
20473 uint32 fieldIndexOffset
= bitIndex
/ 32;
20474 uint32 flag
= 1 << (bitIndex
% 32);
20475 return HasFlag(PLAYER__FIELD_KNOWN_TITLES
+ fieldIndexOffset
, flag
);
20478 void Player::SetTitle(CharTitlesEntry
const* title
, bool lost
)
20480 uint32 fieldIndexOffset
= title
->bit_index
/ 32;
20481 uint32 flag
= 1 << (title
->bit_index
% 32);
20485 if(!HasFlag(PLAYER__FIELD_KNOWN_TITLES
+ fieldIndexOffset
, flag
))
20488 RemoveFlag(PLAYER__FIELD_KNOWN_TITLES
+ fieldIndexOffset
, flag
);
20492 if(HasFlag(PLAYER__FIELD_KNOWN_TITLES
+ fieldIndexOffset
, flag
))
20495 SetFlag(PLAYER__FIELD_KNOWN_TITLES
+ fieldIndexOffset
, flag
);
20498 WorldPacket
data(SMSG_TITLE_EARNED
, 4 + 4);
20499 data
<< uint32(title
->bit_index
);
20500 data
<< uint32(lost
? 0 : 1); // 1 - earned, 0 - lost
20501 GetSession()->SendPacket(&data
);
20504 void Player::ConvertRune(uint8 index
, RuneType newType
)
20506 SetCurrentRune(index
, newType
);
20508 WorldPacket
data(SMSG_CONVERT_RUNE
, 2);
20509 data
<< uint8(index
);
20510 data
<< uint8(newType
);
20511 GetSession()->SendPacket(&data
);
20514 void Player::ResyncRunes(uint8 count
)
20516 WorldPacket
data(SMSG_RESYNC_RUNES
, count
* 2);
20517 for(uint32 i
= 0; i
< count
; ++i
)
20519 data
<< uint8(GetCurrentRune(i
)); // rune type
20520 data
<< uint8(255 - ((GetRuneCooldown(i
) / REGEN_TIME_FULL
) * 51)); // passed cooldown time (0-255)
20522 GetSession()->SendPacket(&data
);
20525 void Player::AddRunePower(uint8 index
)
20527 WorldPacket
data(SMSG_ADD_RUNE_POWER
, 4);
20528 data
<< uint32(1 << index
); // mask (0x00-0x3F probably)
20529 GetSession()->SendPacket(&data
);
20532 static RuneType runeSlotTypes
[MAX_RUNES
] = {
20541 void Player::InitRunes()
20543 if(getClass() != CLASS_DEATH_KNIGHT
)
20546 m_runes
= new Runes
;
20548 m_runes
->runeState
= 0;
20550 for(uint32 i
= 0; i
< MAX_RUNES
; ++i
)
20552 SetBaseRune(i
, runeSlotTypes
[i
]); // init base types
20553 SetCurrentRune(i
, runeSlotTypes
[i
]); // init current types
20554 SetRuneCooldown(i
, 0); // reset cooldowns
20555 m_runes
->SetRuneState(i
);
20558 for(uint32 i
= 0; i
< NUM_RUNE_TYPES
; ++i
)
20559 SetFloatValue(PLAYER_RUNE_REGEN_1
+ i
, 0.1f
);
20563 bool Player::IsBaseRuneSlotsOnCooldown( RuneType runeType
) const
20565 for(uint32 i
= 0; i
< MAX_RUNES
; ++i
)
20566 if (GetBaseRune(i
) == runeType
&& GetRuneCooldown(i
) == 0)
20572 void Player::AutoStoreLoot(uint8 bag
, uint8 slot
, uint32 loot_id
, LootStore
const& store
, bool broadcast
)
20575 loot
.FillLoot (loot_id
,store
,this,true);
20577 uint32 max_slot
= loot
.GetMaxSlotInLootFor(this);
20578 for(uint32 i
= 0; i
< max_slot
; ++i
)
20580 LootItem
* lootItem
= loot
.LootItemInSlot(i
,this);
20582 ItemPosCountVec dest
;
20583 uint8 msg
= CanStoreNewItem (bag
,slot
,dest
,lootItem
->itemid
,lootItem
->count
);
20584 if(msg
!= EQUIP_ERR_OK
&& slot
!= NULL_SLOT
)
20585 msg
= CanStoreNewItem( bag
, NULL_SLOT
,dest
,lootItem
->itemid
,lootItem
->count
);
20586 if( msg
!= EQUIP_ERR_OK
&& bag
!= NULL_BAG
)
20587 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
,dest
,lootItem
->itemid
,lootItem
->count
);
20588 if(msg
!= EQUIP_ERR_OK
)
20590 SendEquipError( msg
, NULL
, NULL
, lootItem
->itemid
);
20594 Item
* pItem
= StoreNewItem (dest
,lootItem
->itemid
,true,lootItem
->randomPropertyId
);
20595 SendNewItem(pItem
, lootItem
->count
, false, false, broadcast
);
20599 uint32
Player::CalculateTalentsPoints() const
20601 uint32 base_talent
= getLevel() < 10 ? 0 : getLevel()-9;
20603 if(getClass() != CLASS_DEATH_KNIGHT
)
20604 return uint32(base_talent
* sWorld
.getConfig(CONFIG_FLOAT_RATE_TALENT
));
20606 uint32 talentPointsForLevel
= getLevel() < 56 ? 0 : getLevel() - 55;
20607 talentPointsForLevel
+= m_questRewardTalentCount
;
20609 if(talentPointsForLevel
> base_talent
)
20610 talentPointsForLevel
= base_talent
;
20612 return uint32(talentPointsForLevel
* sWorld
.getConfig(CONFIG_FLOAT_RATE_TALENT
));
20615 bool Player::IsKnowHowFlyIn(uint32 mapid
, uint32 zone
) const
20617 // continent checked in SpellMgr::GetSpellAllowedInLocationError at cast and area update
20618 uint32 v_map
= GetVirtualMapForMapAndZone(mapid
, zone
);
20619 return v_map
!= 571 || HasSpell(54197); // Cold Weather Flying
20622 struct DoPlayerLearnSpell
20624 DoPlayerLearnSpell(Player
& _player
) : player(_player
) {}
20625 void operator() (uint32 spell_id
) { player
.learnSpell(spell_id
,false); }
20629 void Player::learnSpellHighRank(uint32 spellid
)
20631 learnSpell(spellid
,false);
20633 DoPlayerLearnSpell
worker(*this);
20634 sSpellMgr
.doForHighRanks(spellid
,worker
);
20637 void Player::_LoadSkills(QueryResult
*result
)
20640 // SetPQuery(PLAYER_LOGIN_QUERY_LOADSKILLS, "SELECT skill, value, max FROM character_skills WHERE guid = '%u'", GUID_LOPART(m_guid));
20647 Field
*fields
= result
->Fetch();
20649 uint16 skill
= fields
[0].GetUInt16();
20650 uint16 value
= fields
[1].GetUInt16();
20651 uint16 max
= fields
[2].GetUInt16();
20653 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(skill
);
20656 sLog
.outError("Character %u has skill %u that does not exist.", GetGUIDLow(), skill
);
20660 // set fixed skill ranges
20661 switch(GetSkillRangeType(pSkill
,false))
20663 case SKILL_RANGE_LANGUAGE
: // 300..300
20666 case SKILL_RANGE_MONO
: // 1..1, grey monolite bar
20675 sLog
.outError("Character %u has skill %u with value 0. Will be deleted.", GetGUIDLow(), skill
);
20676 CharacterDatabase
.PExecute("DELETE FROM character_skills WHERE guid = '%u' AND skill = '%u' ", GetGUIDLow(), skill
);
20680 // enable unlearn button for primary professions only
20681 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
20682 SetUInt32Value(PLAYER_SKILL_INDEX(count
), MAKE_PAIR32(skill
,1));
20684 SetUInt32Value(PLAYER_SKILL_INDEX(count
), MAKE_PAIR32(skill
,0));
20686 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count
),MAKE_SKILL_VALUE(value
, max
));
20687 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count
),0);
20689 mSkillStatus
.insert(SkillStatusMap::value_type(skill
, SkillStatusData(count
, SKILL_UNCHANGED
)));
20691 learnSkillRewardedSpells(skill
, value
);
20695 if(count
>= PLAYER_MAX_SKILLS
) // client limit
20697 sLog
.outError("Character %u has more than %u skills.", GetGUIDLow(), PLAYER_MAX_SKILLS
);
20700 } while (result
->NextRow());
20704 for (; count
< PLAYER_MAX_SKILLS
; ++count
)
20706 SetUInt32Value(PLAYER_SKILL_INDEX(count
), 0);
20707 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(count
),0);
20708 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(count
),0);
20711 // special settings
20712 if(getClass()==CLASS_DEATH_KNIGHT
)
20714 uint32 base_level
= std::min(getLevel(),sWorld
.getConfig (CONFIG_UINT32_START_HEROIC_PLAYER_LEVEL
));
20717 uint32 base_skill
= (base_level
-1)*5; // 270 at starting level 55
20719 base_skill
= 1; // skill mast be known and then > 0 in any case
20721 if(GetPureSkillValue (SKILL_FIRST_AID
) < base_skill
)
20722 SetSkill(SKILL_FIRST_AID
,base_skill
, base_skill
);
20723 if(GetPureSkillValue (SKILL_AXES
) < base_skill
)
20724 SetSkill(SKILL_AXES
, base_skill
,base_skill
);
20725 if(GetPureSkillValue (SKILL_DEFENSE
) < base_skill
)
20726 SetSkill(SKILL_DEFENSE
, base_skill
,base_skill
);
20727 if(GetPureSkillValue (SKILL_POLEARMS
) < base_skill
)
20728 SetSkill(SKILL_POLEARMS
, base_skill
,base_skill
);
20729 if(GetPureSkillValue (SKILL_SWORDS
) < base_skill
)
20730 SetSkill(SKILL_SWORDS
, base_skill
,base_skill
);
20731 if(GetPureSkillValue (SKILL_2H_AXES
) < base_skill
)
20732 SetSkill(SKILL_2H_AXES
, base_skill
,base_skill
);
20733 if(GetPureSkillValue (SKILL_2H_SWORDS
) < base_skill
)
20734 SetSkill(SKILL_2H_SWORDS
, base_skill
,base_skill
);
20735 if(GetPureSkillValue (SKILL_UNARMED
) < base_skill
)
20736 SetSkill(SKILL_UNARMED
, base_skill
,base_skill
);
20740 uint32
Player::GetPhaseMaskForSpawn() const
20742 uint32 phase
= PHASEMASK_NORMAL
;
20743 if(!isGameMaster())
20744 phase
= GetPhaseMask();
20747 AuraList
const& phases
= GetAurasByType(SPELL_AURA_PHASE
);
20748 if(!phases
.empty())
20749 phase
= phases
.front()->GetMiscValue();
20752 // some aura phases include 1 normal map in addition to phase itself
20753 if(uint32 n_phase
= phase
& ~PHASEMASK_NORMAL
)
20756 return PHASEMASK_NORMAL
;
20759 uint8
Player::CanEquipUniqueItem(Item
* pItem
, uint8 eslot
, uint32 limit_count
) const
20761 ItemPrototype
const* pProto
= pItem
->GetProto();
20763 // proto based limitations
20764 if(uint8 res
= CanEquipUniqueItem(pProto
,eslot
,limit_count
))
20767 // check unique-equipped on gems
20768 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
20770 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
20773 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
20777 ItemPrototype
const* pGem
= ObjectMgr::GetItemPrototype(enchantEntry
->GemID
);
20781 // include for check equip another gems with same limit category for not equipped item (and then not counted)
20782 uint32 gem_limit_count
= !pItem
->IsEquipped() && pGem
->ItemLimitCategory
20783 ? pItem
->GetGemCountWithLimitCategory(pGem
->ItemLimitCategory
) : 1;
20785 if(uint8 res
= CanEquipUniqueItem(pGem
, eslot
,gem_limit_count
))
20789 return EQUIP_ERR_OK
;
20792 uint8
Player::CanEquipUniqueItem( ItemPrototype
const* itemProto
, uint8 except_slot
, uint32 limit_count
) const
20794 // check unique-equipped on item
20795 if (itemProto
->Flags
& ITEM_FLAGS_UNIQUE_EQUIPPED
)
20797 // there is an equip limit on this item
20798 if(HasItemOrGemWithIdEquipped(itemProto
->ItemId
,1,except_slot
))
20799 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
20802 // check unique-equipped limit
20803 if (itemProto
->ItemLimitCategory
)
20805 ItemLimitCategoryEntry
const* limitEntry
= sItemLimitCategoryStore
.LookupEntry(itemProto
->ItemLimitCategory
);
20807 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
20809 // NOTE: limitEntry->mode not checked because if item have have-limit then it applied and to equip case
20811 if(limit_count
> limitEntry
->maxCount
)
20812 return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS
;
20814 // there is an equip limit on this item
20815 if(HasItemOrGemWithLimitCategoryEquipped(itemProto
->ItemLimitCategory
,limitEntry
->maxCount
-limit_count
+1,except_slot
))
20816 return EQUIP_ERR_ITEM_MAX_LIMIT_CATEGORY_EQUIPPED_EXCEEDED_IS
;
20819 return EQUIP_ERR_OK
;
20822 void Player::HandleFall(MovementInfo
const& movementInfo
)
20824 // calculate total z distance of the fall
20825 float z_diff
= m_lastFallZ
- movementInfo
.GetPos()->z
;
20826 sLog
.outDebug("zDiff = %f", z_diff
);
20828 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
20829 // 14.57 can be calculated by resolving damageperc formula below to 0
20830 if (z_diff
>= 14.57f
&& !isDead() && !isGameMaster() &&
20831 !HasAuraType(SPELL_AURA_HOVER
) && !HasAuraType(SPELL_AURA_FEATHER_FALL
) &&
20832 !HasAuraType(SPELL_AURA_FLY
) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL
) )
20834 //Safe fall, fall height reduction
20835 int32 safe_fall
= GetTotalAuraModifier(SPELL_AURA_SAFE_FALL
);
20837 float damageperc
= 0.018f
*(z_diff
-safe_fall
)-0.2426f
;
20841 uint32 damage
= (uint32
)(damageperc
* GetMaxHealth()*sWorld
.getConfig(CONFIG_FLOAT_RATE_DAMAGE_FALL
));
20843 float height
= movementInfo
.GetPos()->z
;
20844 UpdateGroundPositionZ(movementInfo
.GetPos()->x
, movementInfo
.GetPos()->y
, height
);
20848 //Prevent fall damage from being more than the player maximum health
20849 if (damage
> GetMaxHealth())
20850 damage
= GetMaxHealth();
20853 if (GetDummyAura(43621))
20854 damage
= GetMaxHealth()/2;
20856 uint32 original_health
= GetHealth();
20857 uint32 final_damage
= EnvironmentalDamage(DAMAGE_FALL
, damage
);
20859 // recheck alive, might have died of EnvironmentalDamage, avoid cases when player die in fact like Spirit of Redemption case
20860 if (isAlive() && final_damage
< original_health
)
20861 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING
, uint32(z_diff
*100));
20864 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
20865 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
);
20870 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type
, uint32 miscvalue1
/*=0*/, uint32 miscvalue2
/*=0*/, Unit
*unit
/*=NULL*/, uint32 time
/*=0*/ )
20872 GetAchievementMgr().UpdateAchievementCriteria(type
, miscvalue1
,miscvalue2
,unit
,time
);
20875 void Player::LearnTalent(uint32 talentId
, uint32 talentRank
)
20877 uint32 CurTalentPoints
= GetFreeTalentPoints();
20879 if(CurTalentPoints
== 0)
20882 if (talentRank
>= MAX_TALENT_RANK
)
20885 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry( talentId
);
20890 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentInfo
->TalentTab
);
20895 // prevent learn talent for different class (cheating)
20896 if( (getClassMask() & talentTabInfo
->ClassMask
) == 0 )
20899 // find current max talent rank
20900 uint32 curtalent_maxrank
= 0;
20901 for(int32 k
= MAX_TALENT_RANK
-1; k
> -1; --k
)
20903 if(talentInfo
->RankID
[k
] && HasSpell(talentInfo
->RankID
[k
]))
20905 curtalent_maxrank
= k
+ 1;
20910 // we already have same or higher talent rank learned
20911 if(curtalent_maxrank
>= (talentRank
+ 1))
20914 // check if we have enough talent points
20915 if(CurTalentPoints
< (talentRank
- curtalent_maxrank
+ 1))
20918 // Check if it requires another talent
20919 if (talentInfo
->DependsOn
> 0)
20921 if(TalentEntry
const *depTalentInfo
= sTalentStore
.LookupEntry(talentInfo
->DependsOn
))
20923 bool hasEnoughRank
= false;
20924 for (int i
= talentInfo
->DependsOnRank
; i
< MAX_TALENT_RANK
; ++i
)
20926 if (depTalentInfo
->RankID
[i
] != 0)
20927 if (HasSpell(depTalentInfo
->RankID
[i
]))
20928 hasEnoughRank
= true;
20930 if (!hasEnoughRank
)
20935 // Find out how many points we have in this field
20936 uint32 spentPoints
= 0;
20938 uint32 tTab
= talentInfo
->TalentTab
;
20939 if (talentInfo
->Row
> 0)
20941 unsigned int numRows
= sTalentStore
.GetNumRows();
20942 for (unsigned int i
= 0; i
< numRows
; ++i
) // Loop through all talents.
20944 // Someday, someone needs to revamp
20945 const TalentEntry
*tmpTalent
= sTalentStore
.LookupEntry(i
);
20946 if (tmpTalent
) // the way talents are tracked
20948 if (tmpTalent
->TalentTab
== tTab
)
20950 for (int j
= 0; j
< MAX_TALENT_RANK
; ++j
)
20952 if (tmpTalent
->RankID
[j
] != 0)
20954 if (HasSpell(tmpTalent
->RankID
[j
]))
20956 spentPoints
+= j
+ 1;
20965 // not have required min points spent in talent tree
20966 if(spentPoints
< (talentInfo
->Row
* MAX_TALENT_RANK
))
20969 // spell not set in talent.dbc
20970 uint32 spellid
= talentInfo
->RankID
[talentRank
];
20973 sLog
.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId
, talentRank
);
20978 if(HasSpell(spellid
))
20981 // learn! (other talent ranks will unlearned at learning)
20982 learnSpell(spellid
, false);
20983 sLog
.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId
, talentRank
, spellid
);
20985 // update free talent points
20986 SetFreeTalentPoints(CurTalentPoints
- (talentRank
- curtalent_maxrank
+ 1));
20989 void Player::LearnPetTalent(uint64 petGuid
, uint32 talentId
, uint32 talentRank
)
20991 Pet
*pet
= GetPet();
20996 if(petGuid
!= pet
->GetGUID())
20999 uint32 CurTalentPoints
= pet
->GetFreeTalentPoints();
21001 if(CurTalentPoints
== 0)
21004 if (talentRank
>= MAX_PET_TALENT_RANK
)
21007 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry(talentId
);
21012 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry(talentInfo
->TalentTab
);
21017 CreatureInfo
const *ci
= pet
->GetCreatureInfo();
21022 CreatureFamilyEntry
const *pet_family
= sCreatureFamilyStore
.LookupEntry(ci
->family
);
21027 if(pet_family
->petTalentType
< 0) // not hunter pet
21030 // prevent learn talent for different family (cheating)
21031 if(!((1 << pet_family
->petTalentType
) & talentTabInfo
->petTalentMask
))
21034 // find current max talent rank
21035 int32 curtalent_maxrank
= 0;
21036 for(int32 k
= MAX_TALENT_RANK
-1; k
> -1; --k
)
21038 if(talentInfo
->RankID
[k
] && pet
->HasSpell(talentInfo
->RankID
[k
]))
21040 curtalent_maxrank
= k
+ 1;
21045 // we already have same or higher talent rank learned
21046 if(curtalent_maxrank
>= int32(talentRank
+ 1))
21049 // check if we have enough talent points
21050 if(CurTalentPoints
< (talentRank
- curtalent_maxrank
+ 1))
21053 // Check if it requires another talent
21054 if (talentInfo
->DependsOn
> 0)
21056 if(TalentEntry
const *depTalentInfo
= sTalentStore
.LookupEntry(talentInfo
->DependsOn
))
21058 bool hasEnoughRank
= false;
21059 for (int i
= talentInfo
->DependsOnRank
; i
< MAX_TALENT_RANK
; ++i
)
21061 if (depTalentInfo
->RankID
[i
] != 0)
21062 if (pet
->HasSpell(depTalentInfo
->RankID
[i
]))
21063 hasEnoughRank
= true;
21065 if (!hasEnoughRank
)
21070 // Find out how many points we have in this field
21071 uint32 spentPoints
= 0;
21073 uint32 tTab
= talentInfo
->TalentTab
;
21074 if (talentInfo
->Row
> 0)
21076 unsigned int numRows
= sTalentStore
.GetNumRows();
21077 for (unsigned int i
= 0; i
< numRows
; ++i
) // Loop through all talents.
21079 // Someday, someone needs to revamp
21080 const TalentEntry
*tmpTalent
= sTalentStore
.LookupEntry(i
);
21081 if (tmpTalent
) // the way talents are tracked
21083 if (tmpTalent
->TalentTab
== tTab
)
21085 for (int j
= 0; j
< MAX_TALENT_RANK
; ++j
)
21087 if (tmpTalent
->RankID
[j
] != 0)
21089 if (pet
->HasSpell(tmpTalent
->RankID
[j
]))
21091 spentPoints
+= j
+ 1;
21100 // not have required min points spent in talent tree
21101 if(spentPoints
< (talentInfo
->Row
* MAX_PET_TALENT_RANK
))
21104 // spell not set in talent.dbc
21105 uint32 spellid
= talentInfo
->RankID
[talentRank
];
21108 sLog
.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId
, talentRank
);
21113 if(pet
->HasSpell(spellid
))
21116 // learn! (other talent ranks will unlearned at learning)
21117 pet
->learnSpell(spellid
);
21118 sLog
.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId
, talentRank
, spellid
);
21120 // update free talent points
21121 pet
->SetFreeTalentPoints(CurTalentPoints
- (talentRank
- curtalent_maxrank
+ 1));
21124 void Player::UpdateKnownCurrencies(uint32 itemId
, bool apply
)
21126 if(CurrencyTypesEntry
const* ctEntry
= sCurrencyTypesStore
.LookupEntry(itemId
))
21129 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES
, (UI64LIT(1) << (ctEntry
->BitIndex
- 1)));
21131 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES
, (UI64LIT(1) << (ctEntry
->BitIndex
- 1)));
21135 void Player::UpdateFallInformationIfNeed( MovementInfo
const& minfo
,uint16 opcode
)
21137 if (m_lastFallTime
>= minfo
.GetFallTime() || m_lastFallZ
<= minfo
.GetPos()->z
|| opcode
== MSG_MOVE_FALL_LAND
)
21138 SetFallInformation(minfo
.GetFallTime(), minfo
.GetPos()->z
);
21141 void Player::UnsummonPetTemporaryIfAny()
21143 Pet
* pet
= GetPet();
21147 if(!m_temporaryUnsummonedPetNumber
&& pet
->isControlled() && !pet
->isTemporarySummoned() )
21149 m_temporaryUnsummonedPetNumber
= pet
->GetCharmInfo()->GetPetNumber();
21150 m_oldpetspell
= pet
->GetUInt32Value(UNIT_CREATED_BY_SPELL
);
21153 RemovePet(pet
, PET_SAVE_AS_CURRENT
);
21156 void Player::ResummonPetTemporaryUnSummonedIfAny()
21158 if(!m_temporaryUnsummonedPetNumber
)
21161 // not resummon in not appropriate state
21162 if(IsPetNeedBeTemporaryUnsummoned())
21168 Pet
* NewPet
= new Pet
;
21169 if(!NewPet
->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber
, true))
21172 m_temporaryUnsummonedPetNumber
= 0;
21175 bool Player::canSeeSpellClickOn(Creature
const *c
) const
21177 if(!c
->HasFlag(UNIT_NPC_FLAGS
,UNIT_NPC_FLAG_SPELLCLICK
))
21180 SpellClickInfoMapBounds clickPair
= sObjectMgr
.GetSpellClickInfoMapBounds(c
->GetEntry());
21181 for(SpellClickInfoMap::const_iterator itr
= clickPair
.first
; itr
!= clickPair
.second
; ++itr
)
21182 if(itr
->second
.IsFitToRequirements(this))
21188 void Player::BuildPlayerTalentsInfoData(WorldPacket
*data
)
21190 *data
<< uint32(GetFreeTalentPoints()); // unspentTalentPoints
21191 *data
<< uint8(m_specsCount
); // talent group count (0, 1 or 2)
21192 *data
<< uint8(m_activeSpec
); // talent group index (0 or 1)
21196 // loop through all specs (only 1 for now)
21197 for(uint32 specIdx
= 0; specIdx
< m_specsCount
; ++specIdx
)
21199 uint8 talentIdCount
= 0;
21200 size_t pos
= data
->wpos();
21201 *data
<< uint8(talentIdCount
); // [PH], talentIdCount
21203 // find class talent tabs (all players have 3 talent tabs)
21204 uint32
const* talentTabIds
= GetTalentTabPages(getClass());
21206 for(uint32 i
= 0; i
< 3; ++i
)
21208 uint32 talentTabId
= talentTabIds
[i
];
21210 for(uint32 talentId
= 0; talentId
< sTalentStore
.GetNumRows(); ++talentId
)
21212 TalentEntry
const* talentInfo
= sTalentStore
.LookupEntry(talentId
);
21216 // skip another tab talents
21217 if(talentInfo
->TalentTab
!= talentTabId
)
21220 // find max talent rank
21221 int32 curtalent_maxrank
= -1;
21222 for(int32 k
= MAX_TALENT_RANK
-1; k
> -1; --k
)
21224 if(talentInfo
->RankID
[k
] && HasSpell(talentInfo
->RankID
[k
]))
21226 curtalent_maxrank
= k
;
21231 // not learned talent
21232 if(curtalent_maxrank
< 0)
21235 *data
<< uint32(talentInfo
->TalentID
); // Talent.dbc
21236 *data
<< uint8(curtalent_maxrank
); // talentMaxRank (0-4)
21242 data
->put
<uint8
>(pos
, talentIdCount
); // put real count
21244 *data
<< uint8(MAX_GLYPH_SLOT_INDEX
); // glyphs count
21246 // GlyphProperties.dbc
21247 for(uint8 i
= 0; i
< MAX_GLYPH_SLOT_INDEX
; ++i
)
21248 *data
<< uint16(m_glyphs
[specIdx
][i
].GetId());
21253 void Player::BuildPetTalentsInfoData(WorldPacket
*data
)
21255 uint32 unspentTalentPoints
= 0;
21256 size_t pointsPos
= data
->wpos();
21257 *data
<< uint32(unspentTalentPoints
); // [PH], unspentTalentPoints
21259 uint8 talentIdCount
= 0;
21260 size_t countPos
= data
->wpos();
21261 *data
<< uint8(talentIdCount
); // [PH], talentIdCount
21263 Pet
*pet
= GetPet();
21267 unspentTalentPoints
= pet
->GetFreeTalentPoints();
21269 data
->put
<uint32
>(pointsPos
, unspentTalentPoints
); // put real points
21271 CreatureInfo
const *ci
= pet
->GetCreatureInfo();
21275 CreatureFamilyEntry
const *pet_family
= sCreatureFamilyStore
.LookupEntry(ci
->family
);
21276 if(!pet_family
|| pet_family
->petTalentType
< 0)
21279 for(uint32 talentTabId
= 1; talentTabId
< sTalentTabStore
.GetNumRows(); ++talentTabId
)
21281 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentTabId
);
21285 if(!((1 << pet_family
->petTalentType
) & talentTabInfo
->petTalentMask
))
21288 for(uint32 talentId
= 0; talentId
< sTalentStore
.GetNumRows(); ++talentId
)
21290 TalentEntry
const* talentInfo
= sTalentStore
.LookupEntry(talentId
);
21294 // skip another tab talents
21295 if(talentInfo
->TalentTab
!= talentTabId
)
21298 // find max talent rank
21299 int32 curtalent_maxrank
= -1;
21300 for(int32 k
= 4; k
> -1; --k
)
21302 if(talentInfo
->RankID
[k
] && pet
->HasSpell(talentInfo
->RankID
[k
]))
21304 curtalent_maxrank
= k
;
21309 // not learned talent
21310 if(curtalent_maxrank
< 0)
21313 *data
<< uint32(talentInfo
->TalentID
); // Talent.dbc
21314 *data
<< uint8(curtalent_maxrank
); // talentMaxRank (0-4)
21319 data
->put
<uint8
>(countPos
, talentIdCount
); // put real count
21325 void Player::SendTalentsInfoData(bool pet
)
21327 WorldPacket
data(SMSG_TALENTS_INFO
, 50);
21328 data
<< uint8(pet
? 1 : 0);
21330 BuildPetTalentsInfoData(&data
);
21332 BuildPlayerTalentsInfoData(&data
);
21333 GetSession()->SendPacket(&data
);
21336 void Player::BuildEnchantmentsInfoData(WorldPacket
*data
)
21338 uint32 slotUsedMask
= 0;
21339 size_t slotUsedMaskPos
= data
->wpos();
21340 *data
<< uint32(slotUsedMask
); // slotUsedMask < 0x80000
21342 for(uint32 i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
21344 Item
*item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
);
21349 slotUsedMask
|= (1 << i
);
21351 *data
<< uint32(item
->GetEntry()); // item entry
21353 uint16 enchantmentMask
= 0;
21354 size_t enchantmentMaskPos
= data
->wpos();
21355 *data
<< uint16(enchantmentMask
); // enchantmentMask < 0x1000
21357 for(uint32 j
= 0; j
< MAX_ENCHANTMENT_SLOT
; ++j
)
21359 uint32 enchId
= item
->GetEnchantmentId(EnchantmentSlot(j
));
21364 enchantmentMask
|= (1 << j
);
21366 *data
<< uint16(enchId
); // enchantmentId?
21369 data
->put
<uint16
>(enchantmentMaskPos
, enchantmentMask
);
21371 *data
<< uint16(0); // ?
21372 *data
<< uint8(0); // PGUID!
21373 *data
<< uint32(0); // seed?
21376 data
->put
<uint32
>(slotUsedMaskPos
, slotUsedMask
);
21379 void Player::SendEquipmentSetList()
21382 WorldPacket
data(SMSG_EQUIPMENT_SET_LIST
, 4);
21383 size_t count_pos
= data
.wpos();
21384 data
<< uint32(count
); // count placeholder
21385 for(EquipmentSets::iterator itr
= m_EquipmentSets
.begin(); itr
!= m_EquipmentSets
.end(); ++itr
)
21387 if(itr
->second
.state
==EQUIPMENT_SET_DELETED
)
21389 data
.appendPackGUID(itr
->second
.Guid
);
21390 data
<< uint32(itr
->first
);
21391 data
<< itr
->second
.Name
;
21392 data
<< itr
->second
.IconName
;
21393 for(uint32 i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
21394 data
.appendPackGUID(MAKE_NEW_GUID(itr
->second
.Items
[i
], 0, HIGHGUID_ITEM
));
21396 ++count
; // client have limit but it checked at loading and set
21398 data
.put
<uint32
>(count_pos
, count
);
21399 GetSession()->SendPacket(&data
);
21402 void Player::SetEquipmentSet(uint32 index
, EquipmentSet eqset
)
21404 if(eqset
.Guid
!= 0)
21406 bool found
= false;
21408 for(EquipmentSets::iterator itr
= m_EquipmentSets
.begin(); itr
!= m_EquipmentSets
.end(); ++itr
)
21410 if((itr
->second
.Guid
== eqset
.Guid
) && (itr
->first
== index
))
21417 if(!found
) // something wrong...
21419 sLog
.outError("Player %s tried to save equipment set "UI64FMTD
" (index %u), but that equipment set not found!", GetName(), eqset
.Guid
, index
);
21424 EquipmentSet
& eqslot
= m_EquipmentSets
[index
];
21426 EquipmentSetUpdateState old_state
= eqslot
.state
;
21430 if(eqset
.Guid
== 0)
21432 eqslot
.Guid
= sObjectMgr
.GenerateEquipmentSetGuid();
21434 WorldPacket
data(SMSG_EQUIPMENT_SET_SAVED
, 4 + 1);
21435 data
<< uint32(index
);
21436 data
.appendPackGUID(eqslot
.Guid
);
21437 GetSession()->SendPacket(&data
);
21440 eqslot
.state
= old_state
== EQUIPMENT_SET_NEW
? EQUIPMENT_SET_NEW
: EQUIPMENT_SET_CHANGED
;
21443 void Player::_SaveEquipmentSets()
21445 for(EquipmentSets::iterator itr
= m_EquipmentSets
.begin(); itr
!= m_EquipmentSets
.end();)
21447 uint32 index
= itr
->first
;
21448 EquipmentSet
& eqset
= itr
->second
;
21449 switch(eqset
.state
)
21451 case EQUIPMENT_SET_UNCHANGED
:
21453 break; // nothing do
21454 case EQUIPMENT_SET_CHANGED
:
21455 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'",
21456 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],
21457 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
);
21458 eqset
.state
= EQUIPMENT_SET_UNCHANGED
;
21461 case EQUIPMENT_SET_NEW
:
21462 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')",
21463 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],
21464 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]);
21465 eqset
.state
= EQUIPMENT_SET_UNCHANGED
;
21468 case EQUIPMENT_SET_DELETED
:
21469 CharacterDatabase
.PExecute("DELETE FROM character_equipmentsets WHERE setguid="UI64FMTD
, eqset
.Guid
);
21470 m_EquipmentSets
.erase(itr
++);
21476 void Player::_SaveBGData()
21478 CharacterDatabase
.PExecute("DELETE FROM character_battleground_data WHERE guid='%u'", GetGUIDLow());
21479 if (m_bgData
.bgInstanceID
)
21481 /* guid, bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
21482 CharacterDatabase
.PExecute("INSERT INTO character_battleground_data VALUES ('%u', '%u', '%u', '%f', '%f', '%f', '%f', '%u', '%u', '%u', '%u')",
21483 GetGUIDLow(), m_bgData
.bgInstanceID
, m_bgData
.bgTeam
, m_bgData
.joinPos
.coord_x
, m_bgData
.joinPos
.coord_y
, m_bgData
.joinPos
.coord_z
,
21484 m_bgData
.joinPos
.orientation
, m_bgData
.joinPos
.mapid
, m_bgData
.taxiPath
[0], m_bgData
.taxiPath
[1], m_bgData
.mountSpell
);
21488 void Player::DeleteEquipmentSet(uint64 setGuid
)
21490 for(EquipmentSets::iterator itr
= m_EquipmentSets
.begin(); itr
!= m_EquipmentSets
.end(); ++itr
)
21492 if(itr
->second
.Guid
== setGuid
)
21494 if(itr
->second
.state
== EQUIPMENT_SET_NEW
)
21495 m_EquipmentSets
.erase(itr
);
21497 itr
->second
.state
= EQUIPMENT_SET_DELETED
;
21503 void Player::ActivateSpec(uint8 specNum
)
21505 if(GetActiveSpec() == specNum
)
21508 if(specNum
>= GetSpecsCount())
21511 // unlearn GetActiveSpec() talents (not learned in specNum);
21512 // learn specNum talents
21514 ApplyGlyphs(false);
21516 SetActiveSpec(specNum
);
21518 // recheck action buttons (not checked at loading/spec copy)
21519 ActionButtonList
const& currentActionButtonList
= m_actionButtons
[m_activeSpec
];
21520 for(ActionButtonList::const_iterator itr
= currentActionButtonList
.begin(); itr
!= currentActionButtonList
.end(); ++itr
)
21521 if (itr
->second
.uState
!= ACTIONBUTTON_DELETED
)
21522 // remove broken without any output (it can be not correct because talents not copied at spec creating)
21523 if (!IsActionButtonDataValid(itr
->first
,itr
->second
.GetAction(),itr
->second
.GetType(), this, false))
21524 removeActionButton(m_activeSpec
,itr
->first
);
21528 SendInitialActionButtons();
21530 InitTalentForLevel();
21533 void Player::UpdateSpecCount(uint8 count
)
21535 uint8 curCount
= GetSpecsCount();
21536 if (curCount
== count
)
21539 // maybe current spec data must be copied to 0 spec?
21540 if (m_activeSpec
>= count
)
21543 // copy spec data from new specs
21544 if (count
> curCount
)
21546 // copy action buttons from active spec (more easy in this case iterate first by button)
21547 ActionButtonList
const& currentActionButtonList
= m_actionButtons
[m_activeSpec
];
21549 for(ActionButtonList::const_iterator itr
= currentActionButtonList
.begin(); itr
!= currentActionButtonList
.end(); ++itr
)
21551 if (itr
->second
.uState
!= ACTIONBUTTON_DELETED
)
21553 for(uint8 spec
= curCount
; spec
< count
; ++spec
)
21554 addActionButton(spec
,itr
->first
,itr
->second
.GetAction(),itr
->second
.GetType());
21558 // delete spec data for removed specs
21559 else if (count
< curCount
)
21561 // delete action buttons for removed spec
21562 for(uint8 spec
= count
; spec
< curCount
; ++spec
)
21564 // delete action buttons for removed spec
21565 for(uint8 button
= 0; button
< MAX_ACTION_BUTTONS
; ++button
)
21566 removeActionButton(spec
,button
);
21570 SetSpecsCount(count
);
21572 SendTalentsInfoData(false);
21575 void Player::RemoveAtLoginFlag( AtLoginFlags f
, bool in_db_also
/*= false*/ )
21577 m_atLoginFlags
&= ~f
;
21580 CharacterDatabase
.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(f
), GetGUIDLow());
21583 void Player::SendClearCooldown( uint32 spell_id
, Unit
* target
)
21585 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, 4+8);
21586 data
<< uint32(spell_id
);
21587 data
<< uint64(target
->GetGUID());
21588 SendDirectMessage(&data
);
21591 void Player::BuildTeleportAckMsg( WorldPacket
*data
, float x
, float y
, float z
, float ang
) const
21593 data
->Initialize(MSG_MOVE_TELEPORT_ACK
, 41);
21594 *data
<< GetPackGUID();
21595 *data
<< uint32(0); // this value increments every time
21596 *data
<< uint32(m_movementInfo
.GetMovementFlags()); // movement flags
21597 *data
<< uint16(0); // 2.3.0
21598 *data
<< uint32(getMSTime()); // time
21603 *data
<< uint32(0);
21606 bool Player::HasMovementFlag( MovementFlags f
) const
21608 return m_movementInfo
.HasMovementFlag(f
);
21611 void Player::SetFarSightGUID( uint64 guid
)
21613 if(GetFarSight() == guid
)
21616 SetUInt64Value(PLAYER_FARSIGHT
, guid
);
21618 // need triggering load grids around new view point
21619 UpdateVisibilityForPlayer();
21622 void Player::UpdateVisibilityForPlayer()
21624 WorldObject
const* viewPoint
= GetViewPoint();
21627 CellPair
p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
21630 m
->UpdatePlayerVisibility(this, cell
, p
);
21632 if (this != viewPoint
)
21634 CellPair
pView(MaNGOS::ComputeCellPair(viewPoint
->GetPositionX(), viewPoint
->GetPositionY()));
21635 Cell
cellView(pView
);
21637 m
->UpdateObjectsVisibilityFor(this, cellView
, pView
);
21640 m
->UpdateObjectsVisibilityFor(this, cell
, p
);
21643 void Player::SendDuelCountdown(uint32 counter
)
21645 WorldPacket
data(SMSG_DUEL_COUNTDOWN
, 4);
21646 data
<< uint32(counter
); // seconds
21647 GetSession()->SendPacket(&data
);
21650 bool Player::IsImmunedToSpellEffect(SpellEntry
const* spellInfo
, SpellEffectIndex index
) const
21652 switch(spellInfo
->Effect
[index
])
21654 case SPELL_EFFECT_ATTACK_ME
:
21659 switch(spellInfo
->EffectApplyAuraName
[index
])
21661 case SPELL_AURA_MOD_TAUNT
:
21666 return Unit::IsImmunedToSpellEffect(spellInfo
, index
);
21669 void Player::SetHomebindToLocation(WorldLocation
const& loc
, uint32 area_id
)
21671 m_homebindMapId
= loc
.mapid
;
21672 m_homebindAreaId
= area_id
;
21673 m_homebindX
= loc
.coord_x
;
21674 m_homebindY
= loc
.coord_y
;
21675 m_homebindZ
= loc
.coord_z
;
21677 // update sql homebind
21678 CharacterDatabase
.PExecute("UPDATE character_homebind SET map = '%u', zone = '%u', position_x = '%f', position_y = '%f', position_z = '%f' WHERE guid = '%u'",
21679 m_homebindMapId
, m_homebindAreaId
, m_homebindX
, m_homebindY
, m_homebindZ
, GetGUIDLow());
21682 Object
* Player::GetObjectByTypeMask(ObjectGuid guid
, TypeMask typemask
)
21684 switch(guid
.GetHigh())
21686 case HIGHGUID_ITEM
:
21687 if (typemask
& TYPEMASK_ITEM
)
21688 return GetItemByGuid(guid
);
21690 case HIGHGUID_PLAYER
:
21691 if (GetObjectGuid()==guid
)
21693 if ((typemask
& TYPEMASK_PLAYER
) && IsInWorld())
21694 return ObjectAccessor::FindPlayer(guid
);
21696 case HIGHGUID_GAMEOBJECT
:
21697 if ((typemask
& TYPEMASK_GAMEOBJECT
) && IsInWorld())
21698 return GetMap()->GetGameObject(guid
);
21700 case HIGHGUID_UNIT
:
21701 if ((typemask
& TYPEMASK_UNIT
) && IsInWorld())
21702 return GetMap()->GetCreature(guid
);
21705 if ((typemask
& TYPEMASK_UNIT
) && IsInWorld())
21706 return GetMap()->GetPet(guid
);
21708 case HIGHGUID_VEHICLE
:
21709 if ((typemask
& TYPEMASK_UNIT
) && IsInWorld())
21710 return GetMap()->GetVehicle(guid
);
21712 case HIGHGUID_DYNAMICOBJECT
:
21713 if ((typemask
& TYPEMASK_DYNAMICOBJECT
) && IsInWorld())
21714 return GetMap()->GetDynamicObject(guid
);
21716 case HIGHGUID_TRANSPORT
:
21717 case HIGHGUID_CORPSE
:
21718 case HIGHGUID_MO_TRANSPORT
: