2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
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 "CreatureAI.h"
51 #include "Transports.h"
53 #include "BattleGround.h"
54 #include "BattleGroundMgr.h"
55 #include "ArenaTeam.h"
57 #include "Database/DatabaseImpl.h"
59 #include "SocialMgr.h"
60 #include "AchievementMgr.h"
64 #define ZONE_UPDATE_INTERVAL (1*IN_MILISECONDS)
66 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
67 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
68 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
70 #define SKILL_VALUE(x) PAIR32_LOPART(x)
71 #define SKILL_MAX(x) PAIR32_HIPART(x)
72 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
74 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
75 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
76 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
80 CHARACTER_FLAG_NONE
= 0x00000000,
81 CHARACTER_FLAG_UNK1
= 0x00000001,
82 CHARACTER_FLAG_UNK2
= 0x00000002,
83 CHARACTER_LOCKED_FOR_TRANSFER
= 0x00000004,
84 CHARACTER_FLAG_UNK4
= 0x00000008,
85 CHARACTER_FLAG_UNK5
= 0x00000010,
86 CHARACTER_FLAG_UNK6
= 0x00000020,
87 CHARACTER_FLAG_UNK7
= 0x00000040,
88 CHARACTER_FLAG_UNK8
= 0x00000080,
89 CHARACTER_FLAG_UNK9
= 0x00000100,
90 CHARACTER_FLAG_UNK10
= 0x00000200,
91 CHARACTER_FLAG_HIDE_HELM
= 0x00000400,
92 CHARACTER_FLAG_HIDE_CLOAK
= 0x00000800,
93 CHARACTER_FLAG_UNK13
= 0x00001000,
94 CHARACTER_FLAG_GHOST
= 0x00002000,
95 CHARACTER_FLAG_RENAME
= 0x00004000,
96 CHARACTER_FLAG_UNK16
= 0x00008000,
97 CHARACTER_FLAG_UNK17
= 0x00010000,
98 CHARACTER_FLAG_UNK18
= 0x00020000,
99 CHARACTER_FLAG_UNK19
= 0x00040000,
100 CHARACTER_FLAG_UNK20
= 0x00080000,
101 CHARACTER_FLAG_UNK21
= 0x00100000,
102 CHARACTER_FLAG_UNK22
= 0x00200000,
103 CHARACTER_FLAG_UNK23
= 0x00400000,
104 CHARACTER_FLAG_UNK24
= 0x00800000,
105 CHARACTER_FLAG_LOCKED_BY_BILLING
= 0x01000000,
106 CHARACTER_FLAG_DECLINED
= 0x02000000,
107 CHARACTER_FLAG_UNK27
= 0x04000000,
108 CHARACTER_FLAG_UNK28
= 0x08000000,
109 CHARACTER_FLAG_UNK29
= 0x10000000,
110 CHARACTER_FLAG_UNK30
= 0x20000000,
111 CHARACTER_FLAG_UNK31
= 0x40000000,
112 CHARACTER_FLAG_UNK32
= 0x80000000
115 // corpse reclaim times
116 #define DEATH_EXPIRE_STEP (5*MINUTE)
117 #define MAX_DEATH_COUNT 3
119 static uint32 copseReclaimDelay
[MAX_DEATH_COUNT
] = { 30, 60, 120 };
121 //== PlayerTaxi ================================================
123 PlayerTaxi::PlayerTaxi()
126 memset(m_taximask
, 0, sizeof(m_taximask
));
129 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race
, uint32 chrClass
, uint32 level
)
131 // class specific initial known nodes
134 case CLASS_DEATH_KNIGHT
:
136 for(int i
= 0; i
< TaxiMaskSize
; ++i
)
137 m_taximask
[i
] |= sOldContinentsNodesMask
[i
];
142 // race specific initial known nodes: capital and taxi hub masks
145 case RACE_HUMAN
: SetTaximaskNode(2); break; // Human
146 case RACE_ORC
: SetTaximaskNode(23); break; // Orc
147 case RACE_DWARF
: SetTaximaskNode(6); break; // Dwarf
148 case RACE_NIGHTELF
: SetTaximaskNode(26);
149 SetTaximaskNode(27); break; // Night Elf
150 case RACE_UNDEAD_PLAYER
: SetTaximaskNode(11); break;// Undead
151 case RACE_TAUREN
: SetTaximaskNode(22); break; // Tauren
152 case RACE_GNOME
: SetTaximaskNode(6); break; // Gnome
153 case RACE_TROLL
: SetTaximaskNode(23); break; // Troll
154 case RACE_BLOODELF
: SetTaximaskNode(82); break; // Blood Elf
155 case RACE_DRAENEI
: SetTaximaskNode(94); break; // Draenei
158 // new continent starting masks (It will be accessible only at new map)
159 switch(Player::TeamForRace(race
))
161 case ALLIANCE
: SetTaximaskNode(100); break;
162 case HORDE
: SetTaximaskNode(99); break;
164 // level dependent taxi hubs
166 SetTaximaskNode(213); //Shattered Sun Staging Area
169 void PlayerTaxi::LoadTaxiMask(const char* data
)
171 Tokens tokens
= StrSplit(data
, " ");
174 Tokens::iterator iter
;
175 for (iter
= tokens
.begin(), index
= 0;
176 (index
< TaxiMaskSize
) && (iter
!= tokens
.end()); ++iter
, ++index
)
178 // load and set bits only for existed taxi nodes
179 m_taximask
[index
] = sTaxiNodesMask
[index
] & uint32(atol((*iter
).c_str()));
183 void PlayerTaxi::AppendTaximaskTo( ByteBuffer
& data
, bool all
)
187 for (uint8 i
=0; i
<TaxiMaskSize
; ++i
)
188 data
<< uint32(sTaxiNodesMask
[i
]); // all existed nodes
192 for (uint8 i
=0; i
<TaxiMaskSize
; ++i
)
193 data
<< uint32(m_taximask
[i
]); // known nodes
197 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string
& values
, uint32 team
)
199 ClearTaxiDestinations();
201 Tokens tokens
= StrSplit(values
," ");
203 for(Tokens::iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
)
205 uint32 node
= uint32(atol(iter
->c_str()));
206 AddTaxiDestination(node
);
209 if(m_TaxiDestinations
.empty())
213 if(m_TaxiDestinations
.size() < 2)
216 for(size_t i
= 1; i
< m_TaxiDestinations
.size(); ++i
)
220 objmgr
.GetTaxiPath(m_TaxiDestinations
[i
-1],m_TaxiDestinations
[i
],path
,cost
);
225 // can't load taxi path without mount set (quest taxi path?)
226 if(!objmgr
.GetTaxiMount(GetTaxiSource(),team
))
232 std::string
PlayerTaxi::SaveTaxiDestinationsToString()
234 if(m_TaxiDestinations
.empty())
237 std::ostringstream ss
;
239 for(size_t i
=0; i
< m_TaxiDestinations
.size(); ++i
)
240 ss
<< m_TaxiDestinations
[i
] << " ";
245 uint32
PlayerTaxi::GetCurrentTaxiPath() const
247 if(m_TaxiDestinations
.size() < 2)
253 objmgr
.GetTaxiPath(m_TaxiDestinations
[0],m_TaxiDestinations
[1],path
,cost
);
258 std::ostringstream
& operator<< (std::ostringstream
& ss
, PlayerTaxi
const& taxi
)
261 for(int i
= 0; i
< TaxiMaskSize
; ++i
)
262 ss
<< taxi
.m_taximask
[i
] << " ";
267 //== Player ====================================================
269 UpdateMask
Player::updateVisualBits
;
271 Player::Player (WorldSession
*session
): Unit(), m_achievementMgr(this), m_reputationMgr(this)
278 m_objectType
|= TYPEMASK_PLAYER
;
279 m_objectTypeId
= TYPEID_PLAYER
;
281 m_valuesCount
= PLAYER_END
;
288 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER
)
289 SetAcceptTicket(true);
291 // players always accept
292 if(GetSession()->GetSecurity() == SEC_PLAYER
)
293 SetAcceptWhispers(true);
301 m_usedTalentCount
= 0;
302 m_questRewardTalentCount
= 0;
305 m_weaponChangeTimer
= 0;
308 m_zoneUpdateTimer
= 0;
312 m_nextSave
= sWorld
.getConfig(CONFIG_INTERVAL_SAVE
);
314 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
315 // this must help in case next save after mass player load after server startup
316 m_nextSave
= urand(m_nextSave
/2,m_nextSave
*3/2);
318 clearResurrectRequestData();
320 m_SpellModRemoveCount
= 0;
322 memset(m_items
, 0, sizeof(Item
*)*PLAYER_SLOTS_COUNT
);
326 // group is initialized in the reference constructor
327 SetGroupInvite(NULL
);
328 m_groupUpdateMask
= 0;
329 m_auraUpdateMask
= 0;
333 m_GuildIdInvited
= 0;
334 m_ArenaTeamIdInvited
= 0;
336 m_atLoginFlags
= AT_LOGIN_NONE
;
338 mSemaphoreTeleport_Near
= false;
339 mSemaphoreTeleport_Far
= false;
346 PlayerTalkClass
= new PlayerMenu( GetSession() );
347 m_currentBuybackSlot
= BUYBACK_SLOT_START
;
349 for ( int aX
= 0 ; aX
< 8 ; aX
++ )
350 m_Tutorials
[ aX
] = 0x00;
351 m_TutorialsChanged
= false;
353 m_DailyQuestChanged
= false;
354 m_lastDailyQuestTime
= 0;
356 for (int i
=0; i
<MAX_TIMERS
; ++i
)
357 m_MirrorTimer
[i
] = DISABLED_MIRROR_TIMER
;
359 m_MirrorTimerFlags
= UNDERWATER_NONE
;
360 m_MirrorTimerFlagsLast
= UNDERWATER_NONE
;
366 m_deathExpireTime
= 0;
370 m_DetectInvTimer
= 1*IN_MILISECONDS
;
372 m_bgBattleGroundID
= 0;
373 m_bgTypeID
= BATTLEGROUND_TYPE_NONE
;
374 for (int j
=0; j
< PLAYER_MAX_BATTLEGROUND_QUEUES
; ++j
)
376 m_bgBattleGroundQueueID
[j
].bgQueueTypeId
= BATTLEGROUND_QUEUE_NONE
;
377 m_bgBattleGroundQueueID
[j
].invitedToInstance
= 0;
381 m_logintime
= time(NULL
);
382 m_Last_tick
= m_logintime
;
383 m_WeaponProficiency
= 0;
384 m_ArmorProficiency
= 0;
387 m_canDualWield
= false;
388 m_canTitanGrip
= false;
391 m_temporaryUnsummonedPetNumber
= 0;
392 //cache for UNIT_CREATED_BY_SPELL to allow
393 //returning reagents for temporarily removed pets
394 //when dying/logging out
397 ////////////////////Rest System/////////////////////
404 rest_type
=REST_TYPE_NO
;
405 ////////////////////Rest System/////////////////////
407 m_mailsLoaded
= false;
408 m_mailsUpdated
= false;
410 m_nextMailDelivereTime
= 0;
412 m_resetTalentsCost
= 0;
413 m_resetTalentsTime
= 0;
414 m_itemUpdateQueueBlocked
= false;
416 for (int i
= 0; i
< MAX_MOVE_TYPE
; ++i
)
417 m_forced_speed_changes
[i
] = 0;
421 /////////////////// Instance System /////////////////////
424 m_InstanceValid
= true;
425 m_dungeonDifficulty
= DIFFICULTY_NORMAL
;
429 for (int i
= 0; i
< BASEMOD_END
; ++i
)
431 m_auraBaseMod
[i
][FLAT_MOD
] = 0.0f
;
432 m_auraBaseMod
[i
][PCT_MOD
] = 1.0f
;
435 for (int i
= 0; i
< MAX_COMBAT_RATING
; ++i
)
436 m_baseRatingValue
[i
] = 0;
438 m_baseSpellDamage
= 0;
439 m_baseSpellHealing
= 0;
444 m_lastHonorUpdateTime
= time(NULL
);
453 //Default movement to run mode
454 m_unit_movement_flags
= 0;
459 m_bgAfkReportedTimer
= 0;
460 m_contestedPvPTimer
= 0;
462 m_declinedname
= NULL
;
471 CleanupsBeforeDelete();
473 // it must be unloaded already in PlayerLogout and accessed only for loggined player
476 // Note: buy back item already deleted from DB when player was saved
477 for(int i
= 0; i
< PLAYER_SLOTS_COUNT
; ++i
)
484 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
487 //all mailed items should be deleted, also all mail should be deallocated
488 for (PlayerMails::const_iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
491 for (ItemMap::const_iterator iter
= mMitems
.begin(); iter
!= mMitems
.end(); ++iter
)
492 delete iter
->second
; //if item is duplicated... then server may crash ... but that item should be deallocated
494 delete PlayerTalkClass
;
498 m_transport
->RemovePassenger(this);
501 for(size_t x
= 0; x
< ItemSetEff
.size(); x
++)
503 delete ItemSetEff
[x
];
505 // clean up player-instance binds, may unload some instance saves
506 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; ++i
)
507 for(BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
508 itr
->second
.save
->RemovePlayer(this);
510 delete m_declinedname
;
514 void Player::CleanupsBeforeDelete()
516 if(m_uint32Values
) // only for fully created Object
519 DuelComplete(DUEL_INTERUPTED
);
521 Unit::CleanupsBeforeDelete();
524 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
)
526 //FIXME: outfitId not used in player creating
528 Object::_Create(guidlow
, 0, HIGHGUID_PLAYER
);
532 PlayerInfo
const* info
= objmgr
.GetPlayerInfo(race
, class_
);
535 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
539 for (int i
= 0; i
< PLAYER_SLOTS_COUNT
; ++i
)
545 SetMapId(info
->mapId
);
546 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
);
548 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(class_
);
551 sLog
.outError("Class %u not found in DBC (Wrong DBC files?)",class_
);
555 uint8 powertype
= cEntry
->powerType
;
557 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, DEFAULT_WORLD_OBJECT_SIZE
);
558 SetFloatValue(UNIT_FIELD_COMBATREACH
, 1.5f
);
563 SetDisplayId(info
->displayId_f
);
564 SetNativeDisplayId(info
->displayId_f
);
567 SetDisplayId(info
->displayId_m
);
568 SetNativeDisplayId(info
->displayId_m
);
571 sLog
.outError("Invalid gender %u for player",gender
);
576 setFactionForRace(m_race
);
578 uint32 RaceClassGender
= ( race
) | ( class_
<< 8 ) | ( gender
<< 16 );
580 SetUInt32Value(UNIT_FIELD_BYTES_0
, ( RaceClassGender
| ( powertype
<< 24 ) ) );
581 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_PVP
);
582 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
);
583 SetFlag(UNIT_FIELD_FLAGS_2
, UNIT_FLAG2_REGENERATE_POWER
);
584 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
); // fix cast time showed in spell tooltip on client
585 SetFloatValue(UNIT_FIELD_HOVERHEIGHT
, 1.0f
); // default for players in 3.0.3
587 // -1 is default value
588 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX
, uint32(-1));
590 SetUInt32Value(PLAYER_BYTES
, (skin
| (face
<< 8) | (hairStyle
<< 16) | (hairColor
<< 24)));
591 SetUInt32Value(PLAYER_BYTES_2
, (facialHair
| (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
592 SetByteValue(PLAYER_BYTES_3
, 0, gender
);
594 SetUInt32Value( PLAYER_GUILDID
, 0 );
595 SetUInt32Value( PLAYER_GUILDRANK
, 0 );
596 SetUInt32Value( PLAYER_GUILD_TIMESTAMP
, 0 );
598 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES
, 0 ); // 0=disabled
599 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1
, 0 ); // 0=disabled
600 SetUInt32Value( PLAYER_CHOSEN_TITLE
, 0 );
601 SetUInt32Value( PLAYER_FIELD_KILLS
, 0 );
602 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 0 );
603 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION
, 0 );
604 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0 );
606 // set starting level
607 uint32 start_level
= getClass() != CLASS_DEATH_KNIGHT
608 ? sWorld
.getConfig(CONFIG_START_PLAYER_LEVEL
)
609 : sWorld
.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL
);
611 if (GetSession()->GetSecurity() >= SEC_MODERATOR
)
613 uint32 gm_level
= sWorld
.getConfig(CONFIG_START_GM_LEVEL
);
614 if(gm_level
> start_level
)
615 start_level
= gm_level
;
618 SetUInt32Value(UNIT_FIELD_LEVEL
, start_level
);
622 SetUInt32Value (PLAYER_FIELD_COINAGE
, sWorld
.getConfig(CONFIG_START_PLAYER_MONEY
));
623 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_START_HONOR_POINTS
));
624 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_START_ARENA_POINTS
));
627 m_Last_tick
= time(NULL
);
628 m_Played_time
[0] = 0;
629 m_Played_time
[1] = 0;
631 // base stats and related field values
633 InitTaxiNodesForLevel();
634 InitGlyphsForLevel();
635 InitTalentForLevel();
636 InitPrimaryProffesions(); // to max set before any spell added
638 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
639 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
640 SetHealth(GetMaxHealth());
641 if (getPowerType()==POWER_MANA
)
643 UpdateMaxPower(POWER_MANA
); // Update max Mana (for add bonus from intellect)
644 SetPower(POWER_MANA
,GetMaxPower(POWER_MANA
));
647 if(getPowerType() == POWER_RUNIC_POWER
)
649 SetPower(POWER_RUNE
, 8);
650 SetMaxPower(POWER_RUNE
, 8);
651 SetPower(POWER_RUNIC_POWER
, 0);
652 SetMaxPower(POWER_RUNIC_POWER
, 1000);
656 learnDefaultSpells();
658 // original action bar
659 std::list
<uint16
>::const_iterator action_itr
[4];
660 for(int i
=0; i
<4; ++i
)
661 action_itr
[i
] = info
->action
[i
].begin();
663 for (; action_itr
[0]!=info
->action
[0].end() && action_itr
[1]!=info
->action
[1].end();)
666 for(int i
=0; i
<4 ;++i
)
667 taction
[i
] = (*action_itr
[i
]);
669 addActionButton((uint8
)taction
[0], taction
[1], (uint8
)taction
[2], (uint8
)taction
[3]);
671 for(int i
=0; i
<4 ;++i
)
676 CharStartOutfitEntry
const* oEntry
= NULL
;
677 for (uint32 i
= 1; i
< sCharStartOutfitStore
.GetNumRows(); ++i
)
679 if(CharStartOutfitEntry
const* entry
= sCharStartOutfitStore
.LookupEntry(i
))
681 if(entry
->RaceClassGender
== RaceClassGender
)
691 for(int j
= 0; j
< MAX_OUTFIT_ITEMS
; ++j
)
693 if(oEntry
->ItemId
[j
] <= 0)
696 uint32 item_id
= oEntry
->ItemId
[j
];
699 // Hack for not existed item id in dbc 3.0.3
703 ItemPrototype
const* iProto
= objmgr
.GetItemPrototype(item_id
);
706 sLog
.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id
,getRace(),getClass());
710 // max stack by default (mostly 1), 1 for infinity stackable
711 uint32 count
= iProto
->Stackable
> 0 ? uint32(iProto
->Stackable
) : 1;
713 if(iProto
->Class
==ITEM_CLASS_CONSUMABLE
&& iProto
->SubClass
==ITEM_SUBCLASS_FOOD
)
715 switch(iProto
->Spells
[0].SpellCategory
)
718 if(iProto
->Stackable
> 4)
722 if(iProto
->Stackable
> 2)
728 StoreNewItemInBestSlots(item_id
, count
);
732 for (PlayerCreateInfoItems::const_iterator item_id_itr
= info
->item
.begin(); item_id_itr
!=info
->item
.end(); ++item_id_itr
++)
733 StoreNewItemInBestSlots(item_id_itr
->item_id
, item_id_itr
->item_amount
);
735 // bags and main-hand weapon must equipped at this moment
736 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
737 // or ammo not equipped in special bag
738 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
740 if(Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
743 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
744 uint8 msg
= CanEquipItem( NULL_SLOT
, eDest
, pItem
, false );
745 if( msg
== EQUIP_ERR_OK
)
747 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
748 EquipItem( eDest
, pItem
, true);
750 // move other items to more appropriate slots (ammo not equipped in special bag)
753 ItemPosCountVec sDest
;
754 msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, sDest
, pItem
, false );
755 if( msg
== EQUIP_ERR_OK
)
757 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
758 pItem
= StoreItem( sDest
, pItem
, true);
761 // if this is ammo then use it
762 msg
= CanUseAmmo( pItem
->GetEntry() );
763 if( msg
== EQUIP_ERR_OK
)
764 SetAmmo( pItem
->GetEntry() );
768 // all item positions resolved
773 bool Player::StoreNewItemInBestSlots(uint32 titem_id
, uint32 titem_amount
)
775 sLog
.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id
, titem_amount
);
777 // attempt equip by one
778 while(titem_amount
> 0)
781 uint8 msg
= CanEquipNewItem( NULL_SLOT
, eDest
, titem_id
, false );
782 if( msg
!= EQUIP_ERR_OK
)
785 EquipNewItem( eDest
, titem_id
, true);
786 AutoUnequipOffhandIfNeed();
790 if(titem_amount
== 0)
791 return true; // equipped
794 ItemPosCountVec sDest
;
795 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
796 uint8 msg
= CanStoreNewItem( INVENTORY_SLOT_BAG_0
, NULL_SLOT
, sDest
, titem_id
, titem_amount
);
797 if( msg
== EQUIP_ERR_OK
)
799 StoreNewItem( sDest
, titem_id
, true, Item::GenerateItemRandomPropertyId(titem_id
) );
800 return true; // stored
803 // item can't be added
804 sLog
.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id
,getRace(),getClass(),msg
);
808 void Player::SendMirrorTimer(MirrorTimerType Type
, uint32 MaxValue
, uint32 CurrentValue
, int32 Regen
)
810 if (MaxValue
== DISABLED_MIRROR_TIMER
)
812 if (CurrentValue
!=DISABLED_MIRROR_TIMER
)
813 StopMirrorTimer(Type
);
816 WorldPacket
data(SMSG_START_MIRROR_TIMER
, (21));
817 data
<< (uint32
)Type
;
818 data
<< CurrentValue
;
822 data
<< (uint32
)0; // spell id
823 GetSession()->SendPacket( &data
);
826 void Player::StopMirrorTimer(MirrorTimerType Type
)
828 m_MirrorTimer
[Type
] = DISABLED_MIRROR_TIMER
;
829 WorldPacket
data(SMSG_STOP_MIRROR_TIMER
, 4);
830 data
<< (uint32
)Type
;
831 GetSession()->SendPacket( &data
);
834 void Player::EnvironmentalDamage(EnviromentalDamage type
, uint32 damage
)
836 if(!isAlive() || isGameMaster())
839 // Absorb, resist some environmental damage type
842 if (type
== DAMAGE_LAVA
)
843 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE
, DIRECT_DAMAGE
, damage
, &absorb
, &resist
);
844 else if (type
== DAMAGE_SLIME
)
845 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE
, DIRECT_DAMAGE
, damage
, &absorb
, &resist
);
847 damage
-=absorb
+resist
;
849 WorldPacket
data(SMSG_ENVIRONMENTALDAMAGELOG
, (21));
850 data
<< uint64(GetGUID());
851 data
<< uint8(type
!=DAMAGE_FALL_TO_VOID
? type
: DAMAGE_FALL
);
852 data
<< uint32(damage
);
853 data
<< uint32(absorb
);
854 data
<< uint32(resist
);
855 SendMessageToSet(&data
, true);
857 DealDamage(this, damage
, NULL
, SELF_DAMAGE
, SPELL_SCHOOL_MASK_NORMAL
, NULL
, false);
861 if(type
==DAMAGE_FALL
) // DealDamage not apply item durability loss at self damage
863 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
864 DurabilityLossAll(0.10f
,false);
865 // durability lost message
866 WorldPacket
data2(SMSG_DURABILITY_DAMAGE_DEATH
, 0);
867 GetSession()->SendPacket(&data2
);
870 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM
, 1, type
);
874 int32
Player::getMaxTimer(MirrorTimerType timer
)
879 return MINUTE
*IN_MILISECONDS
;
882 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING
) || GetSession()->GetSecurity() >= sWorld
.getConfig(CONFIG_DISABLE_BREATHING
))
883 return DISABLED_MIRROR_TIMER
;
884 int32 UnderWaterTime
= 3*MINUTE
*IN_MILISECONDS
;
885 AuraList
const& mModWaterBreathing
= GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING
);
886 for(AuraList::const_iterator i
= mModWaterBreathing
.begin(); i
!= mModWaterBreathing
.end(); ++i
)
887 UnderWaterTime
= uint32(UnderWaterTime
* (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
);
888 return UnderWaterTime
;
893 return DISABLED_MIRROR_TIMER
;
894 return 1*IN_MILISECONDS
;
902 void Player::UpdateMirrorTimers()
904 // Desync flags for update on next HandleDrowning
905 if (m_MirrorTimerFlags
)
906 m_MirrorTimerFlagsLast
= ~m_MirrorTimerFlags
;
909 void Player::HandleDrowning(uint32 time_diff
)
911 if (!m_MirrorTimerFlags
)
915 if (m_MirrorTimerFlags
& UNDERWATER_INWATER
)
917 // Breath timer not activated - activate it
918 if (m_MirrorTimer
[BREATH_TIMER
] == DISABLED_MIRROR_TIMER
)
920 m_MirrorTimer
[BREATH_TIMER
] = getMaxTimer(BREATH_TIMER
);
921 SendMirrorTimer(BREATH_TIMER
, m_MirrorTimer
[BREATH_TIMER
], m_MirrorTimer
[BREATH_TIMER
], -1);
923 else // If activated - do tick
925 m_MirrorTimer
[BREATH_TIMER
]-=time_diff
;
926 // Timer limit - need deal damage
927 if (m_MirrorTimer
[BREATH_TIMER
] < 0)
929 m_MirrorTimer
[BREATH_TIMER
]+= 1*IN_MILISECONDS
;
930 // Calculate and deal damage
931 // TODO: Check this formula
932 uint32 damage
= GetMaxHealth() / 5 + urand(0, getLevel()-1);
933 EnvironmentalDamage(DAMAGE_DROWNING
, damage
);
935 else if (!(m_MirrorTimerFlagsLast
& UNDERWATER_INWATER
)) // Update time in client if need
936 SendMirrorTimer(BREATH_TIMER
, getMaxTimer(BREATH_TIMER
), m_MirrorTimer
[BREATH_TIMER
], -1);
939 else if (m_MirrorTimer
[BREATH_TIMER
] != DISABLED_MIRROR_TIMER
) // Regen timer
941 int32 UnderWaterTime
= getMaxTimer(BREATH_TIMER
);
943 m_MirrorTimer
[BREATH_TIMER
]+=10*time_diff
;
944 if (m_MirrorTimer
[BREATH_TIMER
] >= UnderWaterTime
|| !isAlive())
945 StopMirrorTimer(BREATH_TIMER
);
946 else if (m_MirrorTimerFlagsLast
& UNDERWATER_INWATER
)
947 SendMirrorTimer(BREATH_TIMER
, UnderWaterTime
, m_MirrorTimer
[BREATH_TIMER
], 10);
951 if (m_MirrorTimerFlags
& UNDERWARER_INDARKWATER
)
953 // Fatigue timer not activated - activate it
954 if (m_MirrorTimer
[FATIGUE_TIMER
] == DISABLED_MIRROR_TIMER
)
956 m_MirrorTimer
[FATIGUE_TIMER
] = getMaxTimer(FATIGUE_TIMER
);
957 SendMirrorTimer(FATIGUE_TIMER
, m_MirrorTimer
[FATIGUE_TIMER
], m_MirrorTimer
[FATIGUE_TIMER
], -1);
961 m_MirrorTimer
[FATIGUE_TIMER
]-=time_diff
;
962 // Timer limit - need deal damage or teleport ghost to graveyard
963 if (m_MirrorTimer
[FATIGUE_TIMER
] < 0)
965 m_MirrorTimer
[FATIGUE_TIMER
]+= 1*IN_MILISECONDS
;
966 if (isAlive()) // Calculate and deal damage
968 uint32 damage
= GetMaxHealth() / 5 + urand(0, getLevel()-1);
969 EnvironmentalDamage(DAMAGE_EXHAUSTED
, damage
);
971 else if (HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
)) // Teleport ghost to graveyard
974 else if (!(m_MirrorTimerFlagsLast
& UNDERWARER_INDARKWATER
))
975 SendMirrorTimer(FATIGUE_TIMER
, getMaxTimer(FATIGUE_TIMER
), m_MirrorTimer
[FATIGUE_TIMER
], -1);
978 else if (m_MirrorTimer
[FATIGUE_TIMER
] != DISABLED_MIRROR_TIMER
) // Regen timer
980 int32 DarkWaterTime
= getMaxTimer(FATIGUE_TIMER
);
981 m_MirrorTimer
[FATIGUE_TIMER
]+=10*time_diff
;
982 if (m_MirrorTimer
[FATIGUE_TIMER
] >= DarkWaterTime
|| !isAlive())
983 StopMirrorTimer(FATIGUE_TIMER
);
984 else if (m_MirrorTimerFlagsLast
& UNDERWARER_INDARKWATER
)
985 SendMirrorTimer(FATIGUE_TIMER
, DarkWaterTime
, m_MirrorTimer
[FATIGUE_TIMER
], 10);
988 if (m_MirrorTimerFlags
& (UNDERWATER_INLAVA
|UNDERWATER_INSLIME
))
990 // Breath timer not activated - activate it
991 if (m_MirrorTimer
[FIRE_TIMER
] == DISABLED_MIRROR_TIMER
)
992 m_MirrorTimer
[FIRE_TIMER
] = getMaxTimer(FIRE_TIMER
);
995 m_MirrorTimer
[FIRE_TIMER
]-=time_diff
;
996 if (m_MirrorTimer
[FIRE_TIMER
] < 0)
998 m_MirrorTimer
[FIRE_TIMER
]+= 1*IN_MILISECONDS
;
999 // Calculate and deal damage
1000 // TODO: Check this formula
1001 uint32 damage
= urand(600, 700);
1002 if (m_MirrorTimerFlags
&UNDERWATER_INLAVA
)
1003 EnvironmentalDamage(DAMAGE_LAVA
, damage
);
1005 EnvironmentalDamage(DAMAGE_SLIME
, damage
);
1010 m_MirrorTimer
[FIRE_TIMER
] = DISABLED_MIRROR_TIMER
;
1012 // Recheck timers flag
1013 m_MirrorTimerFlags
&=~UNDERWATER_EXIST_TIMERS
;
1014 for (int i
= 0; i
< MAX_TIMERS
; ++i
)
1015 if (m_MirrorTimer
[i
]!=DISABLED_MIRROR_TIMER
)
1017 m_MirrorTimerFlags
|=UNDERWATER_EXIST_TIMERS
;
1020 m_MirrorTimerFlagsLast
= m_MirrorTimerFlags
;
1023 ///The player sobers by 256 every 10 seconds
1024 void Player::HandleSobering()
1028 uint32 drunk
= (m_drunk
<= 256) ? 0 : (m_drunk
- 256);
1029 SetDrunkValue(drunk
);
1032 DrunkenState
Player::GetDrunkenstateByValue(uint16 value
)
1035 return DRUNKEN_SMASHED
;
1037 return DRUNKEN_DRUNK
;
1039 return DRUNKEN_TIPSY
;
1040 return DRUNKEN_SOBER
;
1043 void Player::SetDrunkValue(uint16 newDrunkenValue
, uint32 itemId
)
1045 uint32 oldDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
1047 m_drunk
= newDrunkenValue
;
1048 SetUInt32Value(PLAYER_BYTES_3
,(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFF0001) | (m_drunk
& 0xFFFE));
1050 uint32 newDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
1052 // special drunk invisibility detection
1053 if(newDrunkenState
>= DRUNKEN_DRUNK
)
1054 m_detectInvisibilityMask
|= (1<<6);
1056 m_detectInvisibilityMask
&= ~(1<<6);
1058 if(newDrunkenState
== oldDrunkenState
)
1061 WorldPacket
data(SMSG_CROSSED_INEBRIATION_THRESHOLD
, (8+4+4));
1062 data
<< uint64(GetGUID());
1063 data
<< uint32(newDrunkenState
);
1064 data
<< uint32(itemId
);
1066 SendMessageToSet(&data
, true);
1069 void Player::Update( uint32 p_time
)
1075 if(m_nextMailDelivereTime
&& m_nextMailDelivereTime
<= time(NULL
))
1080 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1081 m_nextMailDelivereTime
= 0;
1084 Unit::Update( p_time
);
1086 // update player only attacks
1087 if(uint32 ranged_att
= getAttackTimer(RANGED_ATTACK
))
1089 setAttackTimer(RANGED_ATTACK
, (p_time
>= ranged_att
? 0 : ranged_att
- p_time
) );
1092 if(uint32 off_att
= getAttackTimer(OFF_ATTACK
))
1094 setAttackTimer(OFF_ATTACK
, (p_time
>= off_att
? 0 : off_att
- p_time
) );
1097 time_t now
= time (NULL
);
1101 UpdateContestedPvP(p_time
);
1103 UpdateDuelFlag(now
);
1105 CheckDuelDistance(now
);
1107 UpdateAfkReport(now
);
1109 // Update items that have just a limited lifetime
1110 if (now
>m_Last_tick
)
1111 UpdateItemDuration(uint32(now
- m_Last_tick
));
1113 if (!m_timedquests
.empty())
1115 std::set
<uint32
>::iterator iter
= m_timedquests
.begin();
1116 while (iter
!= m_timedquests
.end())
1118 QuestStatusData
& q_status
= mQuestStatus
[*iter
];
1119 if( q_status
.m_timer
<= p_time
)
1121 uint32 quest_id
= *iter
;
1122 ++iter
; // current iter will be removed in FailTimedQuest
1123 FailTimedQuest( quest_id
);
1127 q_status
.m_timer
-= p_time
;
1128 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
1134 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING
))
1136 Unit
*pVictim
= getVictim();
1137 if (pVictim
&& !IsNonMeleeSpellCasted(false))
1139 // default combat reach 10
1140 // TODO add weapon,skill check
1142 float pldistance
= ATTACK_DISTANCE
;
1144 if (isAttackReady(BASE_ATTACK
))
1146 if(!IsWithinDistInMap(pVictim
, pldistance
))
1148 setAttackTimer(BASE_ATTACK
,100);
1149 if(m_swingErrorMsg
!= 1) // send single time (client auto repeat)
1151 SendAttackSwingNotInRange();
1152 m_swingErrorMsg
= 1;
1155 //120 degrees of radiant range
1156 else if( !HasInArc( 2*M_PI
/3, pVictim
))
1158 setAttackTimer(BASE_ATTACK
,100);
1159 if(m_swingErrorMsg
!= 2) // send single time (client auto repeat)
1161 SendAttackSwingBadFacingAttack();
1162 m_swingErrorMsg
= 2;
1167 m_swingErrorMsg
= 0; // reset swing error state
1169 // prevent base and off attack in same time, delay attack at 0.2 sec
1170 if(haveOffhandWeapon())
1172 uint32 off_att
= getAttackTimer(OFF_ATTACK
);
1173 if(off_att
< ATTACK_DISPLAY_DELAY
)
1174 setAttackTimer(OFF_ATTACK
,ATTACK_DISPLAY_DELAY
);
1176 AttackerStateUpdate(pVictim
, BASE_ATTACK
);
1177 resetAttackTimer(BASE_ATTACK
);
1181 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK
))
1183 if(!IsWithinDistInMap(pVictim
, pldistance
))
1185 setAttackTimer(OFF_ATTACK
,100);
1187 else if( !HasInArc( 2*M_PI
/3, pVictim
))
1189 setAttackTimer(OFF_ATTACK
,100);
1193 // prevent base and off attack in same time, delay attack at 0.2 sec
1194 uint32 base_att
= getAttackTimer(BASE_ATTACK
);
1195 if(base_att
< ATTACK_DISPLAY_DELAY
)
1196 setAttackTimer(BASE_ATTACK
,ATTACK_DISPLAY_DELAY
);
1198 AttackerStateUpdate(pVictim
, OFF_ATTACK
);
1199 resetAttackTimer(OFF_ATTACK
);
1203 Unit
*owner
= pVictim
->GetOwner();
1204 Unit
*u
= owner
? owner
: pVictim
;
1205 if(u
->IsPvP() && (!duel
|| duel
->opponent
!= u
))
1208 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT
);
1213 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
))
1215 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1217 int time_inn
= time(NULL
)-GetTimeInnEnter();
1218 if (time_inn
>= 10) //freeze update
1220 float bubble
= 0.125*sWorld
.getRate(RATE_REST_INGAME
);
1221 //speed collect rest bonus (section/in hour)
1222 SetRestBonus( GetRestBonus()+ time_inn
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
1223 UpdateInnerTime(time(NULL
));
1228 if(m_regenTimer
> 0)
1230 if(p_time
>= m_regenTimer
)
1233 m_regenTimer
-= p_time
;
1236 if (m_weaponChangeTimer
> 0)
1238 if(p_time
>= m_weaponChangeTimer
)
1239 m_weaponChangeTimer
= 0;
1241 m_weaponChangeTimer
-= p_time
;
1244 if (m_zoneUpdateTimer
> 0)
1246 if(p_time
>= m_zoneUpdateTimer
)
1248 uint32 newzone
, newarea
;
1249 GetZoneAndAreaId(newzone
,newarea
);
1251 if( m_zoneUpdateId
!= newzone
)
1252 UpdateZone(newzone
,newarea
); // also update area
1255 // use area updates as well
1256 // needed for free far all arenas for example
1257 if( m_areaUpdateId
!= newarea
)
1258 UpdateArea(newarea
);
1260 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
1264 m_zoneUpdateTimer
-= p_time
;
1272 if (m_deathState
== JUST_DIED
)
1279 if(p_time
>= m_nextSave
)
1281 // m_nextSave reseted in SaveToDB call
1283 sLog
.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1287 m_nextSave
-= p_time
;
1291 //Handle Water/drowning
1292 HandleDrowning(p_time
);
1294 //Handle detect stealth players
1295 if (m_DetectInvTimer
> 0)
1297 if (p_time
>= m_DetectInvTimer
)
1299 m_DetectInvTimer
= 3000;
1300 HandleStealthedUnitsDetection();
1303 m_DetectInvTimer
-= p_time
;
1307 if (now
> m_Last_tick
)
1309 uint32 elapsed
= uint32(now
- m_Last_tick
);
1310 m_Played_time
[0] += elapsed
; // Total played time
1311 m_Played_time
[1] += elapsed
; // Level played time
1317 m_drunkTimer
+= p_time
;
1319 if (m_drunkTimer
> 10*IN_MILISECONDS
)
1323 // not auto-free ghost from body in instances
1324 if(m_deathTimer
> 0 && !GetBaseMap()->Instanceable())
1326 if(p_time
>= m_deathTimer
)
1333 m_deathTimer
-= p_time
;
1336 UpdateEnchantTime(p_time
);
1337 UpdateHomebindTime(p_time
);
1340 SendUpdateToOutOfRangeGroupMembers();
1342 Pet
* pet
= GetPet();
1343 if(pet
&& !IsWithinDistInMap(pet
, OWNER_MAX_DISTANCE
) && (GetCharmGUID() && (pet
->GetGUID() != GetCharmGUID())))
1345 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
, true);
1350 void Player::setDeathState(DeathState s
)
1352 uint32 ressSpellId
= 0;
1354 bool cur
= isAlive();
1356 if(s
== JUST_DIED
&& cur
)
1358 // drunken state is cleared on death
1360 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1363 clearResurrectRequestData();
1365 // remove form before other mods to prevent incorrect stats calculation
1366 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId
);
1368 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1369 RemovePet(NULL
, PET_SAVE_NOT_IN_SLOT
, true);
1371 // remove uncontrolled pets
1375 // save value before aura remove in Unit::setDeathState
1376 ressSpellId
= GetUInt32Value(PLAYER_SELF_RES_SPELL
);
1380 ressSpellId
= GetResurrectionSpellId();
1381 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP
, 1);
1382 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH
, 1);
1383 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON
, 1);
1385 Unit::setDeathState(s
);
1387 // restore resurrection spell id for player after aura remove
1388 if(s
== JUST_DIED
&& cur
&& ressSpellId
)
1389 SetUInt32Value(PLAYER_SELF_RES_SPELL
, ressSpellId
);
1391 if(isAlive() && !cur
)
1393 //clear aura case after resurrection by another way (spells will be applied before next death)
1394 SetUInt32Value(PLAYER_SELF_RES_SPELL
, 0);
1396 // restore default warrior stance
1397 if(getClass()== CLASS_WARRIOR
)
1398 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
1402 void Player::BuildEnumData( QueryResult
* result
, WorldPacket
* p_data
)
1404 Field
*fields
= result
->Fetch();
1406 *p_data
<< uint64(GetGUID());
1409 *p_data
<< uint8(getRace());
1410 uint8 pClass
= getClass();
1411 *p_data
<< uint8(pClass
);
1412 *p_data
<< uint8(getGender());
1414 uint32 bytes
= GetUInt32Value(PLAYER_BYTES
);
1415 *p_data
<< uint8(bytes
);
1416 *p_data
<< uint8(bytes
>> 8);
1417 *p_data
<< uint8(bytes
>> 16);
1418 *p_data
<< uint8(bytes
>> 24);
1420 bytes
= GetUInt32Value(PLAYER_BYTES_2
);
1421 *p_data
<< uint8(bytes
);
1423 *p_data
<< uint8(getLevel()); // player level
1424 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1425 uint32 zoneId
= MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY(),GetPositionZ());
1426 sLog
.outDebug("Player::BuildEnumData: m:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId
);
1427 *p_data
<< uint32(zoneId
);
1428 *p_data
<< uint32(GetMapId());
1430 *p_data
<< GetPositionX();
1431 *p_data
<< GetPositionY();
1432 *p_data
<< GetPositionZ();
1435 *p_data
<< (result
? fields
[13].GetUInt32() : 0);
1437 uint32 char_flags
= 0;
1438 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
1439 char_flags
|= CHARACTER_FLAG_HIDE_HELM
;
1440 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
1441 char_flags
|= CHARACTER_FLAG_HIDE_CLOAK
;
1442 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
))
1443 char_flags
|= CHARACTER_FLAG_GHOST
;
1444 if(HasAtLoginFlag(AT_LOGIN_RENAME
))
1445 char_flags
|= CHARACTER_FLAG_RENAME
;
1446 if(sWorld
.getConfig(CONFIG_DECLINED_NAMES_USED
) && (fields
[14].GetCppString() != ""))
1447 char_flags
|= CHARACTER_FLAG_DECLINED
;
1449 *p_data
<< uint32(char_flags
); // character flags
1450 // character customize (flags?)
1451 *p_data
<< uint32(HasAtLoginFlag(AT_LOGIN_CUSTOMIZE
) ? 1 : 0);
1452 *p_data
<< uint8(1); // unknown
1456 uint32 petDisplayId
= 0;
1457 uint32 petLevel
= 0;
1458 uint32 petFamily
= 0;
1460 // show pet at selection character in character list only for non-ghost character
1461 if(result
&& isAlive() && (pClass
== CLASS_WARLOCK
|| pClass
== CLASS_HUNTER
))
1463 uint32 entry
= fields
[10].GetUInt32();
1464 CreatureInfo
const* cInfo
= sCreatureStorage
.LookupEntry
<CreatureInfo
>(entry
);
1467 petDisplayId
= fields
[11].GetUInt32();
1468 petLevel
= fields
[12].GetUInt32();
1469 petFamily
= cInfo
->family
;
1473 *p_data
<< uint32(petDisplayId
);
1474 *p_data
<< uint32(petLevel
);
1475 *p_data
<< uint32(petFamily
);
1478 for (uint8 slot
= 0; slot
< EQUIPMENT_SLOT_END
; slot
++)
1480 uint32 visualbase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
1481 uint32 item_id
= GetUInt32Value(visualbase
);
1482 const ItemPrototype
* proto
= objmgr
.GetItemPrototype(item_id
);
1483 SpellItemEnchantmentEntry
const *enchant
= NULL
;
1485 for(uint8 enchantSlot
= PERM_ENCHANTMENT_SLOT
; enchantSlot
<=TEMP_ENCHANTMENT_SLOT
; enchantSlot
++)
1487 uint32 enchantId
= GetUInt32Value(visualbase
+1+enchantSlot
);
1488 if(enchant
= sSpellItemEnchantmentStore
.LookupEntry(enchantId
))
1494 *p_data
<< uint32(proto
->DisplayInfoID
);
1495 *p_data
<< uint8(proto
->InventoryType
);
1496 *p_data
<< uint32(enchant
? enchant
->aura_id
: 0);
1500 *p_data
<< uint32(0);
1501 *p_data
<< uint8(0);
1502 *p_data
<< uint32(0); // enchant?
1505 *p_data
<< uint32(0); // first bag display id
1506 *p_data
<< uint8(0); // first bag inventory type
1507 *p_data
<< uint32(0); // enchant?
1510 bool Player::ToggleAFK()
1512 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1514 bool state
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1516 // afk player not allowed in battleground
1517 if(state
&& InBattleGround())
1518 LeaveBattleground();
1523 bool Player::ToggleDND()
1525 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1527 return HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1530 uint8
Player::chatTag() const
1547 bool Player::TeleportTo(uint32 mapid
, float x
, float y
, float z
, float orientation
, uint32 options
)
1549 if(!MapManager::IsValidMapCoord(mapid
, x
, y
, z
, orientation
))
1551 sLog
.outError("TeleportTo: invalid map %d or absent instance template.", mapid
);
1555 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1556 Pet
* pet
= GetPet();
1558 MapEntry
const* mEntry
= sMapStore
.LookupEntry(mapid
);
1560 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1561 // don't let gm level > 1 either
1562 if(!InBattleGround() && mEntry
->IsBattleGroundOrArena())
1565 // client without expansion support
1566 if(GetSession()->Expansion() < mEntry
->Expansion())
1568 sLog
.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid
);
1571 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1573 SendTransferAborted(mapid
, TRANSFER_ABORT_INSUF_EXPAN_LVL
, mEntry
->Expansion());
1575 return false; // normal client can't teleport to this map...
1579 sLog
.outDebug("Player %s is being teleported to map %u", GetName(), mapid
);
1582 // if we were on a transport, leave
1583 if (!(options
& TELE_TO_NOT_LEAVE_TRANSPORT
) && m_transport
)
1585 m_transport
->RemovePassenger(this);
1587 m_movementInfo
.t_x
= 0.0f
;
1588 m_movementInfo
.t_y
= 0.0f
;
1589 m_movementInfo
.t_z
= 0.0f
;
1590 m_movementInfo
.t_o
= 0.0f
;
1591 m_movementInfo
.t_time
= 0;
1594 // The player was ported to another map and looses the duel immediately.
1595 // We have to perform this check before the teleport, otherwise the
1596 // ObjectAccessor won't find the flag.
1597 if (duel
&& GetMapId()!=mapid
)
1599 GameObject
* obj
= GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER
));
1601 DuelComplete(DUEL_FLED
);
1604 // reset movement flags at teleport, because player will continue move with these flags after teleport
1605 SetUnitMovementFlags(0);
1607 if ((GetMapId() == mapid
) && (!m_transport
))
1609 if (!(options
& TELE_TO_NOT_UNSUMMON_PET
))
1611 //same map, only remove pet if out of range for new position
1612 if(pet
&& pet
->GetDistance(x
,y
,z
) >= OWNER_MAX_DISTANCE
)
1613 UnsummonPetTemporaryIfAny();
1616 if(!(options
& TELE_TO_NOT_LEAVE_COMBAT
))
1619 // this will be used instead of the current location in SaveToDB
1620 m_teleport_dest
= WorldLocation(mapid
, x
, y
, z
, orientation
);
1621 SetFallInformation(0, z
);
1623 // code for finish transfer called in WorldSession::HandleMovementOpcodes()
1624 // at client packet MSG_MOVE_TELEPORT_ACK
1625 SetSemaphoreTeleportNear(true);
1626 // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
1627 if(!GetSession()->PlayerLogout())
1630 BuildTeleportAckMsg(&data
, x
, y
, z
, orientation
);
1631 GetSession()->SendPacket(&data
);
1636 // far teleport to another map
1637 Map
* oldmap
= IsInWorld() ? GetMap() : NULL
;
1638 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1640 // Check enter rights before map getting to avoid creating instance copy for player
1641 // this check not dependent from map instance copy and same for all instance copies of selected map
1642 if (!MapManager::Instance().CanPlayerEnter(mapid
, this))
1645 // If the map is not created, assume it is possible to enter it.
1646 // It will be created in the WorldPortAck.
1647 Map
*map
= MapManager::Instance().FindMap(mapid
);
1648 if (!map
|| map
->CanEnter(this))
1654 ResetContestedPvP();
1656 // remove player from battleground on far teleport (when changing maps)
1657 if(BattleGround
const* bg
= GetBattleGround())
1659 // Note: at battleground join battleground id set before teleport
1660 // and we already will found "current" battleground
1661 // just need check that this is targeted map or leave
1662 if(bg
->GetMapId() != mapid
)
1663 LeaveBattleground(false); // don't teleport to entry point
1666 // remove pet on map change
1668 UnsummonPetTemporaryIfAny();
1670 // remove all dyn objects
1671 RemoveAllDynObjects();
1673 // stop spellcasting
1674 // not attempt interrupt teleportation spell at caster teleport
1675 if(!(options
& TELE_TO_SPELL
))
1676 if(IsNonMeleeSpellCasted(true))
1677 InterruptNonMeleeSpells(true);
1679 if(!GetSession()->PlayerLogout())
1681 // send transfer packets
1682 WorldPacket
data(SMSG_TRANSFER_PENDING
, (4+4+4));
1683 data
<< uint32(mapid
);
1686 data
<< m_transport
->GetEntry() << GetMapId();
1688 GetSession()->SendPacket(&data
);
1690 data
.Initialize(SMSG_NEW_WORLD
, (20));
1693 data
<< (uint32
)mapid
<< m_movementInfo
.t_x
<< m_movementInfo
.t_y
<< m_movementInfo
.t_z
<< m_movementInfo
.t_o
;
1697 data
<< (uint32
)mapid
<< (float)x
<< (float)y
<< (float)z
<< (float)orientation
;
1699 GetSession()->SendPacket( &data
);
1700 SendSavedInstances();
1702 // remove from old map now
1703 if(oldmap
) oldmap
->Remove(this, false);
1706 // new final coordinates
1710 float final_o
= orientation
;
1714 final_x
+= m_movementInfo
.t_x
;
1715 final_y
+= m_movementInfo
.t_y
;
1716 final_z
+= m_movementInfo
.t_z
;
1717 final_o
+= m_movementInfo
.t_o
;
1720 m_teleport_dest
= WorldLocation(mapid
, final_x
, final_y
, final_z
, final_o
);
1721 SetFallInformation(0, final_z
);
1722 // if the player is saved before worldportack (at logout for example)
1723 // this will be used instead of the current location in SaveToDB
1725 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP
| AURA_INTERRUPT_FLAG_MOVE
| AURA_INTERRUPT_FLAG_TURNING
);
1727 // move packet sent by client always after far teleport
1728 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1729 SetSemaphoreTeleportFar(true);
1737 void Player::AddToWorld()
1739 ///- Do not add/remove the player from the object storage
1740 ///- It will crash when updating the ObjectAccessor
1741 ///- The player should only be added when logging in
1744 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; ++i
)
1747 m_items
[i
]->AddToWorld();
1751 void Player::RemoveFromWorld()
1756 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1758 UnsummonAllTotems();
1763 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; ++i
)
1766 m_items
[i
]->RemoveFromWorld();
1769 ///- Do not add/remove the player from the object storage
1770 ///- It will crash when updating the ObjectAccessor
1771 ///- The player should only be removed when logging out
1772 Unit::RemoveFromWorld();
1775 void Player::RewardRage( uint32 damage
, uint32 weaponSpeedHitFactor
, bool attacker
)
1779 float rageconversion
= ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1783 addRage
= ((damage
/rageconversion
*7.5 + weaponSpeedHitFactor
)/2);
1785 // talent who gave more rage on attack
1786 addRage
*= 1.0f
+ GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT
) / 100.0f
;
1790 addRage
= damage
/rageconversion
*2.5;
1792 // Berserker Rage effect
1793 if(HasAura(18499,0))
1797 addRage
*= sWorld
.getRate(RATE_POWER_RAGE_INCOME
);
1799 ModifyPower(POWER_RAGE
, uint32(addRage
*10));
1802 void Player::RegenerateAll()
1804 if (m_regenTimer
!= 0)
1806 uint32 regenDelay
= 2000;
1808 // Not in combat or they have regeneration
1809 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) ||
1810 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
) || IsPolymorphed() )
1813 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN
))
1815 Regenerate(POWER_RAGE
);
1816 if(getClass() == CLASS_DEATH_KNIGHT
)
1817 Regenerate(POWER_RUNIC_POWER
);
1821 Regenerate( POWER_ENERGY
);
1823 Regenerate( POWER_MANA
);
1825 if(getClass() == CLASS_DEATH_KNIGHT
)
1826 Regenerate( POWER_RUNE
);
1828 m_regenTimer
= regenDelay
;
1831 void Player::Regenerate(Powers power
)
1833 uint32 curValue
= GetPower(power
);
1834 uint32 maxValue
= GetMaxPower(power
);
1836 float addvalue
= 0.0f
;
1842 bool recentCast
= IsUnderLastManaUseEffect();
1843 float ManaIncreaseRate
= sWorld
.getRate(RATE_POWER_MANA
);
1846 // Mangos Updates Mana in intervals of 2s, which is correct
1847 addvalue
= GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER
) * ManaIncreaseRate
* 2.00f
;
1851 addvalue
= GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER
) * ManaIncreaseRate
* 2.00f
;
1854 case POWER_RAGE
: // Regenerate rage
1856 float RageDecreaseRate
= sWorld
.getRate(RATE_POWER_RAGE_LOSS
);
1857 addvalue
= 30 * RageDecreaseRate
; // 3 rage by tick
1859 case POWER_ENERGY
: // Regenerate energy (rogue)
1862 case POWER_RUNIC_POWER
:
1864 float RunicPowerDecreaseRate
= sWorld
.getRate(RATE_POWER_RUNICPOWER_LOSS
);
1865 addvalue
= 30 * RunicPowerDecreaseRate
; // 3 RunicPower by tick
1869 for(uint32 i
= 0; i
< MAX_RUNES
; ++i
)
1870 if(uint8 cd
= GetRuneCooldown(i
)) // if we have cooldown, reduce it...
1871 SetRuneCooldown(i
, cd
- 1); // ... by 2 sec (because update is every 2 sec)
1874 case POWER_HAPPINESS
:
1879 // Mana regen calculated in Player::UpdateManaRegen()
1880 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1881 if(power
!= POWER_MANA
)
1883 AuraList
const& ModPowerRegenPCTAuras
= GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT
);
1884 for(AuraList::const_iterator i
= ModPowerRegenPCTAuras
.begin(); i
!= ModPowerRegenPCTAuras
.end(); ++i
)
1885 if ((*i
)->GetModifier()->m_miscvalue
== power
)
1886 addvalue
*= ((*i
)->GetModifier()->m_amount
+ 100) / 100.0f
;
1889 if (power
!= POWER_RAGE
&& power
!= POWER_RUNIC_POWER
)
1891 curValue
+= uint32(addvalue
);
1892 if (curValue
> maxValue
)
1893 curValue
= maxValue
;
1897 if(curValue
<= uint32(addvalue
))
1900 curValue
-= uint32(addvalue
);
1902 SetPower(power
, curValue
);
1905 void Player::RegenerateHealth()
1907 uint32 curValue
= GetHealth();
1908 uint32 maxValue
= GetMaxHealth();
1910 if (curValue
>= maxValue
) return;
1912 float HealthIncreaseRate
= sWorld
.getRate(RATE_HEALTH
);
1914 float addvalue
= 0.0f
;
1917 if ( IsPolymorphed() )
1918 addvalue
= GetMaxHealth()/3;
1919 // normal regen case (maybe partly in combat case)
1920 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) )
1922 addvalue
= OCTRegenHPPerSpirit()* HealthIncreaseRate
;
1925 AuraList
const& mModHealthRegenPct
= GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT
);
1926 for(AuraList::const_iterator i
= mModHealthRegenPct
.begin(); i
!= mModHealthRegenPct
.end(); ++i
)
1927 addvalue
*= (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
;
1929 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
))
1930 addvalue
*= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) / 100.0f
;
1936 // always regeneration bonus (including combat)
1937 addvalue
+= GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
);
1942 ModifyHealth(int32(addvalue
));
1945 bool Player::CanInteractWithNPCs(bool alive
) const
1947 if(alive
&& !isAlive())
1956 Player::GetNPCIfCanInteractWith(uint64 guid
, uint32 npcflagmask
)
1965 // exist (we need look pets also for some interaction (quest/etc)
1966 Creature
*unit
= ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid
);
1971 if(!CanInteractWithNPCs(!unit
->isSpiritService()))
1974 // appropriate npc type
1975 if(npcflagmask
&& !unit
->HasFlag( UNIT_NPC_FLAGS
, npcflagmask
))
1978 // alive or spirit healer
1979 if(!unit
->isAlive() && (!unit
->isSpiritService() || isAlive() ))
1982 // not allow interaction under control, but allow with own pets
1983 if(unit
->GetCharmerGUID())
1987 if( unit
->IsHostileTo(this))
1991 if(FactionTemplateEntry
const* factionTemplate
= sFactionTemplateStore
.LookupEntry(unit
->getFaction()))
1992 if(factionTemplate
->faction
)
1993 if(FactionEntry
const* faction
= sFactionStore
.LookupEntry(factionTemplate
->faction
))
1994 if(faction
->reputationListID
>= 0 && GetReputationMgr().GetRank(faction
) <= REP_UNFRIENDLY
)
1998 if(!unit
->IsWithinDistInMap(this,INTERACTION_DISTANCE
))
2004 GameObject
* Player::GetGameObjectIfCanInteractWith(uint64 guid
, GameobjectTypes type
) const
2006 if(GameObject
*go
= GetMap()->GetGameObject(guid
))
2008 if(go
->GetGoType() == type
)
2013 // TODO: find out how the client calculates the maximal usage distance to spellless working
2014 // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
2015 case GAMEOBJECT_TYPE_GUILD_BANK
:
2016 case GAMEOBJECT_TYPE_MAILBOX
:
2019 case GAMEOBJECT_TYPE_FISHINGHOLE
:
2020 maxdist
= 20.0f
+CONTACT_DISTANCE
; // max spell range
2023 maxdist
= INTERACTION_DISTANCE
;
2027 if (go
->IsWithinDistInMap(this, maxdist
))
2030 sLog
.outError("IsGameObjectOfTypeInRange: GameObject '%s' [GUID: %u] is too far away from player %s [GUID: %u] to be used by him (distance=%f, maximal 10 is allowed)", go
->GetGOInfo()->name
,
2031 go
->GetGUIDLow(), GetName(), GetGUIDLow(), go
->GetDistance(this));
2037 bool Player::IsUnderWater() const
2039 return IsInWater() &&
2040 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2043 void Player::SetInWater(bool apply
)
2045 if(m_isInWater
==apply
)
2048 //define player in water by opcodes
2049 //move player's guid into HateOfflineList of those mobs
2050 //which can't swim and move guid back into ThreatList when
2052 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2053 m_isInWater
= apply
;
2055 // remove auras that need water/land
2056 RemoveAurasWithInterruptFlags(apply
? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER
: AURA_INTERRUPT_FLAG_NOT_UNDERWATER
);
2058 getHostilRefManager().updateThreatTables();
2061 void Player::SetGameMaster(bool on
)
2065 m_ExtraFlags
|= PLAYER_EXTRA_GM_ON
;
2067 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
2069 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
2070 ResetContestedPvP();
2072 getHostilRefManager().setOnlineOfflineState(false);
2075 SetPhaseMask(PHASEMASK_ANYWHERE
,false); // see and visible in all phases
2080 AuraList
const& phases
= GetAurasByType(SPELL_AURA_PHASE
);
2081 SetPhaseMask(!phases
.empty() ? phases
.front()->GetMiscValue() : PHASEMASK_NORMAL
,false);
2083 m_ExtraFlags
&= ~ PLAYER_EXTRA_GM_ON
;
2084 setFactionForRace(getRace());
2085 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
2087 // restore FFA PvP Server state
2088 if(sWorld
.IsFFAPvPRealm())
2089 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
2091 // restore FFA PvP area state, remove not allowed for GM mounts
2092 UpdateArea(m_areaUpdateId
);
2094 getHostilRefManager().setOnlineOfflineState(true);
2097 ObjectAccessor::UpdateVisibilityForPlayer(this);
2100 void Player::SetGMVisible(bool on
)
2104 m_ExtraFlags
&= ~PLAYER_EXTRA_GM_INVISIBLE
; //remove flag
2106 // Reapply stealth/invisibility if active or show if not any
2107 if(HasAuraType(SPELL_AURA_MOD_STEALTH
))
2108 SetVisibility(VISIBILITY_GROUP_STEALTH
);
2109 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY
))
2110 SetVisibility(VISIBILITY_GROUP_INVISIBILITY
);
2112 SetVisibility(VISIBILITY_ON
);
2116 m_ExtraFlags
|= PLAYER_EXTRA_GM_INVISIBLE
; //add flag
2118 SetAcceptWhispers(false);
2119 SetGameMaster(true);
2121 SetVisibility(VISIBILITY_OFF
);
2125 bool Player::IsGroupVisibleFor(Player
* p
) const
2127 switch(sWorld
.getConfig(CONFIG_GROUP_VISIBILITY
))
2129 default: return IsInSameGroupWith(p
);
2130 case 1: return IsInSameRaidWith(p
);
2131 case 2: return GetTeam()==p
->GetTeam();
2135 bool Player::IsInSameGroupWith(Player
const* p
) const
2137 return p
==this || GetGroup() != NULL
&&
2138 GetGroup() == p
->GetGroup() &&
2139 GetGroup()->SameSubGroup((Player
*)this, (Player
*)p
);
2142 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2143 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2144 void Player::UninviteFromGroup()
2146 Group
* group
= GetGroupInvite();
2150 group
->RemoveInvite(this);
2152 if(group
->GetMembersCount() <= 1) // group has just 1 member => disband
2154 if(group
->IsCreated())
2156 group
->Disband(true);
2157 objmgr
.RemoveGroup(group
);
2160 group
->RemoveAllInvites();
2166 void Player::RemoveFromGroup(Group
* group
, uint64 guid
)
2170 if (group
->RemoveMember(guid
, 0) <= 1)
2172 // group->Disband(); already disbanded in RemoveMember
2173 objmgr
.RemoveGroup(group
);
2175 // removemember sets the player's group pointer to NULL
2180 void Player::SendLogXPGain(uint32 GivenXP
, Unit
* victim
, uint32 RestXP
)
2182 WorldPacket
data(SMSG_LOG_XPGAIN
, 21);
2183 data
<< uint64(victim
? victim
->GetGUID() : 0); // guid
2184 data
<< uint32(GivenXP
+RestXP
); // given experience
2185 data
<< uint8(victim
? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2188 data
<< uint32(GivenXP
); // experience without rested bonus
2189 data
<< float(1); // 1 - none 0 - 100% group bonus output
2191 data
<< uint8(0); // new 2.4.0
2192 GetSession()->SendPacket(&data
);
2195 void Player::GiveXP(uint32 xp
, Unit
* victim
)
2203 uint32 level
= getLevel();
2205 // XP to money conversion processed in Player::RewardQuest
2206 if(level
>= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
2209 // handle SPELL_AURA_MOD_XP_PCT auras
2210 Unit::AuraList
const& ModXPPctAuras
= GetAurasByType(SPELL_AURA_MOD_XP_PCT
);
2211 for(Unit::AuraList::const_iterator i
= ModXPPctAuras
.begin();i
!= ModXPPctAuras
.end(); ++i
)
2212 xp
= uint32(xp
*(1.0f
+ (*i
)->GetModifier()->m_amount
/ 100.0f
));
2214 // XP resting bonus for kill
2215 uint32 rested_bonus_xp
= victim
? GetXPRestBonus(xp
) : 0;
2217 SendLogXPGain(xp
,victim
,rested_bonus_xp
);
2219 uint32 curXP
= GetUInt32Value(PLAYER_XP
);
2220 uint32 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2221 uint32 newXP
= curXP
+ xp
+ rested_bonus_xp
;
2223 while( newXP
>= nextLvlXP
&& level
< sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
2227 if ( level
< sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
2228 GiveLevel(level
+ 1);
2231 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2234 SetUInt32Value(PLAYER_XP
, newXP
);
2237 // Update player to next level
2238 // Current player experience not update (must be update by caller)
2239 void Player::GiveLevel(uint32 level
)
2241 if ( level
== getLevel() )
2244 PlayerLevelInfo info
;
2245 objmgr
.GetPlayerLevelInfo(getRace(),getClass(),level
,&info
);
2247 PlayerClassLevelInfo classInfo
;
2248 objmgr
.GetPlayerClassLevelInfo(getClass(),level
,&classInfo
);
2250 // send levelup info to client
2251 WorldPacket
data(SMSG_LEVELUP_INFO
, (4+4+MAX_POWERS
*4+MAX_STATS
*4));
2252 data
<< uint32(level
);
2253 data
<< uint32(int32(classInfo
.basehealth
) - int32(GetCreateHealth()));
2254 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2255 data
<< uint32(int32(classInfo
.basemana
) - int32(GetCreateMana()));
2263 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
) // Stats loop (0-4)
2264 data
<< uint32(int32(info
.stats
[i
]) - GetCreateStat(Stats(i
)));
2266 GetSession()->SendPacket(&data
);
2268 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, objmgr
.GetXPForLevel(level
));
2270 //update level, max level of skills
2271 if(getLevel()!= level
)
2272 m_Played_time
[1] = 0; // Level Played Time reset
2274 UpdateSkillsForLevel ();
2276 // save base values (bonuses already included in stored stats
2277 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2278 SetCreateStat(Stats(i
), info
.stats
[i
]);
2280 SetCreateHealth(classInfo
.basehealth
);
2281 SetCreateMana(classInfo
.basemana
);
2283 InitTalentForLevel();
2284 InitTaxiNodesForLevel();
2285 InitGlyphsForLevel();
2289 // set current level health and mana/energy to maximum after applying all mods.
2290 SetHealth(GetMaxHealth());
2291 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2292 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2293 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2294 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2295 SetPower(POWER_FOCUS
, 0);
2296 SetPower(POWER_HAPPINESS
, 0);
2298 // give level to summoned pet
2299 Pet
* pet
= GetPet();
2300 if(pet
&& pet
->getPetType()==SUMMON_PET
)
2301 pet
->GivePetLevel(level
);
2302 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL
);
2305 void Player::InitTalentForLevel()
2307 uint32 level
= getLevel();
2308 // talents base at level diff ( talents = level - 9 but some can be used already)
2311 // Remove all talent points
2312 if(m_usedTalentCount
> 0) // Free any used talents
2315 SetFreeTalentPoints(0);
2320 uint32 talentPointsForLevel
= CalculateTalentsPoints();
2322 // if used more that have then reset
2323 if(m_usedTalentCount
> talentPointsForLevel
)
2325 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR
)
2328 SetFreeTalentPoints(0);
2330 // else update amount of free points
2332 SetFreeTalentPoints(talentPointsForLevel
-m_usedTalentCount
);
2336 void Player::InitStatsForLevel(bool reapplyMods
)
2338 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2339 _RemoveAllStatBonuses();
2341 PlayerClassLevelInfo classInfo
;
2342 objmgr
.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo
);
2344 PlayerLevelInfo info
;
2345 objmgr
.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info
);
2347 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL
, sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) );
2348 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, objmgr
.GetXPForLevel(getLevel()));
2350 UpdateSkillsForLevel ();
2352 // set default cast time multiplier
2353 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
);
2355 // reset size before reapply auras
2356 SetFloatValue(OBJECT_FIELD_SCALE_X
,1.0f
);
2358 // save base values (bonuses already included in stored stats
2359 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2360 SetCreateStat(Stats(i
), info
.stats
[i
]);
2362 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2363 SetStat(Stats(i
), info
.stats
[i
]);
2365 SetCreateHealth(classInfo
.basehealth
);
2368 SetCreateMana(classInfo
.basemana
);
2370 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2374 //reset rating fields values
2375 for(uint16 index
= PLAYER_FIELD_COMBAT_RATING_1
; index
< PLAYER_FIELD_COMBAT_RATING_1
+ MAX_COMBAT_RATING
; ++index
)
2376 SetUInt32Value(index
, 0);
2378 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS
,0);
2379 for (int i
= 0; i
< 7; ++i
)
2381 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG
+i
, 0);
2382 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS
+i
, 0);
2383 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT
+i
, 1.00f
);
2386 //reset attack power, damage and attack speed fields
2387 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
, 2000.0f
);
2388 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
+ 1, 2000.0f
); // offhand attack time
2389 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME
, 2000.0f
);
2391 SetFloatValue(UNIT_FIELD_MINDAMAGE
, 0.0f
);
2392 SetFloatValue(UNIT_FIELD_MAXDAMAGE
, 0.0f
);
2393 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
, 0.0f
);
2394 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
, 0.0f
);
2395 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
, 0.0f
);
2396 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
, 0.0f
);
2398 SetInt32Value(UNIT_FIELD_ATTACK_POWER
, 0 );
2399 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS
, 0 );
2400 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER
,0.0f
);
2401 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER
, 0 );
2402 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS
,0 );
2403 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER
,0.0f
);
2405 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2406 SetFloatValue(PLAYER_CRIT_PERCENTAGE
,0.0f
);
2407 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE
,0.0f
);
2408 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE
,0.0f
);
2410 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2411 for (uint8 i
= 0; i
< 7; ++i
)
2412 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1
+i
, 0.0f
);
2414 SetFloatValue(PLAYER_PARRY_PERCENTAGE
, 0.0f
);
2415 SetFloatValue(PLAYER_BLOCK_PERCENTAGE
, 0.0f
);
2416 SetUInt32Value(PLAYER_SHIELD_BLOCK
, 0);
2419 SetFloatValue(PLAYER_DODGE_PERCENTAGE
, 0.0f
);
2421 // set armor (resistance 0) to original value (create_agility*2)
2422 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2423 SetResistanceBuffMods(SpellSchools(0), true, 0.0f
);
2424 SetResistanceBuffMods(SpellSchools(0), false, 0.0f
);
2425 // set other resistance to original value (0)
2426 for (int i
= 1; i
< MAX_SPELL_SCHOOL
; ++i
)
2428 SetResistance(SpellSchools(i
), 0);
2429 SetResistanceBuffMods(SpellSchools(i
), true, 0.0f
);
2430 SetResistanceBuffMods(SpellSchools(i
), false, 0.0f
);
2433 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE
,0);
2434 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE
,0);
2435 for(int i
= 0; i
< MAX_SPELL_SCHOOL
; ++i
)
2437 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER
+i
,0);
2438 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER
+i
,0.0f
);
2440 // Reset no reagent cost field
2441 for(int i
= 0; i
< 3; ++i
)
2442 SetUInt32Value(PLAYER_NO_REAGENT_COST_1
+ i
, 0);
2443 // Init data for form but skip reapply item mods for form
2444 InitDataForForm(reapplyMods
);
2447 for (int i
= POWER_MANA
; i
< MAX_POWERS
; ++i
)
2448 SetMaxPower(Powers(i
), uint32(GetCreatePowers(Powers(i
))));
2450 SetMaxHealth(classInfo
.basehealth
); // stamina bonus will applied later
2452 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2453 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID
, 0);
2455 // cleanup unit flags (will be re-applied if need at aura load).
2456 RemoveFlag( UNIT_FIELD_FLAGS
,
2457 UNIT_FLAG_NON_ATTACKABLE
| UNIT_FLAG_DISABLE_MOVE
| UNIT_FLAG_NOT_ATTACKABLE_1
|
2458 UNIT_FLAG_PET_IN_COMBAT
| UNIT_FLAG_SILENCED
| UNIT_FLAG_PACIFIED
|
2459 UNIT_FLAG_STUNNED
| UNIT_FLAG_IN_COMBAT
| UNIT_FLAG_DISARMED
|
2460 UNIT_FLAG_CONFUSED
| UNIT_FLAG_FLEEING
| UNIT_FLAG_NOT_SELECTABLE
|
2461 UNIT_FLAG_SKINNABLE
| UNIT_FLAG_MOUNT
| UNIT_FLAG_TAXI_FLIGHT
);
2462 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
); // must be set
2464 SetFlag(UNIT_FIELD_FLAGS_2
,UNIT_FLAG2_REGENERATE_POWER
);// must be set
2466 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2467 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
| PLAYER_FLAGS_DND
| PLAYER_FLAGS_GM
| PLAYER_FLAGS_GHOST
);
2469 RemoveStandFlags(UNIT_STAND_FLAGS_ALL
); // one form stealth modified bytes
2470 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
| UNIT_BYTE2_FLAG_SANCTUARY
);
2472 // restore if need some important flags
2473 SetUInt32Value(PLAYER_FIELD_BYTES2
, 0 ); // flags empty by default
2475 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2476 _ApplyAllStatBonuses();
2478 // set current level health and mana/energy to maximum after applying all mods.
2479 SetHealth(GetMaxHealth());
2480 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2481 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2482 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2483 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2484 SetPower(POWER_FOCUS
, 0);
2485 SetPower(POWER_HAPPINESS
, 0);
2486 SetPower(POWER_RUNIC_POWER
, 0);
2489 void Player::SendInitialSpells()
2491 time_t curTime
= time(NULL
);
2492 time_t infTime
= curTime
+ MONTH
/2;
2494 uint16 spellCount
= 0;
2496 WorldPacket
data(SMSG_INITIAL_SPELLS
, (1+2+4*m_spells
.size()+2+m_spellCooldowns
.size()*(2+2+2+4+4)));
2499 size_t countPos
= data
.wpos();
2500 data
<< uint16(spellCount
); // spell count placeholder
2502 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2504 if(itr
->second
->state
== PLAYERSPELL_REMOVED
)
2507 if(!itr
->second
->active
|| itr
->second
->disabled
)
2510 data
<< uint16(itr
->first
);
2511 data
<< uint16(0); // it's not slot id
2516 data
.put
<uint16
>(countPos
,spellCount
); // write real count value
2518 uint16 spellCooldowns
= m_spellCooldowns
.size();
2519 data
<< uint16(spellCooldowns
);
2520 for(SpellCooldowns::const_iterator itr
=m_spellCooldowns
.begin(); itr
!=m_spellCooldowns
.end(); ++itr
)
2522 SpellEntry
const *sEntry
= sSpellStore
.LookupEntry(itr
->first
);
2526 // not send infinity cooldown
2527 if(itr
->second
.end
> infTime
)
2530 data
<< uint16(itr
->first
);
2532 time_t cooldown
= 0;
2533 if(itr
->second
.end
> curTime
)
2534 cooldown
= (itr
->second
.end
-curTime
)*IN_MILISECONDS
;
2536 data
<< uint16(itr
->second
.itemid
); // cast item id
2537 data
<< uint16(sEntry
->Category
); // spell category
2538 if(sEntry
->Category
) // may be wrong, but anyway better than nothing...
2540 data
<< uint32(0); // cooldown
2541 data
<< uint32(cooldown
); // category cooldown
2545 data
<< uint32(cooldown
); // cooldown
2546 data
<< uint32(0); // category cooldown
2550 GetSession()->SendPacket(&data
);
2552 sLog
.outDetail( "CHARACTER: Sent Initial Spells" );
2555 void Player::RemoveMail(uint32 id
)
2557 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
2559 if ((*itr
)->messageID
== id
)
2561 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2568 void Player::SendMailResult(uint32 mailId
, uint32 mailAction
, uint32 mailError
, uint32 equipError
, uint32 item_guid
, uint32 item_count
)
2570 WorldPacket
data(SMSG_SEND_MAIL_RESULT
, (4+4+4+(mailError
== MAIL_ERR_BAG_FULL
?4:(mailAction
== MAIL_ITEM_TAKEN
?4+4:0))));
2571 data
<< (uint32
) mailId
;
2572 data
<< (uint32
) mailAction
;
2573 data
<< (uint32
) mailError
;
2574 if ( mailError
== MAIL_ERR_BAG_FULL
)
2575 data
<< (uint32
) equipError
;
2576 else if( mailAction
== MAIL_ITEM_TAKEN
)
2578 data
<< (uint32
) item_guid
; // item guid low?
2579 data
<< (uint32
) item_count
; // item count?
2581 GetSession()->SendPacket(&data
);
2584 void Player::SendNewMail()
2586 // deliver undelivered mail
2587 WorldPacket
data(SMSG_RECEIVED_MAIL
, 4);
2589 GetSession()->SendPacket(&data
);
2592 void Player::UpdateNextMailTimeAndUnreads()
2594 // calculate next delivery time (min. from non-delivered mails
2595 // and recalculate unReadMail
2596 time_t cTime
= time(NULL
);
2597 m_nextMailDelivereTime
= 0;
2599 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
2601 if((*itr
)->deliver_time
> cTime
)
2603 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> (*itr
)->deliver_time
)
2604 m_nextMailDelivereTime
= (*itr
)->deliver_time
;
2606 else if(((*itr
)->checked
& MAIL_CHECK_MASK_READ
) == 0)
2611 void Player::AddNewMailDeliverTime(time_t deliver_time
)
2613 if(deliver_time
<= time(NULL
)) // ready now
2618 else // not ready and no have ready mails
2620 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> deliver_time
)
2621 m_nextMailDelivereTime
= deliver_time
;
2625 bool Player::addSpell(uint32 spell_id
, bool active
, bool learning
, bool dependent
, bool disabled
)
2627 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
2630 // do character spell book cleanup (all characters)
2631 if(!IsInWorld() && !learning
) // spell load case
2633 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id
);
2634 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2637 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id
);
2642 if(!SpellMgr::IsSpellValid(spellInfo
,this,false))
2644 // do character spell book cleanup (all characters)
2645 if(!IsInWorld() && !learning
) // spell load case
2647 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id
);
2648 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2651 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id
);
2656 PlayerSpellState state
= learning
? PLAYERSPELL_NEW
: PLAYERSPELL_UNCHANGED
;
2658 bool dependent_set
= false;
2659 bool disabled_case
= false;
2660 bool superceded_old
= false;
2662 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2663 if (itr
!= m_spells
.end())
2665 uint32 next_active_spell_id
= 0;
2666 // fix activate state for non-stackable low rank (and find next spell for !active case)
2667 if(!SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
2669 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
2670 for(SpellChainMapNext::const_iterator next_itr
= nextMap
.lower_bound(spell_id
); next_itr
!= nextMap
.upper_bound(spell_id
); ++next_itr
)
2672 if(HasSpell(next_itr
->second
))
2674 // high rank already known so this must !active
2676 next_active_spell_id
= next_itr
->second
;
2682 // not do anything if already known in expected state
2683 if(itr
->second
->state
!= PLAYERSPELL_REMOVED
&& itr
->second
->active
== active
&&
2684 itr
->second
->dependent
== dependent
&& itr
->second
->disabled
== disabled
)
2686 if(!IsInWorld() && !learning
) // explicitly load from DB and then exist in it already and set correctly
2687 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2692 // dependent spell known as not dependent, overwrite state
2693 if (itr
->second
->state
!= PLAYERSPELL_REMOVED
&& !itr
->second
->dependent
&& dependent
)
2695 itr
->second
->dependent
= dependent
;
2696 if (itr
->second
->state
!= PLAYERSPELL_NEW
)
2697 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2698 dependent_set
= true;
2701 // update active state for known spell
2702 if(itr
->second
->active
!= active
&& itr
->second
->state
!= PLAYERSPELL_REMOVED
&& !itr
->second
->disabled
)
2704 itr
->second
->active
= active
;
2706 if(!IsInWorld() && !learning
&& !dependent_set
) // explicitly load from DB and then exist in it already and set correctly
2707 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2708 else if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2709 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2713 if (IsPassiveSpell(spell_id
) && IsNeedCastPassiveSpellAtLearn(spellInfo
))
2714 CastSpell (this,spell_id
,true);
2716 else if(IsInWorld())
2718 if(next_active_spell_id
)
2720 // update spell ranks in spellbook and action bar
2721 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2722 data
<< uint16(spell_id
);
2723 data
<< uint16(next_active_spell_id
);
2724 GetSession()->SendPacket( &data
);
2728 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
2729 data
<< uint16(spell_id
);
2730 GetSession()->SendPacket(&data
);
2734 return active
; // learn (show in spell book if active now)
2737 if(itr
->second
->disabled
!= disabled
&& itr
->second
->state
!= PLAYERSPELL_REMOVED
)
2739 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2740 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2741 itr
->second
->disabled
= disabled
;
2746 disabled_case
= true;
2748 else switch(itr
->second
->state
)
2750 case PLAYERSPELL_UNCHANGED
: // known saved spell
2752 case PLAYERSPELL_REMOVED
: // re-learning removed not saved spell
2755 m_spells
.erase(itr
);
2756 state
= PLAYERSPELL_CHANGED
;
2757 break; // need re-add
2759 default: // known not saved yet spell (new or modified)
2761 // can be in case spell loading but learned at some previous spell loading
2762 if(!IsInWorld() && !learning
&& !dependent_set
)
2763 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2770 if(!disabled_case
) // skip new spell adding if spell already known (disabled spells case)
2772 // talent: unlearn all other talent ranks (high and low)
2773 if(TalentSpellPos
const* talentPos
= GetTalentSpellPos(spell_id
))
2775 if(TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry( talentPos
->talent_id
))
2777 for(int i
=0; i
< MAX_TALENT_RANK
; ++i
)
2779 // skip learning spell and no rank spell case
2780 uint32 rankSpellId
= talentInfo
->RankID
[i
];
2781 if(!rankSpellId
|| rankSpellId
==spell_id
)
2784 removeSpell(rankSpellId
);
2788 // non talent spell: learn low ranks (recursive call)
2789 else if(uint32 prev_spell
= spellmgr
.GetPrevSpellInChain(spell_id
))
2791 if(!IsInWorld() || disabled
) // at spells loading, no output, but allow save
2792 addSpell(prev_spell
,active
,true,true,disabled
);
2793 else // at normal learning
2794 learnSpell(prev_spell
,true);
2797 PlayerSpell
*newspell
= new PlayerSpell
;
2798 newspell
->state
= state
;
2799 newspell
->active
= active
;
2800 newspell
->dependent
= dependent
;
2801 newspell
->disabled
= disabled
;
2803 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2804 if(newspell
->active
&& !newspell
->disabled
&& !SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
2806 for( PlayerSpellMap::iterator itr2
= m_spells
.begin(); itr2
!= m_spells
.end(); ++itr2
)
2808 if(itr2
->second
->state
== PLAYERSPELL_REMOVED
) continue;
2809 SpellEntry
const *i_spellInfo
= sSpellStore
.LookupEntry(itr2
->first
);
2810 if(!i_spellInfo
) continue;
2812 if( spellmgr
.IsRankSpellDueToSpell(spellInfo
,itr2
->first
) )
2814 if(itr2
->second
->active
)
2816 if(spellmgr
.IsHighRankOfSpell(spell_id
,itr2
->first
))
2818 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2820 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2821 data
<< uint16(itr2
->first
);
2822 data
<< uint16(spell_id
);
2823 GetSession()->SendPacket( &data
);
2826 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2827 itr2
->second
->active
= false;
2828 if(itr2
->second
->state
!= PLAYERSPELL_NEW
)
2829 itr2
->second
->state
= PLAYERSPELL_CHANGED
;
2830 superceded_old
= true; // new spell replace old in action bars and spell book.
2832 else if(spellmgr
.IsHighRankOfSpell(itr2
->first
,spell_id
))
2834 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2836 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2837 data
<< uint16(spell_id
);
2838 data
<< uint16(itr2
->first
);
2839 GetSession()->SendPacket( &data
);
2842 // mark new spell as disable (not learned yet for client and will not learned)
2843 newspell
->active
= false;
2844 if(newspell
->state
!= PLAYERSPELL_NEW
)
2845 newspell
->state
= PLAYERSPELL_CHANGED
;
2852 m_spells
[spell_id
] = newspell
;
2854 // return false if spell disabled
2855 if (newspell
->disabled
)
2859 uint32 talentCost
= GetTalentSpellCost(spell_id
);
2861 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2862 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2863 if( talentCost
> 0 && IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_LEARN_SPELL
) )
2865 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2866 CastSpell(this, spell_id
, true);
2868 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2869 else if (IsPassiveSpell(spell_id
))
2871 if(IsNeedCastPassiveSpellAtLearn(spellInfo
))
2872 CastSpell(this, spell_id
, true);
2874 else if( IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_SKILL_STEP
) )
2876 CastSpell(this, spell_id
, true);
2880 // update used talent points count
2881 m_usedTalentCount
+= talentCost
;
2883 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2884 if(uint32 freeProfs
= GetFreePrimaryProffesionPoints())
2886 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
2887 SetFreePrimaryProffesions(freeProfs
-1);
2890 // add dependent skills
2891 uint16 maxskill
= GetMaxSkillValueForLevel();
2893 SpellLearnSkillNode
const* spellLearnSkill
= spellmgr
.GetSpellLearnSkill(spell_id
);
2895 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
2896 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
2900 uint32 skill_value
= GetPureSkillValue(spellLearnSkill
->skill
);
2901 uint32 skill_max_value
= GetPureMaxSkillValue(spellLearnSkill
->skill
);
2903 if(skill_value
< spellLearnSkill
->value
)
2904 skill_value
= spellLearnSkill
->value
;
2906 uint32 new_skill_max_value
= spellLearnSkill
->maxvalue
== 0 ? maxskill
: spellLearnSkill
->maxvalue
;
2908 if(skill_max_value
< new_skill_max_value
)
2909 skill_max_value
= new_skill_max_value
;
2911 SetSkill(spellLearnSkill
->skill
,skill_value
,skill_max_value
);
2915 // not ranked skills
2916 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
2918 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
2922 if(HasSkill(pSkill
->id
))
2925 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
2926 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2927 (pSkill
->id
==SKILL_LOCKPICKING
|| pSkill
->id
==SKILL_RUNEFORGING
) && _spell_idx
->second
->max_value
==0 )
2929 switch(GetSkillRangeType(pSkill
,_spell_idx
->second
->racemask
!=0))
2931 case SKILL_RANGE_LANGUAGE
:
2932 SetSkill(pSkill
->id
, 300, 300 );
2934 case SKILL_RANGE_LEVEL
:
2935 SetSkill(pSkill
->id
, 1, GetMaxSkillValueForLevel() );
2937 case SKILL_RANGE_MONO
:
2938 SetSkill(pSkill
->id
, 1, 1 );
2947 // learn dependent spells
2948 SpellLearnSpellMap::const_iterator spell_begin
= spellmgr
.GetBeginSpellLearnSpell(spell_id
);
2949 SpellLearnSpellMap::const_iterator spell_end
= spellmgr
.GetEndSpellLearnSpell(spell_id
);
2951 for(SpellLearnSpellMap::const_iterator itr2
= spell_begin
; itr2
!= spell_end
; ++itr2
)
2953 if(!itr2
->second
.autoLearned
)
2955 if(!IsInWorld() || !itr2
->second
.active
) // at spells loading, no output, but allow save
2956 addSpell(itr2
->second
.spell
,itr2
->second
.active
,true,true,false);
2957 else // at normal learning
2958 learnSpell(itr2
->second
.spell
,true);
2962 if(!GetSession()->PlayerLoading())
2964 // not ranked skills
2965 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
2967 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE
,_spell_idx
->second
->skillId
);
2968 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS
,_spell_idx
->second
->skillId
);
2971 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL
,spell_id
);
2974 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2975 return active
&& !disabled
&& !superceded_old
;
2978 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry
const* spellInfo
) const
2980 bool need_cast
= false;
2982 switch(spellInfo
->Id
)
2984 // some spells not have stance data expacted cast at form change or present
2985 case 5420: need_cast
= (m_form
== FORM_TREE
); break;
2986 case 5419: need_cast
= (m_form
== FORM_TRAVEL
); break;
2987 case 7376: need_cast
= (m_form
== FORM_DEFENSIVESTANCE
); break;
2988 case 7381: need_cast
= (m_form
== FORM_BERSERKERSTANCE
); break;
2989 case 21156: need_cast
= (m_form
== FORM_BATTLESTANCE
); break;
2990 case 21178: need_cast
= (m_form
== FORM_BEAR
|| m_form
== FORM_DIREBEAR
); break;
2991 case 33948: need_cast
= (m_form
== FORM_FLIGHT
); break;
2992 case 34764: need_cast
= (m_form
== FORM_FLIGHT
); break;
2993 case 40121: need_cast
= (m_form
== FORM_FLIGHT_EPIC
); break;
2994 case 40122: need_cast
= (m_form
== FORM_FLIGHT_EPIC
); break;
2995 // another spells have proper stance data
2996 default: need_cast
= !spellInfo
->Stances
|| m_form
!= 0 && (spellInfo
->Stances
& (1<<(m_form
-1))); break;
2999 //Check CasterAuraStates
3000 return need_cast
&& (!spellInfo
->CasterAuraState
|| HasAuraState(AuraState(spellInfo
->CasterAuraState
)));
3003 void Player::learnSpell(uint32 spell_id
, bool dependent
)
3005 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
3007 bool disabled
= (itr
!= m_spells
.end()) ? itr
->second
->disabled
: false;
3008 bool active
= disabled
? itr
->second
->active
: true;
3010 bool learning
= addSpell(spell_id
,active
,true,dependent
,false);
3012 // learn all disabled higher ranks (recursive)
3015 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
3016 for(SpellChainMapNext::const_iterator i
= nextMap
.lower_bound(spell_id
); i
!= nextMap
.upper_bound(spell_id
); ++i
)
3018 PlayerSpellMap::iterator iter
= m_spells
.find(i
->second
);
3019 if (iter
!= m_spells
.end() && iter
->second
->disabled
)
3020 learnSpell(i
->second
,false);
3024 // prevent duplicated entires in spell book, also not send if not in world (loading)
3025 if(!learning
|| !IsInWorld ())
3028 WorldPacket
data(SMSG_LEARNED_SPELL
, 4);
3029 data
<< uint32(spell_id
);
3030 GetSession()->SendPacket(&data
);
3033 void Player::removeSpell(uint32 spell_id
, bool disabled
, bool update_action_bar_for_low_rank
)
3035 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
3036 if (itr
== m_spells
.end())
3039 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| disabled
&& itr
->second
->disabled
)
3042 // unlearn non talent higher ranks (recursive)
3043 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
3044 for(SpellChainMapNext::const_iterator itr2
= nextMap
.lower_bound(spell_id
); itr2
!= nextMap
.upper_bound(spell_id
); ++itr2
)
3045 if(HasSpell(itr2
->second
) && !GetTalentSpellPos(itr2
->second
))
3046 removeSpell(itr2
->second
,disabled
);
3048 bool cur_active
= itr
->second
->active
;
3049 bool cur_dependent
= itr
->second
->dependent
;
3053 itr
->second
->disabled
= disabled
;
3054 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
3055 itr
->second
->state
= PLAYERSPELL_CHANGED
;
3059 if(itr
->second
->state
== PLAYERSPELL_NEW
)
3062 m_spells
.erase(itr
);
3065 itr
->second
->state
= PLAYERSPELL_REMOVED
;
3068 RemoveAurasDueToSpell(spell_id
);
3071 if(PetAura
const* petSpell
= spellmgr
.GetPetAura(spell_id
))
3072 RemovePetAura(petSpell
);
3074 // free talent points
3075 uint32 talentCosts
= GetTalentSpellCost(spell_id
);
3078 if(talentCosts
< m_usedTalentCount
)
3079 m_usedTalentCount
-= talentCosts
;
3081 m_usedTalentCount
= 0;
3084 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3085 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
3087 uint32 freeProfs
= GetFreePrimaryProffesionPoints()+1;
3088 if(freeProfs
<= sWorld
.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL
))
3089 SetFreePrimaryProffesions(freeProfs
);
3092 // remove dependent skill
3093 SpellLearnSkillNode
const* spellLearnSkill
= spellmgr
.GetSpellLearnSkill(spell_id
);
3096 uint32 prev_spell
= spellmgr
.GetPrevSpellInChain(spell_id
);
3097 if(!prev_spell
) // first rank, remove skill
3098 SetSkill(spellLearnSkill
->skill
,0,0);
3101 // search prev. skill setting by spell ranks chain
3102 SpellLearnSkillNode
const* prevSkill
= spellmgr
.GetSpellLearnSkill(prev_spell
);
3103 while(!prevSkill
&& prev_spell
)
3105 prev_spell
= spellmgr
.GetPrevSpellInChain(prev_spell
);
3106 prevSkill
= spellmgr
.GetSpellLearnSkill(spellmgr
.GetFirstSpellInChain(prev_spell
));
3109 if(!prevSkill
) // not found prev skill setting, remove skill
3110 SetSkill(spellLearnSkill
->skill
,0,0);
3111 else // set to prev. skill setting values
3113 uint32 skill_value
= GetPureSkillValue(prevSkill
->skill
);
3114 uint32 skill_max_value
= GetPureMaxSkillValue(prevSkill
->skill
);
3116 if(skill_value
> prevSkill
->value
)
3117 skill_value
= prevSkill
->value
;
3119 uint32 new_skill_max_value
= prevSkill
->maxvalue
== 0 ? GetMaxSkillValueForLevel() : prevSkill
->maxvalue
;
3121 if(skill_max_value
> new_skill_max_value
)
3122 skill_max_value
= new_skill_max_value
;
3124 SetSkill(prevSkill
->skill
,skill_value
,skill_max_value
);
3131 // not ranked skills
3132 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
3133 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
3135 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
3137 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
3141 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
3142 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3143 (pSkill
->id
==SKILL_LOCKPICKING
|| pSkill
->id
==SKILL_RUNEFORGING
) && _spell_idx
->second
->max_value
==0 )
3145 // not reset skills for professions and racial abilities
3146 if( (pSkill
->categoryId
==SKILL_CATEGORY_SECONDARY
|| pSkill
->categoryId
==SKILL_CATEGORY_PROFESSION
) &&
3147 (IsProfessionSkill(pSkill
->id
) || _spell_idx
->second
->racemask
!=0) )
3150 SetSkill(pSkill
->id
, 0, 0 );
3155 // remove dependent spells
3156 SpellLearnSpellMap::const_iterator spell_begin
= spellmgr
.GetBeginSpellLearnSpell(spell_id
);
3157 SpellLearnSpellMap::const_iterator spell_end
= spellmgr
.GetEndSpellLearnSpell(spell_id
);
3159 for(SpellLearnSpellMap::const_iterator itr2
= spell_begin
; itr2
!= spell_end
; ++itr2
)
3160 removeSpell(itr2
->second
.spell
, disabled
);
3162 // activate lesser rank in spellbook/action bar, and cast it if need
3163 bool prev_activate
= false;
3165 if(uint32 prev_id
= spellmgr
.GetPrevSpellInChain (spell_id
))
3167 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
3169 // if talent then lesser rank also talent and need learn
3171 learnSpell (prev_id
,false);
3172 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3173 else if(cur_active
&& !SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
3175 // need manually update dependence state (learn spell ignore like attempts)
3176 PlayerSpellMap::iterator prev_itr
= m_spells
.find(prev_id
);
3177 if (prev_itr
!= m_spells
.end())
3179 if(prev_itr
->second
->dependent
!= cur_dependent
)
3181 prev_itr
->second
->dependent
= cur_dependent
;
3182 if(prev_itr
->second
->state
!= PLAYERSPELL_NEW
)
3183 prev_itr
->second
->state
= PLAYERSPELL_CHANGED
;
3186 // now re-learn if need re-activate
3187 if(cur_active
&& !prev_itr
->second
->active
)
3189 if(addSpell(prev_id
,true,false,prev_itr
->second
->dependent
,prev_itr
->second
->disabled
))
3191 if(update_action_bar_for_low_rank
)
3193 // downgrade spell ranks in spellbook and action bar
3194 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
3195 data
<< uint16(spell_id
);
3196 data
<< uint16(prev_id
);
3197 GetSession()->SendPacket( &data
);
3198 prev_activate
= true;
3206 // remove from spell book if not replaced by lesser rank
3209 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
3210 data
<< uint16(spell_id
);
3211 GetSession()->SendPacket(&data
);
3215 void Player::RemoveArenaSpellCooldowns()
3217 // remove cooldowns on spells that has < 15 min CD
3218 SpellCooldowns::iterator itr
, next
;
3219 // iterate spell cooldowns
3220 for(itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); itr
= next
)
3224 SpellEntry
const * entry
= sSpellStore
.LookupEntry(itr
->first
);
3225 // check if spellentry is present and if the cooldown is less than 15 mins
3227 entry
->RecoveryTime
<= 15 * MINUTE
* IN_MILISECONDS
&&
3228 entry
->CategoryRecoveryTime
<= 15 * MINUTE
* IN_MILISECONDS
)
3231 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, (4+8));
3232 data
<< uint32(itr
->first
);
3233 data
<< uint64(GetGUID());
3234 GetSession()->SendPacket(&data
);
3236 m_spellCooldowns
.erase(itr
);
3241 void Player::RemoveAllSpellCooldown()
3243 if(!m_spellCooldowns
.empty())
3245 for(SpellCooldowns::const_iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); ++itr
)
3247 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, (4+8));
3248 data
<< uint32(itr
->first
);
3249 data
<< uint64(GetGUID());
3250 GetSession()->SendPacket(&data
);
3252 m_spellCooldowns
.clear();
3256 void Player::_LoadSpellCooldowns(QueryResult
*result
)
3258 // some cooldowns can be already set at aura loading...
3260 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3264 time_t curTime
= time(NULL
);
3268 Field
*fields
= result
->Fetch();
3270 uint32 spell_id
= fields
[0].GetUInt32();
3271 uint32 item_id
= fields
[1].GetUInt32();
3272 time_t db_time
= (time_t)fields
[2].GetUInt64();
3274 if(!sSpellStore
.LookupEntry(spell_id
))
3276 sLog
.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id
);
3280 // skip outdated cooldown
3281 if(db_time
<= curTime
)
3284 AddSpellCooldown(spell_id
, item_id
, db_time
);
3286 sLog
.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id
, item_id
, uint32(db_time
-curTime
));
3288 while( result
->NextRow() );
3294 void Player::_SaveSpellCooldowns()
3296 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3298 time_t curTime
= time(NULL
);
3299 time_t infTime
= curTime
+ MONTH
/2;
3301 // remove outdated and save active
3302 for(SpellCooldowns::iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end();)
3304 if(itr
->second
.end
<= curTime
)
3305 m_spellCooldowns
.erase(itr
++);
3306 else if(itr
->second
.end
<= infTime
) // not save locked cooldowns, it will be reset or set at reload
3308 CharacterDatabase
.PExecute("INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ('%u', '%u', '%u', '" I64FMTD
"')", GetGUIDLow(), itr
->first
, itr
->second
.itemid
, uint64(itr
->second
.end
));
3316 uint32
Player::resetTalentsCost() const
3318 // The first time reset costs 1 gold
3319 if(m_resetTalentsCost
< 1*GOLD
)
3322 else if(m_resetTalentsCost
< 5*GOLD
)
3324 // After that it increases in increments of 5 gold
3325 else if(m_resetTalentsCost
< 10*GOLD
)
3329 uint32 months
= (sWorld
.GetGameTime() - m_resetTalentsTime
)/MONTH
;
3332 // This cost will be reduced by a rate of 5 gold per month
3333 int32 new_cost
= int32(m_resetTalentsCost
) - 5*GOLD
*months
;
3334 // to a minimum of 10 gold.
3335 return (new_cost
< 10*GOLD
? 10*GOLD
: new_cost
);
3339 // After that it increases in increments of 5 gold
3340 int32 new_cost
= m_resetTalentsCost
+ 5*GOLD
;
3341 // until it hits a cap of 50 gold.
3342 if(new_cost
> 50*GOLD
)
3349 bool Player::resetTalents(bool no_cost
)
3351 // not need after this call
3352 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS
))
3354 m_atLoginFlags
= m_atLoginFlags
& ~AT_LOGIN_RESET_TALENTS
;
3355 CharacterDatabase
.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS
), GetGUIDLow());
3358 uint32 talentPointsForLevel
= CalculateTalentsPoints();
3360 if (m_usedTalentCount
== 0)
3362 SetFreeTalentPoints(talentPointsForLevel
);
3370 cost
= resetTalentsCost();
3372 if (GetMoney() < cost
)
3374 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, 0, 0, 0);
3379 for (unsigned int i
= 0; i
< sTalentStore
.GetNumRows(); ++i
)
3381 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry(i
);
3383 if (!talentInfo
) continue;
3385 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentInfo
->TalentTab
);
3390 // unlearn only talents for character class
3391 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3392 // to prevent unexpected lost normal learned spell skip another class talents
3393 if( (getClassMask() & talentTabInfo
->ClassMask
) == 0 )
3396 for (int j
= 0; j
< MAX_TALENT_RANK
; ++j
)
3398 for(PlayerSpellMap::iterator itr
= GetSpellMap().begin(); itr
!= GetSpellMap().end();)
3400 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->second
->disabled
)
3406 // remove learned spells (all ranks)
3407 uint32 itrFirstId
= spellmgr
.GetFirstSpellInChain(itr
->first
);
3409 // unlearn if first rank is talent or learned by talent
3410 if (itrFirstId
== talentInfo
->RankID
[j
] || spellmgr
.IsSpellLearnToSpell(talentInfo
->RankID
[j
],itrFirstId
))
3412 removeSpell(itr
->first
,!IsPassiveSpell(itr
->first
));
3413 itr
= GetSpellMap().begin();
3422 SetFreeTalentPoints(talentPointsForLevel
);
3426 ModifyMoney(-(int32
)cost
);
3427 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS
, cost
);
3428 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS
, 1);
3430 m_resetTalentsCost
= cost
;
3431 m_resetTalentsTime
= time(NULL
);
3434 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3435 RemovePet(NULL
,PET_SAVE_NOT_IN_SLOT
, true);
3439 m_canTitanGrip
= false;
3440 if(sWorld
.getConfig(CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET
))
3441 AutoUnequipOffhandIfNeed();
3447 Mail
* Player::GetMail(uint32 id
)
3449 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
3451 if ((*itr
)->messageID
== id
)
3459 void Player::_SetCreateBits(UpdateMask
*updateMask
, Player
*target
) const
3463 Object::_SetCreateBits(updateMask
, target
);
3467 for(uint16 index
= 0; index
< m_valuesCount
; index
++)
3469 if(GetUInt32Value(index
) != 0 && updateVisualBits
.GetBit(index
))
3470 updateMask
->SetBit(index
);
3475 void Player::_SetUpdateBits(UpdateMask
*updateMask
, Player
*target
) const
3479 Object::_SetUpdateBits(updateMask
, target
);
3483 Object::_SetUpdateBits(updateMask
, target
);
3484 *updateMask
&= updateVisualBits
;
3488 void Player::InitVisibleBits()
3490 updateVisualBits
.SetCount(PLAYER_END
);
3492 updateVisualBits
.SetBit(OBJECT_FIELD_GUID
);
3493 updateVisualBits
.SetBit(OBJECT_FIELD_TYPE
);
3494 updateVisualBits
.SetBit(OBJECT_FIELD_ENTRY
);
3495 updateVisualBits
.SetBit(OBJECT_FIELD_SCALE_X
);
3496 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 0);
3497 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 1);
3498 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 0);
3499 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 1);
3500 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 0);
3501 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 1);
3502 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 0);
3503 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 1);
3504 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 0);
3505 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 1);
3506 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_0
);
3507 updateVisualBits
.SetBit(UNIT_FIELD_HEALTH
);
3508 updateVisualBits
.SetBit(UNIT_FIELD_POWER1
);
3509 updateVisualBits
.SetBit(UNIT_FIELD_POWER2
);
3510 updateVisualBits
.SetBit(UNIT_FIELD_POWER3
);
3511 updateVisualBits
.SetBit(UNIT_FIELD_POWER4
);
3512 updateVisualBits
.SetBit(UNIT_FIELD_POWER5
);
3513 updateVisualBits
.SetBit(UNIT_FIELD_POWER6
);
3514 updateVisualBits
.SetBit(UNIT_FIELD_POWER7
);
3515 updateVisualBits
.SetBit(UNIT_FIELD_MAXHEALTH
);
3516 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER1
);
3517 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER2
);
3518 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER3
);
3519 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER4
);
3520 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER5
);
3521 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER6
);
3522 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER7
);
3523 updateVisualBits
.SetBit(UNIT_FIELD_LEVEL
);
3524 updateVisualBits
.SetBit(UNIT_FIELD_FACTIONTEMPLATE
);
3525 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 0);
3526 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 1);
3527 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 2);
3528 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS
);
3529 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS_2
);
3530 updateVisualBits
.SetBit(UNIT_FIELD_AURASTATE
);
3531 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 0);
3532 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 1);
3533 updateVisualBits
.SetBit(UNIT_FIELD_BOUNDINGRADIUS
);
3534 updateVisualBits
.SetBit(UNIT_FIELD_COMBATREACH
);
3535 updateVisualBits
.SetBit(UNIT_FIELD_DISPLAYID
);
3536 updateVisualBits
.SetBit(UNIT_FIELD_NATIVEDISPLAYID
);
3537 updateVisualBits
.SetBit(UNIT_FIELD_MOUNTDISPLAYID
);
3538 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_1
);
3539 updateVisualBits
.SetBit(UNIT_FIELD_PETNUMBER
);
3540 updateVisualBits
.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP
);
3541 updateVisualBits
.SetBit(UNIT_DYNAMIC_FLAGS
);
3542 updateVisualBits
.SetBit(UNIT_CHANNEL_SPELL
);
3543 updateVisualBits
.SetBit(UNIT_MOD_CAST_SPEED
);
3544 updateVisualBits
.SetBit(UNIT_FIELD_BASE_MANA
);
3545 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_2
);
3546 updateVisualBits
.SetBit(UNIT_FIELD_HOVERHEIGHT
);
3548 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 0);
3549 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 1);
3550 updateVisualBits
.SetBit(PLAYER_FLAGS
);
3551 updateVisualBits
.SetBit(PLAYER_GUILDID
);
3552 updateVisualBits
.SetBit(PLAYER_GUILDRANK
);
3553 updateVisualBits
.SetBit(PLAYER_BYTES
);
3554 updateVisualBits
.SetBit(PLAYER_BYTES_2
);
3555 updateVisualBits
.SetBit(PLAYER_BYTES_3
);
3556 updateVisualBits
.SetBit(PLAYER_DUEL_TEAM
);
3557 updateVisualBits
.SetBit(PLAYER_GUILD_TIMESTAMP
);
3559 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3560 for(uint16 i
= PLAYER_QUEST_LOG_1_1
; i
< PLAYER_QUEST_LOG_25_2
; i
+= 4)
3561 updateVisualBits
.SetBit(i
);
3563 // Players visible items are not inventory stuff
3564 for(uint16 i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
3566 uint32 offset
= i
* MAX_VISIBLE_ITEM_OFFSET
;
3569 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR
+ 0 + offset
);
3570 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR
+ 1 + offset
);
3573 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_0
+ 0 + offset
);
3575 // item enchantments
3576 for(uint8 j
= 0; j
< MAX_ENCHANTMENT_SLOT
; ++j
)
3577 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_0
+ 1 + j
+ offset
);
3579 // random properties
3580 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ offset
);
3581 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_SEED
+ offset
);
3582 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_PAD
+ offset
);
3585 updateVisualBits
.SetBit(PLAYER_CHOSEN_TITLE
);
3588 void Player::BuildCreateUpdateBlockForPlayer( UpdateData
*data
, Player
*target
) const
3590 for(int i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
3592 if(m_items
[i
] == NULL
)
3595 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3600 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
3602 if(m_items
[i
] == NULL
)
3605 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3607 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
3609 if(m_items
[i
] == NULL
)
3612 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3616 Unit::BuildCreateUpdateBlockForPlayer( data
, target
);
3619 void Player::DestroyForPlayer( Player
*target
) const
3621 Unit::DestroyForPlayer( target
);
3623 for(int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
3625 if(m_items
[i
] == NULL
)
3628 m_items
[i
]->DestroyForPlayer( target
);
3633 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
3635 if(m_items
[i
] == NULL
)
3638 m_items
[i
]->DestroyForPlayer( target
);
3640 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
3642 if(m_items
[i
] == NULL
)
3645 m_items
[i
]->DestroyForPlayer( target
);
3650 bool Player::HasSpell(uint32 spell
) const
3652 PlayerSpellMap::const_iterator itr
= m_spells
.find(spell
);
3653 return (itr
!= m_spells
.end() && itr
->second
->state
!= PLAYERSPELL_REMOVED
&&
3654 !itr
->second
->disabled
);
3657 bool Player::HasActiveSpell(uint32 spell
) const
3659 PlayerSpellMap::const_iterator itr
= m_spells
.find(spell
);
3660 return (itr
!= m_spells
.end() && itr
->second
->state
!= PLAYERSPELL_REMOVED
&&
3661 itr
->second
->active
&& !itr
->second
->disabled
);
3664 TrainerSpellState
Player::GetTrainerSpellState(TrainerSpell
const* trainer_spell
) const
3667 return TRAINER_SPELL_RED
;
3669 if (!trainer_spell
->learnedSpell
)
3670 return TRAINER_SPELL_RED
;
3673 if(HasSpell(trainer_spell
->learnedSpell
))
3674 return TRAINER_SPELL_GRAY
;
3676 // check race/class requirement
3677 if(!IsSpellFitByClassAndRace(trainer_spell
->learnedSpell
))
3678 return TRAINER_SPELL_RED
;
3680 // check level requirement
3681 if(getLevel() < trainer_spell
->reqLevel
)
3682 return TRAINER_SPELL_RED
;
3684 if(SpellChainNode
const* spell_chain
= spellmgr
.GetSpellChainNode(trainer_spell
->learnedSpell
))
3686 // check prev.rank requirement
3687 if(spell_chain
->prev
&& !HasSpell(spell_chain
->prev
))
3688 return TRAINER_SPELL_RED
;
3690 // check additional spell requirement
3691 if(spell_chain
->req
&& !HasSpell(spell_chain
->req
))
3692 return TRAINER_SPELL_RED
;
3695 // check skill requirement
3696 if(trainer_spell
->reqSkill
&& GetBaseSkillValue(trainer_spell
->reqSkill
) < trainer_spell
->reqSkillValue
)
3697 return TRAINER_SPELL_RED
;
3699 // exist, already checked at loading
3700 SpellEntry
const* spell
= sSpellStore
.LookupEntry(trainer_spell
->learnedSpell
);
3702 // secondary prof. or not prof. spell
3703 uint32 skill
= spell
->EffectMiscValue
[1];
3705 if(spell
->Effect
[1] != SPELL_EFFECT_SKILL
|| !IsPrimaryProfessionSkill(skill
))
3706 return TRAINER_SPELL_GREEN
;
3708 // check primary prof. limit
3709 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell
->Id
) && GetFreePrimaryProffesionPoints() == 0)
3710 return TRAINER_SPELL_GREEN_DISABLED
;
3712 return TRAINER_SPELL_GREEN
;
3715 void Player::DeleteFromDB(uint64 playerguid
, uint32 accountId
, bool updateRealmChars
)
3717 uint32 guid
= GUID_LOPART(playerguid
);
3719 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3720 // bones will be deleted by corpse/bones deleting thread shortly
3721 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid
);
3723 // remove from guild
3724 uint32 guildId
= GetGuildIdFromDB(playerguid
);
3727 Guild
* guild
= objmgr
.GetGuildById(guildId
);
3729 guild
->DelMember(guid
);
3732 // remove from arena teams
3733 LeaveAllArenaTeams(playerguid
);
3735 // the player was uninvited already on logout so just remove from group
3736 QueryResult
*resultGroup
= CharacterDatabase
.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid
);
3739 uint64 leaderGuid
= MAKE_NEW_GUID((*resultGroup
)[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
3741 Group
* group
= objmgr
.GetGroupByLeader(leaderGuid
);
3744 RemoveFromGroup(group
, playerguid
);
3748 // remove signs from petitions (also remove petitions if owner);
3749 RemovePetitionsAndSigns(playerguid
, 10);
3751 // return back all mails with COD and Item 0 1 2 3 4 5 6
3752 QueryResult
*resultMail
= CharacterDatabase
.PQuery("SELECT id,mailTemplateId,sender,subject,itemTextId,money,has_items FROM mail WHERE receiver='%u' AND has_items<>0 AND cod<>0", guid
);
3757 Field
*fields
= resultMail
->Fetch();
3759 uint32 mail_id
= fields
[0].GetUInt32();
3760 uint16 mailTemplateId
= fields
[1].GetUInt16();
3761 uint32 sender
= fields
[2].GetUInt32();
3762 std::string subject
= fields
[3].GetCppString();
3763 uint32 itemTextId
= fields
[4].GetUInt32();
3764 uint32 money
= fields
[5].GetUInt32();
3765 bool has_items
= fields
[6].GetBool();
3767 //we can return mail now
3768 //so firstly delete the old one
3769 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id
);
3774 // data needs to be at first place for Item::LoadFromDB
3775 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
);
3780 Field
*fields2
= resultItems
->Fetch();
3782 uint32 item_guidlow
= fields2
[1].GetUInt32();
3783 uint32 item_template
= fields2
[2].GetUInt32();
3785 ItemPrototype
const* itemProto
= objmgr
.GetItemPrototype(item_template
);
3788 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow
);
3792 Item
*pItem
= NewItemOrBag(itemProto
);
3793 if(!pItem
->LoadFromDB(item_guidlow
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
),resultItems
))
3795 pItem
->FSetState(ITEM_REMOVED
);
3796 pItem
->SaveToDB(); // it also deletes item object !
3800 mi
.AddItem(item_guidlow
, item_template
, pItem
);
3802 while (resultItems
->NextRow());
3808 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id
);
3810 uint32 pl_account
= objmgr
.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
3812 WorldSession::SendReturnToSender(MAIL_NORMAL
, pl_account
, guid
, sender
, subject
, itemTextId
, &mi
, money
, mailTemplateId
);
3814 while (resultMail
->NextRow());
3819 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3820 // Get guids of character's pets, will deleted in transaction
3821 QueryResult
*resultPets
= CharacterDatabase
.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid
);
3823 // NOW we can finally clear other DB data related to character
3824 CharacterDatabase
.BeginTransaction();
3829 Field
*fields3
= resultPets
->Fetch();
3830 uint32 petguidlow
= fields3
[0].GetUInt32();
3831 Pet::DeleteFromDB(petguidlow
);
3832 } while (resultPets
->NextRow());
3836 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",guid
);
3837 CharacterDatabase
.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid
);
3838 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid
);
3839 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid
);
3840 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid
);
3841 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid
);
3842 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid
);
3843 CharacterDatabase
.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid
);
3844 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid
);
3845 CharacterDatabase
.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid
);
3846 CharacterDatabase
.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid
);
3847 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid
);
3848 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid
);
3849 CharacterDatabase
.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid
);
3850 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid
);
3851 CharacterDatabase
.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid
,guid
);
3852 CharacterDatabase
.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid
);
3853 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid
);
3854 CharacterDatabase
.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid
);
3855 CharacterDatabase
.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid
);
3856 CharacterDatabase
.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid
);
3857 CharacterDatabase
.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid
);
3858 CharacterDatabase
.CommitTransaction();
3860 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3861 if(updateRealmChars
) sWorld
.UpdateRealmCharCount(accountId
);
3864 void Player::SetMovement(PlayerMovementType pType
)
3869 case MOVE_ROOT
: data
.Initialize(SMSG_FORCE_MOVE_ROOT
, GetPackGUID().size()+4); break;
3870 case MOVE_UNROOT
: data
.Initialize(SMSG_FORCE_MOVE_UNROOT
, GetPackGUID().size()+4); break;
3871 case MOVE_WATER_WALK
: data
.Initialize(SMSG_MOVE_WATER_WALK
, GetPackGUID().size()+4); break;
3872 case MOVE_LAND_WALK
: data
.Initialize(SMSG_MOVE_LAND_WALK
, GetPackGUID().size()+4); break;
3874 sLog
.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType
);
3877 data
.append(GetPackGUID());
3879 GetSession()->SendPacket( &data
);
3883 - a resurrectable corpse must not be loaded for the player (only bones)
3884 - the player must be in world
3886 void Player::BuildPlayerRepop()
3888 WorldPacket
data(SMSG_PRE_RESURRECT
, GetPackGUID().size());
3889 data
.append(GetPackGUID());
3890 GetSession()->SendPacket(&data
);
3892 if(getRace() == RACE_NIGHTELF
)
3893 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)
3894 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3896 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3897 // there must be SMSG.STOP_MIRROR_TIMER
3898 // there we must send 888 opcode
3900 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3903 sLog
.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3907 // create a corpse and place it at the player's location
3909 Corpse
*corpse
= GetCorpse();
3912 sLog
.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3915 GetMap()->Add(corpse
);
3917 // convert player body to ghost
3920 SetMovement(MOVE_WATER_WALK
);
3921 if(!GetSession()->isLogingOut())
3922 SetMovement(MOVE_UNROOT
);
3924 // BG - remove insignia related
3925 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_SKINNABLE
);
3927 SendCorpseReclaimDelay();
3929 // to prevent cheating
3930 corpse
->ResetGhostTime();
3932 StopMirrorTimers(); //disable timers(bars)
3934 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, (float)1.0); //see radius of death player?
3936 // set and clear other
3937 SetByteValue(UNIT_FIELD_BYTES_1
, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND
);
3940 void Player::SendDelayResponse(const uint32 ml_seconds
)
3942 //FIXME: is this delay time arg really need? 50msec by default in code
3943 WorldPacket
data( SMSG_QUERY_TIME_RESPONSE
, 4+4 );
3944 data
<< (uint32
)time(NULL
);
3946 GetSession()->SendPacket( &data
);
3949 void Player::ResurrectPlayer(float restore_percent
, bool applySickness
)
3951 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // remove spirit healer position
3956 GetSession()->SendPacket(&data
);
3958 // speed change, land walk
3960 // remove death flag + set aura
3961 SetByteValue(UNIT_FIELD_BYTES_1
, 3, 0x00);
3962 if(getRace() == RACE_NIGHTELF
)
3963 RemoveAurasDueToSpell(20584); // speed bonuses
3964 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3966 setDeathState(ALIVE
);
3968 SetMovement(MOVE_LAND_WALK
);
3969 SetMovement(MOVE_UNROOT
);
3973 // set health/powers (0- will be set in caller)
3974 if(restore_percent
>0.0f
)
3976 SetHealth(uint32(GetMaxHealth()*restore_percent
));
3977 SetPower(POWER_MANA
, uint32(GetMaxPower(POWER_MANA
)*restore_percent
));
3978 SetPower(POWER_RAGE
, 0);
3979 SetPower(POWER_ENERGY
, uint32(GetMaxPower(POWER_ENERGY
)*restore_percent
));
3982 // trigger update zone for alive state zone updates
3983 uint32 newzone
, newarea
;
3984 GetZoneAndAreaId(newzone
,newarea
);
3985 UpdateZone(newzone
,newarea
);
3987 // update visibility
3988 ObjectAccessor::UpdateVisibilityForPlayer(this);
3993 //Characters from level 1-10 are not affected by resurrection sickness.
3994 //Characters from level 11-19 will suffer from one minute of sickness
3995 //for each level they are above 10.
3996 //Characters level 20 and up suffer from ten minutes of sickness.
3997 int32 startLevel
= sWorld
.getConfig(CONFIG_DEATH_SICKNESS_LEVEL
);
3999 if(int32(getLevel()) >= startLevel
)
4001 // set resurrection sickness
4002 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,true);
4004 // not full duration
4005 if(int32(getLevel()) < startLevel
+9)
4007 int32 delta
= (int32(getLevel()) - startLevel
+ 1)*MINUTE
;
4009 for(int i
=0; i
< 3; ++i
)
4011 if(Aura
* Aur
= GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,i
))
4013 Aur
->SetAuraDuration(delta
*IN_MILISECONDS
);
4014 Aur
->SendAuraUpdate(false);
4021 void Player::KillPlayer()
4023 SetMovement(MOVE_ROOT
);
4025 StopMirrorTimers(); //disable timers(bars)
4027 setDeathState(CORPSE
);
4028 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4030 SetFlag(UNIT_DYNAMIC_FLAGS
, 0x00);
4031 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, !sMapStore
.LookupEntry(GetMapId())->Instanceable());
4033 // 6 minutes until repop at graveyard
4034 m_deathTimer
= 6*MINUTE
*IN_MILISECONDS
;
4036 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4038 // don't create corpse at this moment, player might be falling
4040 // update visibility
4041 ObjectAccessor::UpdateObjectVisibility(this);
4044 void Player::CreateCorpse()
4046 // prevent existence 2 corpse for player
4049 uint32 _uf
, _pb
, _pb2
, _cfb1
, _cfb2
;
4051 Corpse
*corpse
= new Corpse( (m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
) ? CORPSE_RESURRECTABLE_PVP
: CORPSE_RESURRECTABLE_PVE
);
4054 if(!corpse
->Create(objmgr
.GenerateLowGuid(HIGHGUID_CORPSE
), this))
4060 _uf
= GetUInt32Value(UNIT_FIELD_BYTES_0
);
4061 _pb
= GetUInt32Value(PLAYER_BYTES
);
4062 _pb2
= GetUInt32Value(PLAYER_BYTES_2
);
4064 uint8 race
= (uint8
)(_uf
);
4065 uint8 skin
= (uint8
)(_pb
);
4066 uint8 face
= (uint8
)(_pb
>> 8);
4067 uint8 hairstyle
= (uint8
)(_pb
>> 16);
4068 uint8 haircolor
= (uint8
)(_pb
>> 24);
4069 uint8 facialhair
= (uint8
)(_pb2
);
4071 _cfb1
= ((0x00) | (race
<< 8) | (getGender() << 16) | (skin
<< 24));
4072 _cfb2
= ((face
) | (hairstyle
<< 8) | (haircolor
<< 16) | (facialhair
<< 24));
4074 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_1
, _cfb1
);
4075 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_2
, _cfb2
);
4077 uint32 flags
= CORPSE_FLAG_UNK2
;
4078 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
4079 flags
|= CORPSE_FLAG_HIDE_HELM
;
4080 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
4081 flags
|= CORPSE_FLAG_HIDE_CLOAK
;
4082 if(InBattleGround() && !InArena())
4083 flags
|= CORPSE_FLAG_LOOTABLE
; // to be able to remove insignia
4084 corpse
->SetUInt32Value( CORPSE_FIELD_FLAGS
, flags
);
4086 corpse
->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID
, GetNativeDisplayId() );
4088 corpse
->SetUInt32Value( CORPSE_FIELD_GUILD
, GetGuildId() );
4091 uint16 iIventoryType
;
4093 for (int i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
4097 iDisplayID
= m_items
[i
]->GetProto()->DisplayInfoID
;
4098 iIventoryType
= (uint16
)m_items
[i
]->GetProto()->InventoryType
;
4100 _cfi
= (uint16(iDisplayID
)) | (iIventoryType
)<< 24;
4101 corpse
->SetUInt32Value(CORPSE_FIELD_ITEM
+ i
,_cfi
);
4105 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4106 const MapEntry
*entry
= sMapStore
.LookupEntry(corpse
->GetMapId());
4108 if(entry
->map_type
!= MAP_BATTLEGROUND
)
4111 // register for player, but not show
4112 ObjectAccessor::Instance().AddCorpse(corpse
);
4115 void Player::SpawnCorpseBones()
4117 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4118 SaveToDB(); // prevent loading as ghost without corpse
4121 Corpse
* Player::GetCorpse() const
4123 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4126 void Player::DurabilityLossAll(double percent
, bool inventory
)
4128 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
4129 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4130 DurabilityLoss(pItem
,percent
);
4134 // bags not have durability
4135 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4137 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
4138 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4139 DurabilityLoss(pItem
,percent
);
4141 // keys not have durability
4142 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4144 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
4145 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4146 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
4147 if(Item
* pItem
= GetItemByPos( i
, j
))
4148 DurabilityLoss(pItem
,percent
);
4152 void Player::DurabilityLoss(Item
* item
, double percent
)
4157 uint32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4162 uint32 pDurabilityLoss
= uint32(pMaxDurability
*percent
);
4164 if(pDurabilityLoss
< 1 )
4165 pDurabilityLoss
= 1;
4167 DurabilityPointsLoss(item
,pDurabilityLoss
);
4170 void Player::DurabilityPointsLossAll(int32 points
, bool inventory
)
4172 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
4173 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4174 DurabilityPointsLoss(pItem
,points
);
4178 // bags not have durability
4179 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4181 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
4182 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4183 DurabilityPointsLoss(pItem
,points
);
4185 // keys not have durability
4186 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4188 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
4189 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4190 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
4191 if(Item
* pItem
= GetItemByPos( i
, j
))
4192 DurabilityPointsLoss(pItem
,points
);
4196 void Player::DurabilityPointsLoss(Item
* item
, int32 points
)
4198 int32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4199 int32 pOldDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4200 int32 pNewDurability
= pOldDurability
- points
;
4202 if (pNewDurability
< 0)
4204 else if (pNewDurability
> pMaxDurability
)
4205 pNewDurability
= pMaxDurability
;
4207 if (pOldDurability
!= pNewDurability
)
4209 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4210 if ( pNewDurability
== 0 && pOldDurability
> 0 && item
->IsEquipped())
4211 _ApplyItemMods(item
,item
->GetSlot(), false);
4213 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, pNewDurability
);
4215 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4216 if ( pNewDurability
> 0 && pOldDurability
== 0 && item
->IsEquipped())
4217 _ApplyItemMods(item
,item
->GetSlot(), true);
4219 item
->SetState(ITEM_CHANGED
, this);
4223 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot
)
4225 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
))
4226 DurabilityPointsLoss(pItem
,1);
4229 uint32
Player::DurabilityRepairAll(bool cost
, float discountMod
, bool guildBank
)
4231 uint32 TotalCost
= 0;
4232 // equipped, backpack, bags itself
4233 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
4234 TotalCost
+= DurabilityRepair(( (INVENTORY_SLOT_BAG_0
<< 8) | i
),cost
,discountMod
, guildBank
);
4236 // bank, buyback and keys not repaired
4238 // items in inventory bags
4239 for(int j
= INVENTORY_SLOT_BAG_START
; j
< INVENTORY_SLOT_BAG_END
; ++j
)
4240 for(int i
= 0; i
< MAX_BAG_SIZE
; ++i
)
4241 TotalCost
+= DurabilityRepair(( (j
<< 8) | i
),cost
,discountMod
, guildBank
);
4245 uint32
Player::DurabilityRepair(uint16 pos
, bool cost
, float discountMod
, bool guildBank
)
4247 Item
* item
= GetItemByPos(pos
);
4249 uint32 TotalCost
= 0;
4253 uint32 maxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4257 uint32 curDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4261 uint32 LostDurability
= maxDurability
- curDurability
;
4262 if(LostDurability
>0)
4264 ItemPrototype
const *ditemProto
= item
->GetProto();
4266 DurabilityCostsEntry
const *dcost
= sDurabilityCostsStore
.LookupEntry(ditemProto
->ItemLevel
);
4269 sLog
.outError("RepairDurability: Wrong item lvl %u", ditemProto
->ItemLevel
);
4273 uint32 dQualitymodEntryId
= (ditemProto
->Quality
+1)*2;
4274 DurabilityQualityEntry
const *dQualitymodEntry
= sDurabilityQualityStore
.LookupEntry(dQualitymodEntryId
);
4275 if(!dQualitymodEntry
)
4277 sLog
.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId
);
4281 uint32 dmultiplier
= dcost
->multiplier
[ItemSubClassToDurabilityMultiplierId(ditemProto
->Class
,ditemProto
->SubClass
)];
4282 uint32 costs
= uint32(LostDurability
*dmultiplier
*double(dQualitymodEntry
->quality_mod
));
4284 costs
= uint32(costs
* discountMod
);
4286 if (costs
==0) //fix for ITEM_QUALITY_ARTIFACT
4291 if (GetGuildId()==0)
4293 DEBUG_LOG("You are not member of a guild");
4297 Guild
*pGuild
= objmgr
.GetGuildById(GetGuildId());
4301 if (!pGuild
->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR
))
4303 DEBUG_LOG("You do not have rights to withdraw for repairs");
4307 if (pGuild
->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs
)
4309 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4313 if (pGuild
->GetGuildBankMoney() < costs
)
4315 DEBUG_LOG("There is not enough money in bank");
4319 pGuild
->MemberMoneyWithdraw(costs
, GetGUIDLow());
4322 else if (GetMoney() < costs
)
4324 DEBUG_LOG("You do not have enough money");
4328 ModifyMoney( -int32(costs
) );
4332 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, maxDurability
);
4333 item
->SetState(ITEM_CHANGED
, this);
4335 // reapply mods for total broken and repaired item if equipped
4336 if(IsEquipmentPos(pos
) && !curDurability
)
4337 _ApplyItemMods(item
,pos
& 255, true);
4341 void Player::RepopAtGraveyard()
4343 // note: this can be called also when the player is alive
4344 // for example from WorldSession::HandleMovementOpcodes
4346 AreaTableEntry
const *zone
= GetAreaEntryByAreaID(GetAreaId());
4348 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4349 if(!isAlive() && zone
&& zone
->flags
& AREA_FLAG_NEED_FLY
|| GetTransport())
4351 ResurrectPlayer(0.5f
);
4355 WorldSafeLocsEntry
const *ClosestGrave
= NULL
;
4357 // Special handle for battleground maps
4358 if( BattleGround
*bg
= GetBattleGround() )
4359 ClosestGrave
= bg
->GetClosestGraveYard(this);
4361 ClosestGrave
= objmgr
.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4363 // stop countdown until repop
4366 // if no grave found, stay at the current location
4367 // and don't show spirit healer location
4370 TeleportTo(ClosestGrave
->map_id
, ClosestGrave
->x
, ClosestGrave
->y
, ClosestGrave
->z
, GetOrientation());
4371 if(isDead()) // not send if alive, because it used in TeleportTo()
4373 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // show spirit healer position on minimap
4374 data
<< ClosestGrave
->map_id
;
4375 data
<< ClosestGrave
->x
;
4376 data
<< ClosestGrave
->y
;
4377 data
<< ClosestGrave
->z
;
4378 GetSession()->SendPacket(&data
);
4383 void Player::JoinedChannel(Channel
*c
)
4385 m_channels
.push_back(c
);
4388 void Player::LeftChannel(Channel
*c
)
4390 m_channels
.remove(c
);
4393 void Player::CleanupChannels()
4395 while(!m_channels
.empty())
4397 Channel
* ch
= *m_channels
.begin();
4398 m_channels
.erase(m_channels
.begin()); // remove from player's channel list
4399 ch
->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4400 if (ChannelMgr
* cMgr
= channelMgr(GetTeam()))
4401 cMgr
->LeftChannel(ch
->GetName()); // deleted channel if empty
4404 sLog
.outDebug("Player: channels cleaned up!");
4407 void Player::UpdateLocalChannels(uint32 newZone
)
4409 if(m_channels
.empty())
4412 AreaTableEntry
const* current_zone
= GetAreaEntryByAreaID(newZone
);
4416 ChannelMgr
* cMgr
= channelMgr(GetTeam());
4420 std::string current_zone_name
= current_zone
->area_name
[GetSession()->GetSessionDbcLocale()];
4422 for(JoinedChannelsList::iterator i
= m_channels
.begin(), next
; i
!= m_channels
.end(); i
= next
)
4426 // skip non built-in channels
4427 if(!(*i
)->IsConstant())
4430 ChatChannelsEntry
const* ch
= GetChannelEntryFor((*i
)->GetChannelId());
4434 if((ch
->flags
& 4) == 4) // global channel without zone name in pattern
4438 char new_channel_name_buf
[100];
4439 snprintf(new_channel_name_buf
,100,ch
->pattern
[m_session
->GetSessionDbcLocale()],current_zone_name
.c_str());
4440 Channel
* new_channel
= cMgr
->GetJoinChannel(new_channel_name_buf
,ch
->ChannelID
);
4442 if((*i
)!=new_channel
)
4444 new_channel
->Join(GetGUID(),""); // will output Changed Channel: N. Name
4446 // leave old channel
4447 (*i
)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4448 std::string name
= (*i
)->GetName(); // store name, (*i)erase in LeftChannel
4449 LeftChannel(*i
); // remove from player's channel list
4450 cMgr
->LeftChannel(name
); // delete if empty
4453 sLog
.outDebug("Player: channels cleaned up!");
4456 void Player::LeaveLFGChannel()
4458 for(JoinedChannelsList::iterator i
= m_channels
.begin(); i
!= m_channels
.end(); ++i
)
4462 (*i
)->Leave(GetGUID());
4468 void Player::UpdateDefense()
4470 uint32 defense_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_DEFENSE
);
4472 if(UpdateSkill(SKILL_DEFENSE
,defense_skill_gain
))
4474 // update dependent from defense skill part
4475 UpdateDefenseBonusesMod();
4479 void Player::HandleBaseModValue(BaseModGroup modGroup
, BaseModType modType
, float amount
, bool apply
)
4481 if(modGroup
>= BASEMOD_END
|| modType
>= MOD_END
)
4483 sLog
.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4492 m_auraBaseMod
[modGroup
][modType
] += apply
? amount
: -amount
;
4495 if(amount
<= -100.0f
)
4498 val
= (100.0f
+ amount
) / 100.0f
;
4499 m_auraBaseMod
[modGroup
][modType
] *= apply
? val
: (1.0f
/val
);
4503 if(!CanModifyStats())
4508 case CRIT_PERCENTAGE
: UpdateCritPercentage(BASE_ATTACK
); break;
4509 case RANGED_CRIT_PERCENTAGE
: UpdateCritPercentage(RANGED_ATTACK
); break;
4510 case OFFHAND_CRIT_PERCENTAGE
: UpdateCritPercentage(OFF_ATTACK
); break;
4511 case SHIELD_BLOCK_VALUE
: UpdateShieldBlockValue(); break;
4516 float Player::GetBaseModValue(BaseModGroup modGroup
, BaseModType modType
) const
4518 if(modGroup
>= BASEMOD_END
|| modType
> MOD_END
)
4520 sLog
.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4524 if(modType
== PCT_MOD
&& m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4527 return m_auraBaseMod
[modGroup
][modType
];
4530 float Player::GetTotalBaseModValue(BaseModGroup modGroup
) const
4532 if(modGroup
>= BASEMOD_END
)
4534 sLog
.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4538 if(m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4541 return m_auraBaseMod
[modGroup
][FLAT_MOD
] * m_auraBaseMod
[modGroup
][PCT_MOD
];
4544 uint32
Player::GetShieldBlockValue() const
4546 float value
= (m_auraBaseMod
[SHIELD_BLOCK_VALUE
][FLAT_MOD
] + GetStat(STAT_STRENGTH
) * 0.5f
- 10)*m_auraBaseMod
[SHIELD_BLOCK_VALUE
][PCT_MOD
];
4548 value
= (value
< 0) ? 0 : value
;
4550 return uint32(value
);
4553 float Player::GetMeleeCritFromAgility()
4555 uint32 level
= getLevel();
4556 uint32 pclass
= getClass();
4558 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4560 GtChanceToMeleeCritBaseEntry
const *critBase
= sGtChanceToMeleeCritBaseStore
.LookupEntry(pclass
-1);
4561 GtChanceToMeleeCritEntry
const *critRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4562 if (critBase
==NULL
|| critRatio
==NULL
)
4565 float crit
=critBase
->base
+ GetStat(STAT_AGILITY
)*critRatio
->ratio
;
4569 float Player::GetDodgeFromAgility()
4571 // Table for base dodge values
4572 float dodge_base
[MAX_CLASSES
] = {
4574 0.00652f
, // Paladin
4581 0.02011f
, // Warlock
4585 // Crit/agility to dodge/agility coefficient multipliers
4586 float crit_to_dodge
[MAX_CLASSES
] = {
4600 uint32 level
= getLevel();
4601 uint32 pclass
= getClass();
4603 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4605 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4606 GtChanceToMeleeCritEntry
const *dodgeRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4607 if (dodgeRatio
==NULL
|| pclass
> MAX_CLASSES
)
4610 float dodge
=dodge_base
[pclass
-1] + GetStat(STAT_AGILITY
) * dodgeRatio
->ratio
* crit_to_dodge
[pclass
-1];
4611 return dodge
*100.0f
;
4614 float Player::GetSpellCritFromIntellect()
4616 uint32 level
= getLevel();
4617 uint32 pclass
= getClass();
4619 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4621 GtChanceToSpellCritBaseEntry
const *critBase
= sGtChanceToSpellCritBaseStore
.LookupEntry(pclass
-1);
4622 GtChanceToSpellCritEntry
const *critRatio
= sGtChanceToSpellCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4623 if (critBase
==NULL
|| critRatio
==NULL
)
4626 float crit
=critBase
->base
+ GetStat(STAT_INTELLECT
)*critRatio
->ratio
;
4630 float Player::GetRatingCoefficient(CombatRating cr
) const
4632 uint32 level
= getLevel();
4634 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4636 GtCombatRatingsEntry
const *Rating
= sGtCombatRatingsStore
.LookupEntry(cr
*GT_MAX_LEVEL
+level
-1);
4638 return 1.0f
; // By default use minimum coefficient (not must be called)
4640 return Rating
->ratio
;
4643 float Player::GetRatingBonusValue(CombatRating cr
) const
4645 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
)) / GetRatingCoefficient(cr
);
4648 uint32
Player::GetMeleeCritDamageReduction(uint32 damage
) const
4650 float melee
= GetRatingBonusValue(CR_CRIT_TAKEN_MELEE
)*2.2f
;
4651 if (melee
>33.0f
) melee
= 33.0f
;
4652 return uint32 (melee
* damage
/100.0f
);
4655 uint32
Player::GetRangedCritDamageReduction(uint32 damage
) const
4657 float ranged
= GetRatingBonusValue(CR_CRIT_TAKEN_RANGED
)*2.2f
;
4658 if (ranged
>33.0f
) ranged
=33.0f
;
4659 return uint32 (ranged
* damage
/100.0f
);
4662 uint32
Player::GetSpellCritDamageReduction(uint32 damage
) const
4664 float spell
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
)*2.2f
;
4665 // In wow script resilience limited to 33%
4668 return uint32 (spell
* damage
/ 100.0f
);
4671 uint32
Player::GetDotDamageReduction(uint32 damage
) const
4673 float spellDot
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
);
4674 // Dot resilience not limited (limit it by 100%)
4675 if (spellDot
> 100.0f
)
4677 return uint32 (spellDot
* damage
/ 100.0f
);
4680 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType
) const
4685 return GetUInt32Value(PLAYER_EXPERTISE
) / 4.0f
;
4687 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE
) / 4.0f
;
4694 float Player::OCTRegenHPPerSpirit()
4696 uint32 level
= getLevel();
4697 uint32 pclass
= getClass();
4699 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4701 GtOCTRegenHPEntry
const *baseRatio
= sGtOCTRegenHPStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4702 GtRegenHPPerSptEntry
const *moreRatio
= sGtRegenHPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4703 if (baseRatio
==NULL
|| moreRatio
==NULL
)
4706 // Formula from PaperDollFrame script
4707 float spirit
= GetStat(STAT_SPIRIT
);
4708 float baseSpirit
= spirit
;
4709 if (baseSpirit
>50) baseSpirit
= 50;
4710 float moreSpirit
= spirit
- baseSpirit
;
4711 float regen
= baseSpirit
* baseRatio
->ratio
+ moreSpirit
* moreRatio
->ratio
;
4715 float Player::OCTRegenMPPerSpirit()
4717 uint32 level
= getLevel();
4718 uint32 pclass
= getClass();
4720 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4722 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4723 GtRegenMPPerSptEntry
const *moreRatio
= sGtRegenMPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4724 if (moreRatio
==NULL
)
4727 // Formula get from PaperDollFrame script
4728 float spirit
= GetStat(STAT_SPIRIT
);
4729 float regen
= spirit
* moreRatio
->ratio
;
4733 void Player::ApplyRatingMod(CombatRating cr
, int32 value
, bool apply
)
4735 m_baseRatingValue
[cr
]+=(apply
? value
: -value
);
4737 int32 amount
= uint32(m_baseRatingValue
[cr
]);
4738 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4739 // stat used stored in miscValueB for this aura
4740 AuraList
const& modRatingFromStat
= GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT
);
4741 for(AuraList::const_iterator i
= modRatingFromStat
.begin();i
!= modRatingFromStat
.end(); ++i
)
4742 if ((*i
)->GetMiscValue() & (1<<cr
))
4743 amount
+= int32(GetStat(Stats((*i
)->GetMiscBValue())) * (*i
)->GetModifier()->m_amount
/ 100.0f
);
4746 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
, uint32(amount
));
4748 float RatingCoeffecient
= GetRatingCoefficient(cr
);
4749 float RatingChange
= 0.0f
;
4751 bool affectStats
= CanModifyStats();
4755 case CR_WEAPON_SKILL
: // Implemented in Unit::RollMeleeOutcomeAgainst
4756 case CR_DEFENSE_SKILL
:
4757 UpdateDefenseBonusesMod();
4760 UpdateDodgePercentage();
4763 UpdateParryPercentage();
4766 UpdateBlockPercentage();
4769 UpdateMeleeHitChances();
4772 UpdateRangedHitChances();
4775 UpdateSpellHitChances();
4780 UpdateCritPercentage(BASE_ATTACK
);
4781 UpdateCritPercentage(OFF_ATTACK
);
4784 case CR_CRIT_RANGED
:
4786 UpdateCritPercentage(RANGED_ATTACK
);
4790 UpdateAllSpellCritChances();
4792 case CR_HIT_TAKEN_MELEE
: // Implemented in Unit::MeleeMissChanceCalc
4793 case CR_HIT_TAKEN_RANGED
:
4795 case CR_HIT_TAKEN_SPELL
: // Implemented in Unit::MagicSpellHitResult
4797 case CR_CRIT_TAKEN_MELEE
: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4798 case CR_CRIT_TAKEN_RANGED
:
4800 case CR_CRIT_TAKEN_SPELL
: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4802 case CR_HASTE_MELEE
:
4803 RatingChange
= value
/ RatingCoeffecient
;
4804 ApplyAttackTimePercentMod(BASE_ATTACK
,RatingChange
,apply
);
4805 ApplyAttackTimePercentMod(OFF_ATTACK
,RatingChange
,apply
);
4807 case CR_HASTE_RANGED
:
4808 RatingChange
= value
/ RatingCoeffecient
;
4809 ApplyAttackTimePercentMod(RANGED_ATTACK
, RatingChange
, apply
);
4811 case CR_HASTE_SPELL
:
4812 RatingChange
= value
/ RatingCoeffecient
;
4813 ApplyCastTimePercentMod(RatingChange
,apply
);
4815 case CR_WEAPON_SKILL_MAINHAND
: // Implemented in Unit::RollMeleeOutcomeAgainst
4816 case CR_WEAPON_SKILL_OFFHAND
:
4817 case CR_WEAPON_SKILL_RANGED
:
4822 UpdateExpertise(BASE_ATTACK
);
4823 UpdateExpertise(OFF_ATTACK
);
4826 case CR_ARMOR_PENETRATION
:
4831 void Player::SetRegularAttackTime()
4833 for(int i
= 0; i
< MAX_ATTACK
; ++i
)
4835 Item
*tmpitem
= GetWeaponForAttack(WeaponAttackType(i
));
4836 if(tmpitem
&& !tmpitem
->IsBroken())
4838 ItemPrototype
const *proto
= tmpitem
->GetProto();
4840 SetAttackTime(WeaponAttackType(i
), proto
->Delay
);
4842 SetAttackTime(WeaponAttackType(i
), BASE_ATTACK_TIME
);
4847 //skill+step, checking for max value
4848 bool Player::UpdateSkill(uint32 skill_id
, uint32 step
)
4854 for (; i
< PLAYER_MAX_SKILLS
; ++i
)
4855 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill_id
)
4858 if(i
>=PLAYER_MAX_SKILLS
)
4861 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4862 uint32 value
= SKILL_VALUE(data
);
4863 uint32 max
= SKILL_MAX(data
);
4865 if ((!max
) || (!value
) || (value
>= max
))
4868 if (value
*512 < max
*urand(0,512))
4870 uint32 new_value
= value
+step
;
4874 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,max
));
4875 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,skill_id
);
4882 inline int SkillGainChance(uint32 SkillValue
, uint32 GrayLevel
, uint32 GreenLevel
, uint32 YellowLevel
)
4884 if ( SkillValue
>= GrayLevel
)
4885 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREY
)*10;
4886 if ( SkillValue
>= GreenLevel
)
4887 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREEN
)*10;
4888 if ( SkillValue
>= YellowLevel
)
4889 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_YELLOW
)*10;
4890 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_ORANGE
)*10;
4893 bool Player::UpdateCraftSkill(uint32 spellid
)
4895 sLog
.outDebug("UpdateCraftSkill spellid %d", spellid
);
4897 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spellid
);
4898 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spellid
);
4900 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
4902 if(_spell_idx
->second
->skillId
)
4904 uint32 SkillValue
= GetPureSkillValue(_spell_idx
->second
->skillId
);
4906 // Alchemy Discoveries here
4907 SpellEntry
const* spellEntry
= sSpellStore
.LookupEntry(spellid
);
4908 if(spellEntry
&& spellEntry
->Mechanic
==MECHANIC_DISCOVERY
)
4910 if(uint32 discoveredSpell
= GetSkillDiscoverySpell(_spell_idx
->second
->skillId
, spellid
, this))
4911 learnSpell(discoveredSpell
,false);
4914 uint32 craft_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_CRAFTING
);
4916 return UpdateSkillPro(_spell_idx
->second
->skillId
, SkillGainChance(SkillValue
,
4917 _spell_idx
->second
->max_value
,
4918 (_spell_idx
->second
->max_value
+ _spell_idx
->second
->min_value
)/2,
4919 _spell_idx
->second
->min_value
),
4926 bool Player::UpdateGatherSkill(uint32 SkillId
, uint32 SkillValue
, uint32 RedLevel
, uint32 Multiplicator
)
4928 sLog
.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId
, SkillValue
, RedLevel
);
4930 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
4932 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4935 case SKILL_HERBALISM
:
4936 case SKILL_LOCKPICKING
:
4937 case SKILL_JEWELCRAFTING
:
4938 case SKILL_INSCRIPTION
:
4939 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4940 case SKILL_SKINNING
:
4941 if( sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)==0)
4942 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4944 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)), gathering_skill_gain
);
4946 if (sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)==0)
4947 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4949 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)),gathering_skill_gain
);
4954 bool Player::UpdateFishingSkill()
4956 sLog
.outDebug("UpdateFishingSkill");
4958 uint32 SkillValue
= GetPureSkillValue(SKILL_FISHING
);
4960 int32 chance
= SkillValue
< 75 ? 100 : 2500/(SkillValue
-50);
4962 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
4964 return UpdateSkillPro(SKILL_FISHING
,chance
*10,gathering_skill_gain
);
4967 // levels sync. with spell requirement for skill levels to learn
4968 // bonus abilities in sSkillLineAbilityStore
4969 // Used only to avoid scan DBC at each skill grow
4970 static uint32 bonusSkillLevels
[] = {75,150,225,300,375,450};
4972 bool Player::UpdateSkillPro(uint16 SkillId
, int32 Chance
, uint32 step
)
4974 sLog
.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId
, Chance
/10.0);
4978 if(Chance
<= 0) // speedup in 0 chance case
4980 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
4985 for (; i
< PLAYER_MAX_SKILLS
; ++i
)
4986 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i
))) == SkillId
) break;
4987 if ( i
>= PLAYER_MAX_SKILLS
)
4990 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4991 uint16 SkillValue
= SKILL_VALUE(data
);
4992 uint16 MaxValue
= SKILL_MAX(data
);
4994 if ( !MaxValue
|| !SkillValue
|| SkillValue
>= MaxValue
)
4997 int32 Roll
= irand(1,1000);
4999 if ( Roll
<= Chance
)
5001 uint32 new_value
= SkillValue
+step
;
5002 if(new_value
> MaxValue
)
5003 new_value
= MaxValue
;
5005 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,MaxValue
));
5006 for(uint32
* bsl
= &bonusSkillLevels
[0]; *bsl
; ++bsl
)
5008 if((SkillValue
< *bsl
&& new_value
>= *bsl
))
5010 learnSkillRewardedSpells( SkillId
, new_value
);
5014 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,SkillId
);
5015 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance
/10.0);
5019 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
5023 void Player::UpdateWeaponSkill (WeaponAttackType attType
)
5025 // no skill gain in pvp
5026 Unit
*pVictim
= getVictim();
5027 if(pVictim
&& pVictim
->GetTypeId() == TYPEID_PLAYER
)
5031 return; // always maximized SKILL_FERAL_COMBAT in fact
5033 if(m_form
== FORM_TREE
)
5034 return; // use weapon but not skill up
5036 uint32 weapon_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_WEAPON
);
5042 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
5045 UpdateSkill(SKILL_UNARMED
,weapon_skill_gain
);
5046 else if(tmpitem
->GetProto()->SubClass
!= ITEM_SUBCLASS_WEAPON_FISHING_POLE
)
5047 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
5053 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
5055 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
5059 UpdateAllCritPercentages();
5062 void Player::UpdateCombatSkills(Unit
*pVictim
, WeaponAttackType attType
, bool defence
)
5064 uint32 plevel
= getLevel(); // if defense than pVictim == attacker
5065 uint32 greylevel
= MaNGOS::XP::GetGrayLevel(plevel
);
5066 uint32 moblevel
= pVictim
->getLevelForTarget(this);
5067 if(moblevel
< greylevel
)
5070 if (moblevel
> plevel
+ 5)
5071 moblevel
= plevel
+ 5;
5073 uint32 lvldif
= moblevel
- greylevel
;
5077 uint32 skilldif
= 5 * plevel
- (defence
? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType
));
5081 float chance
= float(3 * lvldif
* skilldif
) / plevel
;
5084 if(getClass() == CLASS_WARRIOR
|| getClass() == CLASS_ROGUE
)
5085 chance
*= 0.1f
* GetStat(STAT_INTELLECT
);
5088 chance
= chance
< 1.0f
? 1.0f
: chance
; //minimum chance to increase skill is 1%
5090 if(roll_chance_f(chance
))
5095 UpdateWeaponSkill(attType
);
5101 void Player::ModifySkillBonus(uint32 skillid
,int32 val
, bool talent
)
5103 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5104 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skillid
)
5106 uint32 bonus_val
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5107 int16 temp_bonus
= SKILL_TEMP_BONUS(bonus_val
);
5108 int16 perm_bonus
= SKILL_PERM_BONUS(bonus_val
);
5110 if(talent
) // permanent bonus stored in high part
5111 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
,perm_bonus
+val
));
5112 else // temporary/item bonus stored in low part
5113 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
+val
,perm_bonus
));
5118 void Player::UpdateSkillsForLevel()
5120 uint16 maxconfskill
= sWorld
.GetConfigMaxSkillValue();
5121 uint32 maxSkill
= GetMaxSkillValueForLevel();
5123 bool alwaysMaxSkill
= sWorld
.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL
);
5125 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5126 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5128 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
5130 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(pskill
);
5134 if(GetSkillRangeType(pSkill
,false) != SKILL_RANGE_LEVEL
)
5137 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
5138 uint32 max
= SKILL_MAX(data
);
5139 uint32 val
= SKILL_VALUE(data
);
5141 /// update only level dependent max skill values
5144 /// miximize skill always
5146 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(maxSkill
,maxSkill
));
5147 /// update max skill value if current max skill not maximized
5148 else if(max
!= maxconfskill
)
5149 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(val
,maxSkill
));
5154 void Player::UpdateSkillsToMaxSkillsForLevel()
5156 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5157 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5159 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
5160 if( IsProfessionOrRidingSkill(pskill
))
5162 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
5164 uint32 max
= SKILL_MAX(data
);
5167 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(max
,max
));
5169 if(pskill
== SKILL_DEFENSE
)
5170 UpdateDefenseBonusesMod();
5174 // This functions sets a skill line value (and adds if doesn't exist yet)
5175 // To "remove" a skill line, set it's values to zero
5176 void Player::SetSkill(uint32 id
, uint16 currVal
, uint16 maxVal
)
5182 for (; i
< PLAYER_MAX_SKILLS
; ++i
)
5183 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == id
) break;
5185 if(i
<PLAYER_MAX_SKILLS
) //has skill
5189 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
5190 learnSkillRewardedSpells(id
, currVal
);
5191 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,id
);
5192 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL
,id
);
5196 // clear skill fields
5197 SetUInt32Value(PLAYER_SKILL_INDEX(i
),0);
5198 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),0);
5199 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
5201 // remove all spells that related to this skill
5202 for (uint32 j
=0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
5203 if(SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
))
5204 if (pAbility
->skillId
==id
)
5205 removeSpell(spellmgr
.GetFirstSpellInChain(pAbility
->spellId
));
5208 else if(currVal
) //add
5210 for (i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5211 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5213 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
5216 sLog
.outError("Skill not found in SkillLineStore: skill #%u", id
);
5219 // enable unlearn button for primary professions only
5220 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
5221 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
5223 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
5224 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
5225 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,id
);
5226 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL
,id
);
5228 // apply skill bonuses
5229 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
5231 // temporary bonuses
5232 AuraList
const& mModSkill
= GetAurasByType(SPELL_AURA_MOD_SKILL
);
5233 for(AuraList::const_iterator j
= mModSkill
.begin(); j
!= mModSkill
.end(); ++j
)
5234 if ((*j
)->GetModifier()->m_miscvalue
== int32(id
))
5235 (*j
)->ApplyModifier(true);
5237 // permanent bonuses
5238 AuraList
const& mModSkillTalent
= GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT
);
5239 for(AuraList::const_iterator j
= mModSkillTalent
.begin(); j
!= mModSkillTalent
.end(); ++j
)
5240 if ((*j
)->GetModifier()->m_miscvalue
== int32(id
))
5241 (*j
)->ApplyModifier(true);
5243 // Learn all spells for skill
5244 learnSkillRewardedSpells(id
, currVal
);
5250 bool Player::HasSkill(uint32 skill
) const
5252 if(!skill
)return false;
5253 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5255 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5263 uint16
Player::GetSkillValue(uint32 skill
) const
5268 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5270 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5272 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5274 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5275 result
+= SKILL_TEMP_BONUS(bonus
);
5276 result
+= SKILL_PERM_BONUS(bonus
);
5277 return result
< 0 ? 0 : result
;
5283 uint16
Player::GetMaxSkillValue(uint32 skill
) const
5286 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5288 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5290 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5292 int32 result
= int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5293 result
+= SKILL_TEMP_BONUS(bonus
);
5294 result
+= SKILL_PERM_BONUS(bonus
);
5295 return result
< 0 ? 0 : result
;
5301 uint16
Player::GetPureMaxSkillValue(uint32 skill
) const
5304 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5306 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5308 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5314 uint16
Player::GetBaseSkillValue(uint32 skill
) const
5317 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5319 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5321 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5322 result
+= SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5323 return result
< 0 ? 0 : result
;
5329 uint16
Player::GetPureSkillValue(uint32 skill
) const
5332 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5334 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5336 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5342 int16
Player::GetSkillPermBonusValue(uint32 skill
) const
5347 for (int i
= 0; i
< PLAYER_MAX_SKILLS
; ++i
)
5349 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5351 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5358 int16
Player::GetSkillTempBonusValue(uint32 skill
) const
5363 for (int i
= 0; i
< PLAYER_MAX_SKILLS
; ++i
)
5365 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5367 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5374 void Player::SendInitialActionButtons() const
5376 sLog
.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5378 WorldPacket
data(SMSG_ACTION_BUTTONS
, (MAX_ACTION_BUTTONS
*4));
5379 for(int button
= 0; button
< MAX_ACTION_BUTTONS
; ++button
)
5381 ActionButtonList::const_iterator itr
= m_actionButtons
.find(button
);
5382 if(itr
!= m_actionButtons
.end() && itr
->second
.uState
!= ACTIONBUTTON_DELETED
)
5384 data
<< uint16(itr
->second
.action
);
5385 data
<< uint8(itr
->second
.misc
);
5386 data
<< uint8(itr
->second
.type
);
5394 GetSession()->SendPacket( &data
);
5395 sLog
.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5398 bool Player::addActionButton(const uint8 button
, const uint16 action
, const uint8 type
, const uint8 misc
)
5400 if(button
>= MAX_ACTION_BUTTONS
)
5402 sLog
.outError( "Action %u not added into button %u for player %s: button must be < 132", action
, button
, GetName() );
5406 // check cheating with adding non-known spells to action bar
5407 if(type
==ACTION_BUTTON_SPELL
)
5409 if(!sSpellStore
.LookupEntry(action
))
5411 sLog
.outError( "Action %u not added into button %u for player %s: spell not exist", action
, button
, GetName() );
5415 if(!HasSpell(action
))
5417 sLog
.outError( "Action %u not added into button %u for player %s: player don't known this spell", action
, button
, GetName() );
5422 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5424 if (buttonItr
==m_actionButtons
.end())
5425 { // just add new button
5426 m_actionButtons
[button
] = ActionButton(action
,type
,misc
);
5429 { // change state of current button
5430 ActionButtonUpdateState uState
= buttonItr
->second
.uState
;
5431 buttonItr
->second
= ActionButton(action
,type
,misc
);
5432 if (uState
!= ACTIONBUTTON_NEW
) buttonItr
->second
.uState
= ACTIONBUTTON_CHANGED
;
5435 sLog
.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action
, button
);
5439 void Player::removeActionButton(uint8 button
)
5441 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5442 if (buttonItr
==m_actionButtons
.end())
5445 if(buttonItr
->second
.uState
==ACTIONBUTTON_NEW
)
5446 m_actionButtons
.erase(buttonItr
); // new and not saved
5448 buttonItr
->second
.uState
= ACTIONBUTTON_DELETED
; // saved, will deleted at next save
5450 sLog
.outDetail( "Action Button '%u' Removed from Player '%u'", button
, GetGUIDLow() );
5453 bool Player::SetPosition(float x
, float y
, float z
, float orientation
, bool teleport
)
5455 // prevent crash when a bad coord is sent by the client
5456 if(!MaNGOS::IsValidMapCoord(x
,y
,z
,orientation
))
5458 sLog
.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x
,y
,z
,orientation
,teleport
,GetGUIDLow());
5464 const float old_x
= GetPositionX();
5465 const float old_y
= GetPositionY();
5466 const float old_z
= GetPositionZ();
5467 const float old_r
= GetOrientation();
5469 if( teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
|| old_r
!= orientation
)
5471 if (teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
)
5472 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE
| AURA_INTERRUPT_FLAG_TURNING
);
5474 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING
);
5476 // move and update visible state if need
5477 m
->PlayerRelocation(this, x
, y
, z
, orientation
);
5479 // reread after Map::Relocation
5486 if(GetGroup() && (old_x
!= x
|| old_y
!= y
))
5487 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION
);
5490 // code block for underwater state update
5491 UpdateUnderwaterState(m
, x
, y
, z
);
5493 CheckExploreSystem();
5498 void Player::SaveRecallPosition()
5500 m_recallMap
= GetMapId();
5501 m_recallX
= GetPositionX();
5502 m_recallY
= GetPositionY();
5503 m_recallZ
= GetPositionZ();
5504 m_recallO
= GetOrientation();
5507 void Player::SendMessageToSet(WorldPacket
*data
, bool self
)
5509 GetMap()->MessageBroadcast(this, data
, self
);
5512 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
)
5514 GetMap()->MessageDistBroadcast(this, data
, dist
, self
);
5517 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
, bool own_team_only
)
5519 GetMap()->MessageDistBroadcast(this, data
, dist
, self
,own_team_only
);
5522 void Player::SendDirectMessage(WorldPacket
*data
)
5524 GetSession()->SendPacket(data
);
5527 void Player::SendCinematicStart(uint32 CinematicSequenceId
)
5529 WorldPacket
data(SMSG_TRIGGER_CINEMATIC
, 4);
5530 data
<< uint32(CinematicSequenceId
);
5531 SendDirectMessage(&data
);
5534 void Player::SendMovieStart(uint32 MovieId
)
5536 WorldPacket
data(SMSG_TRIGGER_MOVIE
, 4);
5537 data
<< uint32(MovieId
);
5538 SendDirectMessage(&data
);
5541 void Player::CheckExploreSystem()
5549 uint16 areaFlag
=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5550 if(areaFlag
==0xffff)
5552 int offset
= areaFlag
/ 32;
5556 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
);
5560 uint32 val
= (uint32
)(1 << (areaFlag
% 32));
5561 uint32 currFields
= GetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
);
5563 if( !(currFields
& val
) )
5565 SetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
, (uint32
)(currFields
| val
));
5567 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA
);
5569 AreaTableEntry
const *p
= GetAreaEntryByAreaFlagAndMap(areaFlag
,GetMapId());
5572 sLog
.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5574 else if(p
->area_level
> 0)
5576 uint32 area
= p
->ID
;
5577 if (getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
5579 SendExplorationExperience(area
,0);
5583 int32 diff
= int32(getLevel()) - p
->area_level
;
5587 XP
= uint32(objmgr
.GetBaseXP(getLevel()+5)*sWorld
.getRate(RATE_XP_EXPLORE
));
5591 int32 exploration_percent
= (100-((diff
-5)*5));
5592 if (exploration_percent
> 100)
5593 exploration_percent
= 100;
5594 else if (exploration_percent
< 0)
5595 exploration_percent
= 0;
5597 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*exploration_percent
/100*sWorld
.getRate(RATE_XP_EXPLORE
));
5601 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*sWorld
.getRate(RATE_XP_EXPLORE
));
5605 SendExplorationExperience(area
,XP
);
5607 sLog
.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area
);
5612 uint32
Player::TeamForRace(uint8 race
)
5614 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5617 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5621 switch(rEntry
->TeamID
)
5623 case 7: return ALLIANCE
;
5624 case 1: return HORDE
;
5627 sLog
.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race
),rEntry
->TeamID
);
5631 uint32
Player::getFactionForRace(uint8 race
)
5633 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5636 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5640 return rEntry
->FactionID
;
5643 void Player::setFactionForRace(uint8 race
)
5645 m_team
= TeamForRace(race
);
5646 setFaction( getFactionForRace(race
) );
5649 ReputationRank
Player::GetReputationRank(uint32 faction
) const
5651 FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(faction
);
5652 return GetReputationMgr().GetRank(factionEntry
);
5655 //Calculate total reputation percent player gain with quest/creature level
5656 int32
Player::CalculateReputationGain(uint32 creatureOrQuestLevel
, int32 rep
, bool for_quest
)
5658 float percent
= 100.0f
;
5660 float rate
= for_quest
? sWorld
.getRate(RATE_REPUTATION_LOWLEVEL_QUEST
) : sWorld
.getRate(RATE_REPUTATION_LOWLEVEL_KILL
);
5662 if(rate
!= 1.0f
&& creatureOrQuestLevel
<= MaNGOS::XP::GetGrayLevel(getLevel()))
5665 int32 repMod
= GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN
);
5667 percent
+= rep
> 0 ? repMod
: -repMod
;
5672 return int32(sWorld
.getRate(RATE_REPUTATION_GAIN
)*rep
*percent
/100);
5675 //Calculates how many reputation points player gains in victim's enemy factions
5676 void Player::RewardReputation(Unit
*pVictim
, float rate
)
5678 if(!pVictim
|| pVictim
->GetTypeId() == TYPEID_PLAYER
)
5681 ReputationOnKillEntry
const* Rep
= objmgr
.GetReputationOnKilEntry(((Creature
*)pVictim
)->GetCreatureInfo()->Entry
);
5686 if(Rep
->repfaction1
&& (!Rep
->team_dependent
|| GetTeam()==ALLIANCE
))
5688 int32 donerep1
= CalculateReputationGain(pVictim
->getLevel(),Rep
->repvalue1
,false);
5689 donerep1
= int32(donerep1
*rate
);
5690 FactionEntry
const *factionEntry1
= sFactionStore
.LookupEntry(Rep
->repfaction1
);
5691 uint32 current_reputation_rank1
= GetReputationMgr().GetRank(factionEntry1
);
5692 if (factionEntry1
&& current_reputation_rank1
<= Rep
->reputation_max_cap1
)
5693 GetReputationMgr().ModifyReputation(factionEntry1
, donerep1
);
5695 // Wiki: Team factions value divided by 2
5696 if (factionEntry1
&& Rep
->is_teamaward1
)
5698 FactionEntry
const *team1_factionEntry
= sFactionStore
.LookupEntry(factionEntry1
->team
);
5699 if(team1_factionEntry
)
5700 GetReputationMgr().ModifyReputation(team1_factionEntry
, donerep1
/ 2);
5704 if(Rep
->repfaction2
&& (!Rep
->team_dependent
|| GetTeam()==HORDE
))
5706 int32 donerep2
= CalculateReputationGain(pVictim
->getLevel(),Rep
->repvalue2
,false);
5707 donerep2
= int32(donerep2
*rate
);
5708 FactionEntry
const *factionEntry2
= sFactionStore
.LookupEntry(Rep
->repfaction2
);
5709 uint32 current_reputation_rank2
= GetReputationMgr().GetRank(factionEntry2
);
5710 if (factionEntry2
&& current_reputation_rank2
<= Rep
->reputation_max_cap2
)
5711 GetReputationMgr().ModifyReputation(factionEntry2
, donerep2
);
5713 // Wiki: Team factions value divided by 2
5714 if (factionEntry2
&& Rep
->is_teamaward2
)
5716 FactionEntry
const *team2_factionEntry
= sFactionStore
.LookupEntry(factionEntry2
->team
);
5717 if(team2_factionEntry
)
5718 GetReputationMgr().ModifyReputation(team2_factionEntry
, donerep2
/ 2);
5723 //Calculate how many reputation points player gain with the quest
5724 void Player::RewardReputation(Quest
const *pQuest
)
5726 // quest reputation reward/loss
5727 for(int i
= 0; i
< QUEST_REPUTATIONS_COUNT
; ++i
)
5729 if(pQuest
->RewRepFaction
[i
] && pQuest
->RewRepValue
[i
] )
5731 int32 rep
= CalculateReputationGain(GetQuestLevel(pQuest
),pQuest
->RewRepValue
[i
],true);
5732 FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(pQuest
->RewRepFaction
[i
]);
5734 GetReputationMgr().ModifyReputation(factionEntry
, rep
);
5738 // TODO: implement reputation spillover
5741 void Player::UpdateArenaFields(void)
5743 /* arena calcs go here */
5746 void Player::UpdateHonorFields()
5748 /// called when rewarding honor and at each save
5749 uint64 now
= time(NULL
);
5750 uint64 today
= uint64(time(NULL
) / DAY
) * DAY
;
5752 if(m_lastHonorUpdateTime
< today
)
5754 uint64 yesterday
= today
- DAY
;
5756 uint16 kills_today
= PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS
));
5758 // update yesterday's contribution
5759 if(m_lastHonorUpdateTime
>= yesterday
)
5761 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
));
5763 // this is the first update today, reset today's contribution
5764 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, 0);
5765 SetUInt32Value(PLAYER_FIELD_KILLS
, MAKE_PAIR32(0,kills_today
));
5769 // no honor/kills yesterday or today, reset
5770 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0);
5771 SetUInt32Value(PLAYER_FIELD_KILLS
, 0);
5775 m_lastHonorUpdateTime
= now
;
5778 ///Calculate the amount of honor gained based on the victim
5779 ///and the size of the group for which the honor is divided
5780 ///An exact honor value can also be given (overriding the calcs)
5781 bool Player::RewardHonor(Unit
*uVictim
, uint32 groupsize
, float honor
)
5783 // do not reward honor in arenas, but enable onkill spellproc
5786 if(!uVictim
|| uVictim
== this || uVictim
->GetTypeId() != TYPEID_PLAYER
)
5789 if( GetBGTeam() == ((Player
*)uVictim
)->GetBGTeam() )
5795 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5796 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE
))
5799 uint64 victim_guid
= 0;
5800 uint32 victim_rank
= 0;
5802 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5803 UpdateHonorFields();
5807 if(!uVictim
|| uVictim
== this || uVictim
->HasAuraType(SPELL_AURA_NO_PVP_CREDIT
))
5810 victim_guid
= uVictim
->GetGUID();
5812 if( uVictim
->GetTypeId() == TYPEID_PLAYER
)
5814 Player
*pVictim
= (Player
*)uVictim
;
5816 if( GetTeam() == pVictim
->GetTeam() && !sWorld
.IsFFAPvPRealm() )
5819 float f
= 1; //need for total kills (?? need more info)
5821 uint32 k_level
= getLevel();
5822 uint32 v_level
= pVictim
->getLevel();
5825 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
5827 // [1..14] Alliance honor titles and player name
5828 // [15..28] Horde honor titles and player name
5829 // [29..38] Other title and player name
5831 uint32 victim_title
= pVictim
->GetUInt32Value(PLAYER_CHOSEN_TITLE
);
5832 // Get Killer titles, CharTitlesEntry::bit_index
5834 // title[1..14] -> rank[5..18]
5835 // title[15..28] -> rank[5..18]
5836 // title[other] -> 0
5837 if (victim_title
== 0)
5838 victim_guid
= 0; // Don't show HK: <rank> message, only log.
5839 else if (victim_title
< 15)
5840 victim_rank
= victim_title
+ 4;
5841 else if (victim_title
< 29)
5842 victim_rank
= victim_title
- 14 + 4;
5844 victim_guid
= 0; // Don't show HK: <rank> message, only log.
5847 k_grey
= MaNGOS::XP::GetGrayLevel(k_level
);
5852 float diff_level
= (k_level
== k_grey
) ? 1 : ((float(v_level
) - float(k_grey
)) / (float(k_level
) - float(k_grey
)));
5854 int32 v_rank
=1; //need more info
5856 honor
= ((f
* diff_level
* (190 + v_rank
*10))/6);
5857 honor
*= ((float)k_level
) / 70.0f
; //factor of dependence on levels of the killer
5859 // count the number of playerkills in one day
5860 ApplyModUInt32Value(PLAYER_FIELD_KILLS
, 1, true);
5861 // and those in a lifetime
5862 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 1, true);
5863 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL
);
5867 Creature
*cVictim
= (Creature
*)uVictim
;
5869 if (!cVictim
->isRacialLeader())
5872 honor
= 100; // ??? need more info
5873 victim_rank
= 19; // HK: Leader
5877 if (uVictim
!= NULL
)
5879 honor
*= sWorld
.getRate(RATE_HONOR
);
5884 honor
*= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
5887 // honor - for show honor points in log
5888 // victim_guid - for show victim name in log
5889 // victim_rank [1..4] HK: <dishonored rank>
5890 // victim_rank [5..19] HK: <alliance\horde rank>
5891 // victim_rank [0,20+] HK: <>
5892 WorldPacket
data(SMSG_PVP_CREDIT
,4+8+4);
5893 data
<< (uint32
) honor
;
5894 data
<< (uint64
) victim_guid
;
5895 data
<< (uint32
) victim_rank
;
5897 GetSession()->SendPacket(&data
);
5900 ModifyHonorPoints(int32(honor
));
5902 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, uint32(honor
), true);
5906 void Player::ModifyHonorPoints( int32 value
)
5910 if (GetHonorPoints() > sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
))
5911 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) + value
);
5913 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() > uint32(-value
) ? GetHonorPoints() + value
: 0);
5916 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() < sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) - value
? GetHonorPoints() + value
: sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
));
5919 void Player::ModifyArenaPoints( int32 value
)
5923 if (GetArenaPoints() > sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
))
5924 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) + value
);
5926 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() > uint32(-value
) ? GetArenaPoints() + value
: 0);
5929 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() < sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) - value
? GetArenaPoints() + value
: sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
));
5932 uint32
Player::GetGuildIdFromDB(uint64 guid
)
5934 QueryResult
* result
= CharacterDatabase
.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid
));
5938 uint32 id
= result
->Fetch()[0].GetUInt32();
5943 uint32
Player::GetRankFromDB(uint64 guid
)
5945 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid
) );
5948 uint32 v
= result
->Fetch()[0].GetUInt32();
5956 uint32
Player::GetArenaTeamIdFromDB(uint64 guid
, uint8 type
)
5958 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
);
5962 uint32 id
= (*result
)[0].GetUInt32();
5967 uint32
Player::GetZoneIdFromDB(uint64 guid
)
5969 uint32 guidLow
= GUID_LOPART(guid
);
5970 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow
);
5973 Field
* fields
= result
->Fetch();
5974 uint32 zone
= fields
[0].GetUInt32();
5979 // stored zone is zero, use generic and slow zone detection
5980 result
= CharacterDatabase
.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow
);
5983 fields
= result
->Fetch();
5984 uint32 map
= fields
[0].GetUInt32();
5985 float posx
= fields
[1].GetFloat();
5986 float posy
= fields
[2].GetFloat();
5987 float posz
= fields
[3].GetFloat();
5990 zone
= MapManager::Instance().GetZoneId(map
,posx
,posy
,posz
);
5992 CharacterDatabase
.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone
, guidLow
);
5998 void Player::UpdateArea(uint32 newArea
)
6000 // FFA_PVP flags are area and not zone id dependent
6001 // so apply them accordingly
6002 m_areaUpdateId
= newArea
;
6004 AreaTableEntry
const* area
= GetAreaEntryByAreaID(newArea
);
6006 if(area
&& (area
->flags
& AREA_FLAG_ARENA
))
6009 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6013 // remove ffa flag only if not ffapvp realm
6014 // removal in sanctuaries and capitals is handled in zone update
6015 if(HasByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
) && !sWorld
.IsFFAPvPRealm())
6016 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6019 UpdateAreaDependentAuras(newArea
);
6022 void Player::UpdateZone(uint32 newZone
, uint32 newArea
)
6024 if(m_zoneUpdateId
!= newZone
)
6025 SendInitWorldStates(newZone
, newArea
); // only if really enters to new zone, not just area change, works strange...
6027 m_zoneUpdateId
= newZone
;
6028 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
6030 // zone changed, so area changed as well, update it
6031 UpdateArea(newArea
);
6033 AreaTableEntry
const* zone
= GetAreaEntryByAreaID(newZone
);
6037 if (sWorld
.getConfig(CONFIG_WEATHER
))
6039 Weather
*wth
= sWorld
.FindWeather(zone
->ID
);
6042 wth
->SendWeatherUpdateToPlayer(this);
6046 if(!sWorld
.AddWeather(zone
->ID
))
6048 // send fine weather packet to remove old zone's weather
6049 Weather::SendFineWeatherUpdateToPlayer(this);
6054 pvpInfo
.inHostileArea
=
6055 GetTeam() == ALLIANCE
&& zone
->team
== AREATEAM_HORDE
||
6056 GetTeam() == HORDE
&& zone
->team
== AREATEAM_ALLY
||
6057 sWorld
.IsPvPRealm() && zone
->team
== AREATEAM_NONE
||
6058 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6060 if(pvpInfo
.inHostileArea
) // in hostile area
6062 if(!IsPvP() || pvpInfo
.endTimer
!= 0)
6063 UpdatePvP(true, true);
6065 else // in friendly area
6067 if(IsPvP() && !HasFlag(PLAYER_FLAGS
,PLAYER_FLAGS_IN_PVP
) && pvpInfo
.endTimer
== 0)
6068 pvpInfo
.endTimer
= time(0); // start toggle-off
6071 if(zone
->flags
& AREA_FLAG_SANCTUARY
) // in sanctuary
6073 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_SANCTUARY
);
6074 if(sWorld
.IsFFAPvPRealm())
6075 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6079 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_SANCTUARY
);
6082 if(zone
->flags
& AREA_FLAG_CAPITAL
) // in capital city
6084 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6085 SetRestType(REST_TYPE_IN_CITY
);
6086 InnEnter(time(0),GetMapId(),0,0,0);
6088 if(sWorld
.IsFFAPvPRealm())
6089 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6091 else // anywhere else
6093 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6095 if(GetRestType()==REST_TYPE_IN_TAVERN
) // has been in tavern. Is still in?
6097 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6099 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6100 SetRestType(REST_TYPE_NO
);
6102 if(sWorld
.IsFFAPvPRealm())
6103 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6106 else // not in tavern (leave city then)
6108 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6109 SetRestType(REST_TYPE_NO
);
6111 // Set player to FFA PVP when not in rested environment.
6112 if(sWorld
.IsFFAPvPRealm())
6113 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6118 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6119 // if player resurrected at teleport this will be applied in resurrect code
6121 DestroyZoneLimitedItem( true, newZone
);
6123 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6124 AutoUnequipOffhandIfNeed();
6126 // recent client version not send leave/join channel packets for built-in local channels
6127 UpdateLocalChannels( newZone
);
6131 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE
);
6133 UpdateZoneDependentAuras(newZone
);
6136 //If players are too far way of duel flag... then player loose the duel
6137 void Player::CheckDuelDistance(time_t currTime
)
6142 uint64 duelFlagGUID
= GetUInt64Value(PLAYER_DUEL_ARBITER
);
6143 GameObject
* obj
= GetMap()->GetGameObject(duelFlagGUID
);
6147 if(duel
->outOfBound
== 0)
6149 if(!IsWithinDistInMap(obj
, 50))
6151 duel
->outOfBound
= currTime
;
6153 WorldPacket
data(SMSG_DUEL_OUTOFBOUNDS
, 0);
6154 GetSession()->SendPacket(&data
);
6159 if(IsWithinDistInMap(obj
, 40))
6161 duel
->outOfBound
= 0;
6163 WorldPacket
data(SMSG_DUEL_INBOUNDS
, 0);
6164 GetSession()->SendPacket(&data
);
6166 else if(currTime
>= (duel
->outOfBound
+10))
6168 DuelComplete(DUEL_FLED
);
6173 void Player::DuelComplete(DuelCompleteType type
)
6175 // duel not requested
6179 WorldPacket
data(SMSG_DUEL_COMPLETE
, (1));
6180 data
<< (uint8
)((type
!= DUEL_INTERUPTED
) ? 1 : 0);
6181 GetSession()->SendPacket(&data
);
6182 duel
->opponent
->GetSession()->SendPacket(&data
);
6184 if(type
!= DUEL_INTERUPTED
)
6186 data
.Initialize(SMSG_DUEL_WINNER
, (1+20)); // we guess size
6187 data
<< (uint8
)((type
==DUEL_WON
) ? 0 : 1); // 0 = just won; 1 = fled
6188 data
<< duel
->opponent
->GetName();
6190 SendMessageToSet(&data
,true);
6193 // cool-down duel spell
6194 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6201 GetSession()->SendPacket(&data);
6202 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6203 data<<duel->opponent->GetGUID();
6207 duel->opponent->GetSession()->SendPacket(&data);*/
6209 //Remove Duel Flag object
6210 GameObject
* obj
= GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER
));
6212 duel
->initiator
->RemoveGameObject(obj
,true);
6215 std::vector
<uint32
> auras2remove
;
6216 AuraMap
const& vAuras
= duel
->opponent
->GetAuras();
6217 for (AuraMap::const_iterator i
= vAuras
.begin(); i
!= vAuras
.end(); ++i
)
6219 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6220 auras2remove
.push_back(i
->second
->GetId());
6223 for(size_t i
=0; i
<auras2remove
.size(); ++i
)
6224 duel
->opponent
->RemoveAurasDueToSpell(auras2remove
[i
]);
6226 auras2remove
.clear();
6227 AuraMap
const& auras
= GetAuras();
6228 for (AuraMap::const_iterator i
= auras
.begin(); i
!= auras
.end(); ++i
)
6230 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == duel
->opponent
->GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6231 auras2remove
.push_back(i
->second
->GetId());
6233 for(size_t i
=0; i
<auras2remove
.size(); ++i
)
6234 RemoveAurasDueToSpell(auras2remove
[i
]);
6236 // cleanup combo points
6237 if(GetComboTarget()==duel
->opponent
->GetGUID())
6239 else if(GetComboTarget()==duel
->opponent
->GetPetGUID())
6242 if(duel
->opponent
->GetComboTarget()==GetGUID())
6243 duel
->opponent
->ClearComboPoints();
6244 else if(duel
->opponent
->GetComboTarget()==GetPetGUID())
6245 duel
->opponent
->ClearComboPoints();
6248 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6249 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6250 duel
->opponent
->SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6251 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6253 delete duel
->opponent
->duel
;
6254 duel
->opponent
->duel
= NULL
;
6259 //---------------------------------------------------------//
6261 void Player::_ApplyItemMods(Item
*item
, uint8 slot
,bool apply
)
6263 if(slot
>= INVENTORY_SLOT_BAG_END
|| !item
)
6266 // not apply/remove mods for broken item
6267 if(item
->IsBroken())
6270 ItemPrototype
const *proto
= item
->GetProto();
6275 sLog
.outDetail("applying mods for item %u ",item
->GetGUIDLow());
6277 uint32 attacktype
= Player::GetAttackBySlot(slot
);
6278 if(attacktype
< MAX_ATTACK
)
6279 _ApplyWeaponDependentAuraMods(item
,WeaponAttackType(attacktype
),apply
);
6281 _ApplyItemBonuses(proto
,slot
,apply
);
6283 if( slot
==EQUIPMENT_SLOT_RANGED
)
6284 _ApplyAmmoBonuses();
6286 ApplyItemEquipSpell(item
,apply
);
6287 ApplyEnchantment(item
, apply
);
6289 if(proto
->Socket
[0].Color
) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6290 CorrectMetaGemEnchants(slot
, apply
);
6292 sLog
.outDebug("_ApplyItemMods complete.");
6295 void Player::_ApplyItemBonuses(ItemPrototype
const *proto
, uint8 slot
, bool apply
)
6297 if(slot
>= INVENTORY_SLOT_BAG_END
|| !proto
)
6300 for (int i
= 0; i
< MAX_ITEM_PROTO_STATS
; ++i
)
6302 uint32 statType
= 0;
6305 if(proto
->ScalingStatDistribution
)
6307 if(ScalingStatDistributionEntry
const *ssd
= sScalingStatDistributionStore
.LookupEntry(proto
->ScalingStatDistribution
))
6309 statType
= ssd
->StatMod
[i
];
6311 if(uint32 modifier
= ssd
->Modifier
[i
])
6313 uint32 level
= ((getLevel() > ssd
->MaxLevel
) ? ssd
->MaxLevel
: getLevel());
6314 if(ScalingStatValuesEntry
const *ssv
= sScalingStatValuesStore
.LookupEntry(level
))
6316 uint32 multiplier
= ssv
->Multiplier
[proto
->GetScalingStatValuesColumn()];
6317 val
= (multiplier
* modifier
) / 10000;
6324 statType
= proto
->ItemStat
[i
].ItemStatType
;
6325 val
= proto
->ItemStat
[i
].ItemStatValue
;
6334 HandleStatModifier(UNIT_MOD_MANA
, BASE_VALUE
, float(val
), apply
);
6336 case ITEM_MOD_HEALTH
: // modify HP
6337 HandleStatModifier(UNIT_MOD_HEALTH
, BASE_VALUE
, float(val
), apply
);
6339 case ITEM_MOD_AGILITY
: // modify agility
6340 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, BASE_VALUE
, float(val
), apply
);
6341 ApplyStatBuffMod(STAT_AGILITY
, float(val
), apply
);
6343 case ITEM_MOD_STRENGTH
: //modify strength
6344 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, BASE_VALUE
, float(val
), apply
);
6345 ApplyStatBuffMod(STAT_STRENGTH
, float(val
), apply
);
6347 case ITEM_MOD_INTELLECT
: //modify intellect
6348 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, BASE_VALUE
, float(val
), apply
);
6349 ApplyStatBuffMod(STAT_INTELLECT
, float(val
), apply
);
6351 case ITEM_MOD_SPIRIT
: //modify spirit
6352 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, BASE_VALUE
, float(val
), apply
);
6353 ApplyStatBuffMod(STAT_SPIRIT
, float(val
), apply
);
6355 case ITEM_MOD_STAMINA
: //modify stamina
6356 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, BASE_VALUE
, float(val
), apply
);
6357 ApplyStatBuffMod(STAT_STAMINA
, float(val
), apply
);
6359 case ITEM_MOD_DEFENSE_SKILL_RATING
:
6360 ApplyRatingMod(CR_DEFENSE_SKILL
, int32(val
), apply
);
6362 case ITEM_MOD_DODGE_RATING
:
6363 ApplyRatingMod(CR_DODGE
, int32(val
), apply
);
6365 case ITEM_MOD_PARRY_RATING
:
6366 ApplyRatingMod(CR_PARRY
, int32(val
), apply
);
6368 case ITEM_MOD_BLOCK_RATING
:
6369 ApplyRatingMod(CR_BLOCK
, int32(val
), apply
);
6371 case ITEM_MOD_HIT_MELEE_RATING
:
6372 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6374 case ITEM_MOD_HIT_RANGED_RATING
:
6375 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6377 case ITEM_MOD_HIT_SPELL_RATING
:
6378 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6380 case ITEM_MOD_CRIT_MELEE_RATING
:
6381 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6383 case ITEM_MOD_CRIT_RANGED_RATING
:
6384 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6386 case ITEM_MOD_CRIT_SPELL_RATING
:
6387 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6389 case ITEM_MOD_HIT_TAKEN_MELEE_RATING
:
6390 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6392 case ITEM_MOD_HIT_TAKEN_RANGED_RATING
:
6393 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6395 case ITEM_MOD_HIT_TAKEN_SPELL_RATING
:
6396 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6398 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING
:
6399 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6401 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING
:
6402 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6404 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING
:
6405 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6407 case ITEM_MOD_HASTE_MELEE_RATING
:
6408 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6410 case ITEM_MOD_HASTE_RANGED_RATING
:
6411 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6413 case ITEM_MOD_HASTE_SPELL_RATING
:
6414 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6416 case ITEM_MOD_HIT_RATING
:
6417 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6418 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6419 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6421 case ITEM_MOD_CRIT_RATING
:
6422 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6423 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6424 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6426 case ITEM_MOD_HIT_TAKEN_RATING
:
6427 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6428 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6429 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6431 case ITEM_MOD_CRIT_TAKEN_RATING
:
6432 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6433 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6434 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6436 case ITEM_MOD_RESILIENCE_RATING
:
6437 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6438 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6439 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6441 case ITEM_MOD_HASTE_RATING
:
6442 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6443 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6444 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6446 case ITEM_MOD_EXPERTISE_RATING
:
6447 ApplyRatingMod(CR_EXPERTISE
, int32(val
), apply
);
6449 case ITEM_MOD_ATTACK_POWER
:
6450 HandleStatModifier(UNIT_MOD_ATTACK_POWER
, TOTAL_VALUE
, float(val
), apply
);
6451 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(val
), apply
);
6453 case ITEM_MOD_RANGED_ATTACK_POWER
:
6454 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(val
), apply
);
6456 case ITEM_MOD_FERAL_ATTACK_POWER
:
6457 ApplyFeralAPBonus(int32(val
), apply
);
6459 case ITEM_MOD_SPELL_HEALING_DONE
:
6460 ApplySpellHealingBonus(int32(val
), apply
);
6462 case ITEM_MOD_SPELL_DAMAGE_DONE
:
6463 ApplySpellDamageBonus(int32(val
), apply
);
6465 case ITEM_MOD_MANA_REGENERATION
:
6466 ApplyManaRegenBonus(int32(val
), apply
);
6468 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
6469 ApplyRatingMod(CR_ARMOR_PENETRATION
, int32(val
), apply
);
6471 case ITEM_MOD_SPELL_POWER
:
6472 ApplySpellHealingBonus(int32(val
), apply
);
6473 ApplySpellDamageBonus(int32(val
), apply
);
6479 HandleStatModifier(UNIT_MOD_ARMOR
, BASE_VALUE
, float(proto
->Armor
), apply
);
6482 HandleBaseModValue(SHIELD_BLOCK_VALUE
, FLAT_MOD
, float(proto
->Block
), apply
);
6485 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY
, BASE_VALUE
, float(proto
->HolyRes
), apply
);
6488 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE
, BASE_VALUE
, float(proto
->FireRes
), apply
);
6490 if (proto
->NatureRes
)
6491 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE
, BASE_VALUE
, float(proto
->NatureRes
), apply
);
6493 if (proto
->FrostRes
)
6494 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST
, BASE_VALUE
, float(proto
->FrostRes
), apply
);
6496 if (proto
->ShadowRes
)
6497 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW
, BASE_VALUE
, float(proto
->ShadowRes
), apply
);
6499 if (proto
->ArcaneRes
)
6500 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE
, BASE_VALUE
, float(proto
->ArcaneRes
), apply
);
6502 WeaponAttackType attType
= BASE_ATTACK
;
6503 float damage
= 0.0f
;
6505 if( slot
== EQUIPMENT_SLOT_RANGED
&& (
6506 proto
->InventoryType
== INVTYPE_RANGED
|| proto
->InventoryType
== INVTYPE_THROWN
||
6507 proto
->InventoryType
== INVTYPE_RANGEDRIGHT
))
6509 attType
= RANGED_ATTACK
;
6511 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6513 attType
= OFF_ATTACK
;
6516 if (proto
->Damage
[0].DamageMin
> 0 )
6518 damage
= apply
? proto
->Damage
[0].DamageMin
: BASE_MINDAMAGE
;
6519 SetBaseWeaponDamage(attType
, MINDAMAGE
, damage
);
6520 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6523 if (proto
->Damage
[0].DamageMax
> 0 )
6525 damage
= apply
? proto
->Damage
[0].DamageMax
: BASE_MAXDAMAGE
;
6526 SetBaseWeaponDamage(attType
, MAXDAMAGE
, damage
);
6529 // Druids get feral AP bonus from weapon dps
6530 if(getClass() == CLASS_DRUID
)
6532 int32 feral_bonus
= proto
->getFeralBonus();
6533 if (feral_bonus
> 0)
6534 ApplyFeralAPBonus(feral_bonus
, apply
);
6537 if(!IsUseEquipedWeapon(slot
==EQUIPMENT_SLOT_MAINHAND
))
6542 if(slot
== EQUIPMENT_SLOT_RANGED
)
6543 SetAttackTime(RANGED_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6544 else if(slot
==EQUIPMENT_SLOT_MAINHAND
)
6545 SetAttackTime(BASE_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6546 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6547 SetAttackTime(OFF_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6550 if(CanModifyStats() && (damage
|| proto
->Delay
))
6551 UpdateDamagePhysical(attType
);
6554 void Player::_ApplyWeaponDependentAuraMods(Item
*item
,WeaponAttackType attackType
,bool apply
)
6556 AuraList
const& auraCritList
= GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT
);
6557 for(AuraList::const_iterator itr
= auraCritList
.begin(); itr
!=auraCritList
.end();++itr
)
6558 _ApplyWeaponDependentAuraCritMod(item
,attackType
,*itr
,apply
);
6560 AuraList
const& auraDamageFlatList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE
);
6561 for(AuraList::const_iterator itr
= auraDamageFlatList
.begin(); itr
!=auraDamageFlatList
.end();++itr
)
6562 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6564 AuraList
const& auraDamagePCTList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
);
6565 for(AuraList::const_iterator itr
= auraDamagePCTList
.begin(); itr
!=auraDamagePCTList
.end();++itr
)
6566 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6569 void Player::_ApplyWeaponDependentAuraCritMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6571 // generic not weapon specific case processes in aura code
6572 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6575 BaseModGroup mod
= BASEMOD_END
;
6578 case BASE_ATTACK
: mod
= CRIT_PERCENTAGE
; break;
6579 case OFF_ATTACK
: mod
= OFFHAND_CRIT_PERCENTAGE
;break;
6580 case RANGED_ATTACK
: mod
= RANGED_CRIT_PERCENTAGE
; break;
6584 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6586 HandleBaseModValue(mod
, FLAT_MOD
, float (aura
->GetModifier()->m_amount
), apply
);
6590 void Player::_ApplyWeaponDependentAuraDamageMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6592 // ignore spell mods for not wands
6593 Modifier
const* modifier
= aura
->GetModifier();
6594 if((modifier
->m_miscvalue
& SPELL_SCHOOL_MASK_NORMAL
)==0 && (getClassMask() & CLASSMASK_WAND_USERS
)==0)
6597 // generic not weapon specific case processes in aura code
6598 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6601 UnitMods unitMod
= UNIT_MOD_END
;
6604 case BASE_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_MAINHAND
; break;
6605 case OFF_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_OFFHAND
; break;
6606 case RANGED_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_RANGED
; break;
6610 UnitModifierType unitModType
= TOTAL_VALUE
;
6611 switch(modifier
->m_auraname
)
6613 case SPELL_AURA_MOD_DAMAGE_DONE
: unitModType
= TOTAL_VALUE
; break;
6614 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
: unitModType
= TOTAL_PCT
; break;
6618 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6620 HandleStatModifier(unitMod
, unitModType
, float(modifier
->m_amount
),apply
);
6624 void Player::ApplyItemEquipSpell(Item
*item
, bool apply
, bool form_change
)
6629 ItemPrototype
const *proto
= item
->GetProto();
6633 for (int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
6635 _Spell
const& spellData
= proto
->Spells
[i
];
6638 if(!spellData
.SpellId
)
6641 // wrong triggering type
6642 if(apply
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_EQUIP
)
6645 // check if it is valid spell
6646 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellData
.SpellId
);
6650 ApplyEquipSpell(spellproto
,item
,apply
,form_change
);
6654 void Player::ApplyEquipSpell(SpellEntry
const* spellInfo
, Item
* item
, bool apply
, bool form_change
)
6658 // Cannot be used in this stance/form
6659 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
) != SPELL_CAST_OK
)
6662 if(form_change
) // check aura active state from other form
6665 for (int k
=0; k
< 3; ++k
)
6667 spellEffectPair spair
= spellEffectPair(spellInfo
->Id
, k
);
6668 for (AuraMap::const_iterator iter
= m_Auras
.lower_bound(spair
); iter
!= m_Auras
.upper_bound(spair
); ++iter
)
6670 if(!item
|| iter
->second
->GetCastItemGUID() == item
->GetGUID())
6680 if(found
) // and skip re-cast already active aura at form change
6684 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item
? "item" : "itemset"), spellInfo
->Id
);
6686 CastSpell(this,spellInfo
,true,item
);
6690 if(form_change
) // check aura compatibility
6692 // Cannot be used in this stance/form
6693 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
)==SPELL_CAST_OK
)
6694 return; // and remove only not compatible at form change
6698 RemoveAurasDueToItemSpell(item
,spellInfo
->Id
); // un-apply all spells , not only at-equipped
6700 RemoveAurasDueToSpell(spellInfo
->Id
); // un-apply spell (item set case)
6704 void Player::UpdateEquipSpellsAtFormChange()
6706 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
6708 if(m_items
[i
] && !m_items
[i
]->IsBroken())
6710 ApplyItemEquipSpell(m_items
[i
],false,true); // remove spells that not fit to form
6711 ApplyItemEquipSpell(m_items
[i
],true,true); // add spells that fit form but not active
6715 // item set bonuses not dependent from item broken state
6716 for(size_t setindex
= 0; setindex
< ItemSetEff
.size(); ++setindex
)
6718 ItemSetEffect
* eff
= ItemSetEff
[setindex
];
6722 for(uint32 y
=0;y
<8; ++y
)
6724 SpellEntry
const* spellInfo
= eff
->spells
[y
];
6728 ApplyEquipSpell(spellInfo
,NULL
,false,true); // remove spells that not fit to form
6729 ApplyEquipSpell(spellInfo
,NULL
,true,true); // add spells that fit form but not active
6734 void Player::CastItemCombatSpell(Item
*item
,Unit
* Target
, WeaponAttackType attType
)
6736 if(!item
|| item
->IsBroken())
6739 ItemPrototype
const *proto
= item
->GetProto();
6743 if (!Target
|| Target
== this )
6746 for (int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
6748 _Spell
const& spellData
= proto
->Spells
[i
];
6751 if(!spellData
.SpellId
)
6754 // wrong triggering type
6755 if(spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_CHANCE_ON_HIT
)
6758 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
6761 sLog
.outError("WORLD: unknown Item spellid %i", spellData
.SpellId
);
6765 // not allow proc extra attack spell at extra attack
6766 if( m_extraAttacks
&& IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_ADD_EXTRA_ATTACKS
) )
6769 float chance
= spellInfo
->procChance
;
6771 if(spellData
.SpellPPMRate
)
6773 uint32 WeaponSpeed
= GetAttackTime(attType
);
6774 chance
= GetPPMProcChance(WeaponSpeed
, spellData
.SpellPPMRate
);
6776 else if(chance
> 100.0f
)
6778 chance
= GetWeaponProcChance();
6781 if (roll_chance_f(chance
))
6782 CastSpell(Target
, spellInfo
->Id
, true, item
);
6785 // item combat enchantments
6786 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
6788 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
6789 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
6790 if(!pEnchant
) continue;
6791 for (int s
=0;s
<3;s
++)
6793 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
)
6796 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
6799 sLog
.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
6803 float chance
= pEnchant
->amount
[s
] != 0 ? float(pEnchant
->amount
[s
]) : GetWeaponProcChance();
6804 if (roll_chance_f(chance
))
6806 if(IsPositiveSpell(pEnchant
->spellid
[s
]))
6807 CastSpell(this, pEnchant
->spellid
[s
], true, item
);
6809 CastSpell(Target
, pEnchant
->spellid
[s
], true, item
);
6815 void Player::CastItemUseSpell(Item
*item
,SpellCastTargets
const& targets
,uint8 cast_count
, uint32 glyphIndex
)
6817 ItemPrototype
const* proto
= item
->GetProto();
6818 // special learning case
6819 if(proto
->Spells
[0].SpellId
==SPELL_ID_GENERIC_LEARN
|| proto
->Spells
[0].SpellId
==SPELL_ID_GENERIC_LEARN_PET
)
6821 uint32 learn_spell_id
= proto
->Spells
[0].SpellId
;
6822 uint32 learning_spell_id
= proto
->Spells
[1].SpellId
;
6824 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(learn_spell_id
);
6827 sLog
.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto
->ItemId
, learn_spell_id
);
6828 SendEquipError(EQUIP_ERR_NONE
,item
,NULL
);
6832 Spell
*spell
= new Spell(this, spellInfo
, false);
6833 spell
->m_CastItem
= item
;
6834 spell
->m_cast_count
= cast_count
; //set count of casts
6835 spell
->m_currentBasePoints
[0] = learning_spell_id
;
6836 spell
->prepare(&targets
);
6840 // use triggered flag only for items with many spell casts and for not first cast
6843 // item spells casted at use
6844 for(int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
6846 _Spell
const& spellData
= proto
->Spells
[i
];
6849 if(!spellData
.SpellId
)
6852 // wrong triggering type
6853 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_NO_DELAY_USE
)
6856 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
6859 sLog
.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto
->ItemId
, spellData
.SpellId
);
6863 Spell
*spell
= new Spell(this, spellInfo
, (count
> 0));
6864 spell
->m_CastItem
= item
;
6865 spell
->m_cast_count
= cast_count
; // set count of casts
6866 spell
->m_glyphIndex
= glyphIndex
; // glyph index
6867 spell
->prepare(&targets
);
6872 // Item enchantments spells casted at use
6873 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
6875 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
6876 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
6877 if(!pEnchant
) continue;
6878 for (int s
=0;s
<3;s
++)
6880 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL
)
6883 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
6886 sLog
.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
6890 Spell
*spell
= new Spell(this, spellInfo
, (count
> 0));
6891 spell
->m_CastItem
= item
;
6892 spell
->m_cast_count
= cast_count
; // set count of casts
6893 spell
->m_glyphIndex
= glyphIndex
; // glyph index
6894 spell
->prepare(&targets
);
6901 void Player::_RemoveAllItemMods()
6903 sLog
.outDebug("_RemoveAllItemMods start.");
6905 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
6909 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6913 // item set bonuses not dependent from item broken state
6915 RemoveItemsSetItem(this,proto
);
6917 if(m_items
[i
]->IsBroken())
6920 ApplyItemEquipSpell(m_items
[i
],false);
6921 ApplyEnchantment(m_items
[i
], false);
6925 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
6929 if(m_items
[i
]->IsBroken())
6931 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6935 uint32 attacktype
= Player::GetAttackBySlot(i
);
6936 if(attacktype
< MAX_ATTACK
)
6937 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),false);
6939 _ApplyItemBonuses(proto
,i
, false);
6941 if( i
== EQUIPMENT_SLOT_RANGED
)
6942 _ApplyAmmoBonuses();
6946 sLog
.outDebug("_RemoveAllItemMods complete.");
6949 void Player::_ApplyAllItemMods()
6951 sLog
.outDebug("_ApplyAllItemMods start.");
6953 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
6957 if(m_items
[i
]->IsBroken())
6960 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6964 uint32 attacktype
= Player::GetAttackBySlot(i
);
6965 if(attacktype
< MAX_ATTACK
)
6966 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),true);
6968 _ApplyItemBonuses(proto
,i
, true);
6970 if( i
== EQUIPMENT_SLOT_RANGED
)
6971 _ApplyAmmoBonuses();
6975 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
6979 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6983 // item set bonuses not dependent from item broken state
6985 AddItemsSetItem(this,m_items
[i
]);
6987 if(m_items
[i
]->IsBroken())
6990 ApplyItemEquipSpell(m_items
[i
],true);
6991 ApplyEnchantment(m_items
[i
], true);
6995 sLog
.outDebug("_ApplyAllItemMods complete.");
6998 void Player::_ApplyAmmoBonuses()
7001 uint32 ammo_id
= GetUInt32Value(PLAYER_AMMO_ID
);
7005 float currentAmmoDPS
;
7007 ItemPrototype
const *ammo_proto
= objmgr
.GetItemPrototype( ammo_id
);
7008 if( !ammo_proto
|| ammo_proto
->Class
!=ITEM_CLASS_PROJECTILE
|| !CheckAmmoCompatibility(ammo_proto
))
7009 currentAmmoDPS
= 0.0f
;
7011 currentAmmoDPS
= ammo_proto
->Damage
[0].DamageMin
;
7013 if(currentAmmoDPS
== GetAmmoDPS())
7016 m_ammoDPS
= currentAmmoDPS
;
7018 if(CanModifyStats())
7019 UpdateDamagePhysical(RANGED_ATTACK
);
7022 bool Player::CheckAmmoCompatibility(const ItemPrototype
*ammo_proto
) const
7027 // check ranged weapon
7028 Item
*weapon
= GetWeaponForAttack( RANGED_ATTACK
);
7029 if(!weapon
|| weapon
->IsBroken() )
7032 ItemPrototype
const* weapon_proto
= weapon
->GetProto();
7033 if(!weapon_proto
|| weapon_proto
->Class
!=ITEM_CLASS_WEAPON
)
7036 // check ammo ws. weapon compatibility
7037 switch(weapon_proto
->SubClass
)
7039 case ITEM_SUBCLASS_WEAPON_BOW
:
7040 case ITEM_SUBCLASS_WEAPON_CROSSBOW
:
7041 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_ARROW
)
7044 case ITEM_SUBCLASS_WEAPON_GUN
:
7045 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_BULLET
)
7055 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7056 Called by remove insignia spell effect */
7057 void Player::RemovedInsignia(Player
* looterPlr
)
7059 if (!GetBattleGroundId())
7062 // If not released spirit, do it !
7063 if(m_deathTimer
> 0)
7070 Corpse
*corpse
= GetCorpse();
7074 // We have to convert player corpse to bones, not to be able to resurrect there
7075 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7076 Corpse
*bones
= ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7080 // Now we must make bones lootable, and send player loot
7081 bones
->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS
, CORPSE_DYNFLAG_LOOTABLE
);
7083 // We store the level of our player in the gold field
7084 // We retrieve this information at Player::SendLoot()
7085 bones
->loot
.gold
= getLevel();
7086 bones
->lootRecipient
= looterPlr
;
7087 looterPlr
->SendLoot(bones
->GetGUID(), LOOT_INSIGNIA
);
7090 void Player::SendLootRelease( uint64 guid
)
7092 WorldPacket
data( SMSG_LOOT_RELEASE_RESPONSE
, (8+1) );
7093 data
<< uint64(guid
) << uint8(1);
7094 SendDirectMessage( &data
);
7097 void Player::SendLoot(uint64 guid
, LootType loot_type
)
7099 if (uint64 lguid
= GetLootGUID())
7100 m_session
->DoLootRelease(lguid
);
7103 PermissionTypes permission
= ALL_PERMISSION
;
7105 sLog
.outDebug("Player::SendLoot");
7106 if (IS_GAMEOBJECT_GUID(guid
))
7108 sLog
.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7109 GameObject
*go
= GetMap()->GetGameObject(guid
);
7111 // not check distance for GO in case owned GO (fishing bobber case, for example)
7112 // And permit out of range GO with no owner in case fishing hole
7113 if (!go
|| (loot_type
!= LOOT_FISHINGHOLE
&& (loot_type
!= LOOT_FISHING
|| go
->GetOwnerGUID() != GetGUID()) && !go
->IsWithinDistInMap(this,INTERACTION_DISTANCE
)))
7115 SendLootRelease(guid
);
7121 if (go
->getLootState() == GO_READY
)
7123 uint32 lootid
= go
->GetLootId();
7127 sLog
.outDebug(" if(lootid)");
7129 loot
->FillLoot(lootid
, LootTemplates_Gameobject
, this, false);
7132 if (loot_type
== LOOT_FISHING
)
7133 go
->getFishLoot(loot
,this);
7135 go
->SetLootState(GO_ACTIVATED
);
7138 else if (IS_ITEM_GUID(guid
))
7140 Item
*item
= GetItemByGuid( guid
);
7144 SendLootRelease(guid
);
7150 if (!item
->m_lootGenerated
)
7152 item
->m_lootGenerated
= true;
7157 case LOOT_DISENCHANTING
:
7158 loot
->FillLoot(item
->GetProto()->DisenchantID
, LootTemplates_Disenchant
, this,true);
7160 case LOOT_PROSPECTING
:
7161 loot
->FillLoot(item
->GetEntry(), LootTemplates_Prospecting
, this,true);
7164 loot
->FillLoot(item
->GetEntry(), LootTemplates_Milling
, this,true);
7167 loot
->FillLoot(item
->GetEntry(), LootTemplates_Item
, this,true);
7168 loot
->generateMoneyLoot(item
->GetProto()->MinMoneyLoot
,item
->GetProto()->MaxMoneyLoot
);
7173 else if (IS_CORPSE_GUID(guid
)) // remove insignia
7175 Corpse
*bones
= ObjectAccessor::GetCorpse(*this, guid
);
7177 if (!bones
|| !((loot_type
== LOOT_CORPSE
) || (loot_type
== LOOT_INSIGNIA
)) || (bones
->GetType() != CORPSE_BONES
) )
7179 SendLootRelease(guid
);
7183 loot
= &bones
->loot
;
7185 if (!bones
->lootForBody
)
7187 bones
->lootForBody
= true;
7188 uint32 pLevel
= bones
->loot
.gold
;
7189 bones
->loot
.clear();
7190 // It may need a better formula
7191 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7192 bones
->loot
.gold
= (uint32
)( urand(50, 150) * 0.016f
* pow( ((float)pLevel
)/5.76f
, 2.5f
) * sWorld
.getRate(RATE_DROP_MONEY
) );
7195 if (bones
->lootRecipient
!= this)
7196 permission
= NONE_PERMISSION
;
7200 Creature
*creature
= GetMap()->GetCreature(guid
);
7202 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7203 if (!creature
|| creature
->isAlive()!=(loot_type
== LOOT_PICKPOCKETING
) || !creature
->IsWithinDistInMap(this,INTERACTION_DISTANCE
))
7205 SendLootRelease(guid
);
7209 if (loot_type
== LOOT_PICKPOCKETING
&& IsFriendlyTo(creature
))
7211 SendLootRelease(guid
);
7215 loot
= &creature
->loot
;
7217 if (loot_type
== LOOT_PICKPOCKETING
)
7219 if (!creature
->lootForPickPocketed
)
7221 creature
->lootForPickPocketed
= true;
7224 if (uint32 lootid
= creature
->GetCreatureInfo()->pickpocketLootId
)
7225 loot
->FillLoot(lootid
, LootTemplates_Pickpocketing
, this, false);
7227 // Generate extra money for pick pocket loot
7228 const uint32 a
= urand(0, creature
->getLevel()/2);
7229 const uint32 b
= urand(0, getLevel()/2);
7230 loot
->gold
= uint32(10 * (a
+ b
) * sWorld
.getRate(RATE_DROP_MONEY
));
7235 // the player whose group may loot the corpse
7236 Player
*recipient
= creature
->GetLootRecipient();
7239 creature
->SetLootRecipient(this);
7243 if (creature
->lootForPickPocketed
)
7245 creature
->lootForPickPocketed
= false;
7249 if (!creature
->lootForBody
)
7251 creature
->lootForBody
= true;
7254 if (uint32 lootid
= creature
->GetCreatureInfo()->lootid
)
7255 loot
->FillLoot(lootid
, LootTemplates_Creature
, recipient
, false);
7257 loot
->generateMoneyLoot(creature
->GetCreatureInfo()->mingold
,creature
->GetCreatureInfo()->maxgold
);
7259 if (Group
* group
= recipient
->GetGroup())
7261 group
->UpdateLooterGuid(creature
,true);
7263 switch (group
->GetLootMethod())
7266 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7267 group
->GroupLoot(recipient
->GetGUID(), loot
, creature
);
7269 case NEED_BEFORE_GREED
:
7270 group
->NeedBeforeGreed(recipient
->GetGUID(), loot
, creature
);
7273 group
->MasterLoot(recipient
->GetGUID(), loot
, creature
);
7281 // possible only if creature->lootForBody && loot->empty() at spell cast check
7282 if (loot_type
== LOOT_SKINNING
)
7285 loot
->FillLoot(creature
->GetCreatureInfo()->SkinLootId
, LootTemplates_Skinning
, this, false);
7287 // set group rights only for loot_type != LOOT_SKINNING
7290 if(Group
* group
= GetGroup())
7292 if (group
== recipient
->GetGroup())
7294 if (group
->GetLootMethod() == FREE_FOR_ALL
)
7295 permission
= ALL_PERMISSION
;
7296 else if (group
->GetLooterGuid() == GetGUID())
7298 if (group
->GetLootMethod() == MASTER_LOOT
)
7299 permission
= MASTER_PERMISSION
;
7301 permission
= ALL_PERMISSION
;
7304 permission
= GROUP_PERMISSION
;
7307 permission
= NONE_PERMISSION
;
7309 else if (recipient
== this)
7310 permission
= ALL_PERMISSION
;
7312 permission
= NONE_PERMISSION
;
7319 // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
7322 case LOOT_INSIGNIA
: loot_type
= LOOT_SKINNING
; break;
7323 case LOOT_FISHINGHOLE
: loot_type
= LOOT_FISHING
; break;
7327 // need know merged fishing/corpse loot type for achievements
7328 loot
->loot_type
= loot_type
;
7330 WorldPacket
data(SMSG_LOOT_RESPONSE
, (9+50)); // we guess size
7332 data
<< uint64(guid
);
7333 data
<< uint8(loot_type
);
7334 data
<< LootView(*loot
, this, permission
);
7336 SendDirectMessage(&data
);
7338 // add 'this' player as one of the players that are looting 'loot'
7339 if (permission
!= NONE_PERMISSION
)
7340 loot
->AddLooter(GetGUID());
7342 if (loot_type
== LOOT_CORPSE
&& !IS_ITEM_GUID(guid
))
7343 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_LOOTING
);
7346 void Player::SendNotifyLootMoneyRemoved()
7348 WorldPacket
data(SMSG_LOOT_CLEAR_MONEY
, 0);
7349 GetSession()->SendPacket( &data
);
7352 void Player::SendNotifyLootItemRemoved(uint8 lootSlot
)
7354 WorldPacket
data(SMSG_LOOT_REMOVED
, 1);
7355 data
<< uint8(lootSlot
);
7356 GetSession()->SendPacket( &data
);
7359 void Player::SendUpdateWorldState(uint32 Field
, uint32 Value
)
7361 WorldPacket
data(SMSG_UPDATE_WORLD_STATE
, 8);
7364 GetSession()->SendPacket(&data
);
7367 void Player::SendInitWorldStates(uint32 zoneid
, uint32 areaid
)
7369 // data depends on zoneid/mapid...
7370 BattleGround
* bg
= GetBattleGround();
7371 uint16 NumberOfFields
= 0;
7372 uint32 mapid
= GetMapId();
7374 sLog
.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid
, zoneid
);
7376 // may be exist better way to do this...
7399 NumberOfFields
= 41;
7402 NumberOfFields
= 15;
7405 NumberOfFields
= 83;
7408 NumberOfFields
= 16;
7412 NumberOfFields
= 40;
7415 NumberOfFields
= 27;
7418 NumberOfFields
= 39;
7421 NumberOfFields
= 38;
7424 NumberOfFields
= 37;
7429 NumberOfFields
= 11;
7432 NumberOfFields
= 11;
7435 NumberOfFields
= 12;
7439 WorldPacket
data(SMSG_INIT_WORLD_STATES
, (4+4+4+2+(NumberOfFields
*8)));
7440 data
<< uint32(mapid
); // mapid
7441 data
<< uint32(zoneid
); // zone id
7442 data
<< uint32(areaid
); // area id, new 2.1.0
7443 data
<< uint16(NumberOfFields
); // count of uint64 blocks
7444 data
<< uint32(0x8d8) << uint32(0x0); // 1
7445 data
<< uint32(0x8d7) << uint32(0x0); // 2
7446 data
<< uint32(0x8d6) << uint32(0x0); // 3
7447 data
<< uint32(0x8d5) << uint32(0x0); // 4
7448 data
<< uint32(0x8d4) << uint32(0x0); // 5
7449 data
<< uint32(0x8d3) << uint32(0x0); // 6
7450 // 7 1 - Arena season in progress, 0 - end of season
7451 data
<< uint32(0xC77) << uint32(sWorld
.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS
));
7452 // 8 Arena season id
7453 data
<< uint32(0xF3D) << uint32(sWorld
.getConfig(CONFIG_ARENA_SEASON_ID
));
7454 if(mapid
== 530) // Outland
7456 data
<< uint32(0x9bf) << uint32(0x0); // 7
7457 data
<< uint32(0x9bd) << uint32(0xF); // 8
7458 data
<< uint32(0x9bb) << uint32(0xF); // 9
7473 data
<< uint32(0x7ae) << uint32(0x1); // 7
7474 data
<< uint32(0x532) << uint32(0x1); // 8
7475 data
<< uint32(0x531) << uint32(0x0); // 9
7476 data
<< uint32(0x52e) << uint32(0x0); // 10
7477 data
<< uint32(0x571) << uint32(0x0); // 11
7478 data
<< uint32(0x570) << uint32(0x0); // 12
7479 data
<< uint32(0x567) << uint32(0x1); // 13
7480 data
<< uint32(0x566) << uint32(0x1); // 14
7481 data
<< uint32(0x550) << uint32(0x1); // 15
7482 data
<< uint32(0x544) << uint32(0x0); // 16
7483 data
<< uint32(0x536) << uint32(0x0); // 17
7484 data
<< uint32(0x535) << uint32(0x1); // 18
7485 data
<< uint32(0x518) << uint32(0x0); // 19
7486 data
<< uint32(0x517) << uint32(0x0); // 20
7487 data
<< uint32(0x574) << uint32(0x0); // 21
7488 data
<< uint32(0x573) << uint32(0x0); // 22
7489 data
<< uint32(0x572) << uint32(0x0); // 23
7490 data
<< uint32(0x56f) << uint32(0x0); // 24
7491 data
<< uint32(0x56e) << uint32(0x0); // 25
7492 data
<< uint32(0x56d) << uint32(0x0); // 26
7493 data
<< uint32(0x56c) << uint32(0x0); // 27
7494 data
<< uint32(0x56b) << uint32(0x0); // 28
7495 data
<< uint32(0x56a) << uint32(0x1); // 29
7496 data
<< uint32(0x569) << uint32(0x1); // 30
7497 data
<< uint32(0x568) << uint32(0x1); // 13
7498 data
<< uint32(0x565) << uint32(0x0); // 32
7499 data
<< uint32(0x564) << uint32(0x0); // 33
7500 data
<< uint32(0x563) << uint32(0x0); // 34
7501 data
<< uint32(0x562) << uint32(0x0); // 35
7502 data
<< uint32(0x561) << uint32(0x0); // 36
7503 data
<< uint32(0x560) << uint32(0x0); // 37
7504 data
<< uint32(0x55f) << uint32(0x0); // 38
7505 data
<< uint32(0x55e) << uint32(0x0); // 39
7506 data
<< uint32(0x55d) << uint32(0x0); // 40
7507 data
<< uint32(0x3c6) << uint32(0x4); // 41
7508 data
<< uint32(0x3c4) << uint32(0x6); // 42
7509 data
<< uint32(0x3c2) << uint32(0x4); // 43
7510 data
<< uint32(0x516) << uint32(0x1); // 44
7511 data
<< uint32(0x515) << uint32(0x0); // 45
7512 data
<< uint32(0x3b6) << uint32(0x6); // 46
7513 data
<< uint32(0x55c) << uint32(0x0); // 47
7514 data
<< uint32(0x55b) << uint32(0x0); // 48
7515 data
<< uint32(0x55a) << uint32(0x0); // 49
7516 data
<< uint32(0x559) << uint32(0x0); // 50
7517 data
<< uint32(0x558) << uint32(0x0); // 51
7518 data
<< uint32(0x557) << uint32(0x0); // 52
7519 data
<< uint32(0x556) << uint32(0x0); // 53
7520 data
<< uint32(0x555) << uint32(0x0); // 54
7521 data
<< uint32(0x554) << uint32(0x1); // 55
7522 data
<< uint32(0x553) << uint32(0x1); // 56
7523 data
<< uint32(0x552) << uint32(0x1); // 57
7524 data
<< uint32(0x551) << uint32(0x1); // 58
7525 data
<< uint32(0x54f) << uint32(0x0); // 59
7526 data
<< uint32(0x54e) << uint32(0x0); // 60
7527 data
<< uint32(0x54d) << uint32(0x1); // 61
7528 data
<< uint32(0x54c) << uint32(0x0); // 62
7529 data
<< uint32(0x54b) << uint32(0x0); // 63
7530 data
<< uint32(0x545) << uint32(0x0); // 64
7531 data
<< uint32(0x543) << uint32(0x1); // 65
7532 data
<< uint32(0x542) << uint32(0x0); // 66
7533 data
<< uint32(0x540) << uint32(0x0); // 67
7534 data
<< uint32(0x53f) << uint32(0x0); // 68
7535 data
<< uint32(0x53e) << uint32(0x0); // 69
7536 data
<< uint32(0x53d) << uint32(0x0); // 70
7537 data
<< uint32(0x53c) << uint32(0x0); // 71
7538 data
<< uint32(0x53b) << uint32(0x0); // 72
7539 data
<< uint32(0x53a) << uint32(0x1); // 73
7540 data
<< uint32(0x539) << uint32(0x0); // 74
7541 data
<< uint32(0x538) << uint32(0x0); // 75
7542 data
<< uint32(0x537) << uint32(0x0); // 76
7543 data
<< uint32(0x534) << uint32(0x0); // 77
7544 data
<< uint32(0x533) << uint32(0x0); // 78
7545 data
<< uint32(0x530) << uint32(0x0); // 79
7546 data
<< uint32(0x52f) << uint32(0x0); // 80
7547 data
<< uint32(0x52d) << uint32(0x1); // 81
7550 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_WS
)
7551 bg
->FillInitialWorldStates(data
);
7554 data
<< uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7555 data
<< uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7556 data
<< uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7557 data
<< uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7558 data
<< uint32(0x60b) << uint32(0x2); // 11 1547 unk
7559 data
<< uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7560 data
<< uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7561 data
<< uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7565 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_AB
)
7566 bg
->FillInitialWorldStates(data
);
7569 data
<< uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7570 data
<< uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7571 data
<< uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7572 data
<< uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7573 data
<< uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7574 data
<< uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7575 data
<< uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7576 data
<< uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7577 data
<< uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7578 data
<< uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7579 data
<< uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7580 data
<< uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7581 data
<< uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7582 data
<< uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7583 data
<< uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7584 data
<< uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7585 data
<< uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7586 data
<< uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7587 data
<< uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7588 data
<< uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7589 data
<< uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7590 data
<< uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7591 data
<< uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7592 data
<< uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7593 data
<< uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7594 data
<< uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7595 data
<< uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7596 data
<< uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7597 data
<< uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7598 data
<< uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7599 data
<< uint32(0x745) << uint32(0x2); // 37 1861 unk
7600 data
<< uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7604 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_EY
)
7605 bg
->FillInitialWorldStates(data
);
7608 data
<< uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7609 data
<< uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7610 data
<< uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7611 data
<< uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7612 data
<< uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7613 data
<< uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7614 data
<< uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7615 data
<< uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7616 data
<< uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7617 data
<< uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7618 data
<< uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7619 data
<< uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7620 data
<< uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7621 data
<< uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7622 data
<< uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7623 data
<< uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7624 data
<< uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7625 data
<< uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7626 data
<< uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7627 data
<< uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7628 data
<< uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7629 data
<< uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7630 data
<< uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7631 data
<< uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7632 data
<< uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7633 data
<< uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7634 data
<< uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7635 data
<< uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7636 data
<< uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7637 data
<< uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7638 data
<< uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7639 data
<< uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7640 // and some more ... unknown
7643 case 3483: // Hellfire Peninsula
7644 data
<< uint32(0x9ba) << uint32(0x1); // 10
7645 data
<< uint32(0x9b9) << uint32(0x1); // 11
7646 data
<< uint32(0x9b5) << uint32(0x0); // 12
7647 data
<< uint32(0x9b4) << uint32(0x1); // 13
7648 data
<< uint32(0x9b3) << uint32(0x0); // 14
7649 data
<< uint32(0x9b2) << uint32(0x0); // 15
7650 data
<< uint32(0x9b1) << uint32(0x1); // 16
7651 data
<< uint32(0x9b0) << uint32(0x0); // 17
7652 data
<< uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7653 data
<< uint32(0x9ac) << uint32(0x0); // 19
7654 data
<< uint32(0x9a8) << uint32(0x0); // 20
7655 data
<< uint32(0x9a7) << uint32(0x0); // 21
7656 data
<< uint32(0x9a6) << uint32(0x1); // 22
7658 case 3519: // Terokkar Forest
7659 data
<< uint32(0xa41) << uint32(0x0); // 10
7660 data
<< uint32(0xa40) << uint32(0x14); // 11
7661 data
<< uint32(0xa3f) << uint32(0x0); // 12
7662 data
<< uint32(0xa3e) << uint32(0x0); // 13
7663 data
<< uint32(0xa3d) << uint32(0x5); // 14
7664 data
<< uint32(0xa3c) << uint32(0x0); // 15
7665 data
<< uint32(0xa87) << uint32(0x0); // 16
7666 data
<< uint32(0xa86) << uint32(0x0); // 17
7667 data
<< uint32(0xa85) << uint32(0x0); // 18
7668 data
<< uint32(0xa84) << uint32(0x0); // 19
7669 data
<< uint32(0xa83) << uint32(0x0); // 20
7670 data
<< uint32(0xa82) << uint32(0x0); // 21
7671 data
<< uint32(0xa81) << uint32(0x0); // 22
7672 data
<< uint32(0xa80) << uint32(0x0); // 23
7673 data
<< uint32(0xa7e) << uint32(0x0); // 24
7674 data
<< uint32(0xa7d) << uint32(0x0); // 25
7675 data
<< uint32(0xa7c) << uint32(0x0); // 26
7676 data
<< uint32(0xa7b) << uint32(0x0); // 27
7677 data
<< uint32(0xa7a) << uint32(0x0); // 28
7678 data
<< uint32(0xa79) << uint32(0x0); // 29
7679 data
<< uint32(0x9d0) << uint32(0x5); // 30
7680 data
<< uint32(0x9ce) << uint32(0x0); // 31
7681 data
<< uint32(0x9cd) << uint32(0x0); // 32
7682 data
<< uint32(0x9cc) << uint32(0x0); // 33
7683 data
<< uint32(0xa88) << uint32(0x0); // 34
7684 data
<< uint32(0xad0) << uint32(0x0); // 35
7685 data
<< uint32(0xacf) << uint32(0x1); // 36
7687 case 3521: // Zangarmarsh
7688 data
<< uint32(0x9e1) << uint32(0x0); // 10
7689 data
<< uint32(0x9e0) << uint32(0x0); // 11
7690 data
<< uint32(0x9df) << uint32(0x0); // 12
7691 data
<< uint32(0xa5d) << uint32(0x1); // 13
7692 data
<< uint32(0xa5c) << uint32(0x0); // 14
7693 data
<< uint32(0xa5b) << uint32(0x1); // 15
7694 data
<< uint32(0xa5a) << uint32(0x0); // 16
7695 data
<< uint32(0xa59) << uint32(0x1); // 17
7696 data
<< uint32(0xa58) << uint32(0x0); // 18
7697 data
<< uint32(0xa57) << uint32(0x0); // 19
7698 data
<< uint32(0xa56) << uint32(0x0); // 20
7699 data
<< uint32(0xa55) << uint32(0x1); // 21
7700 data
<< uint32(0xa54) << uint32(0x0); // 22
7701 data
<< uint32(0x9e7) << uint32(0x0); // 23
7702 data
<< uint32(0x9e6) << uint32(0x0); // 24
7703 data
<< uint32(0x9e5) << uint32(0x0); // 25
7704 data
<< uint32(0xa00) << uint32(0x0); // 26
7705 data
<< uint32(0x9ff) << uint32(0x1); // 27
7706 data
<< uint32(0x9fe) << uint32(0x0); // 28
7707 data
<< uint32(0x9fd) << uint32(0x0); // 29
7708 data
<< uint32(0x9fc) << uint32(0x1); // 30
7709 data
<< uint32(0x9fb) << uint32(0x0); // 31
7710 data
<< uint32(0xa62) << uint32(0x0); // 32
7711 data
<< uint32(0xa61) << uint32(0x1); // 33
7712 data
<< uint32(0xa60) << uint32(0x1); // 34
7713 data
<< uint32(0xa5f) << uint32(0x0); // 35
7715 case 3698: // Nagrand Arena
7716 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_NA
)
7717 bg
->FillInitialWorldStates(data
);
7720 data
<< uint32(0xa0f) << uint32(0x0); // 7
7721 data
<< uint32(0xa10) << uint32(0x0); // 8
7722 data
<< uint32(0xa11) << uint32(0x0); // 9 show
7725 case 3702: // Blade's Edge Arena
7726 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_BE
)
7727 bg
->FillInitialWorldStates(data
);
7730 data
<< uint32(0x9f0) << uint32(0x0); // 7 gold
7731 data
<< uint32(0x9f1) << uint32(0x0); // 8 green
7732 data
<< uint32(0x9f3) << uint32(0x0); // 9 show
7735 case 3968: // Ruins of Lordaeron
7736 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_RL
)
7737 bg
->FillInitialWorldStates(data
);
7740 data
<< uint32(0xbb8) << uint32(0x0); // 7 gold
7741 data
<< uint32(0xbb9) << uint32(0x0); // 8 green
7742 data
<< uint32(0xbba) << uint32(0x0); // 9 show
7745 case 3703: // Shattrath City
7748 data
<< uint32(0x914) << uint32(0x0); // 7
7749 data
<< uint32(0x913) << uint32(0x0); // 8
7750 data
<< uint32(0x912) << uint32(0x0); // 9
7751 data
<< uint32(0x915) << uint32(0x0); // 10
7754 GetSession()->SendPacket(&data
);
7757 uint32
Player::GetXPRestBonus(uint32 xp
)
7759 uint32 rested_bonus
= (uint32
)GetRestBonus(); // xp for each rested bonus
7761 if(rested_bonus
> xp
) // max rested_bonus == xp or (r+x) = 200% xp
7764 SetRestBonus( GetRestBonus() - rested_bonus
);
7766 sLog
.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp
+rested_bonus
,rested_bonus
,GetRestBonus());
7767 return rested_bonus
;
7770 void Player::SetBindPoint(uint64 guid
)
7772 WorldPacket
data(SMSG_BINDER_CONFIRM
, 8);
7773 data
<< uint64(guid
);
7774 GetSession()->SendPacket( &data
);
7777 void Player::SendTalentWipeConfirm(uint64 guid
)
7779 WorldPacket
data(MSG_TALENT_WIPE_CONFIRM
, (8+4));
7780 data
<< uint64(guid
);
7781 data
<< uint32(resetTalentsCost());
7782 GetSession()->SendPacket( &data
);
7785 void Player::SendPetSkillWipeConfirm()
7787 Pet
* pet
= GetPet();
7790 WorldPacket
data(SMSG_PET_UNLEARN_CONFIRM
, (8+4));
7791 data
<< pet
->GetGUID();
7792 data
<< uint32(pet
->resetTalentsCost());
7793 GetSession()->SendPacket( &data
);
7796 /*********************************************************/
7797 /*** STORAGE SYSTEM ***/
7798 /*********************************************************/
7800 void Player::SetVirtualItemSlot( uint8 i
, Item
* item
)
7805 if(!item
->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT
))
7807 uint32 charges
= item
->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
);
7811 item
->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
,charges
-1);
7812 else if(charges
<= 1)
7814 ApplyEnchantment(item
,TEMP_ENCHANTMENT_SLOT
,false);
7815 item
->ClearEnchantment(TEMP_ENCHANTMENT_SLOT
);
7820 void Player::SetSheath( uint32 sheathed
)
7824 case SHEATH_STATE_UNARMED
: // no prepared weapon
7825 SetVirtualItemSlot(0,NULL
);
7826 SetVirtualItemSlot(1,NULL
);
7827 SetVirtualItemSlot(2,NULL
);
7829 case SHEATH_STATE_MELEE
: // prepared melee weapon
7831 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK
,true));
7832 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK
,true));
7833 SetVirtualItemSlot(2,NULL
);
7835 case SHEATH_STATE_RANGED
: // prepared ranged weapon
7836 SetVirtualItemSlot(0,NULL
);
7837 SetVirtualItemSlot(1,NULL
);
7838 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK
,true));
7841 SetVirtualItemSlot(0,NULL
);
7842 SetVirtualItemSlot(1,NULL
);
7843 SetVirtualItemSlot(2,NULL
);
7846 SetByteValue(UNIT_FIELD_BYTES_2
, 0, sheathed
); // this must visualize Sheath changing for other players...
7849 uint8
Player::FindEquipSlot( ItemPrototype
const* proto
, uint32 slot
, bool swap
) const
7851 uint8 pClass
= getClass();
7854 slots
[0] = NULL_SLOT
;
7855 slots
[1] = NULL_SLOT
;
7856 slots
[2] = NULL_SLOT
;
7857 slots
[3] = NULL_SLOT
;
7858 switch( proto
->InventoryType
)
7861 slots
[0] = EQUIPMENT_SLOT_HEAD
;
7864 slots
[0] = EQUIPMENT_SLOT_NECK
;
7866 case INVTYPE_SHOULDERS
:
7867 slots
[0] = EQUIPMENT_SLOT_SHOULDERS
;
7870 slots
[0] = EQUIPMENT_SLOT_BODY
;
7873 slots
[0] = EQUIPMENT_SLOT_CHEST
;
7876 slots
[0] = EQUIPMENT_SLOT_CHEST
;
7879 slots
[0] = EQUIPMENT_SLOT_WAIST
;
7882 slots
[0] = EQUIPMENT_SLOT_LEGS
;
7885 slots
[0] = EQUIPMENT_SLOT_FEET
;
7887 case INVTYPE_WRISTS
:
7888 slots
[0] = EQUIPMENT_SLOT_WRISTS
;
7891 slots
[0] = EQUIPMENT_SLOT_HANDS
;
7893 case INVTYPE_FINGER
:
7894 slots
[0] = EQUIPMENT_SLOT_FINGER1
;
7895 slots
[1] = EQUIPMENT_SLOT_FINGER2
;
7897 case INVTYPE_TRINKET
:
7898 slots
[0] = EQUIPMENT_SLOT_TRINKET1
;
7899 slots
[1] = EQUIPMENT_SLOT_TRINKET2
;
7902 slots
[0] = EQUIPMENT_SLOT_BACK
;
7904 case INVTYPE_WEAPON
:
7906 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
7908 // suggest offhand slot only if know dual wielding
7909 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
7911 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
7914 case INVTYPE_SHIELD
:
7915 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
7917 case INVTYPE_RANGED
:
7918 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7920 case INVTYPE_2HWEAPON
:
7921 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
7922 if (CanDualWield() && CanTitanGrip())
7923 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
7925 case INVTYPE_TABARD
:
7926 slots
[0] = EQUIPMENT_SLOT_TABARD
;
7928 case INVTYPE_WEAPONMAINHAND
:
7929 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
7931 case INVTYPE_WEAPONOFFHAND
:
7932 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
7934 case INVTYPE_HOLDABLE
:
7935 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
7937 case INVTYPE_THROWN
:
7938 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7940 case INVTYPE_RANGEDRIGHT
:
7941 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7944 slots
[0] = INVENTORY_SLOT_BAG_START
+ 0;
7945 slots
[1] = INVENTORY_SLOT_BAG_START
+ 1;
7946 slots
[2] = INVENTORY_SLOT_BAG_START
+ 2;
7947 slots
[3] = INVENTORY_SLOT_BAG_START
+ 3;
7951 switch(proto
->SubClass
)
7953 case ITEM_SUBCLASS_ARMOR_LIBRAM
:
7954 if (pClass
== CLASS_PALADIN
)
7955 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7957 case ITEM_SUBCLASS_ARMOR_IDOL
:
7958 if (pClass
== CLASS_DRUID
)
7959 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7961 case ITEM_SUBCLASS_ARMOR_TOTEM
:
7962 if (pClass
== CLASS_SHAMAN
)
7963 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7965 case ITEM_SUBCLASS_ARMOR_MISC
:
7966 if (pClass
== CLASS_WARLOCK
)
7967 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7969 case ITEM_SUBCLASS_ARMOR_SIGIL
:
7970 if (pClass
== CLASS_DEATH_KNIGHT
)
7971 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7980 if( slot
!= NULL_SLOT
)
7982 if( swap
|| !GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
) )
7984 for (int i
= 0; i
< 4; ++i
)
7986 if ( slots
[i
] == slot
)
7993 // search free slot at first
7994 for (int i
= 0; i
< 4; ++i
)
7996 if ( slots
[i
] != NULL_SLOT
&& !GetItemByPos( INVENTORY_SLOT_BAG_0
, slots
[i
] ) )
7998 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
7999 if(slots
[i
]!=EQUIPMENT_SLOT_OFFHAND
|| !IsTwoHandUsed())
8004 // if not found free and can swap return first appropriate from used
8005 for (int i
= 0; i
< 4; ++i
)
8007 if ( slots
[i
] != NULL_SLOT
&& swap
)
8016 uint8
Player::CanUnequipItems( uint32 item
, uint32 count
) const
8019 uint32 tempcount
= 0;
8021 uint8 res
= EQUIP_ERR_OK
;
8023 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8025 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8026 if( pItem
&& pItem
->GetEntry() == item
)
8028 uint8 ires
= CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
, false);
8029 if(ires
==EQUIP_ERR_OK
)
8031 tempcount
+= pItem
->GetCount();
8032 if( tempcount
>= count
)
8033 return EQUIP_ERR_OK
;
8039 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8041 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8042 if( pItem
&& pItem
->GetEntry() == item
)
8044 tempcount
+= pItem
->GetCount();
8045 if( tempcount
>= count
)
8046 return EQUIP_ERR_OK
;
8049 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
8051 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8052 if( pItem
&& pItem
->GetEntry() == item
)
8054 tempcount
+= pItem
->GetCount();
8055 if( tempcount
>= count
)
8056 return EQUIP_ERR_OK
;
8060 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8062 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8065 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8067 pItem
= GetItemByPos( i
, j
);
8068 if( pItem
&& pItem
->GetEntry() == item
)
8070 tempcount
+= pItem
->GetCount();
8071 if( tempcount
>= count
)
8072 return EQUIP_ERR_OK
;
8078 // not found req. item count and have unequippable items
8082 uint32
Player::GetItemCount( uint32 item
, bool inBankAlso
, Item
* skipItem
) const
8085 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8087 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8088 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8089 count
+= pItem
->GetCount();
8091 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
8093 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8094 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8095 count
+= pItem
->GetCount();
8097 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8099 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8101 count
+= pBag
->GetItemCount(item
,skipItem
);
8104 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8106 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8108 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8109 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8110 count
+= pItem
->GetGemCountWithID(item
);
8116 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; ++i
)
8118 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8119 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8120 count
+= pItem
->GetCount();
8122 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
8124 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8126 count
+= pBag
->GetItemCount(item
,skipItem
);
8129 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8131 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; ++i
)
8133 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8134 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8135 count
+= pItem
->GetGemCountWithID(item
);
8143 Item
* Player::GetItemByGuid( uint64 guid
) const
8145 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8147 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8148 if( pItem
&& pItem
->GetGUID() == guid
)
8151 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
8153 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8154 if( pItem
&& pItem
->GetGUID() == guid
)
8158 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8160 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8163 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8165 Item
* pItem
= pBag
->GetItemByPos( j
);
8166 if( pItem
&& pItem
->GetGUID() == guid
)
8171 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
8173 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8176 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8178 Item
* pItem
= pBag
->GetItemByPos( j
);
8179 if( pItem
&& pItem
->GetGUID() == guid
)
8188 Item
* Player::GetItemByPos( uint16 pos
) const
8190 uint8 bag
= pos
>> 8;
8191 uint8 slot
= pos
& 255;
8192 return GetItemByPos( bag
, slot
);
8195 Item
* Player::GetItemByPos( uint8 bag
, uint8 slot
) const
8197 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< BANK_SLOT_BAG_END
|| slot
>= KEYRING_SLOT_START
&& slot
< QUESTBAG_SLOT_END
) )
8198 return m_items
[slot
];
8199 else if(bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
8200 || bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8202 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8204 return pBag
->GetItemByPos(slot
);
8209 Item
* Player::GetWeaponForAttack(WeaponAttackType attackType
, bool useable
) const
8214 case BASE_ATTACK
: slot
= EQUIPMENT_SLOT_MAINHAND
; break;
8215 case OFF_ATTACK
: slot
= EQUIPMENT_SLOT_OFFHAND
; break;
8216 case RANGED_ATTACK
: slot
= EQUIPMENT_SLOT_RANGED
; break;
8217 default: return NULL
;
8220 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, slot
);
8221 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_WEAPON
)
8227 if( item
->IsBroken() || !IsUseEquipedWeapon(attackType
==BASE_ATTACK
) )
8233 Item
* Player::GetShield(bool useable
) const
8235 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
8236 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_ARMOR
)
8242 if( item
->IsBroken())
8248 uint32
Player::GetAttackBySlot( uint8 slot
)
8252 case EQUIPMENT_SLOT_MAINHAND
: return BASE_ATTACK
;
8253 case EQUIPMENT_SLOT_OFFHAND
: return OFF_ATTACK
;
8254 case EQUIPMENT_SLOT_RANGED
: return RANGED_ATTACK
;
8255 default: return MAX_ATTACK
;
8259 bool Player::HasBankBagSlot( uint8 slot
) const
8261 uint32 maxslot
= GetByteValue(PLAYER_BYTES_2
, 2) + BANK_SLOT_BAG_START
;
8262 if( slot
< maxslot
)
8267 bool Player::IsInventoryPos( uint8 bag
, uint8 slot
)
8269 if( bag
== INVENTORY_SLOT_BAG_0
&& slot
== NULL_SLOT
)
8271 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
) )
8273 if( bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8275 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= KEYRING_SLOT_START
&& slot
< QUESTBAG_SLOT_END
) )
8280 bool Player::IsEquipmentPos( uint8 bag
, uint8 slot
)
8282 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< EQUIPMENT_SLOT_END
) )
8284 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8289 bool Player::IsBankPos( uint8 bag
, uint8 slot
)
8291 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
) )
8293 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8295 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8300 bool Player::IsBagPos( uint16 pos
)
8302 uint8 bag
= pos
>> 8;
8303 uint8 slot
= pos
& 255;
8304 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8306 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8311 bool Player::IsValidPos( uint8 bag
, uint8 slot
)
8317 if (bag
== INVENTORY_SLOT_BAG_0
)
8319 // any post selected
8320 if (slot
== NULL_SLOT
)
8324 if (slot
< EQUIPMENT_SLOT_END
)
8328 if (slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
)
8332 if (slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
)
8336 if (slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_END
)
8340 if (slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
)
8344 if (slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
8350 // bag content slots
8351 if (bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8353 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8357 // any post selected
8358 if (slot
== NULL_SLOT
)
8361 return slot
< pBag
->GetBagSize();
8364 // bank bag content slots
8365 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8367 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8371 // any post selected
8372 if (slot
== NULL_SLOT
)
8375 return slot
< pBag
->GetBagSize();
8383 bool Player::HasItemCount( uint32 item
, uint32 count
, bool inBankAlso
) const
8385 uint32 tempcount
= 0;
8386 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8388 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8389 if( pItem
&& pItem
->GetEntry() == item
)
8391 tempcount
+= pItem
->GetCount();
8392 if( tempcount
>= count
)
8396 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
8398 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8399 if( pItem
&& pItem
->GetEntry() == item
)
8401 tempcount
+= pItem
->GetCount();
8402 if( tempcount
>= count
)
8406 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8408 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8410 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8412 Item
* pItem
= GetItemByPos( i
, j
);
8413 if( pItem
&& pItem
->GetEntry() == item
)
8415 tempcount
+= pItem
->GetCount();
8416 if( tempcount
>= count
)
8425 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; ++i
)
8427 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8428 if( pItem
&& pItem
->GetEntry() == item
)
8430 tempcount
+= pItem
->GetCount();
8431 if( tempcount
>= count
)
8435 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
8437 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8439 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8441 Item
* pItem
= GetItemByPos( i
, j
);
8442 if( pItem
&& pItem
->GetEntry() == item
)
8444 tempcount
+= pItem
->GetCount();
8445 if( tempcount
>= count
)
8456 bool Player::HasItemOrGemWithIdEquipped( uint32 item
, uint32 count
, uint8 except_slot
) const
8458 uint32 tempcount
= 0;
8459 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
8461 if(i
==int(except_slot
))
8464 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8465 if( pItem
&& pItem
->GetEntry() == item
)
8467 tempcount
+= pItem
->GetCount();
8468 if( tempcount
>= count
)
8473 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(item
);
8474 if (pProto
&& pProto
->GemProperties
)
8476 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
8478 if(i
==int(except_slot
))
8481 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8482 if( pItem
&& pItem
->GetProto()->Socket
[0].Color
)
8484 tempcount
+= pItem
->GetGemCountWithID(item
);
8485 if( tempcount
>= count
)
8494 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory
, uint32 count
, uint8 except_slot
) const
8496 uint32 tempcount
= 0;
8497 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
8499 if(i
==int(except_slot
))
8502 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8506 ItemPrototype
const *pProto
= pItem
->GetProto();
8510 if (pProto
->ItemLimitCategory
== limitCategory
)
8512 tempcount
+= pItem
->GetCount();
8513 if( tempcount
>= count
)
8517 if( pProto
->Socket
[0].Color
)
8519 tempcount
+= pItem
->GetGemCountWithLimitCategory(limitCategory
);
8520 if( tempcount
>= count
)
8528 uint8
Player::_CanTakeMoreSimilarItems(uint32 entry
, uint32 count
, Item
* pItem
, uint32
* no_space_count
) const
8530 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
8534 *no_space_count
= count
;
8535 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8539 if(pProto
->MaxCount
<= 0)
8540 return EQUIP_ERR_OK
;
8542 uint32 curcount
= GetItemCount(pProto
->ItemId
,true,pItem
);
8544 if (curcount
+ count
> uint32(pProto
->MaxCount
))
8547 *no_space_count
= count
+curcount
- pProto
->MaxCount
;
8548 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8551 return EQUIP_ERR_OK
;
8554 bool Player::HasItemTotemCategory( uint32 TotemCategory
) const
8557 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8559 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8560 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8563 for(uint8 i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
8565 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8566 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8569 for(uint8 i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8571 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8573 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8575 pItem
= GetItemByPos( i
, j
);
8576 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8584 uint8
Player::_CanStoreItem_InSpecificSlot( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, ItemPrototype
const *pProto
, uint32
& count
, bool swap
, Item
* pSrcItem
) const
8586 Item
* pItem2
= GetItemByPos( bag
, slot
);
8588 // ignore move item (this slot will be empty at move)
8589 if(pItem2
==pSrcItem
)
8594 // empty specific slot - check item fit to slot
8595 if( !pItem2
|| swap
)
8597 if( bag
== INVENTORY_SLOT_BAG_0
)
8600 if(slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_START
+GetMaxKeyringSize() && !(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
))
8601 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8603 // vanitypet case (not use, vanity pets stored as spells)
8604 if(slot
>= VANITYPET_SLOT_START
&& slot
< VANITYPET_SLOT_END
)
8605 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8607 // currencytoken case (disabled until proper implement)
8608 if(slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
&& !(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
))
8609 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8611 // guestbag case (not use)
8612 if(slot
>= QUESTBAG_SLOT_START
&& slot
< QUESTBAG_SLOT_END
)
8613 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8616 if(slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
|| slot
>= PLAYER_SLOT_END
)
8617 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8621 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8623 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8625 ItemPrototype
const* pBagProto
= pBag
->GetProto();
8627 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8629 if( !ItemCanGoIntoBag(pProto
,pBagProto
) )
8630 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8633 // non empty stack with space
8634 need_space
= pProto
->GetMaxStackSize();
8636 // non empty slot, check item type
8640 if(pItem2
->GetEntry() != pProto
->ItemId
)
8641 return EQUIP_ERR_ITEM_CANT_STACK
;
8644 if(pItem2
->GetCount() >= pProto
->GetMaxStackSize())
8645 return EQUIP_ERR_ITEM_CANT_STACK
;
8647 // free stack space or infinity
8648 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
8651 if(need_space
> count
)
8654 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | slot
, need_space
);
8655 if(!newPosition
.isContainedIn(dest
))
8657 dest
.push_back(newPosition
);
8658 count
-= need_space
;
8660 return EQUIP_ERR_OK
;
8663 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
8665 // skip specific bag already processed in first called _CanStoreItem_InBag
8667 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8669 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8671 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8673 ItemPrototype
const* pBagProto
= pBag
->GetProto();
8675 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8677 // specialized bag mode or non-specilized
8678 if( non_specialized
!= (pBagProto
->Class
== ITEM_CLASS_CONTAINER
&& pBagProto
->SubClass
== ITEM_SUBCLASS_CONTAINER
) )
8679 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8681 if( !ItemCanGoIntoBag(pProto
,pBagProto
) )
8682 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8684 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8686 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8690 Item
* pItem2
= GetItemByPos( bag
, j
);
8692 // ignore move item (this slot will be empty at move)
8693 if(pItem2
==pSrcItem
)
8696 // if merge skip empty, if !merge skip non-empty
8697 if((pItem2
!=NULL
)!=merge
)
8702 if(pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->GetMaxStackSize())
8704 uint32 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
8705 if(need_space
> count
)
8708 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
8709 if(!newPosition
.isContainedIn(dest
))
8711 dest
.push_back(newPosition
);
8712 count
-= need_space
;
8715 return EQUIP_ERR_OK
;
8721 uint32 need_space
= pProto
->GetMaxStackSize();
8722 if(need_space
> count
)
8725 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
8726 if(!newPosition
.isContainedIn(dest
))
8728 dest
.push_back(newPosition
);
8729 count
-= need_space
;
8732 return EQUIP_ERR_OK
;
8736 return EQUIP_ERR_OK
;
8739 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
8741 for(uint32 j
= slot_begin
; j
< slot_end
; ++j
)
8743 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8744 if(INVENTORY_SLOT_BAG_0
==skip_bag
&& j
==skip_slot
)
8747 Item
* pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, j
);
8749 // ignore move item (this slot will be empty at move)
8750 if(pItem2
==pSrcItem
)
8753 // if merge skip empty, if !merge skip non-empty
8754 if((pItem2
!=NULL
)!=merge
)
8759 if(pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->GetMaxStackSize())
8761 uint32 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
8762 if(need_space
> count
)
8764 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
8765 if(!newPosition
.isContainedIn(dest
))
8767 dest
.push_back(newPosition
);
8768 count
-= need_space
;
8771 return EQUIP_ERR_OK
;
8777 uint32 need_space
= pProto
->GetMaxStackSize();
8778 if(need_space
> count
)
8781 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
8782 if(!newPosition
.isContainedIn(dest
))
8784 dest
.push_back(newPosition
);
8785 count
-= need_space
;
8788 return EQUIP_ERR_OK
;
8792 return EQUIP_ERR_OK
;
8795 uint8
Player::_CanStoreItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, uint32 entry
, uint32 count
, Item
*pItem
, bool swap
, uint32
* no_space_count
) const
8797 sLog
.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, entry
, count
);
8799 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
8803 *no_space_count
= count
;
8804 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
:EQUIP_ERR_ITEM_NOT_FOUND
;
8807 if(pItem
&& pItem
->IsBindedNotWith(GetGUID()))
8810 *no_space_count
= count
;
8811 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
8814 // check count of items (skip for auto move for same player from bank)
8815 uint32 no_similar_count
= 0; // can't store this amount similar items
8816 uint8 res
= _CanTakeMoreSimilarItems(entry
,count
,pItem
,&no_similar_count
);
8817 if(res
!=EQUIP_ERR_OK
)
8819 if(count
==no_similar_count
)
8822 *no_space_count
= no_similar_count
;
8825 count
-= no_similar_count
;
8829 if( bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
8831 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
8832 if(res
!=EQUIP_ERR_OK
)
8835 *no_space_count
= count
+ no_similar_count
;
8841 if(no_similar_count
==0)
8842 return EQUIP_ERR_OK
;
8845 *no_space_count
= count
+ no_similar_count
;
8846 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8850 // not specific slot or have space for partly store only in specific slot
8853 if( bag
!= NULL_BAG
)
8855 // search stack in bag for merge to
8856 if( pProto
->Stackable
!= 1 )
8858 if( bag
== INVENTORY_SLOT_BAG_0
) // inventory
8860 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,QUESTBAG_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
8861 if(res
!=EQUIP_ERR_OK
)
8864 *no_space_count
= count
+ no_similar_count
;
8870 if(no_similar_count
==0)
8871 return EQUIP_ERR_OK
;
8874 *no_space_count
= count
+ no_similar_count
;
8875 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8878 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
8879 if(res
!=EQUIP_ERR_OK
)
8882 *no_space_count
= count
+ no_similar_count
;
8888 if(no_similar_count
==0)
8889 return EQUIP_ERR_OK
;
8892 *no_space_count
= count
+ no_similar_count
;
8893 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8896 else // equipped bag
8898 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
8899 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
8900 if(res
!=EQUIP_ERR_OK
)
8901 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
8903 if(res
!=EQUIP_ERR_OK
)
8906 *no_space_count
= count
+ no_similar_count
;
8912 if(no_similar_count
==0)
8913 return EQUIP_ERR_OK
;
8916 *no_space_count
= count
+ no_similar_count
;
8917 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8922 // search free slot in bag for place to
8923 if( bag
== INVENTORY_SLOT_BAG_0
) // inventory
8925 // search free slot - keyring case
8926 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
8928 uint32 keyringSize
= GetMaxKeyringSize();
8929 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
8930 if(res
!=EQUIP_ERR_OK
)
8933 *no_space_count
= count
+ no_similar_count
;
8939 if(no_similar_count
==0)
8940 return EQUIP_ERR_OK
;
8943 *no_space_count
= count
+ no_similar_count
;
8944 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8947 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
8948 if(res
!=EQUIP_ERR_OK
)
8951 *no_space_count
= count
+ no_similar_count
;
8957 if(no_similar_count
==0)
8958 return EQUIP_ERR_OK
;
8961 *no_space_count
= count
+ no_similar_count
;
8962 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8965 else if(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
8967 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
8968 if(res
!=EQUIP_ERR_OK
)
8971 *no_space_count
= count
+ no_similar_count
;
8977 if(no_similar_count
==0)
8978 return EQUIP_ERR_OK
;
8981 *no_space_count
= count
+ no_similar_count
;
8982 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8986 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
8987 if(res
!=EQUIP_ERR_OK
)
8990 *no_space_count
= count
+ no_similar_count
;
8996 if(no_similar_count
==0)
8997 return EQUIP_ERR_OK
;
9000 *no_space_count
= count
+ no_similar_count
;
9001 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9004 else // equipped bag
9006 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
9007 if(res
!=EQUIP_ERR_OK
)
9008 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
9010 if(res
!=EQUIP_ERR_OK
)
9013 *no_space_count
= count
+ no_similar_count
;
9019 if(no_similar_count
==0)
9020 return EQUIP_ERR_OK
;
9023 *no_space_count
= count
+ no_similar_count
;
9024 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9029 // not specific bag or have space for partly store only in specific bag
9031 // search stack for merge to
9032 if( pProto
->Stackable
!= 1 )
9034 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,QUESTBAG_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9035 if(res
!=EQUIP_ERR_OK
)
9038 *no_space_count
= count
+ no_similar_count
;
9044 if(no_similar_count
==0)
9045 return EQUIP_ERR_OK
;
9048 *no_space_count
= count
+ no_similar_count
;
9049 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9052 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9053 if(res
!=EQUIP_ERR_OK
)
9056 *no_space_count
= count
+ no_similar_count
;
9062 if(no_similar_count
==0)
9063 return EQUIP_ERR_OK
;
9066 *no_space_count
= count
+ no_similar_count
;
9067 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9070 if( pProto
->BagFamily
)
9072 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9074 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
9075 if(res
!=EQUIP_ERR_OK
)
9080 if(no_similar_count
==0)
9081 return EQUIP_ERR_OK
;
9084 *no_space_count
= count
+ no_similar_count
;
9085 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9090 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9092 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
9093 if(res
!=EQUIP_ERR_OK
)
9098 if(no_similar_count
==0)
9099 return EQUIP_ERR_OK
;
9102 *no_space_count
= count
+ no_similar_count
;
9103 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9108 // search free slot - special bag case
9109 if( pProto
->BagFamily
)
9111 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9113 uint32 keyringSize
= GetMaxKeyringSize();
9114 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9115 if(res
!=EQUIP_ERR_OK
)
9118 *no_space_count
= count
+ no_similar_count
;
9124 if(no_similar_count
==0)
9125 return EQUIP_ERR_OK
;
9128 *no_space_count
= count
+ no_similar_count
;
9129 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9132 else if(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
9134 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9135 if(res
!=EQUIP_ERR_OK
)
9138 *no_space_count
= count
+ no_similar_count
;
9144 if(no_similar_count
==0)
9145 return EQUIP_ERR_OK
;
9148 *no_space_count
= count
+ no_similar_count
;
9149 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9153 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9155 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
9156 if(res
!=EQUIP_ERR_OK
)
9161 if(no_similar_count
==0)
9162 return EQUIP_ERR_OK
;
9165 *no_space_count
= count
+ no_similar_count
;
9166 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9172 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9173 if(res
!=EQUIP_ERR_OK
)
9176 *no_space_count
= count
+ no_similar_count
;
9182 if(no_similar_count
==0)
9183 return EQUIP_ERR_OK
;
9186 *no_space_count
= count
+ no_similar_count
;
9187 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9190 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9192 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
9193 if(res
!=EQUIP_ERR_OK
)
9198 if(no_similar_count
==0)
9199 return EQUIP_ERR_OK
;
9202 *no_space_count
= count
+ no_similar_count
;
9203 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9208 *no_space_count
= count
+ no_similar_count
;
9210 return EQUIP_ERR_INVENTORY_FULL
;
9213 //////////////////////////////////////////////////////////////////////////
9214 uint8
Player::CanStoreItems( Item
**pItems
,int count
) const
9219 int inv_slot_items
[INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
];
9220 int inv_bags
[INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
][MAX_BAG_SIZE
];
9221 int inv_keys
[KEYRING_SLOT_END
-KEYRING_SLOT_START
];
9222 int inv_tokens
[CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
];
9224 memset(inv_slot_items
,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
));
9225 memset(inv_bags
,0,sizeof(int)*(INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
)*MAX_BAG_SIZE
);
9226 memset(inv_keys
,0,sizeof(int)*(KEYRING_SLOT_END
-KEYRING_SLOT_START
));
9227 memset(inv_tokens
,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
));
9229 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
9231 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9233 if (pItem2
&& !pItem2
->IsInTrade())
9235 inv_slot_items
[i
-INVENTORY_SLOT_ITEM_START
] = pItem2
->GetCount();
9239 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; ++i
)
9241 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9243 if (pItem2
&& !pItem2
->IsInTrade())
9245 inv_keys
[i
-KEYRING_SLOT_START
] = pItem2
->GetCount();
9249 for(int i
= CURRENCYTOKEN_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
9251 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9253 if (pItem2
&& !pItem2
->IsInTrade())
9255 inv_tokens
[i
-CURRENCYTOKEN_SLOT_START
] = pItem2
->GetCount();
9259 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9261 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
9263 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9265 pItem2
= GetItemByPos( i
, j
);
9266 if (pItem2
&& !pItem2
->IsInTrade())
9268 inv_bags
[i
-INVENTORY_SLOT_BAG_START
][j
] = pItem2
->GetCount();
9274 // check free space for all items
9275 for (int k
=0;k
<count
;k
++)
9277 Item
*pItem
= pItems
[k
];
9280 if (!pItem
) continue;
9282 sLog
.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k
+1, pItem
->GetEntry(), pItem
->GetCount());
9283 ItemPrototype
const *pProto
= pItem
->GetProto();
9287 return EQUIP_ERR_ITEM_NOT_FOUND
;
9290 if(pItem
->IsBindedNotWith(GetGUID()))
9291 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9294 ItemPrototype
const *pBagProto
;
9296 // item is 'one item only'
9297 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9298 if(res
!= EQUIP_ERR_OK
)
9301 // search stack for merge to
9302 if( pProto
->Stackable
!= 1 )
9304 bool b_found
= false;
9306 for(int t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_END
; t
++)
9308 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9309 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_keys
[t
-KEYRING_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9311 inv_keys
[t
-KEYRING_SLOT_START
] += pItem
->GetCount();
9316 if (b_found
) continue;
9318 for(int t
= CURRENCYTOKEN_SLOT_START
; t
< CURRENCYTOKEN_SLOT_END
; t
++)
9320 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9321 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9323 inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] += pItem
->GetCount();
9328 if (b_found
) continue;
9330 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; t
++)
9332 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9333 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9335 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] += pItem
->GetCount();
9340 if (b_found
) continue;
9342 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9344 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9347 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9349 pItem2
= GetItemByPos( t
, j
);
9350 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9352 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] += pItem
->GetCount();
9359 if (b_found
) continue;
9363 if( pProto
->BagFamily
)
9365 bool b_found
= false;
9366 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9368 uint32 keyringSize
= GetMaxKeyringSize();
9369 for(uint32 t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_START
+keyringSize
; ++t
)
9371 if( inv_keys
[t
-KEYRING_SLOT_START
] == 0 )
9373 inv_keys
[t
-KEYRING_SLOT_START
] = 1;
9380 if (b_found
) continue;
9382 if(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
9384 for(uint32 t
= CURRENCYTOKEN_SLOT_START
; t
< CURRENCYTOKEN_SLOT_END
; ++t
)
9386 if( inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] == 0 )
9388 inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] = 1;
9395 if (b_found
) continue;
9397 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9399 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9402 pBagProto
= pBag
->GetProto();
9404 // not plain container check
9405 if( pBagProto
&& (pBagProto
->Class
!= ITEM_CLASS_CONTAINER
|| pBagProto
->SubClass
!= ITEM_SUBCLASS_CONTAINER
) &&
9406 ItemCanGoIntoBag(pProto
,pBagProto
) )
9408 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9410 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9412 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9420 if (b_found
) continue;
9424 bool b_found
= false;
9425 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; t
++)
9427 if( inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] == 0 )
9429 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] = 1;
9434 if (b_found
) continue;
9436 // search free slot in bags
9437 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9439 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9442 pBagProto
= pBag
->GetProto();
9444 // special bag already checked
9445 if( pBagProto
&& (pBagProto
->Class
!= ITEM_CLASS_CONTAINER
|| pBagProto
->SubClass
!= ITEM_SUBCLASS_CONTAINER
))
9448 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9450 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9452 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9460 // no free slot found?
9462 return EQUIP_ERR_INVENTORY_FULL
;
9465 return EQUIP_ERR_OK
;
9468 //////////////////////////////////////////////////////////////////////////
9469 uint8
Player::CanEquipNewItem( uint8 slot
, uint16
&dest
, uint32 item
, bool swap
) const
9472 Item
*pItem
= Item::CreateItem( item
, 1, this );
9475 uint8 result
= CanEquipItem(slot
, dest
, pItem
, swap
);
9480 return EQUIP_ERR_ITEM_NOT_FOUND
;
9483 uint8
Player::CanEquipItem( uint8 slot
, uint16
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
9488 sLog
.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot
, pItem
->GetEntry(), pItem
->GetCount());
9489 ItemPrototype
const *pProto
= pItem
->GetProto();
9492 if(pItem
->IsBindedNotWith(GetGUID()))
9493 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9495 // check count of items (skip for auto move for same player from bank)
9496 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9497 if(res
!= EQUIP_ERR_OK
)
9500 // check this only in game
9503 // May be here should be more stronger checks; STUNNED checked
9504 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9505 if (hasUnitState(UNIT_STAT_STUNNED
))
9506 return EQUIP_ERR_YOU_ARE_STUNNED
;
9508 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9510 // - in-progress arenas
9511 if( !pProto
->CanChangeEquipStateInCombat() )
9514 return EQUIP_ERR_NOT_IN_COMBAT
;
9516 if(BattleGround
* bg
= GetBattleGround())
9517 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
9518 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
9521 if(isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
!= 0)
9522 return EQUIP_ERR_CANT_DO_RIGHT_NOW
; // maybe exist better err
9524 if(IsNonMeleeSpellCasted(false))
9525 return EQUIP_ERR_CANT_DO_RIGHT_NOW
;
9528 uint8 eslot
= FindEquipSlot( pProto
, slot
, swap
);
9529 if( eslot
== NULL_SLOT
)
9530 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9532 uint8 msg
= CanUseItem( pItem
, not_loading
);
9533 if( msg
!= EQUIP_ERR_OK
)
9535 if( !swap
&& GetItemByPos( INVENTORY_SLOT_BAG_0
, eslot
) )
9536 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE
;
9538 // if swap ignore item (equipped also)
9539 if(uint8 res2
= CanEquipUniqueItem(pItem
, swap
? eslot
: NULL_SLOT
))
9542 // check unique-equipped special item classes
9543 if (pProto
->Class
== ITEM_CLASS_QUIVER
)
9545 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9547 if( Item
* pBag
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
) )
9549 if( ItemPrototype
const* pBagProto
= pBag
->GetProto() )
9551 if( pBagProto
->Class
==pProto
->Class
&& (!swap
|| pBag
->GetSlot() != eslot
) )
9553 if(pBagProto
->SubClass
== ITEM_SUBCLASS_AMMO_POUCH
)
9554 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
;
9556 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER
;
9563 uint32 type
= pProto
->InventoryType
;
9565 if(eslot
== EQUIPMENT_SLOT_OFFHAND
)
9567 if (type
== INVTYPE_WEAPON
|| type
== INVTYPE_WEAPONOFFHAND
)
9570 return EQUIP_ERR_CANT_DUAL_WIELD
;
9572 else if (type
== INVTYPE_2HWEAPON
)
9574 if(!CanDualWield() || !CanTitanGrip())
9575 return EQUIP_ERR_CANT_DUAL_WIELD
;
9579 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED
;
9582 // equip two-hand weapon case (with possible unequip 2 items)
9583 if( type
== INVTYPE_2HWEAPON
)
9585 if (eslot
== EQUIPMENT_SLOT_OFFHAND
)
9587 if (!CanTitanGrip())
9588 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9590 else if (eslot
!= EQUIPMENT_SLOT_MAINHAND
)
9591 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9593 if (!CanTitanGrip())
9595 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9596 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
9597 ItemPosCountVec off_dest
;
9598 if( offItem
&& (!not_loading
||
9599 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0
) << 8 | EQUIPMENT_SLOT_OFFHAND
,false) != EQUIP_ERR_OK
||
9600 CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false ) != EQUIP_ERR_OK
) )
9601 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_INVENTORY_FULL
;
9604 dest
= ((INVENTORY_SLOT_BAG_0
<< 8) | eslot
);
9605 return EQUIP_ERR_OK
;
9609 return EQUIP_ERR_ITEM_NOT_FOUND
;
9611 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
;
9614 uint8
Player::CanUnequipItem( uint16 pos
, bool swap
) const
9616 // Applied only to equipped items and bank bags
9617 if(!IsEquipmentPos(pos
) && !IsBagPos(pos
))
9618 return EQUIP_ERR_OK
;
9620 Item
* pItem
= GetItemByPos(pos
);
9622 // Applied only to existed equipped item
9624 return EQUIP_ERR_OK
;
9626 sLog
.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos
, pItem
->GetEntry(), pItem
->GetCount());
9628 ItemPrototype
const *pProto
= pItem
->GetProto();
9630 return EQUIP_ERR_ITEM_NOT_FOUND
;
9632 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9634 // - in-progress arenas
9635 if( !pProto
->CanChangeEquipStateInCombat() )
9638 return EQUIP_ERR_NOT_IN_COMBAT
;
9640 if(BattleGround
* bg
= GetBattleGround())
9641 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
9642 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
9645 if(!swap
&& pItem
->IsBag() && !((Bag
*)pItem
)->IsEmpty())
9646 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS
;
9648 return EQUIP_ERR_OK
;
9651 uint8
Player::CanBankItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
9654 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
9656 uint32 count
= pItem
->GetCount();
9658 sLog
.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), pItem
->GetCount());
9659 ItemPrototype
const *pProto
= pItem
->GetProto();
9661 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
9663 if( pItem
->IsBindedNotWith(GetGUID()) )
9664 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9666 // check count of items (skip for auto move for same player from bank)
9667 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9668 if(res
!= EQUIP_ERR_OK
)
9672 if( bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
9674 if( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
9676 if (!pItem
->IsBag())
9677 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
;
9679 if( !HasBankBagSlot( slot
) )
9680 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT
;
9682 if( uint8 cantuse
= CanUseItem( pItem
, not_loading
) != EQUIP_ERR_OK
)
9686 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
9687 if(res
!=EQUIP_ERR_OK
)
9691 return EQUIP_ERR_OK
;
9694 // not specific slot or have space for partly store only in specific slot
9697 if( bag
!= NULL_BAG
)
9699 if( pProto
->InventoryType
== INVTYPE_BAG
)
9701 Bag
*pBag
= (Bag
*)pItem
;
9702 if( pBag
&& !pBag
->IsEmpty() )
9703 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
;
9706 // search stack in bag for merge to
9707 if( pProto
->Stackable
!= 1 )
9709 if( bag
== INVENTORY_SLOT_BAG_0
)
9711 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9712 if(res
!=EQUIP_ERR_OK
)
9716 return EQUIP_ERR_OK
;
9720 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
9721 if(res
!=EQUIP_ERR_OK
)
9722 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
9724 if(res
!=EQUIP_ERR_OK
)
9728 return EQUIP_ERR_OK
;
9732 // search free slot in bag
9733 if( bag
== INVENTORY_SLOT_BAG_0
)
9735 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9736 if(res
!=EQUIP_ERR_OK
)
9740 return EQUIP_ERR_OK
;
9744 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
9745 if(res
!=EQUIP_ERR_OK
)
9746 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
9748 if(res
!=EQUIP_ERR_OK
)
9752 return EQUIP_ERR_OK
;
9756 // not specific bag or have space for partly store only in specific bag
9758 // search stack for merge to
9759 if( pProto
->Stackable
!= 1 )
9762 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9763 if(res
!=EQUIP_ERR_OK
)
9767 return EQUIP_ERR_OK
;
9770 if( pProto
->BagFamily
)
9772 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
9774 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
9775 if(res
!=EQUIP_ERR_OK
)
9779 return EQUIP_ERR_OK
;
9783 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
9785 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
9786 if(res
!=EQUIP_ERR_OK
)
9790 return EQUIP_ERR_OK
;
9794 // search free place in special bag
9795 if( pProto
->BagFamily
)
9797 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
9799 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
9800 if(res
!=EQUIP_ERR_OK
)
9804 return EQUIP_ERR_OK
;
9808 // search free space
9809 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9810 if(res
!=EQUIP_ERR_OK
)
9814 return EQUIP_ERR_OK
;
9816 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
9818 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
9819 if(res
!=EQUIP_ERR_OK
)
9823 return EQUIP_ERR_OK
;
9825 return EQUIP_ERR_BANK_FULL
;
9828 uint8
Player::CanUseItem( Item
*pItem
, bool not_loading
) const
9832 sLog
.outDebug( "STORAGE: CanUseItem item = %u", pItem
->GetEntry());
9833 if( !isAlive() && not_loading
)
9834 return EQUIP_ERR_YOU_ARE_DEAD
;
9836 // return EQUIP_ERR_YOU_ARE_STUNNED;
9837 ItemPrototype
const *pProto
= pItem
->GetProto();
9840 if( pItem
->IsBindedNotWith(GetGUID()) )
9841 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9842 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
9843 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
9844 if( pItem
->GetSkill() != 0 )
9846 if( GetSkillValue( pItem
->GetSkill() ) == 0 )
9847 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9849 if( pProto
->RequiredSkill
!= 0 )
9851 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
9852 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9853 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
9854 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
9856 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
9857 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9858 if( pProto
->RequiredReputationFaction
&& uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
9859 return EQUIP_ERR_CANT_EQUIP_REPUTATION
;
9860 if( getLevel() < pProto
->RequiredLevel
)
9861 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
9862 return EQUIP_ERR_OK
;
9865 return EQUIP_ERR_ITEM_NOT_FOUND
;
9868 bool Player::CanUseItem( ItemPrototype
const *pProto
)
9870 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
9874 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
9876 if( pProto
->RequiredSkill
!= 0 )
9878 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
9880 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
9883 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
9885 if( getLevel() < pProto
->RequiredLevel
)
9892 uint8
Player::CanUseAmmo( uint32 item
) const
9894 sLog
.outDebug( "STORAGE: CanUseAmmo item = %u", item
);
9896 return EQUIP_ERR_YOU_ARE_DEAD
;
9898 // return EQUIP_ERR_YOU_ARE_STUNNED;
9899 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
9902 if( pProto
->InventoryType
!= INVTYPE_AMMO
)
9903 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE
;
9904 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
9905 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
9906 if( pProto
->RequiredSkill
!= 0 )
9908 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
9909 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9910 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
9911 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
9913 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
9914 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9915 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
9916 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9918 if( getLevel() < pProto
->RequiredLevel
)
9919 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
9922 if(GetDummyAura(46699))
9923 return EQUIP_ERR_BAG_FULL6
;
9925 return EQUIP_ERR_OK
;
9927 return EQUIP_ERR_ITEM_NOT_FOUND
;
9930 void Player::SetAmmo( uint32 item
)
9936 if( GetUInt32Value(PLAYER_AMMO_ID
) == item
)
9942 uint8 msg
= CanUseAmmo( item
);
9943 if( msg
!= EQUIP_ERR_OK
)
9945 SendEquipError( msg
, NULL
, NULL
);
9950 SetUInt32Value(PLAYER_AMMO_ID
, item
);
9952 _ApplyAmmoBonuses();
9955 void Player::RemoveAmmo()
9957 SetUInt32Value(PLAYER_AMMO_ID
, 0);
9961 if(CanModifyStats())
9962 UpdateDamagePhysical(RANGED_ATTACK
);
9965 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
9966 Item
* Player::StoreNewItem( ItemPosCountVec
const& dest
, uint32 item
, bool update
,int32 randomPropertyId
)
9969 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); ++itr
)
9970 count
+= itr
->count
;
9972 Item
*pItem
= Item::CreateItem( item
, count
, this );
9975 ItemAddedQuestCheck( item
, count
);
9976 if(randomPropertyId
)
9977 pItem
->SetItemRandomProperties(randomPropertyId
);
9978 pItem
= StoreItem( dest
, pItem
, update
);
9983 Item
* Player::StoreItem( ItemPosCountVec
const& dest
, Item
* pItem
, bool update
)
9988 Item
* lastItem
= pItem
;
9989 uint32 entry
= pItem
->GetEntry();
9990 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); )
9992 uint16 pos
= itr
->pos
;
9993 uint32 count
= itr
->count
;
9997 if(itr
== dest
.end())
9999 lastItem
= _StoreItem(pos
,pItem
,count
,false,update
);
10003 lastItem
= _StoreItem(pos
,pItem
,count
,true,update
);
10005 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM
, entry
);
10009 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10010 Item
* Player::_StoreItem( uint16 pos
, Item
*pItem
, uint32 count
, bool clone
, bool update
)
10015 uint8 bag
= pos
>> 8;
10016 uint8 slot
= pos
& 255;
10018 sLog
.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), count
);
10020 Item
*pItem2
= GetItemByPos( bag
, slot
);
10025 pItem
= pItem
->CloneItem(count
,this);
10027 pItem
->SetCount(count
);
10032 if (pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10033 pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10034 (pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
)))
10035 pItem
->SetBinding( true );
10037 if (bag
== INVENTORY_SLOT_BAG_0
)
10039 m_items
[slot
] = pItem
;
10040 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), pItem
->GetGUID() );
10041 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10042 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10044 pItem
->SetSlot( slot
);
10045 pItem
->SetContainer( NULL
);
10047 // need update known currency
10048 if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)
10049 UpdateKnownCurrencies(pItem
->GetEntry(),true);
10051 if (IsInWorld() && update
)
10053 pItem
->AddToWorld();
10054 pItem
->SendUpdateToPlayer( this );
10057 pItem
->SetState(ITEM_CHANGED
, this);
10059 else if (Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
))
10061 pBag
->StoreItem( slot
, pItem
, update
);
10062 if( IsInWorld() && update
)
10064 pItem
->AddToWorld();
10065 pItem
->SendUpdateToPlayer( this );
10067 pItem
->SetState(ITEM_CHANGED
, this);
10068 pBag
->SetState(ITEM_CHANGED
, this);
10071 AddEnchantmentDurations(pItem
);
10072 AddItemDurations(pItem
);
10078 if (pItem2
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10079 pItem2
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10080 (pItem2
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
)))
10081 pItem2
->SetBinding( true );
10083 pItem2
->SetCount( pItem2
->GetCount() + count
);
10084 if (IsInWorld() && update
)
10085 pItem2
->SendUpdateToPlayer( this );
10089 // delete item (it not in any slot currently)
10090 if (IsInWorld() && update
)
10092 pItem
->RemoveFromWorld();
10093 pItem
->DestroyForPlayer( this );
10096 RemoveEnchantmentDurations(pItem
);
10097 RemoveItemDurations(pItem
);
10099 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10100 pItem
->SetState(ITEM_REMOVED
, this);
10103 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10104 AddEnchantmentDurations(pItem2
);
10106 pItem2
->SetState(ITEM_CHANGED
, this);
10112 Item
* Player::EquipNewItem( uint16 pos
, uint32 item
, bool update
)
10114 if (Item
*pItem
= Item::CreateItem( item
, 1, this ))
10116 ItemAddedQuestCheck( item
, 1 );
10117 return EquipItem( pos
, pItem
, update
);
10123 Item
* Player::EquipItem( uint16 pos
, Item
*pItem
, bool update
)
10126 AddEnchantmentDurations(pItem
);
10127 AddItemDurations(pItem
);
10129 uint8 bag
= pos
>> 8;
10130 uint8 slot
= pos
& 255;
10132 Item
*pItem2
= GetItemByPos( bag
, slot
);
10136 VisualizeItem( slot
, pItem
);
10140 ItemPrototype
const *pProto
= pItem
->GetProto();
10142 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10143 if(pProto
&& pProto
->ItemSet
)
10144 AddItemsSetItem(this,pItem
);
10146 _ApplyItemMods(pItem
, slot
, true);
10148 if(pProto
&& isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
== 0)
10150 uint32 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s
;
10152 if (getClass() == CLASS_ROGUE
)
10153 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s
;
10155 SpellEntry
const* spellProto
= sSpellStore
.LookupEntry(cooldownSpell
);
10158 sLog
.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell
);
10161 m_weaponChangeTimer
= spellProto
->StartRecoveryTime
;
10163 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+4);
10164 data
<< uint64(GetGUID());
10166 data
<< uint32(cooldownSpell
);
10168 GetSession()->SendPacket(&data
);
10173 if( IsInWorld() && update
)
10175 pItem
->AddToWorld();
10176 pItem
->SendUpdateToPlayer( this );
10179 ApplyEquipCooldown(pItem
);
10181 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
10182 UpdateExpertise(BASE_ATTACK
);
10183 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10184 UpdateExpertise(OFF_ATTACK
);
10188 pItem2
->SetCount( pItem2
->GetCount() + pItem
->GetCount() );
10189 if( IsInWorld() && update
)
10190 pItem2
->SendUpdateToPlayer( this );
10192 // delete item (it not in any slot currently)
10193 //pItem->DeleteFromDB();
10194 if( IsInWorld() && update
)
10196 pItem
->RemoveFromWorld();
10197 pItem
->DestroyForPlayer( this );
10200 RemoveEnchantmentDurations(pItem
);
10201 RemoveItemDurations(pItem
);
10203 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10204 pItem
->SetState(ITEM_REMOVED
, this);
10205 pItem2
->SetState(ITEM_CHANGED
, this);
10207 ApplyEquipCooldown(pItem2
);
10212 // only for full equip instead adding to stack
10213 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM
, pItem
->GetEntry());
10218 void Player::QuickEquipItem( uint16 pos
, Item
*pItem
)
10222 AddEnchantmentDurations(pItem
);
10223 AddItemDurations(pItem
);
10225 uint8 slot
= pos
& 255;
10226 VisualizeItem( slot
, pItem
);
10230 pItem
->AddToWorld();
10231 pItem
->SendUpdateToPlayer( this );
10236 void Player::SetVisibleItemSlot(uint8 slot
, Item
*pItem
)
10238 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10239 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10240 // entry // Size: 1
10241 // inspected enchantments // Size: 6
10243 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10244 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10249 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), pItem
->GetUInt64Value(ITEM_FIELD_CREATOR
));
10251 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
10252 SetUInt32Value(VisibleBase
+ 0, pItem
->GetEntry());
10254 for(int i
= 0; i
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++i
)
10255 SetUInt32Value(VisibleBase
+ 1 + i
, pItem
->GetEnchantmentId(EnchantmentSlot(i
)));
10257 // Use SetInt16Value to prevent set high part to FFFF for negative value
10258 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0, pItem
->GetItemRandomPropertyId());
10259 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), pItem
->GetItemSuffixFactor());
10263 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10265 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
10266 SetUInt32Value(VisibleBase
+ 0, 0);
10268 for(int i
= 0; i
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++i
)
10269 SetUInt32Value(VisibleBase
+ 1 + i
, 0);
10271 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 0 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10272 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10276 void Player::VisualizeItem( uint8 slot
, Item
*pItem
)
10281 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10282 if( pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
|| pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
|| pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
)
10283 pItem
->SetBinding( true );
10285 sLog
.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot
, pItem
->GetEntry());
10287 m_items
[slot
] = pItem
;
10288 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), pItem
->GetGUID() );
10289 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10290 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10291 pItem
->SetSlot( slot
);
10292 pItem
->SetContainer( NULL
);
10294 if( slot
< EQUIPMENT_SLOT_END
)
10295 SetVisibleItemSlot(slot
,pItem
);
10297 pItem
->SetState(ITEM_CHANGED
, this);
10300 void Player::RemoveItem( uint8 bag
, uint8 slot
, bool update
)
10302 // note: removeitem does not actually change the item
10303 // it only takes the item out of storage temporarily
10304 // note2: if removeitem is to be used for delinking
10305 // the item must be removed from the player's updatequeue
10307 Item
*pItem
= GetItemByPos( bag
, slot
);
10310 sLog
.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10312 RemoveEnchantmentDurations(pItem
);
10313 RemoveItemDurations(pItem
);
10315 if( bag
== INVENTORY_SLOT_BAG_0
)
10317 if ( slot
< INVENTORY_SLOT_BAG_END
)
10319 ItemPrototype
const *pProto
= pItem
->GetProto();
10320 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10322 if(pProto
&& pProto
->ItemSet
)
10323 RemoveItemsSetItem(this,pProto
);
10325 _ApplyItemMods(pItem
, slot
, false);
10327 // remove item dependent auras and casts (only weapon and armor slots)
10328 if(slot
< EQUIPMENT_SLOT_END
)
10330 RemoveItemDependentAurasAndCasts(pItem
);
10332 // remove held enchantments, update expertise
10333 if ( slot
== EQUIPMENT_SLOT_MAINHAND
)
10335 if (pItem
->GetItemSuffixFactor())
10337 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3
);
10338 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4
);
10342 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0
);
10343 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1
);
10346 UpdateExpertise(BASE_ATTACK
);
10348 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10349 UpdateExpertise(OFF_ATTACK
);
10352 // need update known currency
10353 else if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)
10354 UpdateKnownCurrencies(pItem
->GetEntry(),false);
10356 m_items
[slot
] = NULL
;
10357 SetUInt64Value((uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
*2)), 0);
10359 if ( slot
< EQUIPMENT_SLOT_END
)
10360 SetVisibleItemSlot(slot
,NULL
);
10364 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
10366 pBag
->RemoveItem(slot
, update
);
10368 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10369 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10370 pItem
->SetSlot( NULL_SLOT
);
10371 if( IsInWorld() && update
)
10372 pItem
->SendUpdateToPlayer( this );
10376 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10377 void Player::MoveItemFromInventory(uint8 bag
, uint8 slot
, bool update
)
10379 if(Item
* it
= GetItemByPos(bag
,slot
))
10381 ItemRemovedQuestCheck(it
->GetEntry(),it
->GetCount());
10382 RemoveItem( bag
,slot
,update
);
10383 it
->RemoveFromUpdateQueueOf(this);
10384 if(it
->IsInWorld())
10386 it
->RemoveFromWorld();
10387 it
->DestroyForPlayer( this );
10392 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10393 void Player::MoveItemToInventory(ItemPosCountVec
const& dest
, Item
* pItem
, bool update
, bool in_characterInventoryDB
)
10395 // update quest counters
10396 ItemAddedQuestCheck(pItem
->GetEntry(),pItem
->GetCount());
10399 Item
* pLastItem
= StoreItem( dest
, pItem
, update
);
10401 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10402 if(pLastItem
==pItem
)
10404 // update owner for last item (this can be original item with wrong owner
10405 if(pLastItem
->GetOwnerGUID() != GetGUID())
10406 pLastItem
->SetOwnerGUID(GetGUID());
10408 // if this original item then it need create record in inventory
10409 // in case trade we already have item in other player inventory
10410 pLastItem
->SetState(in_characterInventoryDB
? ITEM_CHANGED
: ITEM_NEW
, this);
10414 void Player::DestroyItem( uint8 bag
, uint8 slot
, bool update
)
10416 Item
*pItem
= GetItemByPos( bag
, slot
);
10419 sLog
.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10421 // start from destroy contained items (only equipped bag can have its)
10422 if (pItem
->IsBag() && pItem
->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10424 for (int i
= 0; i
< MAX_BAG_SIZE
; ++i
)
10425 DestroyItem(slot
,i
,update
);
10428 if(pItem
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_WRAPPED
))
10429 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem
->GetGUIDLow());
10431 RemoveEnchantmentDurations(pItem
);
10432 RemoveItemDurations(pItem
);
10434 ItemRemovedQuestCheck( pItem
->GetEntry(), pItem
->GetCount() );
10436 if( bag
== INVENTORY_SLOT_BAG_0
)
10438 SetUInt64Value((uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
*2)), 0);
10440 // equipment and equipped bags can have applied bonuses
10441 if ( slot
< INVENTORY_SLOT_BAG_END
)
10443 ItemPrototype
const *pProto
= pItem
->GetProto();
10445 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10446 if(pProto
&& pProto
->ItemSet
)
10447 RemoveItemsSetItem(this,pProto
);
10449 _ApplyItemMods(pItem
, slot
, false);
10452 if ( slot
< EQUIPMENT_SLOT_END
)
10454 // remove item dependent auras and casts (only weapon and armor slots)
10455 RemoveItemDependentAurasAndCasts(pItem
);
10457 // update expertise
10458 if ( slot
== EQUIPMENT_SLOT_MAINHAND
)
10459 UpdateExpertise(BASE_ATTACK
);
10460 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10461 UpdateExpertise(OFF_ATTACK
);
10463 // equipment visual show
10464 SetVisibleItemSlot(slot
,NULL
);
10466 // need update known currency
10467 else if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)
10468 UpdateKnownCurrencies(pItem
->GetEntry(),false);
10470 m_items
[slot
] = NULL
;
10472 else if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
))
10473 pBag
->RemoveItem(slot
, update
);
10475 if( IsInWorld() && update
)
10477 pItem
->RemoveFromWorld();
10478 pItem
->DestroyForPlayer(this);
10481 //pItem->SetOwnerGUID(0);
10482 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10483 pItem
->SetSlot( NULL_SLOT
);
10484 pItem
->SetState(ITEM_REMOVED
, this);
10488 void Player::DestroyItemCount( uint32 item
, uint32 count
, bool update
, bool unequip_check
)
10490 sLog
.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item
, count
);
10491 uint32 remcount
= 0;
10494 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
10496 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10498 if (pItem
->GetEntry() == item
)
10500 if (pItem
->GetCount() + remcount
<= count
)
10502 // all items in inventory can unequipped
10503 remcount
+= pItem
->GetCount();
10504 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10506 if (remcount
>=count
)
10511 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10512 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10513 if (IsInWorld() & update
)
10514 pItem
->SendUpdateToPlayer( this );
10515 pItem
->SetState(ITEM_CHANGED
, this);
10522 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
10524 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10526 if (pItem
->GetEntry() == item
)
10528 if (pItem
->GetCount() + remcount
<= count
)
10530 // all keys can be unequipped
10531 remcount
+= pItem
->GetCount();
10532 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10534 if (remcount
>=count
)
10539 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10540 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10541 if (IsInWorld() & update
)
10542 pItem
->SendUpdateToPlayer( this );
10543 pItem
->SetState(ITEM_CHANGED
, this);
10550 // in inventory bags
10551 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
10553 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10555 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
10557 if(Item
* pItem
= pBag
->GetItemByPos(j
))
10559 if (pItem
->GetEntry() == item
)
10561 // all items in bags can be unequipped
10562 if (pItem
->GetCount() + remcount
<= count
)
10564 remcount
+= pItem
->GetCount();
10565 DestroyItem( i
, j
, update
);
10567 if (remcount
>=count
)
10572 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10573 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10574 if (IsInWorld() && update
)
10575 pItem
->SendUpdateToPlayer( this );
10576 pItem
->SetState(ITEM_CHANGED
, this);
10585 // in equipment and bag list
10586 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
10588 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10590 if (pItem
&& pItem
->GetEntry() == item
)
10592 if (pItem
->GetCount() + remcount
<= count
)
10594 if (!unequip_check
|| CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
,false) == EQUIP_ERR_OK
)
10596 remcount
+= pItem
->GetCount();
10597 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10599 if (remcount
>=count
)
10605 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10606 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10607 if (IsInWorld() & update
)
10608 pItem
->SendUpdateToPlayer( this );
10609 pItem
->SetState(ITEM_CHANGED
, this);
10617 void Player::DestroyZoneLimitedItem( bool update
, uint32 new_zone
)
10619 sLog
.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone
);
10622 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
10623 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10624 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
))
10625 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10627 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
10628 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10629 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
))
10630 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10632 // in inventory bags
10633 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
10634 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10635 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
10636 if (Item
* pItem
= pBag
->GetItemByPos(j
))
10637 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
))
10638 DestroyItem( i
, j
, update
);
10640 // in equipment and bag list
10641 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
10642 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10643 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
))
10644 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10647 void Player::DestroyConjuredItems( bool update
)
10649 // used when entering arena
10650 // destroys all conjured items
10651 sLog
.outDebug( "STORAGE: DestroyConjuredItems" );
10654 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
10655 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10656 if (pItem
->IsConjuredConsumable())
10657 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10659 // in inventory bags
10660 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
10661 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10662 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
10663 if (Item
* pItem
= pBag
->GetItemByPos(j
))
10664 if (pItem
->IsConjuredConsumable())
10665 DestroyItem( i
, j
, update
);
10667 // in equipment and bag list
10668 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
10669 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10670 if (pItem
->IsConjuredConsumable())
10671 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10674 void Player::DestroyItemCount( Item
* pItem
, uint32
&count
, bool update
)
10679 sLog
.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem
->GetGUIDLow(),pItem
->GetEntry(), count
);
10681 if( pItem
->GetCount() <= count
)
10683 count
-= pItem
->GetCount();
10685 DestroyItem( pItem
->GetBagSlot(),pItem
->GetSlot(), update
);
10689 ItemRemovedQuestCheck( pItem
->GetEntry(), count
);
10690 pItem
->SetCount( pItem
->GetCount() - count
);
10692 if( IsInWorld() & update
)
10693 pItem
->SendUpdateToPlayer( this );
10694 pItem
->SetState(ITEM_CHANGED
, this);
10698 void Player::SplitItem( uint16 src
, uint16 dst
, uint32 count
)
10700 uint8 srcbag
= src
>> 8;
10701 uint8 srcslot
= src
& 255;
10703 uint8 dstbag
= dst
>> 8;
10704 uint8 dstslot
= dst
& 255;
10706 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
10709 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
10713 // not let split all items (can be only at cheating)
10714 if(pSrcItem
->GetCount() == count
)
10716 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
10720 // not let split more existed items (can be only at cheating)
10721 if(pSrcItem
->GetCount() < count
)
10723 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT
, pSrcItem
, NULL
);
10727 if(pSrcItem
->m_lootGenerated
) // prevent split looting item (item
10729 //best error message found for attempting to split while looting
10730 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
10734 sLog
.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag
, dstslot
, pSrcItem
->GetEntry(), count
);
10735 Item
*pNewItem
= pSrcItem
->CloneItem( count
, this );
10738 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
10742 if( IsInventoryPos( dst
) )
10744 // change item amount before check (for unique max count check)
10745 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
10747 ItemPosCountVec dest
;
10748 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pNewItem
, false );
10749 if( msg
!= EQUIP_ERR_OK
)
10752 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
10753 SendEquipError( msg
, pSrcItem
, NULL
);
10758 pSrcItem
->SendUpdateToPlayer( this );
10759 pSrcItem
->SetState(ITEM_CHANGED
, this);
10760 StoreItem( dest
, pNewItem
, true);
10762 else if( IsBankPos ( dst
) )
10764 // change item amount before check (for unique max count check)
10765 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
10767 ItemPosCountVec dest
;
10768 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pNewItem
, false );
10769 if( msg
!= EQUIP_ERR_OK
)
10772 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
10773 SendEquipError( msg
, pSrcItem
, NULL
);
10778 pSrcItem
->SendUpdateToPlayer( this );
10779 pSrcItem
->SetState(ITEM_CHANGED
, this);
10780 BankItem( dest
, pNewItem
, true);
10782 else if( IsEquipmentPos ( dst
) )
10784 // change item amount before check (for unique max count check), provide space for splitted items
10785 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
10788 uint8 msg
= CanEquipItem( dstslot
, dest
, pNewItem
, false );
10789 if( msg
!= EQUIP_ERR_OK
)
10792 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
10793 SendEquipError( msg
, pSrcItem
, NULL
);
10798 pSrcItem
->SendUpdateToPlayer( this );
10799 pSrcItem
->SetState(ITEM_CHANGED
, this);
10800 EquipItem( dest
, pNewItem
, true);
10801 AutoUnequipOffhandIfNeed();
10805 void Player::SwapItem( uint16 src
, uint16 dst
)
10807 uint8 srcbag
= src
>> 8;
10808 uint8 srcslot
= src
& 255;
10810 uint8 dstbag
= dst
>> 8;
10811 uint8 dstslot
= dst
& 255;
10813 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
10814 Item
*pDstItem
= GetItemByPos( dstbag
, dstslot
);
10819 sLog
.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag
, dstslot
, pSrcItem
->GetEntry());
10823 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD
, pSrcItem
, pDstItem
);
10829 if(pSrcItem
->m_lootGenerated
) // prevent swap looting item
10831 //best error message found for attempting to swap while looting
10832 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pSrcItem
, NULL
);
10836 // check unequip potability for equipped items and bank bags
10837 if(IsEquipmentPos ( src
) || IsBagPos ( src
))
10839 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10840 uint8 msg
= CanUnequipItem( src
, !IsBagPos ( src
) || IsBagPos ( dst
) || pDstItem
&& pDstItem
->IsBag() && ((Bag
*)pDstItem
)->IsEmpty());
10841 if(msg
!= EQUIP_ERR_OK
)
10843 SendEquipError( msg
, pSrcItem
, pDstItem
);
10848 // prevent put equipped/bank bag in self
10849 if( IsBagPos ( src
) && srcslot
== dstbag
)
10851 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
10859 if(pDstItem
->m_lootGenerated
) // prevent swap looting item
10861 //best error message found for attempting to swap while looting
10862 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pDstItem
, NULL
);
10866 // check unequip potability for equipped items and bank bags
10867 if(IsEquipmentPos ( dst
) || IsBagPos ( dst
))
10869 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10870 uint8 msg
= CanUnequipItem( dst
, !IsBagPos ( dst
) || IsBagPos ( src
) || pSrcItem
->IsBag() && ((Bag
*)pSrcItem
)->IsEmpty());
10871 if(msg
!= EQUIP_ERR_OK
)
10873 SendEquipError( msg
, pSrcItem
, pDstItem
);
10879 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
10880 // or swap empty bag with another empty or not empty bag (with items exchange)
10885 if( IsInventoryPos( dst
) )
10887 ItemPosCountVec dest
;
10888 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pSrcItem
, false );
10889 if( msg
!= EQUIP_ERR_OK
)
10891 SendEquipError( msg
, pSrcItem
, NULL
);
10895 RemoveItem(srcbag
, srcslot
, true);
10896 StoreItem( dest
, pSrcItem
, true);
10898 else if( IsBankPos ( dst
) )
10900 ItemPosCountVec dest
;
10901 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pSrcItem
, false);
10902 if( msg
!= EQUIP_ERR_OK
)
10904 SendEquipError( msg
, pSrcItem
, NULL
);
10908 RemoveItem(srcbag
, srcslot
, true);
10909 BankItem( dest
, pSrcItem
, true);
10911 else if( IsEquipmentPos ( dst
) )
10914 uint8 msg
= CanEquipItem( dstslot
, dest
, pSrcItem
, false );
10915 if( msg
!= EQUIP_ERR_OK
)
10917 SendEquipError( msg
, pSrcItem
, NULL
);
10921 RemoveItem(srcbag
, srcslot
, true);
10922 EquipItem( dest
, pSrcItem
, true);
10923 AutoUnequipOffhandIfNeed();
10929 // attempt merge to / fill target item
10930 if(!pSrcItem
->IsBag() && !pDstItem
->IsBag())
10933 ItemPosCountVec sDest
;
10935 if( IsInventoryPos( dst
) )
10936 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
10937 else if( IsBankPos ( dst
) )
10938 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
10939 else if( IsEquipmentPos ( dst
) )
10940 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, false );
10944 // can be merge/fill
10945 if(msg
== EQUIP_ERR_OK
)
10947 if( pSrcItem
->GetCount() + pDstItem
->GetCount() <= pSrcItem
->GetProto()->GetMaxStackSize())
10949 RemoveItem(srcbag
, srcslot
, true);
10951 if( IsInventoryPos( dst
) )
10952 StoreItem( sDest
, pSrcItem
, true);
10953 else if( IsBankPos ( dst
) )
10954 BankItem( sDest
, pSrcItem
, true);
10955 else if( IsEquipmentPos ( dst
) )
10957 EquipItem( eDest
, pSrcItem
, true);
10958 AutoUnequipOffhandIfNeed();
10963 pSrcItem
->SetCount( pSrcItem
->GetCount() + pDstItem
->GetCount() - pSrcItem
->GetProto()->GetMaxStackSize());
10964 pDstItem
->SetCount( pSrcItem
->GetProto()->GetMaxStackSize());
10965 pSrcItem
->SetState(ITEM_CHANGED
, this);
10966 pDstItem
->SetState(ITEM_CHANGED
, this);
10969 pSrcItem
->SendUpdateToPlayer( this );
10970 pDstItem
->SendUpdateToPlayer( this );
10977 // impossible merge/fill, do real swap
10980 // check src->dest move possibility
10981 ItemPosCountVec sDest
;
10983 if( IsInventoryPos( dst
) )
10984 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
10985 else if( IsBankPos( dst
) )
10986 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
10987 else if( IsEquipmentPos( dst
) )
10989 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, true );
10990 if( msg
== EQUIP_ERR_OK
)
10991 msg
= CanUnequipItem( eDest
, true );
10994 if( msg
!= EQUIP_ERR_OK
)
10996 SendEquipError( msg
, pSrcItem
, pDstItem
);
11000 // check dest->src move possibility
11001 ItemPosCountVec sDest2
;
11003 if( IsInventoryPos( src
) )
11004 msg
= CanStoreItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11005 else if( IsBankPos( src
) )
11006 msg
= CanBankItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11007 else if( IsEquipmentPos( src
) )
11009 msg
= CanEquipItem( srcslot
, eDest2
, pDstItem
, true);
11010 if( msg
== EQUIP_ERR_OK
)
11011 msg
= CanUnequipItem( eDest2
, true);
11014 if( msg
!= EQUIP_ERR_OK
)
11016 SendEquipError( msg
, pDstItem
, pSrcItem
);
11020 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11021 if(pSrcItem
->IsBag() && pDstItem
->IsBag())
11023 Bag
* emptyBag
= NULL
;
11024 Bag
* fullBag
= NULL
;
11025 if(((Bag
*)pSrcItem
)->IsEmpty() && !IsBagPos(src
))
11027 emptyBag
= (Bag
*)pSrcItem
;
11028 fullBag
= (Bag
*)pDstItem
;
11030 else if(((Bag
*)pDstItem
)->IsEmpty() && !IsBagPos(dst
))
11032 emptyBag
= (Bag
*)pDstItem
;
11033 fullBag
= (Bag
*)pSrcItem
;
11036 // bag swap (with items exchange) case
11037 if(emptyBag
&& fullBag
)
11039 ItemPrototype
const* emotyProto
= emptyBag
->GetProto();
11043 for(int i
=0; i
< fullBag
->GetBagSize(); ++i
)
11045 Item
*bagItem
= fullBag
->GetItemByPos(i
);
11049 ItemPrototype
const* bagItemProto
= bagItem
->GetProto();
11050 if (!bagItemProto
|| !ItemCanGoIntoBag(bagItemProto
, emotyProto
))
11052 // one from items not go to empry target bag
11053 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
11061 if (count
> emptyBag
->GetBagSize())
11063 // too small targeted bag
11064 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
, pSrcItem
, pDstItem
);
11069 count
= 0; // will pos in new bag
11070 for(int i
=0; i
< fullBag
->GetBagSize(); ++i
)
11072 Item
*bagItem
= fullBag
->GetItemByPos(i
);
11076 fullBag
->RemoveItem(i
, true);
11077 emptyBag
->StoreItem(count
, bagItem
, true);
11078 bagItem
->SetState(ITEM_CHANGED
, this);
11085 // now do moves, remove...
11086 RemoveItem(dstbag
, dstslot
, false);
11087 RemoveItem(srcbag
, srcslot
, false);
11090 if( IsInventoryPos( dst
) )
11091 StoreItem(sDest
, pSrcItem
, true);
11092 else if( IsBankPos( dst
) )
11093 BankItem(sDest
, pSrcItem
, true);
11094 else if( IsEquipmentPos( dst
) )
11095 EquipItem(eDest
, pSrcItem
, true);
11098 if( IsInventoryPos( src
) )
11099 StoreItem(sDest2
, pDstItem
, true);
11100 else if( IsBankPos( src
) )
11101 BankItem(sDest2
, pDstItem
, true);
11102 else if( IsEquipmentPos( src
) )
11103 EquipItem(eDest2
, pDstItem
, true);
11105 AutoUnequipOffhandIfNeed();
11108 void Player::AddItemToBuyBackSlot( Item
*pItem
)
11112 uint32 slot
= m_currentBuybackSlot
;
11113 // if current back slot non-empty search oldest or free
11116 uint32 oldest_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
);
11117 uint32 oldest_slot
= BUYBACK_SLOT_START
;
11119 for(uint32 i
= BUYBACK_SLOT_START
+1; i
< BUYBACK_SLOT_END
; ++i
)
11128 uint32 i_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ i
- BUYBACK_SLOT_START
);
11130 if(oldest_time
> i_time
)
11132 oldest_time
= i_time
;
11138 slot
= oldest_slot
;
11141 RemoveItemFromBuyBackSlot( slot
, true );
11142 sLog
.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem
->GetEntry(), slot
);
11144 m_items
[slot
] = pItem
;
11145 time_t base
= time(NULL
);
11146 uint32 etime
= uint32(base
- m_logintime
+ (30 * 3600));
11147 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11149 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ eslot
* 2, pItem
->GetGUID() );
11150 ItemPrototype
const *pProto
= pItem
->GetProto();
11152 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, pProto
->SellPrice
* pItem
->GetCount() );
11154 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11155 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, (uint32
)etime
);
11157 // move to next (for non filled list is move most optimized choice)
11158 if(m_currentBuybackSlot
< BUYBACK_SLOT_END
-1)
11159 ++m_currentBuybackSlot
;
11163 Item
* Player::GetItemFromBuyBackSlot( uint32 slot
)
11165 sLog
.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot
);
11166 if( slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11167 return m_items
[slot
];
11171 void Player::RemoveItemFromBuyBackSlot( uint32 slot
, bool del
)
11173 sLog
.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot
);
11174 if( slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11176 Item
*pItem
= m_items
[slot
];
11179 pItem
->RemoveFromWorld();
11180 if(del
) pItem
->SetState(ITEM_REMOVED
, this);
11183 m_items
[slot
] = NULL
;
11185 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11186 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ eslot
* 2, 0 );
11187 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11188 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, 0 );
11190 // if current backslot is filled set to now free slot
11191 if(m_items
[m_currentBuybackSlot
])
11192 m_currentBuybackSlot
= slot
;
11196 void Player::SendEquipError( uint8 msg
, Item
* pItem
, Item
*pItem2
)
11198 sLog
.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg
);
11199 WorldPacket
data( SMSG_INVENTORY_CHANGE_FAILURE
, (msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
? 22 : 18) );
11200 data
<< uint8(msg
);
11204 data
<< uint64(pItem
? pItem
->GetGUID() : 0);
11205 data
<< uint64(pItem2
? pItem2
->GetGUID() : 0);
11206 data
<< uint8(0); // not 0 there...
11208 if(msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
)
11213 if(ItemPrototype
const* proto
= pItem
->GetProto())
11214 level
= proto
->RequiredLevel
;
11216 data
<< uint32(level
); // new 2.4.0
11219 GetSession()->SendPacket(&data
);
11222 void Player::SendBuyError( uint8 msg
, Creature
* pCreature
, uint32 item
, uint32 param
)
11224 sLog
.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11225 WorldPacket
data( SMSG_BUY_FAILED
, (8+4+4+1) );
11226 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11227 data
<< uint32(item
);
11229 data
<< uint32(param
);
11230 data
<< uint8(msg
);
11231 GetSession()->SendPacket(&data
);
11234 void Player::SendSellError( uint8 msg
, Creature
* pCreature
, uint64 guid
, uint32 param
)
11236 sLog
.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11237 WorldPacket
data( SMSG_SELL_ITEM
,(8+8+(param
?4:0)+1)); // last check 2.0.10
11238 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11239 data
<< uint64(guid
);
11241 data
<< uint32(param
);
11242 data
<< uint8(msg
);
11243 GetSession()->SendPacket(&data
);
11246 void Player::ClearTrade()
11249 acceptTrade
= false;
11250 for(int i
= 0; i
< TRADE_SLOT_COUNT
; ++i
)
11251 tradeItems
[i
] = NULL_SLOT
;
11254 void Player::TradeCancel(bool sendback
)
11258 // send yellow "Trade canceled" message to both traders
11262 ws
->SendCancelTrade();
11263 ws
= pTrader
->GetSession();
11264 if(!ws
->PlayerLogout())
11265 ws
->SendCancelTrade();
11269 pTrader
->ClearTrade();
11270 // prevent loss of reference
11271 pTrader
->pTrader
= NULL
;
11276 void Player::UpdateItemDuration(uint32 time
, bool realtimeonly
)
11278 if(m_itemDuration
.empty())
11281 sLog
.outDebug("Player::UpdateItemDuration(%u,%u)", time
,realtimeonly
);
11283 for(ItemDurationList::const_iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); )
11286 ++itr
; // current element can be erased in UpdateDuration
11288 if (realtimeonly
&& item
->GetProto()->Duration
< 0 || !realtimeonly
)
11289 item
->UpdateDuration(this,time
);
11293 void Player::UpdateEnchantTime(uint32 time
)
11295 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11299 if(!itr
->item
->GetEnchantmentId(itr
->slot
))
11301 next
= m_enchantDuration
.erase(itr
);
11303 else if(itr
->leftduration
<= time
)
11305 ApplyEnchantment(itr
->item
,itr
->slot
,false,false);
11306 itr
->item
->ClearEnchantment(itr
->slot
);
11307 next
= m_enchantDuration
.erase(itr
);
11309 else if(itr
->leftduration
> time
)
11311 itr
->leftduration
-= time
;
11317 void Player::AddEnchantmentDurations(Item
*item
)
11319 for(int x
=0;x
<MAX_ENCHANTMENT_SLOT
;++x
)
11321 if(!item
->GetEnchantmentId(EnchantmentSlot(x
)))
11324 uint32 duration
= item
->GetEnchantmentDuration(EnchantmentSlot(x
));
11326 AddEnchantmentDuration(item
,EnchantmentSlot(x
),duration
);
11330 void Player::RemoveEnchantmentDurations(Item
*item
)
11332 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();)
11334 if(itr
->item
== item
)
11336 // save duration in item
11337 item
->SetEnchantmentDuration(EnchantmentSlot(itr
->slot
),itr
->leftduration
);
11338 itr
= m_enchantDuration
.erase(itr
);
11345 void Player::RemoveAllEnchantments(EnchantmentSlot slot
)
11347 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11348 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11351 if(itr
->slot
==slot
)
11353 if(itr
->item
&& itr
->item
->GetEnchantmentId(slot
))
11355 // remove from stats
11356 ApplyEnchantment(itr
->item
,slot
,false,false);
11358 itr
->item
->ClearEnchantment(slot
);
11360 // remove from update list
11361 next
= m_enchantDuration
.erase(itr
);
11367 // remove enchants from inventory items
11368 // NOTE: no need to remove these from stats, since these aren't equipped
11370 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
11372 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11373 if( pItem
&& pItem
->GetEnchantmentId(slot
) )
11374 pItem
->ClearEnchantment(slot
);
11377 // in inventory bags
11378 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
11380 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11383 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
11385 Item
* pItem
= pBag
->GetItemByPos(j
);
11386 if( pItem
&& pItem
->GetEnchantmentId(slot
) )
11387 pItem
->ClearEnchantment(slot
);
11393 // duration == 0 will remove item enchant
11394 void Player::AddEnchantmentDuration(Item
*item
,EnchantmentSlot slot
,uint32 duration
)
11399 if(slot
>= MAX_ENCHANTMENT_SLOT
)
11402 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
11404 if(itr
->item
== item
&& itr
->slot
== slot
)
11406 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
11407 m_enchantDuration
.erase(itr
);
11411 if(item
&& duration
> 0 )
11413 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item
->GetGUID(),slot
,uint32(duration
/1000));
11414 m_enchantDuration
.push_back(EnchantDuration(item
,slot
,duration
));
11418 void Player::ApplyEnchantment(Item
*item
,bool apply
)
11420 for(uint32 slot
= 0; slot
< MAX_ENCHANTMENT_SLOT
; ++slot
)
11421 ApplyEnchantment(item
, EnchantmentSlot(slot
), apply
);
11424 void Player::ApplyEnchantment(Item
*item
,EnchantmentSlot slot
,bool apply
, bool apply_dur
, bool ignore_condition
)
11429 if(!item
->IsEquipped())
11432 if(slot
>= MAX_ENCHANTMENT_SLOT
)
11435 uint32 enchant_id
= item
->GetEnchantmentId(slot
);
11439 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
11443 if(!ignore_condition
&& pEnchant
->EnchantmentCondition
&& !((Player
*)this)->EnchantmentFitsRequirements(pEnchant
->EnchantmentCondition
, -1))
11446 if (!item
->IsBroken())
11448 for (int s
=0; s
<3; s
++)
11450 uint32 enchant_display_type
= pEnchant
->type
[s
];
11451 uint32 enchant_amount
= pEnchant
->amount
[s
];
11452 uint32 enchant_spell_id
= pEnchant
->spellid
[s
];
11454 switch(enchant_display_type
)
11456 case ITEM_ENCHANTMENT_TYPE_NONE
:
11458 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
:
11459 // processed in Player::CastItemCombatSpell
11461 case ITEM_ENCHANTMENT_TYPE_DAMAGE
:
11462 if (item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
11463 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11464 else if (item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
11465 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11466 else if (item
->GetSlot() == EQUIPMENT_SLOT_RANGED
)
11467 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11469 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL
:
11470 if(enchant_spell_id
)
11474 int32 basepoints
= 0;
11475 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11476 if (item
->GetItemRandomPropertyId())
11478 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11481 // Search enchant_amount
11482 for (int k
=0; k
<3; k
++)
11484 if(item_rand
->enchant_id
[k
] == enchant_id
)
11486 basepoints
= int32((item_rand
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11492 // Cast custom spell vs all equal basepoints getted from enchant_amount
11494 CastCustomSpell(this,enchant_spell_id
,&basepoints
,&basepoints
,&basepoints
,true,item
);
11496 CastSpell(this,enchant_spell_id
,true,item
);
11499 RemoveAurasDueToItemSpell(item
,enchant_spell_id
);
11502 case ITEM_ENCHANTMENT_TYPE_RESISTANCE
:
11503 if (!enchant_amount
)
11505 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11508 for (int k
=0; k
<3; k
++)
11510 if(item_rand
->enchant_id
[k
] == enchant_id
)
11512 enchant_amount
= uint32((item_rand
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11519 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START
+ enchant_spell_id
), TOTAL_VALUE
, float(enchant_amount
), apply
);
11521 case ITEM_ENCHANTMENT_TYPE_STAT
:
11523 if (!enchant_amount
)
11525 ItemRandomSuffixEntry
const *item_rand_suffix
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11526 if(item_rand_suffix
)
11528 for (int k
=0; k
<3; k
++)
11530 if(item_rand_suffix
->enchant_id
[k
] == enchant_id
)
11532 enchant_amount
= uint32((item_rand_suffix
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11539 sLog
.outDebug("Adding %u to stat nb %u",enchant_amount
,enchant_spell_id
);
11540 switch (enchant_spell_id
)
11542 case ITEM_MOD_AGILITY
:
11543 sLog
.outDebug("+ %u AGILITY",enchant_amount
);
11544 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11545 ApplyStatBuffMod(STAT_AGILITY
, enchant_amount
, apply
);
11547 case ITEM_MOD_STRENGTH
:
11548 sLog
.outDebug("+ %u STRENGTH",enchant_amount
);
11549 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11550 ApplyStatBuffMod(STAT_STRENGTH
, enchant_amount
, apply
);
11552 case ITEM_MOD_INTELLECT
:
11553 sLog
.outDebug("+ %u INTELLECT",enchant_amount
);
11554 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11555 ApplyStatBuffMod(STAT_INTELLECT
, enchant_amount
, apply
);
11557 case ITEM_MOD_SPIRIT
:
11558 sLog
.outDebug("+ %u SPIRIT",enchant_amount
);
11559 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11560 ApplyStatBuffMod(STAT_SPIRIT
, enchant_amount
, apply
);
11562 case ITEM_MOD_STAMINA
:
11563 sLog
.outDebug("+ %u STAMINA",enchant_amount
);
11564 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11565 ApplyStatBuffMod(STAT_STAMINA
, enchant_amount
, apply
);
11567 case ITEM_MOD_DEFENSE_SKILL_RATING
:
11568 ((Player
*)this)->ApplyRatingMod(CR_DEFENSE_SKILL
, enchant_amount
, apply
);
11569 sLog
.outDebug("+ %u DEFENCE", enchant_amount
);
11571 case ITEM_MOD_DODGE_RATING
:
11572 ((Player
*)this)->ApplyRatingMod(CR_DODGE
, enchant_amount
, apply
);
11573 sLog
.outDebug("+ %u DODGE", enchant_amount
);
11575 case ITEM_MOD_PARRY_RATING
:
11576 ((Player
*)this)->ApplyRatingMod(CR_PARRY
, enchant_amount
, apply
);
11577 sLog
.outDebug("+ %u PARRY", enchant_amount
);
11579 case ITEM_MOD_BLOCK_RATING
:
11580 ((Player
*)this)->ApplyRatingMod(CR_BLOCK
, enchant_amount
, apply
);
11581 sLog
.outDebug("+ %u SHIELD_BLOCK", enchant_amount
);
11583 case ITEM_MOD_HIT_MELEE_RATING
:
11584 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
11585 sLog
.outDebug("+ %u MELEE_HIT", enchant_amount
);
11587 case ITEM_MOD_HIT_RANGED_RATING
:
11588 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
11589 sLog
.outDebug("+ %u RANGED_HIT", enchant_amount
);
11591 case ITEM_MOD_HIT_SPELL_RATING
:
11592 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
11593 sLog
.outDebug("+ %u SPELL_HIT", enchant_amount
);
11595 case ITEM_MOD_CRIT_MELEE_RATING
:
11596 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
11597 sLog
.outDebug("+ %u MELEE_CRIT", enchant_amount
);
11599 case ITEM_MOD_CRIT_RANGED_RATING
:
11600 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
11601 sLog
.outDebug("+ %u RANGED_CRIT", enchant_amount
);
11603 case ITEM_MOD_CRIT_SPELL_RATING
:
11604 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
11605 sLog
.outDebug("+ %u SPELL_CRIT", enchant_amount
);
11607 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11609 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11610 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11612 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11613 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11615 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11616 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11618 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11619 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11621 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11622 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11624 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11625 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11627 // case ITEM_MOD_HASTE_MELEE_RATING:
11628 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11630 // case ITEM_MOD_HASTE_RANGED_RATING:
11631 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11633 case ITEM_MOD_HASTE_SPELL_RATING
:
11634 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
11636 case ITEM_MOD_HIT_RATING
:
11637 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
11638 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
11639 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
11640 sLog
.outDebug("+ %u HIT", enchant_amount
);
11642 case ITEM_MOD_CRIT_RATING
:
11643 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
11644 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
11645 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
11646 sLog
.outDebug("+ %u CRITICAL", enchant_amount
);
11648 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11649 // case ITEM_MOD_HIT_TAKEN_RATING:
11650 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11651 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11652 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11654 // case ITEM_MOD_CRIT_TAKEN_RATING:
11655 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11656 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11657 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11659 case ITEM_MOD_RESILIENCE_RATING
:
11660 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, enchant_amount
, apply
);
11661 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, enchant_amount
, apply
);
11662 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, enchant_amount
, apply
);
11663 sLog
.outDebug("+ %u RESILIENCE", enchant_amount
);
11665 case ITEM_MOD_HASTE_RATING
:
11666 ((Player
*)this)->ApplyRatingMod(CR_HASTE_MELEE
, enchant_amount
, apply
);
11667 ((Player
*)this)->ApplyRatingMod(CR_HASTE_RANGED
, enchant_amount
, apply
);
11668 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
11669 sLog
.outDebug("+ %u HASTE", enchant_amount
);
11671 case ITEM_MOD_EXPERTISE_RATING
:
11672 ((Player
*)this)->ApplyRatingMod(CR_EXPERTISE
, enchant_amount
, apply
);
11673 sLog
.outDebug("+ %u EXPERTISE", enchant_amount
);
11675 case ITEM_MOD_ATTACK_POWER
:
11676 HandleStatModifier(UNIT_MOD_ATTACK_POWER
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11677 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11678 sLog
.outDebug("+ %u ATTACK_POWER", enchant_amount
);
11680 case ITEM_MOD_RANGED_ATTACK_POWER
:
11681 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11682 sLog
.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount
);
11684 case ITEM_MOD_FERAL_ATTACK_POWER
:
11685 ((Player
*)this)->ApplyFeralAPBonus(enchant_amount
, apply
);
11686 sLog
.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount
);
11688 case ITEM_MOD_SPELL_HEALING_DONE
:
11689 ((Player
*)this)->ApplySpellHealingBonus(enchant_amount
, apply
);
11690 sLog
.outDebug("+ %u SPELL_HEALING_DONE", enchant_amount
);
11692 case ITEM_MOD_SPELL_DAMAGE_DONE
:
11693 ((Player
*)this)->ApplySpellDamageBonus(enchant_amount
, apply
);
11694 sLog
.outDebug("+ %u SPELL_DAMAGE_DONE", enchant_amount
);
11696 case ITEM_MOD_MANA_REGENERATION
:
11697 ((Player
*)this)->ApplyManaRegenBonus(enchant_amount
, apply
);
11698 sLog
.outDebug("+ %u MANA_REGENERATION", enchant_amount
);
11700 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
11701 ((Player
*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION
, enchant_amount
, apply
);
11702 sLog
.outDebug("+ %u ARMOR PENETRATION", enchant_amount
);
11704 case ITEM_MOD_SPELL_POWER
:
11705 ((Player
*)this)->ApplySpellHealingBonus(enchant_amount
, apply
);
11706 ((Player
*)this)->ApplySpellDamageBonus(enchant_amount
, apply
);
11707 sLog
.outDebug("+ %u SPELL_POWER", enchant_amount
);
11714 case ITEM_ENCHANTMENT_TYPE_TOTEM
: // Shaman Rockbiter Weapon
11716 if(getClass() == CLASS_SHAMAN
)
11718 float addValue
= 0.0f
;
11719 if(item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
11721 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/1000.0f
);
11722 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, addValue
, apply
);
11724 else if(item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
11726 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/1000.0f
);
11727 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, addValue
, apply
);
11732 case ITEM_ENCHANTMENT_TYPE_USE_SPELL
:
11733 // processed in Player::CastItemUseSpell
11735 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET
:
11739 sLog
.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id
, enchant_display_type
);
11741 } /*switch(enchant_display_type)*/
11745 // visualize enchantment at player and equipped items
11746 if(slot
< MAX_INSPECTED_ENCHANTMENT_SLOT
)
11748 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (item
->GetSlot() * MAX_VISIBLE_ITEM_OFFSET
);
11749 SetUInt32Value(VisibleBase
+ 1 + slot
, apply
? item
->GetEnchantmentId(slot
) : 0);
11757 uint32 duration
= item
->GetEnchantmentDuration(slot
);
11759 AddEnchantmentDuration(item
,slot
,duration
);
11763 // duration == 0 will remove EnchantDuration
11764 AddEnchantmentDuration(item
,slot
,0);
11769 void Player::SendEnchantmentDurations()
11771 for(EnchantDurationList::const_iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
11773 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr
->item
->GetGUID(),itr
->slot
,uint32(itr
->leftduration
)/1000);
11777 void Player::SendItemDurations()
11779 for(ItemDurationList::const_iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end();++itr
)
11781 (*itr
)->SendTimeUpdate(this);
11785 void Player::SendNewItem(Item
*item
, uint32 count
, bool received
, bool created
, bool broadcast
)
11787 if(!item
) // prevent crash
11790 // last check 2.0.10
11791 WorldPacket
data( SMSG_ITEM_PUSH_RESULT
, (8+4+4+4+1+4+4+4+4+4) );
11792 data
<< GetGUID(); // player GUID
11793 data
<< uint32(received
); // 0=looted, 1=from npc
11794 data
<< uint32(created
); // 0=received, 1=created
11795 data
<< uint32(1); // always 0x01 (probably meant to be count of listed items)
11796 data
<< (uint8
)item
->GetBagSlot(); // bagslot
11797 // item slot, but when added to stack: 0xFFFFFFFF
11798 data
<< (uint32
) ((item
->GetCount()==count
) ? item
->GetSlot() : -1);
11799 data
<< uint32(item
->GetEntry()); // item id
11800 data
<< uint32(item
->GetItemSuffixFactor()); // SuffixFactor
11801 data
<< uint32(item
->GetItemRandomPropertyId()); // random item property id
11802 data
<< uint32(count
); // count of items
11803 data
<< GetItemCount(item
->GetEntry()); // count of items in inventory
11805 if (broadcast
&& GetGroup())
11806 GetGroup()->BroadcastPacket(&data
, true);
11808 GetSession()->SendPacket(&data
);
11811 /*********************************************************/
11812 /*** QUEST SYSTEM ***/
11813 /*********************************************************/
11815 void Player::PrepareQuestMenu( uint64 guid
)
11818 QuestRelations
* pObjectQR
;
11819 QuestRelations
* pObjectQIR
;
11821 // pets also can have quests
11822 Creature
*pCreature
= ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid
);
11825 pObject
= (Object
*)pCreature
;
11826 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
11827 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
11831 GameObject
*pGameObject
= GetMap()->GetGameObject(guid
);
11834 pObject
= (Object
*)pGameObject
;
11835 pObjectQR
= &objmgr
.mGOQuestRelations
;
11836 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
11842 QuestMenu
&qm
= PlayerTalkClass
->GetQuestMenu();
11845 for(QuestRelations::const_iterator i
= pObjectQIR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQIR
->upper_bound(pObject
->GetEntry()); ++i
)
11847 uint32 quest_id
= i
->second
;
11848 QuestStatus status
= GetQuestStatus( quest_id
);
11849 if ( status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus( quest_id
) )
11850 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_REWARD_REP
);
11851 else if ( status
== QUEST_STATUS_INCOMPLETE
)
11852 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_INCOMPLETE
);
11853 else if (status
== QUEST_STATUS_AVAILABLE
)
11854 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_CHAT
);
11857 for(QuestRelations::const_iterator i
= pObjectQR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++i
)
11859 uint32 quest_id
= i
->second
;
11860 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
11861 if(!pQuest
) continue;
11863 QuestStatus status
= GetQuestStatus( quest_id
);
11865 if (pQuest
->IsAutoComplete() && CanTakeQuest(pQuest
, false))
11866 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_REWARD_REP
);
11867 else if ( status
== QUEST_STATUS_NONE
&& CanTakeQuest( pQuest
, false ) )
11868 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_AVAILABLE
);
11872 void Player::SendPreparedQuest( uint64 guid
)
11874 QuestMenu
& questMenu
= PlayerTalkClass
->GetQuestMenu();
11875 if( questMenu
.Empty() )
11878 QuestMenuItem
const& qmi0
= questMenu
.GetItem( 0 );
11880 uint32 status
= qmi0
.m_qIcon
;
11882 // single element case
11883 if ( questMenu
.MenuItemCount() == 1 )
11885 // Auto open -- maybe also should verify there is no greeting
11886 uint32 quest_id
= qmi0
.m_qId
;
11887 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
11890 if( status
== DIALOG_STATUS_REWARD_REP
&& !GetQuestRewardStatus( quest_id
) )
11891 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, CanRewardQuest(pQuest
,false), true );
11892 else if( status
== DIALOG_STATUS_INCOMPLETE
)
11893 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, false, true );
11894 // Send completable on repeatable quest if player don't have quest
11895 else if( pQuest
->IsRepeatable() && !pQuest
->IsDaily() )
11896 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, CanCompleteRepeatableQuest(pQuest
), true );
11898 PlayerTalkClass
->SendQuestGiverQuestDetails( pQuest
, guid
, true );
11901 // multiply entries
11907 std::string title
= "";
11909 // need pet case for some quests
11910 Creature
*pCreature
= ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid
);
11913 uint32 textid
= pCreature
->GetNpcTextId();
11914 GossipText
const* gossiptext
= objmgr
.GetGossipText(textid
);
11917 qe
._Delay
= 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
11918 qe
._Emote
= 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
11923 qe
= gossiptext
->Options
[0].Emotes
[0];
11925 if(!gossiptext
->Options
[0].Text_0
.empty())
11927 title
= gossiptext
->Options
[0].Text_0
;
11929 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
11932 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
11935 if (nl
->Text_0
[0].size() > loc_idx
&& !nl
->Text_0
[0][loc_idx
].empty())
11936 title
= nl
->Text_0
[0][loc_idx
];
11942 title
= gossiptext
->Options
[0].Text_1
;
11944 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
11947 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
11950 if (nl
->Text_1
[0].size() > loc_idx
&& !nl
->Text_1
[0][loc_idx
].empty())
11951 title
= nl
->Text_1
[0][loc_idx
];
11957 PlayerTalkClass
->SendQuestGiverQuestList( qe
, title
, guid
);
11961 bool Player::IsActiveQuest( uint32 quest_id
) const
11963 QuestStatusMap::const_iterator itr
= mQuestStatus
.find(quest_id
);
11965 return itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
;
11968 Quest
const * Player::GetNextQuest( uint64 guid
, Quest
const *pQuest
)
11971 QuestRelations
* pObjectQR
;
11972 QuestRelations
* pObjectQIR
;
11974 Creature
*pCreature
= ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid
);
11977 pObject
= (Object
*)pCreature
;
11978 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
11979 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
11983 GameObject
*pGameObject
= GetMap()->GetGameObject(guid
);
11986 pObject
= (Object
*)pGameObject
;
11987 pObjectQR
= &objmgr
.mGOQuestRelations
;
11988 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
11994 uint32 nextQuestID
= pQuest
->GetNextQuestInChain();
11995 for(QuestRelations::const_iterator itr
= pObjectQR
->lower_bound(pObject
->GetEntry()); itr
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++itr
)
11997 if (itr
->second
== nextQuestID
)
11998 return objmgr
.GetQuestTemplate(nextQuestID
);
12004 bool Player::CanSeeStartQuest( Quest
const *pQuest
)
12006 if( SatisfyQuestRace( pQuest
, false ) && SatisfyQuestSkillOrClass( pQuest
, false ) &&
12007 SatisfyQuestExclusiveGroup( pQuest
, false ) && SatisfyQuestReputation( pQuest
, false ) &&
12008 SatisfyQuestPreviousQuest( pQuest
, false ) && SatisfyQuestNextChain( pQuest
, false ) &&
12009 SatisfyQuestPrevChain( pQuest
, false ) && SatisfyQuestDay( pQuest
, false ) )
12011 return getLevel() + sWorld
.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF
) >= pQuest
->GetMinLevel();
12017 bool Player::CanTakeQuest( Quest
const *pQuest
, bool msg
)
12019 return SatisfyQuestStatus( pQuest
, msg
) && SatisfyQuestExclusiveGroup( pQuest
, msg
)
12020 && SatisfyQuestRace( pQuest
, msg
) && SatisfyQuestLevel( pQuest
, msg
)
12021 && SatisfyQuestSkillOrClass( pQuest
, msg
) && SatisfyQuestReputation( pQuest
, msg
)
12022 && SatisfyQuestPreviousQuest( pQuest
, msg
) && SatisfyQuestTimed( pQuest
, msg
)
12023 && SatisfyQuestNextChain( pQuest
, msg
) && SatisfyQuestPrevChain( pQuest
, msg
)
12024 && SatisfyQuestDay( pQuest
, msg
);
12027 bool Player::CanAddQuest( Quest
const *pQuest
, bool msg
)
12029 if( !SatisfyQuestLog( msg
) )
12032 uint32 srcitem
= pQuest
->GetSrcItemId();
12035 uint32 count
= pQuest
->GetSrcItemCount();
12036 ItemPosCountVec dest
;
12037 uint8 msg2
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
12039 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12040 if( msg2
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
12042 else if( msg2
!= EQUIP_ERR_OK
)
12044 SendEquipError( msg2
, NULL
, NULL
);
12051 bool Player::CanCompleteQuest( uint32 quest_id
)
12055 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12056 if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
12057 return false; // not allow re-complete quest
12059 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12064 // auto complete quest
12065 if (qInfo
->IsAutoComplete() && CanTakeQuest(qInfo
, false))
12068 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
12071 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12073 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12075 if( qInfo
->ReqItemCount
[i
]!= 0 && q_status
.m_itemcount
[i
] < qInfo
->ReqItemCount
[i
] )
12080 if ( qInfo
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
12082 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12084 if( qInfo
->ReqCreatureOrGOId
[i
] == 0 )
12087 if( qInfo
->ReqCreatureOrGOCount
[i
] != 0 && q_status
.m_creatureOrGOcount
[i
] < qInfo
->ReqCreatureOrGOCount
[i
] )
12092 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT
) && !q_status
.m_explored
)
12095 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && q_status
.m_timer
== 0 )
12098 if ( qInfo
->GetRewOrReqMoney() < 0 )
12100 if ( GetMoney() < uint32(-qInfo
->GetRewOrReqMoney()) )
12104 uint32 repFacId
= qInfo
->GetRepObjectiveFaction();
12105 if ( repFacId
&& GetReputationMgr().GetReputation(repFacId
) < qInfo
->GetRepObjectiveValue() )
12114 bool Player::CanCompleteRepeatableQuest( Quest
const *pQuest
)
12116 // Solve problem that player don't have the quest and try complete it.
12117 // if repeatable she must be able to complete event if player don't have it.
12118 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12119 if( !CanTakeQuest(pQuest
, false) )
12122 if (pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12123 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12124 if( pQuest
->ReqItemId
[i
] && pQuest
->ReqItemCount
[i
] && !HasItemCount(pQuest
->ReqItemId
[i
],pQuest
->ReqItemCount
[i
]) )
12127 if( !CanRewardQuest(pQuest
, false) )
12133 bool Player::CanRewardQuest( Quest
const *pQuest
, bool msg
)
12135 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12136 if(!pQuest
->IsAutoComplete() && GetQuestStatus(pQuest
->GetQuestId()) != QUEST_STATUS_COMPLETE
)
12139 // daily quest can't be rewarded (25 daily quest already completed)
12140 if(!SatisfyQuestDay(pQuest
,true))
12143 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12144 if(GetQuestRewardStatus(pQuest
->GetQuestId()))
12147 // prevent receive reward with quest items in bank
12148 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12150 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12152 if( pQuest
->ReqItemCount
[i
]!= 0 &&
12153 GetItemCount(pQuest
->ReqItemId
[i
]) < pQuest
->ReqItemCount
[i
] )
12156 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, NULL
, NULL
);
12162 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12163 if(pQuest
->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest
->GetRewOrReqMoney()) )
12169 bool Player::CanRewardQuest( Quest
const *pQuest
, uint32 reward
, bool msg
)
12171 // prevent receive reward with quest items in bank or for not completed quest
12172 if(!CanRewardQuest(pQuest
,msg
))
12175 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
12177 if( pQuest
->RewChoiceItemId
[reward
] )
12179 ItemPosCountVec dest
;
12180 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] );
12181 if( res
!= EQUIP_ERR_OK
)
12183 SendEquipError( res
, NULL
, NULL
);
12189 if ( pQuest
->GetRewItemsCount() > 0 )
12191 for (uint32 i
= 0; i
< pQuest
->GetRewItemsCount(); ++i
)
12193 if( pQuest
->RewItemId
[i
] )
12195 ItemPosCountVec dest
;
12196 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] );
12197 if( res
!= EQUIP_ERR_OK
)
12199 SendEquipError( res
, NULL
, NULL
);
12209 void Player::AddQuest( Quest
const *pQuest
, Object
*questGiver
)
12211 uint16 log_slot
= FindQuestSlot( 0 );
12212 assert(log_slot
< MAX_QUEST_LOG_SIZE
);
12214 uint32 quest_id
= pQuest
->GetQuestId();
12216 // if not exist then created with set uState==NEW and rewarded=false
12217 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
12219 // check for repeatable quests status reset
12220 questStatusData
.m_status
= QUEST_STATUS_INCOMPLETE
;
12221 questStatusData
.m_explored
= false;
12223 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12225 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12226 questStatusData
.m_itemcount
[i
] = 0;
12229 if ( pQuest
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
12231 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12232 questStatusData
.m_creatureOrGOcount
[i
] = 0;
12235 GiveQuestSourceItem( pQuest
);
12236 AdjustQuestReqItemCount( pQuest
, questStatusData
);
12238 if( pQuest
->GetRepObjectiveFaction() )
12239 if(FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(pQuest
->GetRepObjectiveFaction()))
12240 GetReputationMgr().SetVisible(factionEntry
);
12243 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
12245 uint32 limittime
= pQuest
->GetLimitTime();
12247 // shared timed quest
12248 if(questGiver
&& questGiver
->GetTypeId()==TYPEID_PLAYER
)
12249 limittime
= ((Player
*)questGiver
)->getQuestStatusMap()[quest_id
].m_timer
/ IN_MILISECONDS
;
12251 AddTimedQuest( quest_id
);
12252 questStatusData
.m_timer
= limittime
* IN_MILISECONDS
;
12253 qtime
= static_cast<uint32
>(time(NULL
)) + limittime
;
12256 questStatusData
.m_timer
= 0;
12258 SetQuestSlot(log_slot
, quest_id
, qtime
);
12260 if (questStatusData
.uState
!= QUEST_NEW
)
12261 questStatusData
.uState
= QUEST_CHANGED
;
12263 //starting initial quest script
12264 if(questGiver
&& pQuest
->GetQuestStartScript()!=0)
12265 sWorld
.ScriptsStart(sQuestStartScripts
, pQuest
->GetQuestStartScript(), questGiver
, this);
12267 // Some spells applied at quest activation
12268 SpellAreaForQuestMapBounds saBounds
= spellmgr
.GetSpellAreaForQuestMapBounds(quest_id
,true);
12269 if(saBounds
.first
!= saBounds
.second
)
12272 GetZoneAndAreaId(zone
,area
);
12274 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
12275 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,zone
,area
))
12276 if( !HasAura(itr
->second
->spellId
,0) )
12277 CastSpell(this,itr
->second
->spellId
,true);
12280 UpdateForQuestsGO();
12283 void Player::CompleteQuest( uint32 quest_id
)
12287 SetQuestStatus( quest_id
, QUEST_STATUS_COMPLETE
);
12289 uint16 log_slot
= FindQuestSlot( quest_id
);
12290 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12291 SetQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
12293 if(Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
))
12295 if( qInfo
->HasFlag(QUEST_FLAGS_AUTO_REWARDED
) )
12296 RewardQuest(qInfo
,0,this,false);
12298 SendQuestComplete( quest_id
);
12303 void Player::IncompleteQuest( uint32 quest_id
)
12307 SetQuestStatus( quest_id
, QUEST_STATUS_INCOMPLETE
);
12309 uint16 log_slot
= FindQuestSlot( quest_id
);
12310 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12311 RemoveQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
12315 void Player::RewardQuest( Quest
const *pQuest
, uint32 reward
, Object
* questGiver
, bool announce
)
12317 uint32 quest_id
= pQuest
->GetQuestId();
12319 for (int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12321 if ( pQuest
->ReqItemId
[i
] )
12322 DestroyItemCount( pQuest
->ReqItemId
[i
], pQuest
->ReqItemCount
[i
], true);
12325 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12326 // SetTimedQuest( 0 );
12327 m_timedquests
.erase(pQuest
->GetQuestId());
12329 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
12331 if( pQuest
->RewChoiceItemId
[reward
] )
12333 ItemPosCountVec dest
;
12334 if( CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] ) == EQUIP_ERR_OK
)
12336 Item
* item
= StoreNewItem( dest
, pQuest
->RewChoiceItemId
[reward
], true);
12337 SendNewItem(item
, pQuest
->RewChoiceItemCount
[reward
], true, false);
12342 if ( pQuest
->GetRewItemsCount() > 0 )
12344 for (uint32 i
=0; i
< pQuest
->GetRewItemsCount(); ++i
)
12346 if( pQuest
->RewItemId
[i
] )
12348 ItemPosCountVec dest
;
12349 if( CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] ) == EQUIP_ERR_OK
)
12351 Item
* item
= StoreNewItem( dest
, pQuest
->RewItemId
[i
], true);
12352 SendNewItem(item
, pQuest
->RewItemCount
[i
], true, false);
12358 RewardReputation( pQuest
);
12360 if( pQuest
->GetRewSpellCast() > 0 )
12361 CastSpell( this, pQuest
->GetRewSpellCast(), true);
12362 else if( pQuest
->GetRewSpell() > 0)
12363 CastSpell( this, pQuest
->GetRewSpell(), true);
12365 uint16 log_slot
= FindQuestSlot( quest_id
);
12366 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12367 SetQuestSlot(log_slot
,0);
12369 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12371 // Not give XP in case already completed once repeatable quest
12372 uint32 XP
= q_status
.m_rewarded
? 0 : uint32(pQuest
->XPValue( this )*sWorld
.getRate(RATE_XP_QUEST
));
12374 if ( getLevel() < sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
12375 GiveXP( XP
, NULL
);
12378 uint32 money
= uint32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getRate(RATE_DROP_MONEY
));
12379 ModifyMoney( money
);
12380 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD
, money
);
12383 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12384 if(pQuest
->GetRewOrReqMoney())
12386 ModifyMoney( pQuest
->GetRewOrReqMoney() );
12388 if(pQuest
->GetRewOrReqMoney() > 0)
12389 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD
, pQuest
->GetRewOrReqMoney());
12393 if(pQuest
->GetRewHonorableKills())
12394 RewardHonor(NULL
, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorableKills()));
12397 if(pQuest
->GetCharTitleId())
12399 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
12400 SetTitle(titleEntry
);
12403 if(pQuest
->GetBonusTalents())
12405 m_questRewardTalentCount
+=pQuest
->GetBonusTalents();
12406 InitTalentForLevel();
12409 // Send reward mail
12410 if(pQuest
->GetRewMailTemplateId())
12412 MailMessageType mailType
;
12413 uint32 senderGuidOrEntry
;
12414 switch(questGiver
->GetTypeId())
12417 mailType
= MAIL_CREATURE
;
12418 senderGuidOrEntry
= questGiver
->GetEntry();
12420 case TYPEID_GAMEOBJECT
:
12421 mailType
= MAIL_GAMEOBJECT
;
12422 senderGuidOrEntry
= questGiver
->GetEntry();
12425 mailType
= MAIL_ITEM
;
12426 senderGuidOrEntry
= questGiver
->GetEntry();
12428 case TYPEID_PLAYER
:
12429 mailType
= MAIL_NORMAL
;
12430 senderGuidOrEntry
= questGiver
->GetGUIDLow();
12433 mailType
= MAIL_NORMAL
;
12434 senderGuidOrEntry
= GetGUIDLow();
12438 Loot questMailLoot
;
12440 questMailLoot
.FillLoot(pQuest
->GetQuestId(), LootTemplates_QuestMail
, this,true);
12443 MailItemsInfo mi
; // item list preparing
12445 uint32 max_slot
= questMailLoot
.GetMaxSlotInLootFor(this);
12446 for(uint32 i
= 0; mi
.size() < MAX_MAIL_ITEMS
&& i
< max_slot
; ++i
)
12448 if(LootItem
* lootitem
= questMailLoot
.LootItemInSlot(i
,this))
12450 if(Item
* item
= Item::CreateItem(lootitem
->itemid
,lootitem
->count
,this))
12452 item
->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12453 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
12458 WorldSession::SendMailTo(this, mailType
, MAIL_STATIONERY_NORMAL
, senderGuidOrEntry
, GetGUIDLow(), "", 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
,pQuest
->GetRewMailDelaySecs(),pQuest
->GetRewMailTemplateId());
12461 if(pQuest
->IsDaily())
12463 SetDailyQuestStatus(quest_id
);
12464 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST
, 1);
12467 if ( !pQuest
->IsRepeatable() )
12468 SetQuestStatus(quest_id
, QUEST_STATUS_COMPLETE
);
12470 SetQuestStatus(quest_id
, QUEST_STATUS_NONE
);
12472 q_status
.m_rewarded
= true;
12475 SendQuestReward( pQuest
, XP
, questGiver
);
12477 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12478 if (pQuest
->GetZoneOrSort() > 0)
12479 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE
, pQuest
->GetZoneOrSort());
12480 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT
);
12481 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST
, pQuest
->GetQuestId());
12486 // remove auras from spells with quest reward state limitations
12487 SpellAreaForQuestMapBounds saEndBounds
= spellmgr
.GetSpellAreaForQuestEndMapBounds(quest_id
);
12488 if(saEndBounds
.first
!= saEndBounds
.second
)
12490 GetZoneAndAreaId(zone
,area
);
12492 for(SpellAreaForAreaMap::const_iterator itr
= saEndBounds
.first
; itr
!= saEndBounds
.second
; ++itr
)
12493 if(!itr
->second
->IsFitToRequirements(this,zone
,area
))
12494 RemoveAurasDueToSpell(itr
->second
->spellId
);
12497 // Some spells applied at quest reward
12498 SpellAreaForQuestMapBounds saBounds
= spellmgr
.GetSpellAreaForQuestMapBounds(quest_id
,false);
12499 if(saBounds
.first
!= saBounds
.second
)
12502 GetZoneAndAreaId(zone
,area
);
12504 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
12505 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,zone
,area
))
12506 if( !HasAura(itr
->second
->spellId
,0) )
12507 CastSpell(this,itr
->second
->spellId
,true);
12511 void Player::FailQuest( uint32 quest_id
)
12515 IncompleteQuest( quest_id
);
12517 uint16 log_slot
= FindQuestSlot( quest_id
);
12518 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12520 SetQuestSlotTimer(log_slot
, 1 );
12521 SetQuestSlotState(log_slot
,QUEST_STATE_FAIL
);
12523 SendQuestFailed( quest_id
);
12527 void Player::FailTimedQuest( uint32 quest_id
)
12531 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12533 q_status
.m_timer
= 0;
12534 if (q_status
.uState
!= QUEST_NEW
)
12535 q_status
.uState
= QUEST_CHANGED
;
12537 IncompleteQuest( quest_id
);
12539 uint16 log_slot
= FindQuestSlot( quest_id
);
12540 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12542 SetQuestSlotTimer(log_slot
, 1 );
12543 SetQuestSlotState(log_slot
,QUEST_STATE_FAIL
);
12545 SendQuestTimerFailed( quest_id
);
12549 bool Player::SatisfyQuestSkillOrClass( Quest
const* qInfo
, bool msg
)
12551 int32 zoneOrSort
= qInfo
->GetZoneOrSort();
12552 int32 skillOrClass
= qInfo
->GetSkillOrClass();
12554 // skip zone zoneOrSort and 0 case skillOrClass
12555 if( zoneOrSort
>= 0 && skillOrClass
== 0 )
12558 int32 questSort
= -zoneOrSort
;
12559 uint8 reqSortClass
= ClassByQuestSort(questSort
);
12561 // check class sort cases in zoneOrSort
12562 if( reqSortClass
!= 0 && getClass() != reqSortClass
)
12565 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12570 if( skillOrClass
< 0 )
12572 uint8 reqClass
= -int32(skillOrClass
);
12573 if(getClass() != reqClass
)
12576 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12581 else if( skillOrClass
> 0 )
12583 uint32 reqSkill
= skillOrClass
;
12584 if( GetSkillValue( reqSkill
) < qInfo
->GetRequiredSkillValue() )
12587 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12595 bool Player::SatisfyQuestLevel( Quest
const* qInfo
, bool msg
)
12597 if( getLevel() < qInfo
->GetMinLevel() )
12600 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12606 bool Player::SatisfyQuestLog( bool msg
)
12609 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE
)
12614 WorldPacket
data( SMSG_QUESTLOG_FULL
, 0 );
12615 GetSession()->SendPacket( &data
);
12616 sLog
.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12621 bool Player::SatisfyQuestPreviousQuest( Quest
const* qInfo
, bool msg
)
12623 // No previous quest (might be first quest in a series)
12624 if( qInfo
->prevQuests
.empty())
12627 for(Quest::PrevQuests::const_iterator iter
= qInfo
->prevQuests
.begin(); iter
!= qInfo
->prevQuests
.end(); ++iter
)
12629 uint32 prevId
= abs(*iter
);
12631 QuestStatusMap::const_iterator i_prevstatus
= mQuestStatus
.find( prevId
);
12632 Quest
const* qPrevInfo
= objmgr
.GetQuestTemplate(prevId
);
12634 if( qPrevInfo
&& i_prevstatus
!= mQuestStatus
.end() )
12636 // If any of the positive previous quests completed, return true
12637 if( *iter
> 0 && i_prevstatus
->second
.m_rewarded
)
12639 // skip one-from-all exclusive group
12640 if(qPrevInfo
->GetExclusiveGroup() >= 0)
12643 // each-from-all exclusive group ( < 0)
12644 // can be start if only all quests in prev quest exclusive group completed and rewarded
12645 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
12646 ObjectMgr::ExclusiveQuestGroups::const_iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
12648 assert(iter2
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
12650 for(; iter2
!= end
; ++iter2
)
12652 uint32 exclude_Id
= iter2
->second
;
12654 // skip checked quest id, only state of other quests in group is interesting
12655 if(exclude_Id
== prevId
)
12658 QuestStatusMap::const_iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12660 // alternative quest from group also must be completed and rewarded(reported)
12661 if( i_exstatus
== mQuestStatus
.end() || !i_exstatus
->second
.m_rewarded
)
12664 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12670 // If any of the negative previous quests active, return true
12671 if( *iter
< 0 && (i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
12672 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
))))
12674 // skip one-from-all exclusive group
12675 if(qPrevInfo
->GetExclusiveGroup() >= 0)
12678 // each-from-all exclusive group ( < 0)
12679 // can be start if only all quests in prev quest exclusive group active
12680 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
12681 ObjectMgr::ExclusiveQuestGroups::const_iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
12683 assert(iter2
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
12685 for(; iter2
!= end
; ++iter2
)
12687 uint32 exclude_Id
= iter2
->second
;
12689 // skip checked quest id, only state of other quests in group is interesting
12690 if(exclude_Id
== prevId
)
12693 QuestStatusMap::const_iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12695 // alternative quest from group also must be active
12696 if( i_exstatus
== mQuestStatus
.end() ||
12697 i_exstatus
->second
.m_status
!= QUEST_STATUS_INCOMPLETE
&&
12698 (i_prevstatus
->second
.m_status
!= QUEST_STATUS_COMPLETE
|| GetQuestRewardStatus(prevId
)) )
12701 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12710 // Has only positive prev. quests in non-rewarded state
12711 // and negative prev. quests in non-active state
12713 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12718 bool Player::SatisfyQuestRace( Quest
const* qInfo
, bool msg
)
12720 uint32 reqraces
= qInfo
->GetRequiredRaces();
12721 if ( reqraces
== 0 )
12723 if( (reqraces
& getRaceMask()) == 0 )
12726 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE
);
12732 bool Player::SatisfyQuestReputation( Quest
const* qInfo
, bool msg
)
12734 uint32 fIdMin
= qInfo
->GetRequiredMinRepFaction(); //Min required rep
12735 if(fIdMin
&& GetReputationMgr().GetReputation(fIdMin
) < qInfo
->GetRequiredMinRepValue())
12738 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12742 uint32 fIdMax
= qInfo
->GetRequiredMaxRepFaction(); //Max required rep
12743 if(fIdMax
&& GetReputationMgr().GetReputation(fIdMax
) >= qInfo
->GetRequiredMaxRepValue())
12746 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12753 bool Player::SatisfyQuestStatus( Quest
const* qInfo
, bool msg
)
12755 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( qInfo
->GetQuestId() );
12756 if ( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
)
12759 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON
);
12765 bool Player::SatisfyQuestTimed( Quest
const* qInfo
, bool msg
)
12767 if ( (find(m_timedquests
.begin(), m_timedquests
.end(), qInfo
->GetQuestId()) != m_timedquests
.end()) && qInfo
->HasFlag(QUEST_MANGOS_FLAGS_TIMED
) )
12770 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED
);
12776 bool Player::SatisfyQuestExclusiveGroup( Quest
const* qInfo
, bool msg
)
12778 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12779 if(qInfo
->GetExclusiveGroup() <= 0)
12782 ObjectMgr::ExclusiveQuestGroups::const_iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qInfo
->GetExclusiveGroup());
12783 ObjectMgr::ExclusiveQuestGroups::const_iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qInfo
->GetExclusiveGroup());
12785 assert(iter
!=end
); // always must be found if qInfo->ExclusiveGroup != 0
12787 for(; iter
!= end
; ++iter
)
12789 uint32 exclude_Id
= iter
->second
;
12791 // skip checked quest id, only state of other quests in group is interesting
12792 if(exclude_Id
== qInfo
->GetQuestId())
12795 // not allow have daily quest if daily quest from exclusive group already recently completed
12796 Quest
const* Nquest
= objmgr
.GetQuestTemplate(exclude_Id
);
12797 if( !SatisfyQuestDay(Nquest
, false) )
12800 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12804 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12806 // alternative quest already started or completed
12807 if( i_exstatus
!= mQuestStatus
.end()
12808 && (i_exstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
|| i_exstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
12811 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12818 bool Player::SatisfyQuestNextChain( Quest
const* qInfo
, bool msg
)
12820 if(!qInfo
->GetNextQuestInChain())
12823 // next quest in chain already started or completed
12824 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( qInfo
->GetNextQuestInChain() );
12825 if( itr
!= mQuestStatus
.end()
12826 && (itr
->second
.m_status
== QUEST_STATUS_COMPLETE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
12829 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12833 // check for all quests further up the chain
12834 // only necessary if there are quest chains with more than one quest that can be skipped
12835 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12839 bool Player::SatisfyQuestPrevChain( Quest
const* qInfo
, bool msg
)
12841 // No previous quest in chain
12842 if( qInfo
->prevChainQuests
.empty())
12845 for(Quest::PrevChainQuests::const_iterator iter
= qInfo
->prevChainQuests
.begin(); iter
!= qInfo
->prevChainQuests
.end(); ++iter
)
12847 uint32 prevId
= *iter
;
12849 QuestStatusMap::const_iterator i_prevstatus
= mQuestStatus
.find( prevId
);
12851 if( i_prevstatus
!= mQuestStatus
.end() )
12853 // If any of the previous quests in chain active, return false
12854 if( i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
12855 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
)))
12858 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12863 // check for all quests further down the chain
12864 // only necessary if there are quest chains with more than one quest that can be skipped
12865 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12869 // No previous quest in chain active
12873 bool Player::SatisfyQuestDay( Quest
const* qInfo
, bool msg
)
12875 if(!qInfo
->IsDaily())
12878 bool have_slot
= false;
12879 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
12881 uint32 id
= GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
);
12882 if(qInfo
->GetQuestId()==id
)
12892 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING
);
12899 bool Player::GiveQuestSourceItem( Quest
const *pQuest
)
12901 uint32 srcitem
= pQuest
->GetSrcItemId();
12904 uint32 count
= pQuest
->GetSrcItemCount();
12908 ItemPosCountVec dest
;
12909 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
12910 if( msg
== EQUIP_ERR_OK
)
12912 Item
* item
= StoreNewItem(dest
, srcitem
, true);
12913 SendNewItem(item
, count
, true, false);
12916 // player already have max amount required item, just report success
12917 else if( msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
12920 SendEquipError( msg
, NULL
, NULL
);
12927 bool Player::TakeQuestSourceItem( uint32 quest_id
, bool msg
)
12929 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12932 uint32 srcitem
= qInfo
->GetSrcItemId();
12935 uint32 count
= qInfo
->GetSrcItemCount();
12939 // exist one case when destroy source quest item not possible:
12940 // non un-equippable item (equipped non-empty bag, for example)
12941 uint8 res
= CanUnequipItems(srcitem
,count
);
12942 if(res
!= EQUIP_ERR_OK
)
12945 SendEquipError( res
, NULL
, NULL
);
12949 DestroyItemCount(srcitem
, count
, true, true);
12955 bool Player::GetQuestRewardStatus( uint32 quest_id
) const
12957 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12960 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
12961 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
12962 if( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
12963 && !qInfo
->IsRepeatable() )
12964 return itr
->second
.m_rewarded
;
12971 QuestStatus
Player::GetQuestStatus( uint32 quest_id
) const
12975 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
12976 if( itr
!= mQuestStatus
.end() )
12977 return itr
->second
.m_status
;
12979 return QUEST_STATUS_NONE
;
12982 bool Player::CanShareQuest(uint32 quest_id
) const
12984 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12985 if( qInfo
&& qInfo
->HasFlag(QUEST_FLAGS_SHARABLE
) )
12987 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
12988 if( itr
!= mQuestStatus
.end() )
12989 return itr
->second
.m_status
== QUEST_STATUS_NONE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
;
12994 void Player::SetQuestStatus( uint32 quest_id
, QuestStatus status
)
12996 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12999 if( status
== QUEST_STATUS_NONE
|| status
== QUEST_STATUS_INCOMPLETE
|| status
== QUEST_STATUS_COMPLETE
)
13001 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
13002 m_timedquests
.erase(qInfo
->GetQuestId());
13005 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
13007 q_status
.m_status
= status
;
13008 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13011 UpdateForQuestsGO();
13014 // not used in MaNGOS, but used in scripting code
13015 uint32
Player::GetReqKillOrCastCurrentCount(uint32 quest_id
, int32 entry
)
13017 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13021 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13022 if ( qInfo
->ReqCreatureOrGOId
[j
] == entry
)
13023 return mQuestStatus
[quest_id
].m_creatureOrGOcount
[j
];
13028 void Player::AdjustQuestReqItemCount( Quest
const* pQuest
, QuestStatusData
& questStatusData
)
13030 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13032 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
13034 uint32 reqitemcount
= pQuest
->ReqItemCount
[i
];
13035 if( reqitemcount
!= 0 )
13037 uint32 curitemcount
= GetItemCount(pQuest
->ReqItemId
[i
],true);
13039 questStatusData
.m_itemcount
[i
] = std::min(curitemcount
, reqitemcount
);
13040 if (questStatusData
.uState
!= QUEST_NEW
) questStatusData
.uState
= QUEST_CHANGED
;
13046 uint16
Player::FindQuestSlot( uint32 quest_id
) const
13048 for ( uint16 i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13049 if ( GetQuestSlotQuestId(i
) == quest_id
)
13052 return MAX_QUEST_LOG_SIZE
;
13055 void Player::AreaExploredOrEventHappens( uint32 questId
)
13059 uint16 log_slot
= FindQuestSlot( questId
);
13060 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13062 QuestStatusData
& q_status
= mQuestStatus
[questId
];
13064 if(!q_status
.m_explored
)
13066 q_status
.m_explored
= true;
13067 if (q_status
.uState
!= QUEST_NEW
)
13068 q_status
.uState
= QUEST_CHANGED
;
13071 if( CanCompleteQuest( questId
) )
13072 CompleteQuest( questId
);
13076 //not used in mangosd, function for external script library
13077 void Player::GroupEventHappens( uint32 questId
, WorldObject
const* pEventObject
)
13079 if( Group
*pGroup
= GetGroup() )
13081 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
13083 Player
*pGroupGuy
= itr
->getSource();
13085 // for any leave or dead (with not released body) group member at appropriate distance
13086 if( pGroupGuy
&& pGroupGuy
->IsAtGroupRewardDistance(pEventObject
) && !pGroupGuy
->GetCorpse() )
13087 pGroupGuy
->AreaExploredOrEventHappens(questId
);
13091 AreaExploredOrEventHappens(questId
);
13094 void Player::ItemAddedQuestCheck( uint32 entry
, uint32 count
)
13096 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13098 uint32 questid
= GetQuestSlotQuestId(i
);
13099 if ( questid
== 0 )
13102 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13104 if ( q_status
.m_status
!= QUEST_STATUS_INCOMPLETE
)
13107 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13108 if( !qInfo
|| !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13111 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13113 uint32 reqitem
= qInfo
->ReqItemId
[j
];
13114 if ( reqitem
== entry
)
13116 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
13117 uint32 curitemcount
= q_status
.m_itemcount
[j
];
13118 if ( curitemcount
< reqitemcount
)
13120 uint32 additemcount
= ( curitemcount
+ count
<= reqitemcount
? count
: reqitemcount
- curitemcount
);
13121 q_status
.m_itemcount
[j
] += additemcount
;
13122 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13124 SendQuestUpdateAddItem( qInfo
, j
, additemcount
);
13126 if ( CanCompleteQuest( questid
) )
13127 CompleteQuest( questid
);
13132 UpdateForQuestsGO();
13135 void Player::ItemRemovedQuestCheck( uint32 entry
, uint32 count
)
13137 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13139 uint32 questid
= GetQuestSlotQuestId(i
);
13142 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13145 if( !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13148 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13150 uint32 reqitem
= qInfo
->ReqItemId
[j
];
13151 if ( reqitem
== entry
)
13153 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13155 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
13156 uint32 curitemcount
;
13157 if( q_status
.m_status
!= QUEST_STATUS_COMPLETE
)
13158 curitemcount
= q_status
.m_itemcount
[j
];
13160 curitemcount
= GetItemCount(entry
,true);
13161 if ( curitemcount
< reqitemcount
+ count
)
13163 uint32 remitemcount
= ( curitemcount
<= reqitemcount
? count
: count
+ reqitemcount
- curitemcount
);
13164 q_status
.m_itemcount
[j
] = curitemcount
- remitemcount
;
13165 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13167 IncompleteQuest( questid
);
13173 UpdateForQuestsGO();
13176 void Player::KilledMonster( uint32 entry
, uint64 guid
)
13178 uint32 addkillcount
= 1;
13179 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE
, entry
, addkillcount
);
13180 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13182 uint32 questid
= GetQuestSlotQuestId(i
);
13186 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13189 // just if !ingroup || !noraidgroup || raidgroup
13190 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13191 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
&& (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo
->GetType() == QUEST_TYPE_RAID
))
13193 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
13195 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13197 // skip GO activate objective or none
13198 if(qInfo
->ReqCreatureOrGOId
[j
] <=0)
13201 // skip Cast at creature objective
13202 if(qInfo
->ReqSpell
[j
] !=0 )
13205 uint32 reqkill
= qInfo
->ReqCreatureOrGOId
[j
];
13207 if ( reqkill
== entry
)
13209 uint32 reqkillcount
= qInfo
->ReqCreatureOrGOCount
[j
];
13210 uint32 curkillcount
= q_status
.m_creatureOrGOcount
[j
];
13211 if ( curkillcount
< reqkillcount
)
13213 q_status
.m_creatureOrGOcount
[j
] = curkillcount
+ addkillcount
;
13214 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13216 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curkillcount
, addkillcount
);
13218 if ( CanCompleteQuest( questid
) )
13219 CompleteQuest( questid
);
13221 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13230 void Player::CastedCreatureOrGO( uint32 entry
, uint64 guid
, uint32 spell_id
)
13232 bool isCreature
= IS_CREATURE_GUID(guid
);
13234 uint32 addCastCount
= 1;
13235 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13237 uint32 questid
= GetQuestSlotQuestId(i
);
13241 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13245 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13247 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13249 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
13251 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13253 // skip kill creature objective (0) or wrong spell casts
13254 if(qInfo
->ReqSpell
[j
] != spell_id
)
13257 uint32 reqTarget
= 0;
13261 // creature activate objectives
13262 if(qInfo
->ReqCreatureOrGOId
[j
] > 0)
13263 // checked at quest_template loading
13264 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
13268 // GO activate objective
13269 if(qInfo
->ReqCreatureOrGOId
[j
] < 0)
13270 // checked at quest_template loading
13271 reqTarget
= - qInfo
->ReqCreatureOrGOId
[j
];
13274 // other not this creature/GO related objectives
13275 if( reqTarget
!= entry
)
13278 uint32 reqCastCount
= qInfo
->ReqCreatureOrGOCount
[j
];
13279 uint32 curCastCount
= q_status
.m_creatureOrGOcount
[j
];
13280 if ( curCastCount
< reqCastCount
)
13282 q_status
.m_creatureOrGOcount
[j
] = curCastCount
+ addCastCount
;
13283 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13285 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curCastCount
, addCastCount
);
13288 if ( CanCompleteQuest( questid
) )
13289 CompleteQuest( questid
);
13291 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13299 void Player::TalkedToCreature( uint32 entry
, uint64 guid
)
13301 uint32 addTalkCount
= 1;
13302 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13304 uint32 questid
= GetQuestSlotQuestId(i
);
13308 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13312 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13314 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13316 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
13318 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13320 // skip spell casts and Gameobject objectives
13321 if(qInfo
->ReqSpell
[j
] > 0 || qInfo
->ReqCreatureOrGOId
[j
] < 0)
13324 uint32 reqTarget
= 0;
13326 if(qInfo
->ReqCreatureOrGOId
[j
] > 0) // creature activate objectives
13327 // checked at quest_template loading
13328 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
13332 if ( reqTarget
== entry
)
13334 uint32 reqTalkCount
= qInfo
->ReqCreatureOrGOCount
[j
];
13335 uint32 curTalkCount
= q_status
.m_creatureOrGOcount
[j
];
13336 if ( curTalkCount
< reqTalkCount
)
13338 q_status
.m_creatureOrGOcount
[j
] = curTalkCount
+ addTalkCount
;
13339 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13341 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curTalkCount
, addTalkCount
);
13343 if ( CanCompleteQuest( questid
) )
13344 CompleteQuest( questid
);
13346 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13355 void Player::MoneyChanged( uint32 count
)
13357 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13359 uint32 questid
= GetQuestSlotQuestId(i
);
13363 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13364 if( qInfo
&& qInfo
->GetRewOrReqMoney() < 0 )
13366 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13368 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13370 if(int32(count
) >= -qInfo
->GetRewOrReqMoney())
13372 if ( CanCompleteQuest( questid
) )
13373 CompleteQuest( questid
);
13376 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
13378 if(int32(count
) < -qInfo
->GetRewOrReqMoney())
13379 IncompleteQuest( questid
);
13385 void Player::ReputationChanged(FactionEntry
const* factionEntry
)
13387 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13389 if(uint32 questid
= GetQuestSlotQuestId(i
))
13391 if(Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
))
13393 if(qInfo
->GetRepObjectiveFaction() == factionEntry
->ID
)
13395 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13396 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13398 if(GetReputationMgr().GetReputation(factionEntry
) >= qInfo
->GetRepObjectiveValue())
13399 if ( CanCompleteQuest( questid
) )
13400 CompleteQuest( questid
);
13402 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
13404 if(GetReputationMgr().GetReputation(factionEntry
) < qInfo
->GetRepObjectiveValue())
13405 IncompleteQuest( questid
);
13413 bool Player::HasQuestForItem( uint32 itemid
) const
13415 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13417 uint32 questid
= GetQuestSlotQuestId(i
);
13418 if ( questid
== 0 )
13421 QuestStatusMap::const_iterator qs_itr
= mQuestStatus
.find(questid
);
13422 if(qs_itr
== mQuestStatus
.end())
13425 QuestStatusData
const& q_status
= qs_itr
->second
;
13427 if (q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13429 Quest
const* qinfo
= objmgr
.GetQuestTemplate(questid
);
13433 // hide quest if player is in raid-group and quest is no raid quest
13434 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
13437 // There should be no mixed ReqItem/ReqSource drop
13438 // This part for ReqItem drop
13439 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13441 if(itemid
== qinfo
->ReqItemId
[j
] && q_status
.m_itemcount
[j
] < qinfo
->ReqItemCount
[j
] )
13444 // This part - for ReqSource
13445 for (int j
= 0; j
< QUEST_SOURCE_ITEM_IDS_COUNT
; ++j
)
13447 // examined item is a source item
13448 if (qinfo
->ReqSourceId
[j
] == itemid
)
13450 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(itemid
);
13453 if (pProto
->MaxCount
&& GetItemCount(itemid
,true) < pProto
->MaxCount
)
13456 // allows custom amount drop when not 0
13457 if (qinfo
->ReqSourceCount
[j
])
13459 if (GetItemCount(itemid
,true) < qinfo
->ReqSourceCount
[j
])
13461 } else if (GetItemCount(itemid
,true) < pProto
->Stackable
)
13470 void Player::SendQuestComplete( uint32 quest_id
)
13474 WorldPacket
data( SMSG_QUESTUPDATE_COMPLETE
, 4 );
13475 data
<< uint32(quest_id
);
13476 GetSession()->SendPacket( &data
);
13477 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id
);
13481 void Player::SendQuestReward( Quest
const *pQuest
, uint32 XP
, Object
* questGiver
)
13483 uint32 questid
= pQuest
->GetQuestId();
13484 sLog
.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid
);
13485 WorldPacket
data( SMSG_QUESTGIVER_QUEST_COMPLETE
, (4+4+4+4+4) );
13486 data
<< uint32(questid
);
13488 if ( getLevel() < sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
13490 data
<< uint32(XP
);
13491 data
<< uint32(pQuest
->GetRewOrReqMoney());
13496 data
<< uint32(pQuest
->GetRewOrReqMoney() + int32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getRate(RATE_DROP_MONEY
)));
13499 data
<< uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorableKills()));
13500 data
<< uint32(pQuest
->GetBonusTalents()); // bonus talents
13501 GetSession()->SendPacket( &data
);
13503 if (pQuest
->GetQuestCompleteScript() != 0)
13504 sWorld
.ScriptsStart(sQuestEndScripts
, pQuest
->GetQuestCompleteScript(), questGiver
, this);
13507 void Player::SendQuestFailed( uint32 quest_id
)
13511 WorldPacket
data( SMSG_QUESTGIVER_QUEST_FAILED
, 4+4 );
13513 data
<< uint32(0); // failed reason (4 for inventory is full)
13514 GetSession()->SendPacket( &data
);
13515 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13519 void Player::SendQuestTimerFailed( uint32 quest_id
)
13523 WorldPacket
data( SMSG_QUESTUPDATE_FAILEDTIMER
, 4 );
13525 GetSession()->SendPacket( &data
);
13526 sLog
.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13530 void Player::SendCanTakeQuestResponse( uint32 msg
)
13532 WorldPacket
data( SMSG_QUESTGIVER_QUEST_INVALID
, 4 );
13533 data
<< uint32(msg
);
13534 GetSession()->SendPacket( &data
);
13535 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13538 void Player::SendPushToPartyResponse( Player
*pPlayer
, uint32 msg
)
13542 WorldPacket
data( MSG_QUEST_PUSH_RESULT
, (8+1) );
13543 data
<< uint64(pPlayer
->GetGUID());
13544 data
<< uint8(msg
); // valid values: 0-8
13545 GetSession()->SendPacket( &data
);
13546 sLog
.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13550 void Player::SendQuestUpdateAddItem( Quest
const* pQuest
, uint32 item_idx
, uint32 count
)
13552 WorldPacket
data( SMSG_QUESTUPDATE_ADD_ITEM
, 0 );
13553 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13554 //data << pQuest->ReqItemId[item_idx];
13556 GetSession()->SendPacket( &data
);
13559 void Player::SendQuestUpdateAddCreatureOrGo( Quest
const* pQuest
, uint64 guid
, uint32 creatureOrGO_idx
, uint32 old_count
, uint32 add_count
)
13561 assert(old_count
+ add_count
< 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13563 int32 entry
= pQuest
->ReqCreatureOrGOId
[ creatureOrGO_idx
];
13565 // client expected gameobject template id in form (id|0x80000000)
13566 entry
= (-entry
) | 0x80000000;
13568 WorldPacket
data( SMSG_QUESTUPDATE_ADD_KILL
, (4*4+8) );
13569 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13570 data
<< uint32(pQuest
->GetQuestId());
13571 data
<< uint32(entry
);
13572 data
<< uint32(old_count
+ add_count
);
13573 data
<< uint32(pQuest
->ReqCreatureOrGOCount
[ creatureOrGO_idx
]);
13574 data
<< uint64(guid
);
13575 GetSession()->SendPacket(&data
);
13577 uint16 log_slot
= FindQuestSlot( pQuest
->GetQuestId() );
13578 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13579 SetQuestSlotCounter(log_slot
,creatureOrGO_idx
,GetQuestSlotCounter(log_slot
,creatureOrGO_idx
)+add_count
);
13582 /*********************************************************/
13583 /*** LOAD SYSTEM ***/
13584 /*********************************************************/
13586 bool Player::MinimalLoadFromDB( QueryResult
*result
, uint32 guid
)
13588 bool delete_result
= true;
13591 // 0 1 2 3 4 5 6 7 8 9
13592 result
= CharacterDatabase
.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid
);
13593 if(!result
) return false;
13595 else delete_result
= false;
13597 Field
*fields
= result
->Fetch();
13599 if(!LoadValues( fields
[1].GetString()))
13601 sLog
.outError("Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid
));
13602 if(delete_result
) delete result
;
13606 // overwrite possible wrong/corrupted guid
13607 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
13609 m_name
= fields
[2].GetCppString();
13611 Relocate(fields
[3].GetFloat(),fields
[4].GetFloat(),fields
[5].GetFloat());
13612 SetMapId(fields
[6].GetUInt32());
13613 // the instance id is not needed at character enum
13615 m_Played_time
[0] = fields
[7].GetUInt32();
13616 m_Played_time
[1] = fields
[8].GetUInt32();
13618 m_atLoginFlags
= fields
[9].GetUInt32();
13620 // I don't see these used anywhere ..
13623 _LoadBoundInstances();*/
13625 if (delete_result
) delete result
;
13627 for (int i
= 0; i
< PLAYER_SLOTS_COUNT
; ++i
)
13630 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
13631 m_deathState
= DEAD
;
13636 void Player::_LoadDeclinedNames(QueryResult
* result
)
13642 delete m_declinedname
;
13644 m_declinedname
= new DeclinedName
;
13645 Field
*fields
= result
->Fetch();
13646 for(int i
= 0; i
< MAX_DECLINED_NAME_CASES
; ++i
)
13647 m_declinedname
->name
[i
] = fields
[i
].GetCppString();
13652 void Player::_LoadArenaTeamInfo(QueryResult
*result
)
13654 // arenateamid, played_week, played_season, personal_rating
13655 memset((void*)&m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
], 0, sizeof(uint32
)*18);
13661 Field
*fields
= result
->Fetch();
13663 uint32 arenateamid
= fields
[0].GetUInt32();
13664 uint32 played_week
= fields
[1].GetUInt32();
13665 uint32 played_season
= fields
[2].GetUInt32();
13666 uint32 personal_rating
= fields
[3].GetUInt32();
13668 ArenaTeam
* aTeam
= objmgr
.GetArenaTeamById(arenateamid
);
13671 sLog
.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid
, played_week
, played_season
, personal_rating
);
13674 uint8 arenaSlot
= aTeam
->GetSlot();
13676 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6] = arenateamid
; // TeamID
13677 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 1] = ((aTeam
->GetCaptain() == GetGUID()) ? (uint32
)0 : (uint32
)1); // Captain 0, member 1
13678 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 2] = played_week
; // Played Week
13679 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 3] = played_season
; // Played Season
13680 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 4] = 0; // Unk
13681 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 5] = personal_rating
; // Personal Rating
13683 }while (result
->NextRow());
13687 bool Player::LoadPositionFromDB(uint32
& mapid
, float& x
,float& y
,float& z
,float& o
, bool& in_flight
, uint64 guid
)
13689 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid
));
13693 Field
*fields
= result
->Fetch();
13695 x
= fields
[0].GetFloat();
13696 y
= fields
[1].GetFloat();
13697 z
= fields
[2].GetFloat();
13698 o
= fields
[3].GetFloat();
13699 mapid
= fields
[4].GetUInt32();
13700 in_flight
= !fields
[5].GetCppString().empty();
13706 bool Player::LoadValuesArrayFromDB(Tokens
& data
, uint64 guid
)
13708 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid
));
13712 Field
*fields
= result
->Fetch();
13714 data
= StrSplit(fields
[0].GetCppString(), " ");
13721 uint32
Player::GetUInt32ValueFromArray(Tokens
const& data
, uint16 index
)
13723 if(index
>= data
.size())
13726 return (uint32
)atoi(data
[index
].c_str());
13729 float Player::GetFloatValueFromArray(Tokens
const& data
, uint16 index
)
13732 uint32 temp
= Player::GetUInt32ValueFromArray(data
,index
);
13733 memcpy(&result
, &temp
, sizeof(result
));
13738 uint32
Player::GetUInt32ValueFromDB(uint16 index
, uint64 guid
)
13741 if(!LoadValuesArrayFromDB(data
,guid
))
13744 return GetUInt32ValueFromArray(data
,index
);
13747 float Player::GetFloatValueFromDB(uint16 index
, uint64 guid
)
13750 uint32 temp
= Player::GetUInt32ValueFromDB(index
, guid
);
13751 memcpy(&result
, &temp
, sizeof(result
));
13756 bool Player::LoadFromDB( uint32 guid
, SqlQueryHolder
*holder
)
13758 //// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 [28] [29] 30 31 32 33 34 35 36 37 38 39 40
13759 //QueryResult *result = CharacterDatabase.PQuery("SELECT guid, account, data, name, race, class, position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, dungeon_difficulty, arena_pending_points,bgid,bgteam,bgmap,bgx,bgy,bgz,bgo FROM characters WHERE guid = '%u'", guid);
13760 QueryResult
*result
= holder
->GetResult(PLAYER_LOGIN_QUERY_LOADFROM
);
13764 sLog
.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid
);
13768 Field
*fields
= result
->Fetch();
13770 uint32 dbAccountId
= fields
[1].GetUInt32();
13772 // check if the character's account in the db and the logged in account match.
13773 // player should be able to load/delete character only with correct account!
13774 if( dbAccountId
!= GetSession()->GetAccountId() )
13776 sLog
.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid
,GetSession()->GetAccountId(),dbAccountId
);
13781 Object::_Create( guid
, 0, HIGHGUID_PLAYER
);
13783 m_name
= fields
[3].GetCppString();
13785 // check name limitations
13786 if(!ObjectMgr::IsValidName(m_name
) || (GetSession()->GetSecurity() == SEC_PLAYER
&& objmgr
.IsReservedName(m_name
)))
13789 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME
),guid
);
13793 if(!LoadValues( fields
[2].GetString()))
13795 sLog
.outError("Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid
));
13800 // overwrite possible wrong/corrupted guid
13801 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
13803 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13804 for(uint8 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
13806 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), 0 );
13807 SetVisibleItemSlot(slot
,NULL
);
13811 delete m_items
[slot
];
13812 m_items
[slot
] = NULL
;
13816 // update money limits
13817 if(GetMoney() > MAX_MONEY_AMOUNT
)
13818 SetMoney(MAX_MONEY_AMOUNT
);
13820 sLog
.outDebug("Load Basic value of player %s is: ", m_name
.c_str());
13823 m_race
= fields
[4].GetUInt8();
13824 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13825 //Other way is to saves m_team into characters table.
13826 setFactionForRace(m_race
);
13829 m_class
= fields
[5].GetUInt8();
13831 // load home bind and check in same time class/race pair, it used later for restore broken positions
13832 if(!_LoadHomeBind(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND
)))
13835 InitPrimaryProffesions(); // to max set before any spell loaded
13837 // init saved position, and fix it later if problematic
13838 uint32 transGUID
= fields
[24].GetUInt32();
13839 Relocate(fields
[6].GetFloat(),fields
[7].GetFloat(),fields
[8].GetFloat(),fields
[10].GetFloat());
13840 SetMapId(fields
[9].GetUInt32());
13841 SetDifficulty(fields
[32].GetUInt32()); // may be changed in _LoadGroup
13843 _LoadGroup(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP
));
13845 _LoadArenaTeamInfo(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO
));
13847 uint32 arena_currency
= GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
) + fields
[33].GetUInt32();
13848 if (arena_currency
> sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
))
13849 arena_currency
= sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
);
13851 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, arena_currency
);
13853 // check arena teams integrity
13854 for(uint32 arena_slot
= 0; arena_slot
< MAX_ARENA_SLOT
; ++arena_slot
)
13856 uint32 arena_team_id
= GetArenaTeamId(arena_slot
);
13860 if(ArenaTeam
* at
= objmgr
.GetArenaTeamById(arena_team_id
))
13861 if(at
->HaveMember(GetGUID()))
13864 // arena team not exist or not member, cleanup fields
13865 for(int j
=0; j
< 6; ++j
)
13866 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arena_slot
* 6 + j
, 0);
13869 _LoadBoundInstances(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES
));
13871 if(!IsPositionValid())
13873 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());
13874 RelocateToHomebind();
13878 m_movementInfo
.t_x
= 0.0f
;
13879 m_movementInfo
.t_y
= 0.0f
;
13880 m_movementInfo
.t_z
= 0.0f
;
13881 m_movementInfo
.t_o
= 0.0f
;
13884 uint32 bgid
= fields
[34].GetUInt32();
13885 uint32 bgteam
= fields
[35].GetUInt32();
13887 if(bgid
) //saved in BattleGround
13889 SetBattleGroundEntryPoint(fields
[36].GetUInt32(),fields
[37].GetFloat(),fields
[38].GetFloat(),fields
[39].GetFloat(),fields
[40].GetFloat());
13891 // check entry point and fix to homebind if need
13892 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(m_bgEntryPoint
.mapid
);
13893 if(!mapEntry
|| mapEntry
->Instanceable() || !MapManager::IsValidMapCoord(m_bgEntryPoint
))
13894 SetBattleGroundEntryPoint(m_homebindMapId
,m_homebindX
,m_homebindY
,m_homebindZ
,0.0f
);
13896 BattleGround
*currentBg
= sBattleGroundMgr
.GetBattleGround(bgid
, BATTLEGROUND_TYPE_NONE
);
13898 if(currentBg
&& currentBg
->IsPlayerInBattleGround(GetGUID()))
13900 BattleGroundQueueTypeId bgQueueTypeId
= sBattleGroundMgr
.BGQueueTypeId(currentBg
->GetTypeID(), currentBg
->GetArenaType());
13901 AddBattleGroundQueueId(bgQueueTypeId
);
13903 SetBattleGroundId(currentBg
->GetInstanceID(), currentBg
->GetTypeID());
13906 //join player to battleground group
13907 currentBg
->EventPlayerLoggedIn(this, GetGUID());
13908 currentBg
->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), bgteam
);
13910 SetInviteForBattleGroundQueueType(bgQueueTypeId
,currentBg
->GetInstanceID());
13914 Relocate(GetBattleGroundEntryPoint());
13915 //RemoveArenaAuras(true);
13920 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(GetMapId());
13921 // if server restart after player save in BG or area
13922 // player can have current coordinates in to BG/Arean map, fix this
13923 if(!mapEntry
|| mapEntry
->IsBattleGroundOrArena())
13925 // return to BG master
13926 SetMapId(fields
[36].GetUInt32());
13927 Relocate(fields
[37].GetFloat(),fields
[38].GetFloat(),fields
[39].GetFloat(),fields
[40].GetFloat());
13929 // check entry point and fix to homebind if need
13930 mapEntry
= sMapStore
.LookupEntry(GetMapId());
13931 if(!mapEntry
|| mapEntry
->IsBattleGroundOrArena() || !IsPositionValid())
13932 RelocateToHomebind();
13936 if (transGUID
!= 0)
13938 m_movementInfo
.t_x
= fields
[20].GetFloat();
13939 m_movementInfo
.t_y
= fields
[21].GetFloat();
13940 m_movementInfo
.t_z
= fields
[22].GetFloat();
13941 m_movementInfo
.t_o
= fields
[23].GetFloat();
13943 if( !MaNGOS::IsValidMapCoord(
13944 GetPositionX()+m_movementInfo
.t_x
,GetPositionY()+m_movementInfo
.t_y
,
13945 GetPositionZ()+m_movementInfo
.t_z
,GetOrientation()+m_movementInfo
.t_o
) ||
13946 // transport size limited
13947 m_movementInfo
.t_x
> 50 || m_movementInfo
.t_y
> 50 || m_movementInfo
.t_z
> 50 )
13949 sLog
.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
13950 guid
,GetPositionX()+m_movementInfo
.t_x
,GetPositionY()+m_movementInfo
.t_y
,
13951 GetPositionZ()+m_movementInfo
.t_z
,GetOrientation()+m_movementInfo
.t_o
);
13953 RelocateToHomebind();
13955 m_movementInfo
.t_x
= 0.0f
;
13956 m_movementInfo
.t_y
= 0.0f
;
13957 m_movementInfo
.t_z
= 0.0f
;
13958 m_movementInfo
.t_o
= 0.0f
;
13964 if (transGUID
!= 0)
13966 for (MapManager::TransportSet::const_iterator iter
= MapManager::Instance().m_Transports
.begin(); iter
!= MapManager::Instance().m_Transports
.end(); ++iter
)
13968 if( (*iter
)->GetGUIDLow() == transGUID
)
13970 MapEntry
const* transMapEntry
= sMapStore
.LookupEntry((*iter
)->GetMapId());
13971 // client without expansion support
13972 if(GetSession()->Expansion() < transMapEntry
->Expansion())
13974 sLog
.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter
)->GetMapId());
13978 m_transport
= *iter
;
13979 m_transport
->AddPassenger(this);
13980 SetMapId(m_transport
->GetMapId());
13987 sLog
.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
13990 RelocateToHomebind();
13992 m_movementInfo
.t_x
= 0.0f
;
13993 m_movementInfo
.t_y
= 0.0f
;
13994 m_movementInfo
.t_z
= 0.0f
;
13995 m_movementInfo
.t_o
= 0.0f
;
14000 else // not transport case
14002 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(GetMapId());
14003 // client without expansion support
14004 if(GetSession()->Expansion() < mapEntry
->Expansion())
14006 sLog
.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
14007 RelocateToHomebind();
14011 // NOW player must have valid map
14012 // load the player's map here if it's not already loaded
14013 Map
*map
= GetMap();
14015 // since the player may not be bound to the map yet, make sure subsequent
14016 // getmap calls won't create new maps
14017 SetInstanceId(map
->GetInstanceId());
14019 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14020 if(GetInstanceId() && !sInstanceSaveManager
.GetInstanceSave(GetInstanceId()))
14022 AreaTrigger
const* at
= objmgr
.GetMapEntranceTrigger(GetMapId());
14024 Relocate(at
->target_X
, at
->target_Y
, at
->target_Z
, at
->target_Orientation
);
14026 sLog
.outError("Player %s(GUID: %u) logged in to a reset instance (map: %u) and there is no aretrigger leading to this map. Thus he can't be ported back to the entrance. This _might_ be an exploit attempt.", GetName(), GetGUIDLow(), GetMapId());
14029 SaveRecallPosition();
14031 time_t now
= time(NULL
);
14032 time_t logoutTime
= time_t(fields
[16].GetUInt64());
14034 // since last logout (in seconds)
14035 uint64 time_diff
= uint64(now
- logoutTime
);
14037 // set value, including drunk invisibility detection
14038 // calculate sobering. after 15 minutes logged out, the player will be sober again
14040 if(time_diff
> 15*MINUTE
)
14043 soberFactor
= 1-time_diff
/(15.0f
*MINUTE
);
14044 uint16 newDrunkenValue
= uint16(soberFactor
*(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFE));
14045 SetDrunkValue(newDrunkenValue
);
14047 m_rest_bonus
= fields
[15].GetFloat();
14048 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14049 float bubble0
= 0.031;
14050 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14051 float bubble1
= 0.125;
14053 if((int32
)fields
[16].GetUInt32() > 0)
14055 float bubble
= fields
[17].GetUInt32() > 0
14056 ? bubble1
*sWorld
.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY
)
14057 : bubble0
*sWorld
.getRate(RATE_REST_OFFLINE_IN_WILDERNESS
);
14059 SetRestBonus(GetRestBonus()+ time_diff
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
14062 m_cinematic
= fields
[12].GetUInt32();
14063 m_Played_time
[0]= fields
[13].GetUInt32();
14064 m_Played_time
[1]= fields
[14].GetUInt32();
14066 m_resetTalentsCost
= fields
[18].GetUInt32();
14067 m_resetTalentsTime
= time_t(fields
[19].GetUInt64());
14069 // reserve some flags
14070 uint32 old_safe_flags
= GetUInt32Value(PLAYER_FLAGS
) & ( PLAYER_FLAGS_HIDE_CLOAK
| PLAYER_FLAGS_HIDE_HELM
);
14072 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
) )
14073 SetUInt32Value(PLAYER_FLAGS
, 0 | old_safe_flags
);
14075 m_taxi
.LoadTaxiMask( fields
[11].GetString() ); // must be before InitTaxiNodesForLevel
14077 uint32 extraflags
= fields
[25].GetUInt32();
14079 m_stableSlots
= fields
[26].GetUInt32();
14080 if(m_stableSlots
> MAX_PET_STABLES
)
14082 sLog
.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES
,uint32(m_stableSlots
));
14083 m_stableSlots
= MAX_PET_STABLES
;
14086 m_atLoginFlags
= fields
[27].GetUInt32();
14089 // Update Honor kills data
14090 m_lastHonorUpdateTime
= logoutTime
;
14091 UpdateHonorFields();
14093 m_deathExpireTime
= (time_t)fields
[30].GetUInt64();
14094 if(m_deathExpireTime
> now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
)
14095 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
-1;
14097 std::string taxi_nodes
= fields
[31].GetCppString();
14101 // clear channel spell data (if saved at channel spell casting)
14102 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT
, 0);
14103 SetUInt32Value(UNIT_CHANNEL_SPELL
,0);
14105 // clear charm/summon related fields
14112 // reset some aura modifiers before aura apply
14113 SetFarSightGUID(0);
14114 SetUInt32Value(PLAYER_TRACK_CREATURES
, 0 );
14115 SetUInt32Value(PLAYER_TRACK_RESOURCES
, 0 );
14119 // make sure the unit is considered out of combat for proper loading
14122 // make sure the unit is considered not in duel for proper loading
14123 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
14124 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
14126 // remember loaded power/health values to restore after stats initialization and modifier applying
14127 uint32 savedHealth
= GetHealth();
14128 uint32 savedPower
[MAX_POWERS
];
14129 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
14130 savedPower
[i
] = GetPower(Powers(i
));
14132 // reset stats before loading any modifiers
14133 InitStatsForLevel();
14134 InitTaxiNodesForLevel();
14135 InitGlyphsForLevel();
14138 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14140 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14143 _LoadAuras(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS
), time_diff
);
14146 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14147 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
14148 m_deathState
= DEAD
;
14150 _LoadSpells(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS
));
14152 // after spell load, learn rewarded spell if need also
14153 _LoadQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS
));
14154 _LoadDailyQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS
));
14156 // after spell and quest load
14157 InitTalentForLevel();
14158 learnDefaultSpells();
14160 _LoadTutorials(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS
));
14162 // must be before inventory (some items required reputation check)
14163 m_reputationMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION
));
14165 _LoadInventory(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY
), time_diff
);
14167 // update items with duration and realtime
14168 UpdateItemDuration(time_diff
, true);
14170 _LoadActions(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS
));
14172 // unread mails and next delivery time, actual mails not loaded
14173 _LoadMailInit(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT
), holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE
));
14175 m_social
= sSocialMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST
), GetGUIDLow());
14177 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14178 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14179 if(uint32 curTitle
= GetUInt32Value(PLAYER_CHOSEN_TITLE
))
14181 if(!HasTitle(curTitle
))
14182 SetUInt32Value(PLAYER_CHOSEN_TITLE
,0);
14185 // Not finish taxi flight path
14186 if(!m_taxi
.LoadTaxiDestinationsFromString(taxi_nodes
,GetTeam()))
14188 // problems with taxi path loading
14189 TaxiNodesEntry
const* nodeEntry
= NULL
;
14190 if(uint32 node_id
= m_taxi
.GetTaxiSource())
14191 nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
14193 if(!nodeEntry
) // don't know taxi start node, to homebind
14195 sLog
.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14196 RelocateToHomebind();
14197 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14199 else // have start node, to it
14201 sLog
.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14202 SetMapId(nodeEntry
->map_id
);
14203 Relocate(nodeEntry
->x
, nodeEntry
->y
, nodeEntry
->z
,0.0f
);
14204 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14206 m_taxi
.ClearTaxiDestinations();
14208 else if(uint32 node_id
= m_taxi
.GetTaxiSource())
14210 // save source node as recall coord to prevent recall and fall from sky
14211 TaxiNodesEntry
const* nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
14212 assert(nodeEntry
); // checked in m_taxi.LoadTaxiDestinationsFromString
14213 m_recallMap
= nodeEntry
->map_id
;
14214 m_recallX
= nodeEntry
->x
;
14215 m_recallY
= nodeEntry
->y
;
14216 m_recallZ
= nodeEntry
->z
;
14218 // flight will started later
14221 // has to be called after last Relocate() in Player::LoadFromDB
14222 SetFallInformation(0, GetPositionZ());
14224 _LoadSpellCooldowns(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS
));
14226 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14227 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14229 RemoveAllAurasOnDeath();
14231 //apply all stat bonuses from items and auras
14232 SetCanModifyStats(true);
14235 // restore remembered power/health values (but not more max values)
14236 SetHealth(savedHealth
> GetMaxHealth() ? GetMaxHealth() : savedHealth
);
14237 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
14238 SetPower(Powers(i
),savedPower
[i
] > GetMaxPower(Powers(i
)) ? GetMaxPower(Powers(i
)) : savedPower
[i
]);
14240 sLog
.outDebug("The value of player %s after load item and aura is: ", m_name
.c_str());
14244 if(GetSession()->GetSecurity() > SEC_PLAYER
)
14246 switch(sWorld
.getConfig(CONFIG_GM_LOGIN_STATE
))
14249 case 0: break; // disable
14250 case 1: SetGameMaster(true); break; // enable
14251 case 2: // save state
14252 if(extraflags
& PLAYER_EXTRA_GM_ON
)
14253 SetGameMaster(true);
14257 switch(sWorld
.getConfig(CONFIG_GM_VISIBLE_STATE
))
14260 case 0: SetGMVisible(false); break; // invisible
14261 case 1: break; // visible
14262 case 2: // save state
14263 if(extraflags
& PLAYER_EXTRA_GM_INVISIBLE
)
14264 SetGMVisible(false);
14268 switch(sWorld
.getConfig(CONFIG_GM_ACCEPT_TICKETS
))
14271 case 0: break; // disable
14272 case 1: SetAcceptTicket(true); break; // enable
14273 case 2: // save state
14274 if(extraflags
& PLAYER_EXTRA_GM_ACCEPT_TICKETS
)
14275 SetAcceptTicket(true);
14279 switch(sWorld
.getConfig(CONFIG_GM_CHAT
))
14282 case 0: break; // disable
14283 case 1: SetGMChat(true); break; // enable
14284 case 2: // save state
14285 if(extraflags
& PLAYER_EXTRA_GM_CHAT
)
14290 switch(sWorld
.getConfig(CONFIG_GM_WISPERING_TO
))
14293 case 0: break; // disable
14294 case 1: SetAcceptWhispers(true); break; // enable
14295 case 2: // save state
14296 if(extraflags
& PLAYER_EXTRA_ACCEPT_WHISPERS
)
14297 SetAcceptWhispers(true);
14302 _LoadDeclinedNames(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES
));
14304 m_achievementMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS
), holder
->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS
));
14305 m_achievementMgr
.CheckAllAchievementCriteria();
14309 bool Player::isAllowedToLoot(Creature
* creature
)
14311 if(Player
* recipient
= creature
->GetLootRecipient())
14313 if (recipient
== this)
14315 if( Group
* otherGroup
= recipient
->GetGroup())
14317 Group
* thisGroup
= GetGroup();
14320 return thisGroup
== otherGroup
;
14325 // prevent other players from looting if the recipient got disconnected
14326 return !creature
->hasLootRecipient();
14329 void Player::_LoadActions(QueryResult
*result
)
14331 m_actionButtons
.clear();
14333 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14339 Field
*fields
= result
->Fetch();
14341 uint8 button
= fields
[0].GetUInt8();
14343 if(addActionButton(button
, fields
[1].GetUInt16(), fields
[2].GetUInt8(), fields
[3].GetUInt8()))
14344 m_actionButtons
[button
].uState
= ACTIONBUTTON_UNCHANGED
;
14347 sLog
.outError( " ...at loading, and will deleted in DB also");
14349 // Will deleted in DB at next save (it can create data until save but marked as deleted)
14350 m_actionButtons
[button
].uState
= ACTIONBUTTON_DELETED
;
14353 while( result
->NextRow() );
14359 void Player::_LoadAuras(QueryResult
*result
, uint32 timediff
)
14362 for (int i
= 0; i
< TOTAL_AURAS
; ++i
)
14363 m_modAuras
[i
].clear();
14365 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14371 Field
*fields
= result
->Fetch();
14372 uint64 caster_guid
= fields
[0].GetUInt64();
14373 uint32 spellid
= fields
[1].GetUInt32();
14374 uint32 effindex
= fields
[2].GetUInt32();
14375 uint32 stackcount
= fields
[3].GetUInt32();
14376 int32 damage
= (int32
)fields
[4].GetUInt32();
14377 int32 maxduration
= (int32
)fields
[5].GetUInt32();
14378 int32 remaintime
= (int32
)fields
[6].GetUInt32();
14379 int32 remaincharges
= (int32
)fields
[7].GetUInt32();
14381 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellid
);
14384 sLog
.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid
,effindex
);
14390 sLog
.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid
,effindex
);
14394 // negative effects should continue counting down after logout
14395 if (remaintime
!= -1 && !IsPositiveEffect(spellid
, effindex
))
14397 if(remaintime
<= int32(timediff
))
14400 remaintime
-= timediff
;
14403 // prevent wrong values of remaincharges
14404 if(spellproto
->procCharges
)
14406 if(remaincharges
<= 0 || remaincharges
> spellproto
->procCharges
)
14407 remaincharges
= spellproto
->procCharges
;
14413 for(uint32 i
=0; i
<stackcount
; ++i
)
14415 Aura
* aura
= CreateAura(spellproto
, effindex
, NULL
, this, NULL
);
14417 damage
= aura
->GetModifier()->m_amount
;
14419 // reset stolen single target auras
14420 if (caster_guid
!= GetGUID() && aura
->IsSingleTarget())
14421 aura
->SetIsSingleTarget(false);
14423 aura
->SetLoadedState(caster_guid
,damage
,maxduration
,remaintime
,remaincharges
);
14425 sLog
.outDetail("Added aura spellid %u, effect %u", spellproto
->Id
, effindex
);
14428 while( result
->NextRow() );
14433 if(m_class
== CLASS_WARRIOR
)
14434 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
14437 void Player::_LoadGlyphAuras()
14439 for (uint8 i
= 0; i
< MAX_GLYPH_SLOT_INDEX
; ++i
)
14441 if (uint32 glyph
= GetGlyph(i
))
14443 if (GlyphPropertiesEntry
const *gp
= sGlyphPropertiesStore
.LookupEntry(glyph
))
14445 if (GlyphSlotEntry
const *gs
= sGlyphSlotStore
.LookupEntry(GetGlyphSlot(i
)))
14447 if(gp
->TypeFlags
== gs
->TypeFlags
)
14449 CastSpell(this, gp
->SpellId
, true);
14453 sLog
.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name
.c_str(), gp
->TypeFlags
, gs
->TypeFlags
);
14456 sLog
.outError("Player %s has not existing glyph slot entry %u on index %u", m_name
.c_str(), GetGlyphSlot(i
), i
);
14459 sLog
.outError("Player %s has not existing glyph entry %u on index %u", m_name
.c_str(), glyph
, i
);
14461 // On any error remove glyph
14467 void Player::LoadCorpse()
14471 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14475 if(Corpse
*corpse
= GetCorpse())
14477 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, corpse
&& !sMapStore
.LookupEntry(corpse
->GetMapId())->Instanceable() );
14481 //Prevent Dead Player login without corpse
14482 ResurrectPlayer(0.5f
);
14487 void Player::_LoadInventory(QueryResult
*result
, uint32 timediff
)
14489 //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());
14490 std::map
<uint64
, Bag
*> bagMap
; // fast guid lookup for bags
14491 //NOTE: the "order by `bag`" is important because it makes sure
14492 //the bagMap is filled before items in the bags are loaded
14493 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14494 //expected to be equipped before offhand items (TODO: fixme)
14496 uint32 zone
= GetZoneId();
14500 std::list
<Item
*> problematicItems
;
14502 // prevent items from being added to the queue when stored
14503 m_itemUpdateQueueBlocked
= true;
14506 Field
*fields
= result
->Fetch();
14507 uint32 bag_guid
= fields
[1].GetUInt32();
14508 uint8 slot
= fields
[2].GetUInt8();
14509 uint32 item_guid
= fields
[3].GetUInt32();
14510 uint32 item_id
= fields
[4].GetUInt32();
14512 ItemPrototype
const * proto
= objmgr
.GetItemPrototype(item_id
);
14516 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14517 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid
);
14518 sLog
.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id
);
14522 Item
*item
= NewItemOrBag(proto
);
14524 if(!item
->LoadFromDB(item_guid
, GetGUID(), result
))
14526 sLog
.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id
);
14527 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14528 item
->FSetState(ITEM_REMOVED
);
14529 item
->SaveToDB(); // it also deletes item object !
14533 // not allow have in alive state item limited to another map/zone
14534 if(isAlive() && item
->IsLimitedToAnotherMapOrZone(GetMapId(),zone
) )
14536 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14537 item
->FSetState(ITEM_REMOVED
);
14538 item
->SaveToDB(); // it also deletes item object !
14542 // "Conjured items disappear if you are logged out for more than 15 minutes"
14543 if ((timediff
> 15*60) && (item
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_CONJURED
)))
14545 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14546 item
->FSetState(ITEM_REMOVED
);
14547 item
->SaveToDB(); // it also deletes item object !
14551 bool success
= true;
14555 // the item is not in a bag
14556 item
->SetContainer( NULL
);
14557 item
->SetSlot(slot
);
14559 if( IsInventoryPos( INVENTORY_SLOT_BAG_0
, slot
) )
14561 ItemPosCountVec dest
;
14562 if( CanStoreItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false ) == EQUIP_ERR_OK
)
14563 item
= StoreItem(dest
, item
, true);
14567 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0
, slot
) )
14570 if( CanEquipItem( slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
14571 QuickEquipItem(dest
, item
);
14575 else if( IsBankPos( INVENTORY_SLOT_BAG_0
, slot
) )
14577 ItemPosCountVec dest
;
14578 if( CanBankItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
14579 item
= BankItem(dest
, item
, true);
14586 // store bags that may contain items in them
14587 if(item
->IsBag() && IsBagPos(item
->GetPos()))
14588 bagMap
[item_guid
] = (Bag
*)item
;
14593 item
->SetSlot(NULL_SLOT
);
14594 // the item is in a bag, find the bag
14595 std::map
<uint64
, Bag
*>::const_iterator itr
= bagMap
.find(bag_guid
);
14596 if(itr
!= bagMap
.end())
14597 itr
->second
->StoreItem(slot
, item
, true );
14602 // item's state may have changed after stored
14604 item
->SetState(ITEM_UNCHANGED
, this);
14607 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
);
14608 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14609 problematicItems
.push_back(item
);
14611 } while (result
->NextRow());
14614 m_itemUpdateQueueBlocked
= false;
14616 // send by mail problematic items
14617 while(!problematicItems
.empty())
14620 MailItemsInfo mi
; // item list preparing
14622 for(int i
= 0; !problematicItems
.empty() && i
< MAX_MAIL_ITEMS
; ++i
)
14624 Item
* item
= problematicItems
.front();
14625 problematicItems
.pop_front();
14627 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
14630 std::string subject
= GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM
);
14632 WorldSession::SendMailTo(this, MAIL_NORMAL
, MAIL_STATIONERY_GM
, GetGUIDLow(), GetGUIDLow(), subject
, 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
);
14636 _ApplyAllItemMods();
14639 // load mailed item which should receive current player
14640 void Player::_LoadMailedItems(Mail
*mail
)
14642 // data needs to be at first place for Item::LoadFromDB
14643 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
);
14649 Field
*fields
= result
->Fetch();
14650 uint32 item_guid_low
= fields
[1].GetUInt32();
14651 uint32 item_template
= fields
[2].GetUInt32();
14653 mail
->AddItem(item_guid_low
, item_template
);
14655 ItemPrototype
const *proto
= objmgr
.GetItemPrototype(item_template
);
14659 sLog
.outError( "Player %u have unknown item_template (ProtoType) in mailed items(GUID: %u template: %u) in mail (%u), deleted.", GetGUIDLow(), item_guid_low
, item_template
,mail
->messageID
);
14660 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
14661 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low
);
14665 Item
*item
= NewItemOrBag(proto
);
14667 if(!item
->LoadFromDB(item_guid_low
, 0, result
))
14669 sLog
.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail
->messageID
, item_guid_low
);
14670 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
14671 item
->FSetState(ITEM_REMOVED
);
14672 item
->SaveToDB(); // it also deletes item object !
14677 } while (result
->NextRow());
14682 void Player::_LoadMailInit(QueryResult
*resultUnread
, QueryResult
*resultDelivery
)
14684 //set a count of unread mails
14685 //QueryResult *resultMails = CharacterDatabase.PQuery("SELECT COUNT(id) FROM mail WHERE receiver = '%u' AND (checked & 1)=0 AND deliver_time <= '" I64FMTD "'", GUID_LOPART(playerGuid),(uint64)cTime);
14688 Field
*fieldMail
= resultUnread
->Fetch();
14689 unReadMails
= fieldMail
[0].GetUInt8();
14690 delete resultUnread
;
14693 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14694 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14695 if (resultDelivery
)
14697 Field
*fieldMail
= resultDelivery
->Fetch();
14698 m_nextMailDelivereTime
= (time_t)fieldMail
[0].GetUInt64();
14699 delete resultDelivery
;
14703 void Player::_LoadMail()
14706 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14707 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());
14712 Field
*fields
= result
->Fetch();
14713 Mail
*m
= new Mail
;
14714 m
->messageID
= fields
[0].GetUInt32();
14715 m
->messageType
= fields
[1].GetUInt8();
14716 m
->sender
= fields
[2].GetUInt32();
14717 m
->receiver
= fields
[3].GetUInt32();
14718 m
->subject
= fields
[4].GetCppString();
14719 m
->itemTextId
= fields
[5].GetUInt32();
14720 bool has_items
= fields
[6].GetBool();
14721 m
->expire_time
= (time_t)fields
[7].GetUInt64();
14722 m
->deliver_time
= (time_t)fields
[8].GetUInt64();
14723 m
->money
= fields
[9].GetUInt32();
14724 m
->COD
= fields
[10].GetUInt32();
14725 m
->checked
= fields
[11].GetUInt32();
14726 m
->stationery
= fields
[12].GetUInt8();
14727 m
->mailTemplateId
= fields
[13].GetInt16();
14729 if(m
->mailTemplateId
&& !sMailTemplateStore
.LookupEntry(m
->mailTemplateId
))
14731 sLog
.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m
->messageID
, m
->mailTemplateId
);
14732 m
->mailTemplateId
= 0;
14735 m
->state
= MAIL_STATE_UNCHANGED
;
14738 _LoadMailedItems(m
);
14740 m_mail
.push_back(m
);
14741 } while( result
->NextRow() );
14744 m_mailsLoaded
= true;
14747 void Player::LoadPet()
14749 //fixme: the pet should still be loaded if the player is not in world
14750 // just not added to the map
14753 Pet
*pet
= new Pet
;
14754 if(!pet
->LoadPetFromDB(this,0,0,true))
14759 void Player::_LoadQuestStatus(QueryResult
*result
)
14761 mQuestStatus
.clear();
14765 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14766 //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());
14772 Field
*fields
= result
->Fetch();
14774 uint32 quest_id
= fields
[0].GetUInt32();
14775 // used to be new, no delete?
14776 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
14780 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
14782 uint32 qstatus
= fields
[1].GetUInt32();
14783 if(qstatus
< MAX_QUEST_STATUS
)
14784 questStatusData
.m_status
= QuestStatus(qstatus
);
14787 questStatusData
.m_status
= QUEST_STATUS_NONE
;
14788 sLog
.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id
,qstatus
);
14791 questStatusData
.m_rewarded
= ( fields
[2].GetUInt8() > 0 );
14792 questStatusData
.m_explored
= ( fields
[3].GetUInt8() > 0 );
14794 time_t quest_time
= time_t(fields
[4].GetUInt64());
14796 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && !GetQuestRewardStatus(quest_id
) && questStatusData
.m_status
!= QUEST_STATUS_NONE
)
14798 AddTimedQuest( quest_id
);
14800 if (quest_time
<= sWorld
.GetGameTime())
14801 questStatusData
.m_timer
= 1;
14803 questStatusData
.m_timer
= (quest_time
- sWorld
.GetGameTime()) * IN_MILISECONDS
;
14808 questStatusData
.m_creatureOrGOcount
[0] = fields
[5].GetUInt32();
14809 questStatusData
.m_creatureOrGOcount
[1] = fields
[6].GetUInt32();
14810 questStatusData
.m_creatureOrGOcount
[2] = fields
[7].GetUInt32();
14811 questStatusData
.m_creatureOrGOcount
[3] = fields
[8].GetUInt32();
14812 questStatusData
.m_itemcount
[0] = fields
[9].GetUInt32();
14813 questStatusData
.m_itemcount
[1] = fields
[10].GetUInt32();
14814 questStatusData
.m_itemcount
[2] = fields
[11].GetUInt32();
14815 questStatusData
.m_itemcount
[3] = fields
[12].GetUInt32();
14817 questStatusData
.uState
= QUEST_UNCHANGED
;
14819 // add to quest log
14820 if( slot
< MAX_QUEST_LOG_SIZE
&&
14821 ( questStatusData
.m_status
==QUEST_STATUS_INCOMPLETE
||
14822 questStatusData
.m_status
==QUEST_STATUS_COMPLETE
&&
14823 (!questStatusData
.m_rewarded
|| pQuest
->IsDaily()) ) )
14825 SetQuestSlot(slot
,quest_id
,quest_time
);
14827 if(questStatusData
.m_status
== QUEST_STATUS_COMPLETE
)
14828 SetQuestSlotState(slot
,QUEST_STATE_COMPLETE
);
14830 for(uint8 idx
= 0; idx
< QUEST_OBJECTIVES_COUNT
; ++idx
)
14831 if(questStatusData
.m_creatureOrGOcount
[idx
])
14832 SetQuestSlotCounter(slot
,idx
,questStatusData
.m_creatureOrGOcount
[idx
]);
14837 if(questStatusData
.m_rewarded
)
14839 // learn rewarded spell if unknown
14840 learnQuestRewardedSpells(pQuest
);
14842 // set rewarded title if any
14843 if(pQuest
->GetCharTitleId())
14845 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
14846 SetTitle(titleEntry
);
14849 if(pQuest
->GetBonusTalents())
14850 m_questRewardTalentCount
+=pQuest
->GetBonusTalents();
14853 sLog
.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData
.m_status
, quest_id
, GetGUIDLow());
14856 while( result
->NextRow() );
14861 // clear quest log tail
14862 for ( uint16 i
= slot
; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14866 void Player::_LoadDailyQuestStatus(QueryResult
*result
)
14868 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
14869 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
14871 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14875 uint32 quest_daily_idx
= 0;
14879 if(quest_daily_idx
>= PLAYER_MAX_DAILY_QUESTS
) // max amount with exist data in query
14881 sLog
.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
14885 Field
*fields
= result
->Fetch();
14887 uint32 quest_id
= fields
[0].GetUInt32();
14889 // save _any_ from daily quest times (it must be after last reset anyway)
14890 m_lastDailyQuestTime
= (time_t)fields
[1].GetUInt64();
14892 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
14896 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
14899 sLog
.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id
, GetGUIDLow());
14901 while( result
->NextRow() );
14906 m_DailyQuestChanged
= false;
14909 void Player::_LoadSpells(QueryResult
*result
)
14911 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
14917 Field
*fields
= result
->Fetch();
14919 addSpell(fields
[0].GetUInt16(), fields
[1].GetBool(), false, false, fields
[2].GetBool());
14921 while( result
->NextRow() );
14927 void Player::_LoadTutorials(QueryResult
*result
)
14929 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
14935 Field
*fields
= result
->Fetch();
14937 for (int iI
=0; iI
<8; ++iI
)
14938 m_Tutorials
[iI
] = fields
[iI
].GetUInt32();
14940 while( result
->NextRow() );
14945 m_TutorialsChanged
= false;
14948 void Player::_LoadGroup(QueryResult
*result
)
14950 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
14953 uint64 leaderGuid
= MAKE_NEW_GUID((*result
)[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
14955 Group
* group
= objmgr
.GetGroupByLeader(leaderGuid
);
14958 uint8 subgroup
= group
->GetMemberGroup(GetGUID());
14959 SetGroup(group
, subgroup
);
14960 if(getLevel() >= LEVELREQUIREMENT_HEROIC
)
14962 // the group leader may change the instance difficulty while the player is offline
14963 SetDifficulty(group
->GetDifficulty());
14969 void Player::_LoadBoundInstances(QueryResult
*result
)
14971 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; ++i
)
14972 m_boundInstances
[i
].clear();
14974 Group
*group
= GetGroup();
14976 //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));
14981 Field
*fields
= result
->Fetch();
14982 bool perm
= fields
[1].GetBool();
14983 uint32 mapId
= fields
[2].GetUInt32();
14984 uint32 instanceId
= fields
[0].GetUInt32();
14985 uint8 difficulty
= fields
[3].GetUInt8();
14986 time_t resetTime
= (time_t)fields
[4].GetUInt64();
14987 // the resettime for normal instances is only saved when the InstanceSave is unloaded
14988 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
14989 // and in that case it is not used
14991 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(mapId
);
14992 if(!mapEntry
|| !mapEntry
->IsDungeon())
14994 sLog
.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId
);
14995 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
15001 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
);
15002 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
15006 // since non permanent binds are always solo bind, they can always be reset
15007 InstanceSave
*save
= sInstanceSaveManager
.AddInstanceSave(mapId
, instanceId
, difficulty
, resetTime
, !perm
, true);
15008 if(save
) BindToInstance(save
, perm
, true);
15009 } while(result
->NextRow());
15014 InstancePlayerBind
* Player::GetBoundInstance(uint32 mapid
, uint8 difficulty
)
15016 // some instances only have one difficulty
15017 const MapEntry
* entry
= sMapStore
.LookupEntry(mapid
);
15018 if(!entry
|| !entry
->SupportsHeroicMode()) difficulty
= DIFFICULTY_NORMAL
;
15020 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
15021 if(itr
!= m_boundInstances
[difficulty
].end())
15022 return &itr
->second
;
15027 void Player::UnbindInstance(uint32 mapid
, uint8 difficulty
, bool unload
)
15029 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
15030 UnbindInstance(itr
, difficulty
, unload
);
15033 void Player::UnbindInstance(BoundInstancesMap::iterator
&itr
, uint8 difficulty
, bool unload
)
15035 if(itr
!= m_boundInstances
[difficulty
].end())
15037 if(!unload
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr
->second
.save
->GetInstanceId());
15038 itr
->second
.save
->RemovePlayer(this); // save can become invalid
15039 m_boundInstances
[difficulty
].erase(itr
++);
15043 InstancePlayerBind
* Player::BindToInstance(InstanceSave
*save
, bool permanent
, bool load
)
15047 InstancePlayerBind
& bind
= m_boundInstances
[save
->GetDifficulty()][save
->GetMapId()];
15050 // update the save when the group kills a boss
15051 if(permanent
!= bind
.perm
|| save
!= bind
.save
)
15052 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());
15055 if(!load
) CharacterDatabase
.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save
->GetInstanceId(), permanent
);
15057 if(bind
.save
!= save
)
15059 if(bind
.save
) bind
.save
->RemovePlayer(this);
15060 save
->AddPlayer(this);
15063 if(permanent
) save
->SetCanReset(false);
15066 bind
.perm
= permanent
;
15067 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());
15074 void Player::SendRaidInfo()
15076 uint32 counter
= 0;
15078 WorldPacket
data(SMSG_RAID_INSTANCE_INFO
, 4);
15080 size_t p_counter
= data
.wpos();
15081 data
<< uint32(counter
); // placeholder
15083 for(int i
= 0; i
< TOTAL_DIFFICULTIES
; ++i
)
15085 for (BoundInstancesMap::const_iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15087 if(itr
->second
.perm
)
15089 InstanceSave
*save
= itr
->second
.save
;
15090 data
<< uint32(save
->GetMapId());
15091 data
<< uint32(save
->GetResetTime() - time(NULL
));
15092 data
<< uint32(save
->GetInstanceId());
15093 data
<< uint32(save
->GetDifficulty());
15098 data
.put
<uint32
>(p_counter
,counter
);
15099 GetSession()->SendPacket(&data
);
15103 - called on every successful teleportation to a map
15105 void Player::SendSavedInstances()
15107 bool hasBeenSaved
= false;
15110 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; ++i
)
15112 for (BoundInstancesMap::const_iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15114 if(itr
->second
.perm
) // only permanent binds are sent
15116 hasBeenSaved
= true;
15122 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15123 data
.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP
);
15124 data
<< uint32(hasBeenSaved
);
15125 GetSession()->SendPacket(&data
);
15130 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; ++i
)
15132 for (BoundInstancesMap::const_iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15134 if(itr
->second
.perm
)
15136 data
.Initialize(SMSG_UPDATE_LAST_INSTANCE
);
15137 data
<< uint32(itr
->second
.save
->GetMapId());
15138 GetSession()->SendPacket(&data
);
15144 /// convert the player's binds to the group
15145 void Player::ConvertInstancesToGroup(Player
*player
, Group
*group
, uint64 player_guid
)
15147 bool has_binds
= false;
15148 bool has_solo
= false;
15150 if(player
) { player_guid
= player
->GetGUID(); if(!group
) group
= player
->GetGroup(); }
15151 assert(player_guid
);
15153 // copy all binds to the group, when changing leader it's assumed the character
15154 // will not have any solo binds
15158 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; ++i
)
15160 for (BoundInstancesMap::iterator itr
= player
->m_boundInstances
[i
].begin(); itr
!= player
->m_boundInstances
[i
].end();)
15163 if(group
) group
->BindToInstance(itr
->second
.save
, itr
->second
.perm
, true);
15164 // permanent binds are not removed
15165 if(!itr
->second
.perm
)
15167 player
->UnbindInstance(itr
, i
, true); // increments itr
15176 // if the player's not online we don't know what binds it has
15177 if(!player
|| !group
|| has_binds
) CharacterDatabase
.PExecute("INSERT INTO group_instance SELECT guid, instance, permanent FROM character_instance WHERE guid = '%u'", GUID_LOPART(player_guid
));
15178 // the following should not get executed when changing leaders
15179 if(!player
|| has_solo
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid
));
15182 bool Player::_LoadHomeBind(QueryResult
*result
)
15184 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(), getClass());
15187 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
15192 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15195 Field
*fields
= result
->Fetch();
15196 m_homebindMapId
= fields
[0].GetUInt32();
15197 m_homebindZoneId
= fields
[1].GetUInt16();
15198 m_homebindX
= fields
[2].GetFloat();
15199 m_homebindY
= fields
[3].GetFloat();
15200 m_homebindZ
= fields
[4].GetFloat();
15203 MapEntry
const* bindMapEntry
= sMapStore
.LookupEntry(m_homebindMapId
);
15205 // accept saved data only for valid position (and non instanceable), and accessable
15206 if( MapManager::IsValidMapCoord(m_homebindMapId
,m_homebindX
,m_homebindY
,m_homebindZ
) &&
15207 !bindMapEntry
->Instanceable() && GetSession()->Expansion() >= bindMapEntry
->Expansion())
15212 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15217 m_homebindMapId
= info
->mapId
;
15218 m_homebindZoneId
= info
->zoneId
;
15219 m_homebindX
= info
->positionX
;
15220 m_homebindY
= info
->positionY
;
15221 m_homebindZ
= info
->positionZ
;
15223 CharacterDatabase
.PExecute("INSERT INTO character_homebind (guid,map,zone,position_x,position_y,position_z) VALUES ('%u', '%u', '%u', '%f', '%f', '%f')", GetGUIDLow(), m_homebindMapId
, (uint32
)m_homebindZoneId
, m_homebindX
, m_homebindY
, m_homebindZ
);
15226 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
15227 m_homebindMapId
, m_homebindZoneId
, m_homebindX
, m_homebindY
, m_homebindZ
);
15232 /*********************************************************/
15233 /*** SAVE SYSTEM ***/
15234 /*********************************************************/
15236 void Player::SaveToDB()
15238 // delay auto save at any saves (manual, in code, or autosave)
15239 m_nextSave
= sWorld
.getConfig(CONFIG_INTERVAL_SAVE
);
15241 // first save/honor gain after midnight will also update the player's honor fields
15242 UpdateHonorFields();
15244 int is_save_resting
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
) ? 1 : 0;
15245 //save, far from tavern/city
15246 //save, but in tavern/city
15247 sLog
.outDebug("The value of player %s at save: ", m_name
.c_str());
15250 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15251 uint32 tmp_bytes
= GetUInt32Value(UNIT_FIELD_BYTES_1
);
15252 uint32 tmp_bytes2
= GetUInt32Value(UNIT_FIELD_BYTES_2
);
15253 uint32 tmp_flags
= GetUInt32Value(UNIT_FIELD_FLAGS
);
15254 uint32 tmp_pflags
= GetUInt32Value(PLAYER_FLAGS
);
15255 uint32 tmp_displayid
= GetDisplayId();
15257 // Set player sit state to standing on save, also stealth and shifted form
15258 SetByteValue(UNIT_FIELD_BYTES_1
, 0, UNIT_STAND_STATE_STAND
);
15259 SetByteValue(UNIT_FIELD_BYTES_2
, 3, 0); // shapeshift
15260 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_STUNNED
);
15261 SetDisplayId(GetNativeDisplayId());
15263 bool inworld
= IsInWorld();
15265 CharacterDatabase
.BeginTransaction();
15267 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15269 std::string sql_name
= m_name
;
15270 CharacterDatabase
.escape_string(sql_name
);
15272 std::ostringstream ss
;
15273 ss
<< "INSERT INTO characters (guid,account,name,race,class,"
15274 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15275 "taximask, online, cinematic, "
15276 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15277 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15278 "death_expire_time, taxi_path, arena_pending_points, bgid, bgteam, bgmap, bgx, bgy, bgz, bgo) VALUES ("
15279 << GetGUIDLow() << ", "
15280 << GetSession()->GetAccountId() << ", '"
15281 << sql_name
<< "', "
15283 << m_class
<< ", ";
15285 if(!IsBeingTeleported())
15287 ss
<< GetMapId() << ", "
15288 << (uint32
)GetDifficulty() << ", "
15289 << finiteAlways(GetPositionX()) << ", "
15290 << finiteAlways(GetPositionY()) << ", "
15291 << finiteAlways(GetPositionZ()) << ", "
15292 << finiteAlways(GetOrientation()) << ", '";
15296 ss
<< GetTeleportDest().mapid
<< ", "
15297 << (uint32
)GetDifficulty() << ", "
15298 << finiteAlways(GetTeleportDest().x
) << ", "
15299 << finiteAlways(GetTeleportDest().y
) << ", "
15300 << finiteAlways(GetTeleportDest().z
) << ", "
15301 << finiteAlways(GetTeleportDest().o
) << ", '";
15305 for( i
= 0; i
< m_valuesCount
; ++i
)
15307 ss
<< GetUInt32Value(i
) << " ";
15312 ss
<< m_taxi
; // string with TaxiMaskSize numbers
15315 ss
<< (inworld
? 1 : 0);
15321 ss
<< m_Played_time
[0];
15323 ss
<< m_Played_time
[1];
15326 ss
<< finiteAlways(m_rest_bonus
);
15328 ss
<< (uint64
)time(NULL
);
15330 ss
<< is_save_resting
;
15332 ss
<< m_resetTalentsCost
;
15334 ss
<< (uint64
)m_resetTalentsTime
;
15337 ss
<< finiteAlways(m_movementInfo
.t_x
);
15339 ss
<< finiteAlways(m_movementInfo
.t_y
);
15341 ss
<< finiteAlways(m_movementInfo
.t_z
);
15343 ss
<< finiteAlways(m_movementInfo
.t_o
);
15346 ss
<< m_transport
->GetGUIDLow();
15351 ss
<< m_ExtraFlags
;
15354 ss
<< uint32(m_stableSlots
); // to prevent save uint8 as char
15357 ss
<< uint32(m_atLoginFlags
);
15363 ss
<< (uint64
)m_deathExpireTime
;
15366 ss
<< m_taxi
.SaveTaxiDestinationsToString();
15368 ss
<< GetBattleGroundId();
15372 ss
<< m_bgEntryPoint
.mapid
<< ", "
15373 << finiteAlways(m_bgEntryPoint
.x
) << ", "
15374 << finiteAlways(m_bgEntryPoint
.y
) << ", "
15375 << finiteAlways(m_bgEntryPoint
.z
) << ", "
15376 << finiteAlways(m_bgEntryPoint
.o
);
15379 CharacterDatabase
.Execute( ss
.str().c_str() );
15381 if(m_mailsUpdated
) //save mails only when needed
15385 _SaveQuestStatus();
15386 _SaveDailyQuestStatus();
15389 _SaveSpellCooldowns();
15392 m_achievementMgr
.SaveToDB();
15393 m_reputationMgr
.SaveToDB();
15395 CharacterDatabase
.CommitTransaction();
15397 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15398 SetDisplayId(tmp_displayid
);
15399 SetUInt32Value(UNIT_FIELD_BYTES_1
, tmp_bytes
);
15400 SetUInt32Value(UNIT_FIELD_BYTES_2
, tmp_bytes2
);
15401 SetUInt32Value(UNIT_FIELD_FLAGS
, tmp_flags
);
15402 SetUInt32Value(PLAYER_FLAGS
, tmp_pflags
);
15404 // save pet (hunter pet level and experience and all type pets health/mana).
15405 if(Pet
* pet
= GetPet())
15406 pet
->SavePetToDB(PET_SAVE_AS_CURRENT
);
15409 // fast save function for item/money cheating preventing - save only inventory and money state
15410 void Player::SaveInventoryAndGoldToDB()
15413 //money is in data field
15414 SaveDataFieldToDB();
15417 void Player::_SaveActions()
15419 for(ActionButtonList::iterator itr
= m_actionButtons
.begin(); itr
!= m_actionButtons
.end(); )
15421 switch (itr
->second
.uState
)
15423 case ACTIONBUTTON_NEW
:
15424 CharacterDatabase
.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15425 GetGUIDLow(), (uint32
)itr
->first
, (uint32
)itr
->second
.action
, (uint32
)itr
->second
.type
, (uint32
)itr
->second
.misc
);
15426 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
15429 case ACTIONBUTTON_CHANGED
:
15430 CharacterDatabase
.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15431 (uint32
)itr
->second
.action
, (uint32
)itr
->second
.type
, (uint32
)itr
->second
.misc
, GetGUIDLow(), (uint32
)itr
->first
);
15432 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
15435 case ACTIONBUTTON_DELETED
:
15436 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32
)itr
->first
);
15437 m_actionButtons
.erase(itr
++);
15446 void Player::_SaveAuras()
15448 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15450 AuraMap
const& auras
= GetAuras();
15455 spellEffectPair lastEffectPair
= auras
.begin()->first
;
15456 uint32 stackCounter
= 1;
15458 for(AuraMap::const_iterator itr
= auras
.begin(); ; ++itr
)
15460 if(itr
== auras
.end() || lastEffectPair
!= itr
->first
)
15462 AuraMap::const_iterator itr2
= itr
;
15463 // save previous spellEffectPair to db
15466 SpellEntry
const *spellInfo
= itr2
->second
->GetSpellProto();
15468 //skip all auras from spells that are passive or need a shapeshift
15469 if (!(itr2
->second
->IsPassive() || itr2
->second
->IsRemovedOnShapeLost()))
15471 //do not save single target auras (unless they were cast by the player)
15472 if (!(itr2
->second
->GetCasterGUID() != GetGUID() && itr2
->second
->IsSingleTarget()))
15475 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15476 for (i
= 0; i
< 3; ++i
)
15477 if (spellInfo
->EffectApplyAuraName
[i
] == SPELL_AURA_MOD_SHAPESHIFT
||
15478 spellInfo
->EffectApplyAuraName
[i
] == SPELL_AURA_MOD_STEALTH
)
15483 CharacterDatabase
.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15484 "VALUES ('%u', '" I64FMTD
"' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15485 GetGUIDLow(), itr2
->second
->GetCasterGUID(), (uint32
)itr2
->second
->GetId(), (uint32
)itr2
->second
->GetEffIndex(), stackCounter
, itr2
->second
->GetModifier()->m_amount
,int(itr2
->second
->GetAuraMaxDuration()),int(itr2
->second
->GetAuraDuration()),int(itr2
->second
->GetAuraCharges()));
15490 if(itr
== auras
.end())
15494 if (lastEffectPair
== itr
->first
)
15498 lastEffectPair
= itr
->first
;
15504 void Player::_SaveInventory()
15506 // force items in buyback slots to new state
15507 // and remove those that aren't already
15508 for (uint8 i
= BUYBACK_SLOT_START
; i
< BUYBACK_SLOT_END
; ++i
)
15510 Item
*item
= m_items
[i
];
15511 if (!item
|| item
->GetState() == ITEM_NEW
) continue;
15512 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
15513 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item
->GetGUIDLow());
15514 m_items
[i
]->FSetState(ITEM_NEW
);
15517 // update enchantment durations
15518 for(EnchantDurationList::const_iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
15520 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
15524 if (m_itemUpdateQueue
.empty()) return;
15526 // do not save if the update queue is corrupt
15527 bool error
= false;
15528 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); ++i
)
15530 Item
*item
= m_itemUpdateQueue
[i
];
15531 if(!item
|| item
->GetState() == ITEM_REMOVED
) continue;
15532 Item
*test
= GetItemByPos( item
->GetBagSlot(), item
->GetSlot());
15536 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());
15539 else if (test
!= item
)
15541 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());
15548 sLog
.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15549 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED
);
15553 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); ++i
)
15555 Item
*item
= m_itemUpdateQueue
[i
];
15556 if(!item
) continue;
15558 Bag
*container
= item
->GetContainer();
15559 uint32 bag_guid
= container
? container
->GetGUIDLow() : 0;
15561 switch(item
->GetState())
15564 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());
15567 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());
15570 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
15572 case ITEM_UNCHANGED
:
15576 item
->SaveToDB(); // item have unchanged inventory record and can be save standalone
15578 m_itemUpdateQueue
.clear();
15581 void Player::_SaveMail()
15583 if (!m_mailsLoaded
)
15586 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
15589 if (m
->state
== MAIL_STATE_CHANGED
)
15591 CharacterDatabase
.PExecute("UPDATE mail SET itemTextId = '%u',has_items = '%u',expire_time = '" I64FMTD
"', deliver_time = '" I64FMTD
"',money = '%u',cod = '%u',checked = '%u' WHERE id = '%u'",
15592 m
->itemTextId
, m
->HasItems() ? 1 : 0, (uint64
)m
->expire_time
, (uint64
)m
->deliver_time
, m
->money
, m
->COD
, m
->checked
, m
->messageID
);
15593 if(m
->removedItems
.size())
15595 for(std::vector
<uint32
>::const_iterator itr2
= m
->removedItems
.begin(); itr2
!= m
->removedItems
.end(); ++itr2
)
15596 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2
);
15597 m
->removedItems
.clear();
15599 m
->state
= MAIL_STATE_UNCHANGED
;
15601 else if (m
->state
== MAIL_STATE_DELETED
)
15604 for(std::vector
<MailItemInfo
>::const_iterator itr2
= m
->items
.begin(); itr2
!= m
->items
.end(); ++itr2
)
15605 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2
->item_guid
);
15607 CharacterDatabase
.PExecute("DELETE FROM item_text WHERE id = '%u'", m
->itemTextId
);
15608 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", m
->messageID
);
15609 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m
->messageID
);
15613 //deallocate deleted mails...
15614 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); )
15616 if ((*itr
)->state
== MAIL_STATE_DELETED
)
15621 itr
= m_mail
.begin();
15627 m_mailsUpdated
= false;
15630 void Player::_SaveQuestStatus()
15632 // we don't need transactions here.
15633 for( QuestStatusMap::iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
15635 switch (i
->second
.uState
)
15638 CharacterDatabase
.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15639 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD
"', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15640 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]);
15642 case QUEST_CHANGED
:
15643 CharacterDatabase
.PExecute("UPDATE character_queststatus SET status = '%u',rewarded = '%u',explored = '%u',timer = '" I64FMTD
"',mobcount1 = '%u',mobcount2 = '%u',mobcount3 = '%u',mobcount4 = '%u',itemcount1 = '%u',itemcount2 = '%u',itemcount3 = '%u',itemcount4 = '%u' WHERE guid = '%u' AND quest = '%u' ",
15644 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
);
15646 case QUEST_UNCHANGED
:
15649 i
->second
.uState
= QUEST_UNCHANGED
;
15653 void Player::_SaveDailyQuestStatus()
15655 if(!m_DailyQuestChanged
)
15658 m_DailyQuestChanged
= false;
15660 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15662 // we don't need transactions here.
15663 CharacterDatabase
.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15664 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
15665 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
15666 CharacterDatabase
.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD
"')",
15667 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
),uint64(m_lastDailyQuestTime
));
15670 void Player::_SaveSpells()
15672 for (PlayerSpellMap::iterator itr
= m_spells
.begin(), next
= m_spells
.begin(); itr
!= m_spells
.end();)
15674 if (itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->second
->state
== PLAYERSPELL_CHANGED
)
15675 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr
->first
);
15677 // add only changed/new not dependent spells
15678 if (!itr
->second
->dependent
&& (itr
->second
->state
== PLAYERSPELL_NEW
|| itr
->second
->state
== PLAYERSPELL_CHANGED
))
15679 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);
15681 if (itr
->second
->state
== PLAYERSPELL_REMOVED
)
15683 delete itr
->second
;
15684 m_spells
.erase(itr
++);
15688 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
15695 void Player::_SaveTutorials()
15697 if(!m_TutorialsChanged
)
15701 // it's better than rebuilding indexes multiple times
15702 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID
);
15705 Rows
= result
->Fetch()[0].GetUInt32();
15711 CharacterDatabase
.PExecute("UPDATE character_tutorial SET tut0='%u', tut1='%u', tut2='%u', tut3='%u', tut4='%u', tut5='%u', tut6='%u', tut7='%u' WHERE account = '%u' AND realmid = '%u'",
15712 m_Tutorials
[0], m_Tutorials
[1], m_Tutorials
[2], m_Tutorials
[3], m_Tutorials
[4], m_Tutorials
[5], m_Tutorials
[6], m_Tutorials
[7], GetSession()->GetAccountId(), realmID
);
15716 CharacterDatabase
.PExecute("INSERT INTO character_tutorial (account,realmid,tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7) VALUES ('%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')", GetSession()->GetAccountId(), realmID
, m_Tutorials
[0], m_Tutorials
[1], m_Tutorials
[2], m_Tutorials
[3], m_Tutorials
[4], m_Tutorials
[5], m_Tutorials
[6], m_Tutorials
[7]);
15719 m_TutorialsChanged
= false;
15722 void Player::outDebugValues() const
15724 if(!sLog
.IsOutDebug()) // optimize disabled debug output
15727 sLog
.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA
));
15728 sLog
.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY
), GetStat(STAT_STRENGTH
));
15729 sLog
.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT
), GetStat(STAT_SPIRIT
));
15730 sLog
.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA
), GetStat(STAT_SPIRIT
));
15731 sLog
.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE
));
15732 sLog
.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY
), GetResistance(SPELL_SCHOOL_FIRE
));
15733 sLog
.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE
), GetResistance(SPELL_SCHOOL_FROST
));
15734 sLog
.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW
), GetResistance(SPELL_SCHOOL_ARCANE
));
15735 sLog
.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE
), GetFloatValue(UNIT_FIELD_MAXDAMAGE
));
15736 sLog
.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
));
15737 sLog
.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
));
15738 sLog
.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK
), GetAttackTime(RANGED_ATTACK
));
15741 /*********************************************************/
15742 /*** FLOOD FILTER SYSTEM ***/
15743 /*********************************************************/
15745 void Player::UpdateSpeakTime()
15747 // ignore chat spam protection for GMs in any mode
15748 if(GetSession()->GetSecurity() > SEC_PLAYER
)
15751 time_t current
= time (NULL
);
15752 if(m_speakTime
> current
)
15754 uint32 max_count
= sWorld
.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT
);
15759 if(m_speakCount
>= max_count
)
15761 // prevent overwrite mute time, if message send just before mutes set, for example.
15762 time_t new_mute
= current
+ sWorld
.getConfig(CONFIG_CHATFLOOD_MUTE_TIME
);
15763 if(GetSession()->m_muteTime
< new_mute
)
15764 GetSession()->m_muteTime
= new_mute
;
15772 m_speakTime
= current
+ sWorld
.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY
);
15775 bool Player::CanSpeak() const
15777 return GetSession()->m_muteTime
<= time (NULL
);
15780 /*********************************************************/
15781 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15782 /*********************************************************/
15784 void Player::SendAttackSwingNotInRange()
15786 WorldPacket
data(SMSG_ATTACKSWING_NOTINRANGE
, 0);
15787 GetSession()->SendPacket( &data
);
15790 void Player::SavePositionInDB(uint32 mapid
, float x
,float y
,float z
,float o
,uint32 zone
,uint64 guid
)
15792 std::ostringstream ss
;
15793 ss
<< "UPDATE characters SET position_x='"<<x
<<"',position_y='"<<y
15794 << "',position_z='"<<z
<<"',orientation='"<<o
<<"',map='"<<mapid
15795 << "',zone='"<<zone
<<"',trans_x='0',trans_y='0',trans_z='0',"
15796 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
15797 sLog
.outDebug(ss
.str().c_str());
15798 CharacterDatabase
.Execute(ss
.str().c_str());
15801 void Player::SaveDataFieldToDB()
15803 std::ostringstream ss
;
15804 ss
<<"UPDATE characters SET data='";
15806 for(uint16 i
= 0; i
< m_valuesCount
; ++i
)
15808 ss
<< GetUInt32Value(i
) << " ";
15810 ss
<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
15812 CharacterDatabase
.Execute(ss
.str().c_str());
15815 bool Player::SaveValuesArrayInDB(Tokens
const& tokens
, uint64 guid
)
15817 std::ostringstream ss2
;
15818 ss2
<<"UPDATE characters SET data='";
15820 for (Tokens::const_iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
, ++i
)
15822 ss2
<<tokens
[i
]<<" ";
15824 ss2
<<"' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
15826 return CharacterDatabase
.Execute(ss2
.str().c_str());
15829 void Player::SetUInt32ValueInArray(Tokens
& tokens
,uint16 index
, uint32 value
)
15832 snprintf(buf
,11,"%u",value
);
15834 if(index
>= tokens
.size())
15837 tokens
[index
] = buf
;
15840 void Player::SetUInt32ValueInDB(uint16 index
, uint32 value
, uint64 guid
)
15843 if(!LoadValuesArrayFromDB(tokens
,guid
))
15846 if(index
>= tokens
.size())
15850 snprintf(buf
,11,"%u",value
);
15851 tokens
[index
] = buf
;
15853 SaveValuesArrayInDB(tokens
,guid
);
15856 void Player::SetFloatValueInDB(uint16 index
, float value
, uint64 guid
)
15859 memcpy(&temp
, &value
, sizeof(value
));
15860 Player::SetUInt32ValueInDB(index
, temp
, guid
);
15863 void Player::Customize(uint64 guid
, uint8 gender
, uint8 skin
, uint8 face
, uint8 hairStyle
, uint8 hairColor
, uint8 facialHair
)
15866 if(!LoadValuesArrayFromDB(tokens
, guid
))
15869 uint32 unit_bytes0
= GetUInt32ValueFromArray(tokens
, UNIT_FIELD_BYTES_0
);
15870 uint8 race
= unit_bytes0
& 0xFF;
15871 uint8 class_
= (unit_bytes0
>> 8) & 0xFF;
15873 PlayerInfo
const* info
= objmgr
.GetPlayerInfo(race
, class_
);
15877 unit_bytes0
&= ~(0xFF << 16);
15878 unit_bytes0
|= (gender
<< 16);
15879 SetUInt32ValueInArray(tokens
, UNIT_FIELD_BYTES_0
, unit_bytes0
);
15881 SetUInt32ValueInArray(tokens
, UNIT_FIELD_DISPLAYID
, gender
? info
->displayId_f
: info
->displayId_m
);
15882 SetUInt32ValueInArray(tokens
, UNIT_FIELD_NATIVEDISPLAYID
, gender
? info
->displayId_f
: info
->displayId_m
);
15884 SetUInt32ValueInArray(tokens
, PLAYER_BYTES
, (skin
| (face
<< 8) | (hairStyle
<< 16) | (hairColor
<< 24)));
15886 uint32 player_bytes2
= GetUInt32ValueFromArray(tokens
, PLAYER_BYTES_2
);
15887 player_bytes2
&= ~0xFF;
15888 player_bytes2
|= facialHair
;
15889 SetUInt32ValueInArray(tokens
, PLAYER_BYTES_2
, player_bytes2
);
15891 uint32 player_bytes3
= GetUInt32ValueFromArray(tokens
, PLAYER_BYTES_3
);
15892 player_bytes3
&= ~0xFF;
15893 player_bytes3
|= gender
;
15894 SetUInt32ValueInArray(tokens
, PLAYER_BYTES_3
, player_bytes3
);
15896 SaveValuesArrayInDB(tokens
, guid
);
15899 void Player::SendAttackSwingNotStanding()
15901 WorldPacket
data(SMSG_ATTACKSWING_NOTSTANDING
, 0);
15902 GetSession()->SendPacket( &data
);
15905 void Player::SendAttackSwingDeadTarget()
15907 WorldPacket
data(SMSG_ATTACKSWING_DEADTARGET
, 0);
15908 GetSession()->SendPacket( &data
);
15911 void Player::SendAttackSwingCantAttack()
15913 WorldPacket
data(SMSG_ATTACKSWING_CANT_ATTACK
, 0);
15914 GetSession()->SendPacket( &data
);
15917 void Player::SendAttackSwingCancelAttack()
15919 WorldPacket
data(SMSG_CANCEL_COMBAT
, 0);
15920 GetSession()->SendPacket( &data
);
15923 void Player::SendAttackSwingBadFacingAttack()
15925 WorldPacket
data(SMSG_ATTACKSWING_BADFACING
, 0);
15926 GetSession()->SendPacket( &data
);
15929 void Player::SendAutoRepeatCancel()
15931 WorldPacket
data(SMSG_CANCEL_AUTO_REPEAT
, GetPackGUID().size());
15932 data
.append(GetPackGUID()); // may be it's target guid
15933 GetSession()->SendPacket( &data
);
15936 void Player::SendExplorationExperience(uint32 Area
, uint32 Experience
)
15938 WorldPacket
data( SMSG_EXPLORATION_EXPERIENCE
, 8 );
15940 data
<< Experience
;
15941 GetSession()->SendPacket(&data
);
15944 void Player::SendDungeonDifficulty(bool IsInGroup
)
15946 uint8 val
= 0x00000001;
15947 WorldPacket
data(MSG_SET_DUNGEON_DIFFICULTY
, 12);
15948 data
<< (uint32
)GetDifficulty();
15949 data
<< uint32(val
);
15950 data
<< uint32(IsInGroup
);
15951 GetSession()->SendPacket(&data
);
15954 void Player::SendResetFailedNotify(uint32 mapid
)
15956 WorldPacket
data(SMSG_RESET_FAILED_NOTIFY
, 4);
15957 data
<< uint32(mapid
);
15958 GetSession()->SendPacket(&data
);
15961 /// Reset all solo instances and optionally send a message on success for each
15962 void Player::ResetInstances(uint8 method
)
15964 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
15966 // we assume that when the difficulty changes, all instances that can be reset will be
15967 uint8 dif
= GetDifficulty();
15969 for (BoundInstancesMap::iterator itr
= m_boundInstances
[dif
].begin(); itr
!= m_boundInstances
[dif
].end();)
15971 InstanceSave
*p
= itr
->second
.save
;
15972 const MapEntry
*entry
= sMapStore
.LookupEntry(itr
->first
);
15973 if(!entry
|| !p
->CanReset())
15979 if(method
== INSTANCE_RESET_ALL
)
15981 // the "reset all instances" method can only reset normal maps
15982 if(dif
== DIFFICULTY_HEROIC
|| entry
->map_type
== MAP_RAID
)
15989 // if the map is loaded, reset it
15990 Map
*map
= MapManager::Instance().FindMap(p
->GetMapId(), p
->GetInstanceId());
15991 if(map
&& map
->IsDungeon())
15992 ((InstanceMap
*)map
)->Reset(method
);
15994 // since this is a solo instance there should not be any players inside
15995 if(method
== INSTANCE_RESET_ALL
|| method
== INSTANCE_RESET_CHANGE_DIFFICULTY
)
15996 SendResetInstanceSuccess(p
->GetMapId());
15999 m_boundInstances
[dif
].erase(itr
++);
16001 // the following should remove the instance save from the manager and delete it as well
16002 p
->RemovePlayer(this);
16006 void Player::SendResetInstanceSuccess(uint32 MapId
)
16008 WorldPacket
data(SMSG_INSTANCE_RESET
, 4);
16010 GetSession()->SendPacket(&data
);
16013 void Player::SendResetInstanceFailed(uint32 reason
, uint32 MapId
)
16015 // TODO: find what other fail reasons there are besides players in the instance
16016 WorldPacket
data(SMSG_INSTANCE_RESET_FAILED
, 4);
16019 GetSession()->SendPacket(&data
);
16022 /*********************************************************/
16023 /*** Update timers ***/
16024 /*********************************************************/
16026 ///checks the 15 afk reports per 5 minutes limit
16027 void Player::UpdateAfkReport(time_t currTime
)
16029 if(m_bgAfkReportedTimer
<= currTime
)
16031 m_bgAfkReportedCount
= 0;
16032 m_bgAfkReportedTimer
= currTime
+5*MINUTE
;
16036 void Player::UpdateContestedPvP(uint32 diff
)
16038 if(!m_contestedPvPTimer
||isInCombat())
16040 if(m_contestedPvPTimer
<= diff
)
16042 ResetContestedPvP();
16045 m_contestedPvPTimer
-= diff
;
16048 void Player::UpdatePvPFlag(time_t currTime
)
16052 if(pvpInfo
.endTimer
== 0 || currTime
< (pvpInfo
.endTimer
+ 300))
16058 void Player::UpdateDuelFlag(time_t currTime
)
16060 if(!duel
|| duel
->startTimer
== 0 ||currTime
< duel
->startTimer
+ 3)
16063 SetUInt32Value(PLAYER_DUEL_TEAM
, 1);
16064 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 2);
16066 duel
->startTimer
= 0;
16067 duel
->startTime
= currTime
;
16068 duel
->opponent
->duel
->startTimer
= 0;
16069 duel
->opponent
->duel
->startTime
= currTime
;
16072 void Player::RemovePet(Pet
* pet
, PetSaveMode mode
, bool returnreagent
)
16077 if(returnreagent
&& (pet
|| m_temporaryUnsummonedPetNumber
))
16079 //returning of reagents only for players, so best done here
16080 uint32 spellId
= pet
? pet
->GetUInt32Value(UNIT_CREATED_BY_SPELL
) : m_oldpetspell
;
16081 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellId
);
16085 for(uint32 i
= 0; i
< 7; ++i
)
16087 if(spellInfo
->Reagent
[i
] > 0)
16089 ItemPosCountVec dest
; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16090 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, spellInfo
->Reagent
[i
], spellInfo
->ReagentCount
[i
] );
16091 if( msg
== EQUIP_ERR_OK
)
16093 Item
* item
= StoreNewItem( dest
, spellInfo
->Reagent
[i
], true);
16095 SendNewItem(item
,spellInfo
->ReagentCount
[i
],true,false);
16100 m_temporaryUnsummonedPetNumber
= 0;
16103 if(!pet
|| pet
->GetOwnerGUID()!=GetGUID())
16106 // only if current pet in slot
16107 switch(pet
->getPetType())
16113 m_guardianPets
.erase(pet
->GetGUID());
16116 if(GetPetGUID() == pet
->GetGUID())
16125 switch(pet
->GetEntry())
16127 //warlock pets except imp are removed(?) when logging out
16132 mode
= PET_SAVE_NOT_IN_SLOT
;
16137 pet
->SavePetToDB(mode
);
16139 pet
->CleanupsBeforeDelete();
16140 pet
->AddObjectToRemoveList();
16141 pet
->m_removed
= true;
16143 if(pet
->isControlled())
16145 WorldPacket
data(SMSG_PET_SPELLS
, 8+4);
16148 GetSession()->SendPacket(&data
);
16151 SetGroupUpdateFlag(GROUP_UPDATE_PET
);
16155 void Player::RemoveMiniPet()
16157 if(Pet
* pet
= GetMiniPet())
16159 pet
->Remove(PET_SAVE_AS_DELETED
);
16164 Pet
* Player::GetMiniPet()
16168 return ObjectAccessor::GetPet(m_miniPet
);
16171 void Player::RemoveGuardians()
16173 while(!m_guardianPets
.empty())
16175 uint64 guid
= *m_guardianPets
.begin();
16176 if(Pet
* pet
= ObjectAccessor::GetPet(guid
))
16177 pet
->Remove(PET_SAVE_AS_DELETED
);
16179 m_guardianPets
.erase(guid
);
16183 bool Player::HasGuardianWithEntry(uint32 entry
)
16185 // pet guid middle part is entry (and creature also)
16186 // and in guardian list must be guardians with same entry _always_
16187 for(GuardianPetList::const_iterator itr
= m_guardianPets
.begin(); itr
!= m_guardianPets
.end(); ++itr
)
16188 if(GUID_ENPART(*itr
)==entry
)
16194 void Player::Uncharm()
16196 Unit
* charm
= GetCharm();
16200 charm
->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM
);
16201 charm
->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS
);
16204 void Player::BuildPlayerChat(WorldPacket
*data
, uint8 msgtype
, const std::string
& text
, uint32 language
) const
16206 *data
<< (uint8
)msgtype
;
16207 *data
<< (uint32
)language
;
16208 *data
<< (uint64
)GetGUID();
16209 *data
<< (uint32
)language
; //language 2.1.0 ?
16210 *data
<< (uint64
)GetGUID();
16211 *data
<< (uint32
)(text
.length()+1);
16213 *data
<< (uint8
)chatTag();
16216 void Player::Say(const std::string
& text
, const uint32 language
)
16218 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16219 BuildPlayerChat(&data
, CHAT_MSG_SAY
, text
, language
);
16220 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_SAY
),true);
16223 void Player::Yell(const std::string
& text
, const uint32 language
)
16225 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16226 BuildPlayerChat(&data
, CHAT_MSG_YELL
, text
, language
);
16227 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_YELL
),true);
16230 void Player::TextEmote(const std::string
& text
)
16232 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16233 BuildPlayerChat(&data
, CHAT_MSG_EMOTE
, text
, LANG_UNIVERSAL
);
16234 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE
),true, !sWorld
.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT
) );
16237 void Player::Whisper(const std::string
& text
, uint32 language
,uint64 receiver
)
16239 if (language
!= LANG_ADDON
) // if not addon data
16240 language
= LANG_UNIVERSAL
; // whispers should always be readable
16242 Player
*rPlayer
= objmgr
.GetPlayer(receiver
);
16244 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16245 if(!rPlayer
->isDND() || isGameMaster())
16247 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16248 BuildPlayerChat(&data
, CHAT_MSG_WHISPER
, text
, language
);
16249 rPlayer
->GetSession()->SendPacket(&data
);
16251 data
.Initialize(SMSG_MESSAGECHAT
, 200);
16252 rPlayer
->BuildPlayerChat(&data
, CHAT_MSG_REPLY
, text
, language
);
16253 GetSession()->SendPacket(&data
);
16257 // announce to player that player he is whispering to is dnd and cannot receive his message
16258 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND
, rPlayer
->GetName(), rPlayer
->dndMsg
.c_str());
16261 if(!isAcceptWhispers())
16263 SetAcceptWhispers(true);
16264 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON
);
16267 // announce to player that player he is whispering to is afk
16268 if(rPlayer
->isAFK())
16269 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK
, rPlayer
->GetName(), rPlayer
->afkMsg
.c_str());
16271 // if player whisper someone, auto turn of dnd to be able to receive an answer
16272 if(isDND() && !rPlayer
->isGameMaster())
16276 void Player::PetSpellInitialize()
16278 Pet
* pet
= GetPet();
16283 sLog
.outDebug("Pet Spells Groups");
16285 CharmInfo
*charmInfo
= pet
->GetCharmInfo();
16287 WorldPacket
data(SMSG_PET_SPELLS
, 8+4+4+4+10*4);
16288 data
<< uint64(pet
->GetGUID());
16289 data
<< uint32(pet
->GetCreatureInfo()->family
); // creature family (required for pet talents)
16291 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState()) << uint16(0);
16294 for(uint32 i
= 0; i
< 10; ++i
)
16296 data
<< uint32(charmInfo
->GetActionBarEntry(i
)->Raw
);
16299 size_t spellsCountPos
= data
.wpos();
16303 data
<< uint8(addlist
); // placeholder
16305 if(pet
->isControlled() && ((pet
->getPetType() == HUNTER_PET
) || ((pet
->GetCreatureInfo()->type
== CREATURE_TYPE_DEMON
) && (getClass() == CLASS_WARLOCK
))))
16308 for (PetSpellMap::const_iterator itr
= pet
->m_spells
.begin(); itr
!= pet
->m_spells
.end(); ++itr
)
16310 if(itr
->second
->state
== PETSPELL_REMOVED
)
16313 data
<< uint16(itr
->first
);
16314 data
<< uint16(itr
->second
->active
); // pet spell active state isn't boolean
16319 data
.put
<uint8
>(spellsCountPos
, addlist
);
16321 uint8 cooldownsCount
= pet
->m_CreatureSpellCooldowns
.size() + pet
->m_CreatureCategoryCooldowns
.size();
16322 data
<< uint8(cooldownsCount
);
16324 time_t curTime
= time(NULL
);
16326 for(CreatureSpellCooldowns::const_iterator itr
= pet
->m_CreatureSpellCooldowns
.begin(); itr
!= pet
->m_CreatureSpellCooldowns
.end(); ++itr
)
16328 time_t cooldown
= (itr
->second
> curTime
) ? (itr
->second
- curTime
) * IN_MILISECONDS
: 0;
16330 data
<< uint16(itr
->first
); // spellid
16331 data
<< uint16(0); // spell category?
16332 data
<< uint32(cooldown
); // cooldown
16333 data
<< uint32(0); // category cooldown
16336 for(CreatureSpellCooldowns::const_iterator itr
= pet
->m_CreatureCategoryCooldowns
.begin(); itr
!= pet
->m_CreatureCategoryCooldowns
.end(); ++itr
)
16338 time_t cooldown
= (itr
->second
> curTime
) ? (itr
->second
- curTime
) * IN_MILISECONDS
: 0;
16340 data
<< uint16(itr
->first
); // spellid
16341 data
<< uint16(0); // spell category?
16342 data
<< uint32(0); // cooldown
16343 data
<< uint32(cooldown
); // category cooldown
16346 GetSession()->SendPacket(&data
);
16349 void Player::PossessSpellInitialize()
16351 Unit
* charm
= GetCharm();
16356 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
16360 sLog
.outError("Player::PossessSpellInitialize(): charm ("I64FMTD
") has no charminfo!", charm
->GetGUID());
16365 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);// first line + actionbar + spellcount + spells + last adds
16368 data
<< uint64(charm
->GetGUID());
16369 data
<< uint32(0x00000000);
16373 for(uint32 i
= 0; i
< 10; ++i
) //40
16375 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
16378 data
<< uint8(addlist
); //1
16381 data
<< uint8(count
); // cooldowns count
16383 GetSession()->SendPacket(&data
);
16386 void Player::CharmSpellInitialize()
16388 Unit
* charm
= GetCharm();
16393 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
16396 sLog
.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD
") has no charminfo!", charm
->GetGUID());
16402 if(charm
->GetTypeId() != TYPEID_PLAYER
)
16404 CreatureInfo
const *cinfo
= ((Creature
*)charm
)->GetCreatureInfo();
16406 if(cinfo
&& cinfo
->type
== CREATURE_TYPE_DEMON
&& getClass() == CLASS_WARLOCK
)
16408 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
16410 if(charmInfo
->GetCharmSpell(i
)->spellId
)
16416 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);// first line + actionbar + spellcount + spells + last adds
16418 data
<< uint64(charm
->GetGUID());
16419 data
<< uint32(0x00000000);
16421 if(charm
->GetTypeId() != TYPEID_PLAYER
)
16422 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState());
16424 data
<< uint8(0) << uint8(0);
16427 for(uint32 i
= 0; i
< 10; ++i
) //40
16429 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
16432 data
<< uint8(addlist
); //1
16436 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
16438 CharmSpellEntry
*cspell
= charmInfo
->GetCharmSpell(i
);
16439 if(cspell
->spellId
)
16441 data
<< uint16(cspell
->spellId
);
16442 data
<< uint16(cspell
->active
);
16448 data
<< uint8(count
); // cooldowns count
16450 GetSession()->SendPacket(&data
);
16453 bool Player::IsAffectedBySpellmod(SpellEntry
const *spellInfo
, SpellModifier
*mod
, Spell
const* spell
)
16455 if (!mod
|| !spellInfo
)
16458 if(mod
->charges
== -1 && mod
->lastAffected
) // marked as expired but locked until spell casting finish
16460 // prevent apply to any spell except spell that trigger expire
16463 if(mod
->lastAffected
!= spell
)
16466 else if(mod
->lastAffected
!= FindCurrentSpellBySpellId(spellInfo
->Id
))
16470 return spellmgr
.IsAffectedByMod(spellInfo
, mod
);
16473 void Player::AddSpellMod(SpellModifier
* mod
, bool apply
)
16475 uint16 Opcode
= (mod
->type
== SPELLMOD_FLAT
) ? SMSG_SET_FLAT_SPELL_MODIFIER
: SMSG_SET_PCT_SPELL_MODIFIER
;
16477 for(int eff
=0;eff
<96;++eff
)
16481 if (eff
<64) _mask
= uint64(1) << (eff
- 0);
16482 else _mask2
= uint64(1) << (eff
-64);
16483 if ( mod
->mask
& _mask
|| mod
->mask2
& _mask2
)
16486 for (SpellModList::const_iterator itr
= m_spellMods
[mod
->op
].begin(); itr
!= m_spellMods
[mod
->op
].end(); ++itr
)
16488 if ((*itr
)->type
== mod
->type
&& ((*itr
)->mask
& _mask
|| (*itr
)->mask2
& _mask2
))
16489 val
+= (*itr
)->value
;
16491 val
+= apply
? mod
->value
: -(mod
->value
);
16492 WorldPacket
data(Opcode
, (1+1+4));
16493 data
<< uint8(eff
);
16494 data
<< uint8(mod
->op
);
16495 data
<< int32(val
);
16496 SendDirectMessage(&data
);
16501 m_spellMods
[mod
->op
].push_back(mod
);
16504 if (mod
->charges
== -1)
16505 --m_SpellModRemoveCount
;
16506 m_spellMods
[mod
->op
].remove(mod
);
16511 void Player::RemoveSpellMods(Spell
const* spell
)
16513 if(!spell
|| (m_SpellModRemoveCount
== 0))
16516 for(int i
=0;i
<MAX_SPELLMOD
;++i
)
16518 for (SpellModList::const_iterator itr
= m_spellMods
[i
].begin(); itr
!= m_spellMods
[i
].end();)
16520 SpellModifier
*mod
= *itr
;
16523 if (mod
&& mod
->charges
== -1 && (mod
->lastAffected
== spell
|| mod
->lastAffected
==NULL
))
16525 RemoveAurasDueToSpell(mod
->spellId
);
16526 if (m_spellMods
[i
].empty())
16529 itr
= m_spellMods
[i
].begin();
16535 // send Proficiency
16536 void Player::SendProficiency(uint8 pr1
, uint32 pr2
)
16538 WorldPacket
data(SMSG_SET_PROFICIENCY
, 8);
16539 data
<< pr1
<< pr2
;
16540 GetSession()->SendPacket (&data
);
16543 void Player::RemovePetitionsAndSigns(uint64 guid
, uint32 type
)
16545 QueryResult
*result
= NULL
;
16547 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
16549 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16552 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.
16553 { // and SendPetitionQueryOpcode reads data from the DB
16554 Field
*fields
= result
->Fetch();
16555 uint64 ownerguid
= MAKE_NEW_GUID(fields
[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
16556 uint64 petitionguid
= MAKE_NEW_GUID(fields
[1].GetUInt32(), 0, HIGHGUID_ITEM
);
16558 // send update if charter owner in game
16559 Player
* owner
= objmgr
.GetPlayer(ownerguid
);
16561 owner
->GetSession()->SendPetitionQueryOpcode(petitionguid
);
16563 } while ( result
->NextRow() );
16568 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
16570 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16573 CharacterDatabase
.BeginTransaction();
16576 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid
));
16577 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid
));
16581 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16582 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16584 CharacterDatabase
.CommitTransaction();
16587 void Player::LeaveAllArenaTeams(uint64 guid
)
16589 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
));
16595 Field
*fields
= result
->Fetch();
16596 uint32 at_id
= fields
[0].GetUInt32();
16599 ArenaTeam
* at
= objmgr
.GetArenaTeamById(at_id
);
16601 at
->DelMember(guid
);
16603 } while (result
->NextRow());
16608 void Player::SetRestBonus (float rest_bonus_new
)
16610 // Prevent resting on max level
16611 if(getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
16612 rest_bonus_new
= 0;
16614 if(rest_bonus_new
< 0)
16615 rest_bonus_new
= 0;
16617 float rest_bonus_max
= (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)*1.5/2;
16619 if(rest_bonus_new
> rest_bonus_max
)
16620 m_rest_bonus
= rest_bonus_max
;
16622 m_rest_bonus
= rest_bonus_new
;
16624 // update data for client
16625 if(m_rest_bonus
>10)
16626 SetByteValue(PLAYER_BYTES_2
, 3, 0x01); // Set Reststate = Rested
16627 else if(m_rest_bonus
<=1)
16628 SetByteValue(PLAYER_BYTES_2
, 3, 0x02); // Set Reststate = Normal
16631 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE
, uint32(m_rest_bonus
));
16634 void Player::HandleStealthedUnitsDetection()
16636 std::list
<Unit
*> stealthedUnits
;
16638 CellPair
p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16640 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
16641 cell
.SetNoCreate();
16643 MaNGOS::AnyStealthedCheck u_check
;
16644 MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
> searcher(this,stealthedUnits
, u_check
);
16646 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, WorldTypeMapContainer
> world_unit_searcher(searcher
);
16647 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, GridTypeMapContainer
> grid_unit_searcher(searcher
);
16649 CellLock
<GridReadGuard
> cell_lock(cell
, p
);
16650 cell_lock
->Visit(cell_lock
, world_unit_searcher
, *GetMap());
16651 cell_lock
->Visit(cell_lock
, grid_unit_searcher
, *GetMap());
16653 for (std::list
<Unit
*>::iterator i
= stealthedUnits
.begin(); i
!= stealthedUnits
.end();)
16657 i
= stealthedUnits
.erase(i
);
16661 if ((*i
)->isVisibleForOrDetect(this,true))
16664 (*i
)->SendUpdateToPlayer(this);
16665 m_clientGUIDs
.insert((*i
)->GetGUID());
16667 #ifdef MANGOS_DEBUG
16668 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
16669 sLog
.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i
)->GetGUIDLow(),(*i
)->GetTypeId(),GetGUIDLow(),GetDistance(*i
));
16672 // target aura duration for caster show only if target exist at caster client
16673 // send data at target visibility change (adding to client)
16674 if((*i
)!=this && (*i
)->isType(TYPEMASK_UNIT
))
16675 SendAurasForTarget(*i
);
16677 i
= stealthedUnits
.erase(i
);
16685 bool Player::ActivateTaxiPathTo(std::vector
<uint32
> const& nodes
, uint32 mount_id
, Creature
* npc
)
16687 if(nodes
.size() < 2)
16690 // not let cheating with start flight mounted
16693 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16694 data
<< uint32(ERR_TAXIPLAYERALREADYMOUNTED
);
16695 GetSession()->SendPacket(&data
);
16699 if( m_ShapeShiftFormSpellId
&& m_form
!= FORM_BATTLESTANCE
&& m_form
!= FORM_BERSERKERSTANCE
&& m_form
!= FORM_DEFENSIVESTANCE
&& m_form
!= FORM_SHADOW
)
16701 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16702 data
<< uint32(ERR_TAXIPLAYERSHAPESHIFTED
);
16703 GetSession()->SendPacket(&data
);
16707 // 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
16708 if(GetSession()->isLogingOut() ||
16709 (!m_currentSpells
[CURRENT_GENERIC_SPELL
] ||
16710 m_currentSpells
[CURRENT_GENERIC_SPELL
]->m_spellInfo
->Effect
[0] != SPELL_EFFECT_SEND_TAXI
)&&
16711 IsNonMeleeSpellCasted(false) ||
16714 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16715 data
<< uint32(ERR_TAXIPLAYERBUSY
);
16716 GetSession()->SendPacket(&data
);
16720 if(HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_DISABLE_MOVE
))
16723 uint32 sourcenode
= nodes
[0];
16725 // starting node too far away (cheat?)
16726 TaxiNodesEntry
const* node
= sTaxiNodesStore
.LookupEntry(sourcenode
);
16727 if( !node
|| node
->map_id
!= GetMapId() ||
16728 (node
->x
- GetPositionX())*(node
->x
- GetPositionX())+
16729 (node
->y
- GetPositionY())*(node
->y
- GetPositionY())+
16730 (node
->z
- GetPositionZ())*(node
->z
- GetPositionZ()) >
16731 (2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
) )
16733 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16734 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
16735 GetSession()->SendPacket(&data
);
16739 // Prepare to flight start now
16741 // stop combat at start taxi flight if any
16744 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16747 // clean not finished taxi path if any
16748 m_taxi
.ClearTaxiDestinations();
16750 // 0 element current node
16751 m_taxi
.AddTaxiDestination(sourcenode
);
16753 // fill destinations path tail
16754 uint32 sourcepath
= 0;
16755 uint32 totalcost
= 0;
16757 uint32 prevnode
= sourcenode
;
16758 uint32 lastnode
= 0;
16760 for(uint32 i
= 1; i
< nodes
.size(); ++i
)
16764 lastnode
= nodes
[i
];
16765 objmgr
.GetTaxiPath(prevnode
, lastnode
, path
, cost
);
16769 m_taxi
.ClearTaxiDestinations();
16775 if(prevnode
== sourcenode
)
16778 m_taxi
.AddTaxiDestination(lastnode
);
16780 prevnode
= lastnode
;
16783 if(!mount_id
) // if not provide then attempt use default.
16784 mount_id
= objmgr
.GetTaxiMount(sourcenode
, GetTeam());
16786 if (mount_id
== 0 || sourcepath
== 0)
16788 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16789 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
16790 GetSession()->SendPacket(&data
);
16791 m_taxi
.ClearTaxiDestinations();
16795 uint32 money
= GetMoney();
16799 totalcost
= (uint32
)ceil(totalcost
*GetReputationPriceDiscount(npc
));
16802 if(money
< totalcost
)
16804 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16805 data
<< uint32(ERR_TAXINOTENOUGHMONEY
);
16806 GetSession()->SendPacket(&data
);
16807 m_taxi
.ClearTaxiDestinations();
16811 //Checks and preparations done, DO FLIGHT
16812 ModifyMoney(-(int32
)totalcost
);
16813 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING
, totalcost
);
16815 // prevent stealth flight
16816 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH
);
16818 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16819 data
<< uint32(ERR_TAXIOK
);
16820 GetSession()->SendPacket(&data
);
16822 sLog
.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16824 GetSession()->SendDoFlight(mount_id
, sourcepath
);
16829 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask
, uint32 unTimeMs
)
16831 // last check 2.0.10
16832 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+m_spells
.size()*8);
16834 data
<< uint8(0x0); // flags (0x1, 0x2)
16835 time_t curTime
= time(NULL
);
16836 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
16838 if (itr
->second
->state
== PLAYERSPELL_REMOVED
)
16840 uint32 unSpellId
= itr
->first
;
16841 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(unSpellId
);
16848 // Not send cooldown for this spells
16849 if (spellInfo
->Attributes
& SPELL_ATTR_DISABLED_WHILE_ACTIVE
)
16852 if((idSchoolMask
& GetSpellSchoolMask(spellInfo
)) && GetSpellCooldownDelay(unSpellId
) < unTimeMs
)
16855 data
<< unTimeMs
; // in m.secs
16856 AddSpellCooldown(unSpellId
, 0, curTime
+ unTimeMs
/IN_MILISECONDS
);
16859 GetSession()->SendPacket(&data
);
16862 void Player::InitDataForForm(bool reapplyMods
)
16864 SpellShapeshiftEntry
const* ssEntry
= sSpellShapeshiftStore
.LookupEntry(m_form
);
16865 if(ssEntry
&& ssEntry
->attackSpeed
)
16867 SetAttackTime(BASE_ATTACK
,ssEntry
->attackSpeed
);
16868 SetAttackTime(OFF_ATTACK
,ssEntry
->attackSpeed
);
16869 SetAttackTime(RANGED_ATTACK
, BASE_ATTACK_TIME
);
16872 SetRegularAttackTime();
16878 if(getPowerType()!=POWER_ENERGY
)
16879 setPowerType(POWER_ENERGY
);
16883 case FORM_DIREBEAR
:
16885 if(getPowerType()!=POWER_RAGE
)
16886 setPowerType(POWER_RAGE
);
16889 default: // 0, for example
16891 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(getClass());
16892 if(cEntry
&& cEntry
->powerType
< MAX_POWERS
&& uint32(getPowerType()) != cEntry
->powerType
)
16893 setPowerType(Powers(cEntry
->powerType
));
16898 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
16900 UpdateEquipSpellsAtFormChange();
16902 UpdateAttackPowerAndDamage();
16903 UpdateAttackPowerAndDamage(true);
16906 // Return true is the bought item has a max count to force refresh of window by caller
16907 bool Player::BuyItemFromVendor(uint64 vendorguid
, uint32 item
, uint8 count
, uint64 bagguid
, uint8 slot
)
16909 // cheating attempt
16910 if(count
< 1) count
= 1;
16915 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
16918 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, NULL
, item
, 0);
16922 Creature
*pCreature
= GetNPCIfCanInteractWith(vendorguid
,UNIT_NPC_FLAG_VENDOR
);
16925 sLog
.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid
)) );
16926 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR
, NULL
, item
, 0);
16930 VendorItemData
const* vItems
= pCreature
->GetVendorItems();
16931 if(!vItems
|| vItems
->Empty())
16933 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
16937 size_t vendor_slot
= vItems
->FindItemSlot(item
);
16938 if(vendor_slot
>= vItems
->GetItemCount())
16940 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
16944 VendorItem
const* crItem
= vItems
->m_items
[vendor_slot
];
16946 // check current item amount if it limited
16947 if( crItem
->maxcount
!= 0 )
16949 if(pCreature
->GetVendorItemCurrentCount(crItem
) < pProto
->BuyCount
* count
)
16951 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD
, pCreature
, item
, 0);
16956 if( uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
16958 SendBuyError( BUY_ERR_REPUTATION_REQUIRE
, pCreature
, item
, 0);
16962 if(crItem
->ExtendedCost
)
16964 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
16967 sLog
.outError("Item %u have wrong ExtendedCost field value %u", pProto
->ItemId
, crItem
->ExtendedCost
);
16971 // honor points price
16972 if(GetHonorPoints() < (iece
->reqhonorpoints
* count
))
16974 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS
, NULL
, NULL
);
16978 // arena points price
16979 if(GetArenaPoints() < (iece
->reqarenapoints
* count
))
16981 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS
, NULL
, NULL
);
16986 for (uint8 i
= 0; i
< 5; ++i
)
16988 if(iece
->reqitem
[i
] && !HasItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
)))
16990 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS
, NULL
, NULL
);
16995 // check for personal arena rating requirement
16996 if( GetMaxPersonalArenaRatingRequirement() < iece
->reqpersonalarenarating
)
16998 // probably not the proper equip err
16999 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK
,NULL
,NULL
);
17004 uint32 price
= pProto
->BuyPrice
* count
;
17006 // reputation discount
17007 price
= uint32(floor(price
* GetReputationPriceDiscount(pCreature
)));
17009 if( GetMoney() < price
)
17011 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, pCreature
, item
, 0);
17015 uint8 bag
= 0; // init for case invalid bagGUID
17017 if (bagguid
!= NULL_BAG
&& slot
!= NULL_SLOT
)
17020 if( bagguid
== GetGUID() )
17022 bag
= INVENTORY_SLOT_BAG_0
;
17026 for (int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
;++i
)
17028 pBag
= (Bag
*)GetItemByPos(INVENTORY_SLOT_BAG_0
,i
);
17031 if( bagguid
== pBag
->GetGUID() )
17041 if( IsInventoryPos( bag
, slot
) || (bagguid
== NULL_BAG
&& slot
== NULL_SLOT
) )
17043 ItemPosCountVec dest
;
17044 uint8 msg
= CanStoreNewItem( bag
, slot
, dest
, item
, pProto
->BuyCount
* count
);
17045 if( msg
!= EQUIP_ERR_OK
)
17047 SendEquipError( msg
, NULL
, NULL
);
17051 ModifyMoney( -(int32
)price
);
17052 if(crItem
->ExtendedCost
) // case for new honor system
17054 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
17055 if(iece
->reqhonorpoints
)
17056 ModifyHonorPoints( - int32(iece
->reqhonorpoints
* count
));
17057 if(iece
->reqarenapoints
)
17058 ModifyArenaPoints( - int32(iece
->reqarenapoints
* count
));
17059 for (uint8 i
= 0; i
< 5; ++i
)
17061 if(iece
->reqitem
[i
])
17062 DestroyItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
), true);
17066 if(Item
*it
= StoreNewItem( dest
, item
, true ))
17068 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
17070 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
17071 data
<< pCreature
->GetGUID();
17072 data
<< (uint32
)(vendor_slot
+1); // numbered from 1 at client
17073 data
<< (uint32
)(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
17074 data
<< (uint32
)count
;
17075 GetSession()->SendPacket(&data
);
17077 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
17080 else if( IsEquipmentPos( bag
, slot
) )
17082 if(pProto
->BuyCount
* count
!= 1)
17084 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
, NULL
, NULL
);
17089 uint8 msg
= CanEquipNewItem( slot
, dest
, item
, false );
17090 if( msg
!= EQUIP_ERR_OK
)
17092 SendEquipError( msg
, NULL
, NULL
);
17096 ModifyMoney( -(int32
)price
);
17097 if(crItem
->ExtendedCost
) // case for new honor system
17099 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
17100 if(iece
->reqhonorpoints
)
17101 ModifyHonorPoints( - int32(iece
->reqhonorpoints
));
17102 if(iece
->reqarenapoints
)
17103 ModifyArenaPoints( - int32(iece
->reqarenapoints
));
17104 for (uint8 i
= 0; i
< 5; ++i
)
17106 if(iece
->reqitem
[i
])
17107 DestroyItemCount(iece
->reqitem
[i
], iece
->reqitemcount
[i
], true);
17111 if(Item
*it
= EquipNewItem( dest
, item
, true ))
17113 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
17115 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
17116 data
<< pCreature
->GetGUID();
17117 data
<< (uint32
)(vendor_slot
+1); // numbered from 1 at client
17118 data
<< (uint32
)(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
17119 data
<< (uint32
)count
;
17120 GetSession()->SendPacket(&data
);
17122 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
17124 AutoUnequipOffhandIfNeed();
17129 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
, NULL
, NULL
);
17133 return crItem
->maxcount
!=0;
17136 uint32
Player::GetMaxPersonalArenaRatingRequirement()
17138 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17139 // the personal rating of the arena team must match the required limit as well
17140 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17141 uint32 max_personal_rating
= 0;
17142 for(int i
= 0; i
< MAX_ARENA_SLOT
; ++i
)
17144 if(ArenaTeam
* at
= objmgr
.GetArenaTeamById(GetArenaTeamId(i
)))
17146 uint32 p_rating
= GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ (i
* 6) + 5);
17147 uint32 t_rating
= at
->GetRating();
17148 p_rating
= p_rating
<t_rating
? p_rating
: t_rating
;
17149 if(max_personal_rating
< p_rating
)
17150 max_personal_rating
= p_rating
;
17153 return max_personal_rating
;
17156 void Player::UpdateHomebindTime(uint32 time
)
17158 // GMs never get homebind timer online
17159 if (m_InstanceValid
|| isGameMaster())
17161 if(m_HomebindTimer
) // instance valid, but timer not reset
17164 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
17167 GetSession()->SendPacket(&data
);
17169 // instance is valid, reset homebind timer
17170 m_HomebindTimer
= 0;
17172 else if (m_HomebindTimer
> 0)
17174 if (time
>= m_HomebindTimer
)
17176 // teleport to homebind location
17177 TeleportTo(m_homebindMapId
, m_homebindX
, m_homebindY
, m_homebindZ
, GetOrientation());
17180 m_HomebindTimer
-= time
;
17184 // instance is invalid, start homebind timer
17185 m_HomebindTimer
= 60000;
17186 // send message to player
17187 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
17188 data
<< m_HomebindTimer
;
17190 GetSession()->SendPacket(&data
);
17191 sLog
.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17195 void Player::UpdatePvP(bool state
, bool ovrride
)
17197 if(!state
|| ovrride
)
17200 if(Pet
* pet
= GetPet())
17201 pet
->SetPvP(state
);
17202 if(Unit
* charmed
= GetCharm())
17203 charmed
->SetPvP(state
);
17205 pvpInfo
.endTimer
= 0;
17209 if(pvpInfo
.endTimer
!= 0)
17210 pvpInfo
.endTimer
= time(NULL
);
17215 if(Pet
* pet
= GetPet())
17216 pet
->SetPvP(state
);
17217 if(Unit
* charmed
= GetCharm())
17218 charmed
->SetPvP(state
);
17223 void Player::AddSpellAndCategoryCooldowns(SpellEntry
const* spellInfo
, uint32 itemId
, Spell
* spell
, bool infinityCooldown
)
17225 // init cooldown values
17230 // some special item spells without correct cooldown in SpellInfo
17231 // cooldown information stored in item prototype
17232 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
17236 if(ItemPrototype
const* proto
= ObjectMgr::GetItemPrototype(itemId
))
17238 for(int idx
= 0; idx
< 5; ++idx
)
17240 if(proto
->Spells
[idx
].SpellId
== spellInfo
->Id
)
17242 cat
= proto
->Spells
[idx
].SpellCategory
;
17243 rec
= proto
->Spells
[idx
].SpellCooldown
;
17244 catrec
= proto
->Spells
[idx
].SpellCategoryCooldown
;
17251 // if no cooldown found above then base at DBC data
17252 if(rec
< 0 && catrec
< 0)
17254 cat
= spellInfo
->Category
;
17255 rec
= spellInfo
->RecoveryTime
;
17256 catrec
= spellInfo
->CategoryRecoveryTime
;
17259 time_t curTime
= time(NULL
);
17264 // overwrite time for selected category
17265 if(infinityCooldown
)
17267 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
17268 // but not allow ignore until reset or re-login
17269 catrecTime
= catrec
> 0 ? curTime
+MONTH
: 0;
17270 recTime
= rec
> 0 ? curTime
+MONTH
: catrecTime
;
17274 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
17275 // prevent 0 cooldowns set by another way
17276 if (rec
<= 0 && catrec
<= 0 && (cat
== 76 || IsAutoRepeatRangedSpell(spellInfo
) && spellInfo
->Id
!= SPELL_ID_AUTOSHOT
))
17277 rec
= GetAttackTime(RANGED_ATTACK
);
17279 // Now we have cooldown data (if found any), time to apply mods
17281 ApplySpellMod(spellInfo
->Id
, SPELLMOD_COOLDOWN
, rec
, spell
);
17284 ApplySpellMod(spellInfo
->Id
, SPELLMOD_COOLDOWN
, catrec
, spell
);
17286 // replace negative cooldowns by 0
17287 if (rec
< 0) rec
= 0;
17288 if (catrec
< 0) catrec
= 0;
17290 // no cooldown after applying spell mods
17291 if( rec
== 0 && catrec
== 0)
17294 catrecTime
= catrec
? curTime
+catrec
/IN_MILISECONDS
: 0;
17295 recTime
= rec
? curTime
+rec
/IN_MILISECONDS
: catrecTime
;
17298 // self spell cooldown
17300 AddSpellCooldown(spellInfo
->Id
, itemId
, recTime
);
17303 if (cat
&& catrec
> 0)
17305 SpellCategoryStore::const_iterator i_scstore
= sSpellCategoryStore
.find(cat
);
17306 if(i_scstore
!= sSpellCategoryStore
.end())
17308 for(SpellCategorySet::const_iterator i_scset
= i_scstore
->second
.begin(); i_scset
!= i_scstore
->second
.end(); ++i_scset
)
17310 if(*i_scset
== spellInfo
->Id
) // skip main spell, already handled above
17313 AddSpellCooldown(*i_scset
, itemId
, catrecTime
);
17319 void Player::AddSpellCooldown(uint32 spellid
, uint32 itemid
, time_t end_time
)
17323 sc
.itemid
= itemid
;
17324 m_spellCooldowns
[spellid
] = sc
;
17327 void Player::SendCooldownEvent(SpellEntry
const *spellInfo
, uint32 itemId
, Spell
* spell
)
17329 // start cooldowns at server side, if any
17330 AddSpellAndCategoryCooldowns(spellInfo
,itemId
,spell
);
17332 // Send activate cooldown timer (possible 0) at client side
17333 WorldPacket
data(SMSG_COOLDOWN_EVENT
, (4+8));
17334 data
<< spellInfo
->Id
;
17336 SendDirectMessage(&data
);
17339 void Player::UpdatePotionCooldown(Spell
* spell
)
17341 // no potion used i combat or still in combat
17342 if(!m_lastPotionId
|| isInCombat())
17345 // Call not from spell cast, send cooldown event for item spells if no in combat
17348 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
17349 if(ItemPrototype
const* proto
= ObjectMgr::GetItemPrototype(m_lastPotionId
))
17350 for(int idx
= 0; idx
< 5; ++idx
)
17351 if(proto
->Spells
[idx
].SpellId
&& proto
->Spells
[idx
].SpellTrigger
== ITEM_SPELLTRIGGER_ON_USE
)
17352 if(SpellEntry
const* spellInfo
= sSpellStore
.LookupEntry(proto
->Spells
[idx
].SpellId
))
17353 SendCooldownEvent(spellInfo
,m_lastPotionId
);
17355 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
17357 SendCooldownEvent(spell
->m_spellInfo
,m_lastPotionId
,spell
);
17359 m_lastPotionId
= 0;
17362 //slot to be excluded while counting
17363 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition
, int8 slot
)
17365 if(!enchantmentcondition
)
17368 SpellItemEnchantmentConditionEntry
const *Condition
= sSpellItemEnchantmentConditionStore
.LookupEntry(enchantmentcondition
);
17373 uint8 curcount
[4] = {0, 0, 0, 0};
17375 //counting current equipped gem colors
17376 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
17380 Item
*pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
17381 if(pItem2
&& pItem2
->GetProto()->Socket
[0].Color
)
17383 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17385 uint32 enchant_id
= pItem2
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17389 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17393 uint32 gemid
= enchantEntry
->GemID
;
17397 ItemPrototype
const* gemProto
= sItemStorage
.LookupEntry
<ItemPrototype
>(gemid
);
17401 GemPropertiesEntry
const* gemProperty
= sGemPropertiesStore
.LookupEntry(gemProto
->GemProperties
);
17405 uint8 GemColor
= gemProperty
->color
;
17407 for(uint8 b
= 0, tmpcolormask
= 1; b
< 4; b
++, tmpcolormask
<<= 1)
17409 if(tmpcolormask
& GemColor
)
17416 bool activate
= true;
17418 for(int i
= 0; i
< 5; ++i
)
17420 if(!Condition
->Color
[i
])
17423 uint32 _cur_gem
= curcount
[Condition
->Color
[i
] - 1];
17425 // if have <CompareColor> use them as count, else use <value> from Condition
17426 uint32 _cmp_gem
= Condition
->CompareColor
[i
] ? curcount
[Condition
->CompareColor
[i
] - 1]: Condition
->Value
[i
];
17428 switch(Condition
->Comparator
[i
])
17430 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17431 activate
&= (_cur_gem
< _cmp_gem
) ? true : false;
17433 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17434 activate
&= (_cur_gem
> _cmp_gem
) ? true : false;
17436 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17437 activate
&= (_cur_gem
>= _cmp_gem
) ? true : false;
17442 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");
17447 void Player::CorrectMetaGemEnchants(uint8 exceptslot
, bool apply
)
17449 //cycle all equipped items
17450 for(uint32 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
17452 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17453 if(slot
== exceptslot
)
17456 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
17458 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
)
17461 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17463 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17467 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17471 uint32 condition
= enchantEntry
->EnchantmentCondition
;
17474 //was enchant active with/without item?
17475 bool wasactive
= EnchantmentFitsRequirements(condition
, apply
? exceptslot
: -1);
17476 //should it now be?
17477 if(wasactive
^ EnchantmentFitsRequirements(condition
, apply
? -1 : exceptslot
))
17479 // ignore item gem conditions
17480 //if state changed, (dis)apply enchant
17481 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
),!wasactive
,true,true);
17488 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17489 void Player::ToggleMetaGemsActive(uint8 exceptslot
, bool apply
)
17491 //cycle all equipped items
17492 for(int slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
17494 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17495 if(slot
== exceptslot
)
17498 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
17500 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
) //if item has no sockets or no item is equipped go to next item
17503 //cycle all (gem)enchants
17504 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17506 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17507 if(!enchant_id
) //if no enchant go to next enchant(slot)
17510 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17514 //only metagems to be (de)activated, so only enchants with condition
17515 uint32 condition
= enchantEntry
->EnchantmentCondition
;
17517 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
), apply
);
17522 void Player::LeaveBattleground(bool teleportToEntryPoint
)
17524 if(BattleGround
*bg
= GetBattleGround())
17526 bg
->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint
, true);
17528 // call after remove to be sure that player resurrected for correct cast
17529 if( bg
->isBattleGround() && !isGameMaster() && sWorld
.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER
) )
17531 if( bg
->GetStatus() == STATUS_IN_PROGRESS
|| bg
->GetStatus() == STATUS_WAIT_JOIN
)
17532 CastSpell(this, 26013, true); // Deserter
17537 bool Player::CanJoinToBattleground() const
17539 // check Deserter debuff
17540 if(GetDummyAura(26013))
17546 bool Player::CanReportAfkDueToLimit()
17548 // a player can complain about 15 people per 5 minutes
17549 if(m_bgAfkReportedCount
>= 15)
17551 ++m_bgAfkReportedCount
;
17555 ///This player has been blamed to be inactive in a battleground
17556 void Player::ReportedAfkBy(Player
* reporter
)
17558 BattleGround
*bg
= GetBattleGround();
17559 if(!bg
|| bg
!= reporter
->GetBattleGround() || GetTeam() != reporter
->GetTeam())
17562 // check if player has 'Idle' or 'Inactive' debuff
17563 if(m_bgAfkReporter
.find(reporter
->GetGUIDLow())==m_bgAfkReporter
.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter
->CanReportAfkDueToLimit())
17565 m_bgAfkReporter
.insert(reporter
->GetGUIDLow());
17566 // 3 players have to complain to apply debuff
17567 if(m_bgAfkReporter
.size() >= 3)
17569 // cast 'Idle' spell
17570 CastSpell(this, 43680, true);
17571 m_bgAfkReporter
.clear();
17576 bool Player::IsVisibleInGridForPlayer( Player
* pl
) const
17578 // gamemaster in GM mode see all, including ghosts
17579 if(pl
->isGameMaster() && GetSession()->GetSecurity() <= pl
->GetSession()->GetSecurity())
17582 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17583 if (InBattleGround())
17585 if (!(isAlive() || m_deathTimer
> 0) && !IsFriendlyTo(pl
) )
17590 // Live player see live player or dead player with not realized corpse
17591 if(pl
->isAlive() || pl
->m_deathTimer
> 0)
17593 return isAlive() || m_deathTimer
> 0;
17596 // Ghost see other friendly ghosts, that's for sure
17597 if(!(isAlive() || m_deathTimer
> 0) && IsFriendlyTo(pl
))
17600 // Dead player see live players near own corpse
17603 Corpse
*corpse
= pl
->GetCorpse();
17606 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17607 if(corpse
->IsWithinDistInMap(this,(20+25)*sWorld
.getRate(RATE_CREATURE_AGGRO
)))
17612 // and not see any other
17616 bool Player::IsVisibleGloballyFor( Player
* u
) const
17621 // Always can see self
17625 // Visible units, always are visible for all players
17626 if (GetVisibility() == VISIBILITY_ON
)
17629 // GMs are visible for higher gms (or players are visible for gms)
17630 if (u
->GetSession()->GetSecurity() > SEC_PLAYER
)
17631 return GetSession()->GetSecurity() <= u
->GetSession()->GetSecurity();
17633 // non faction visibility non-breakable for non-GMs
17634 if (GetVisibility() == VISIBILITY_OFF
)
17637 // non-gm stealth/invisibility not hide from global player lists
17641 void Player::UpdateVisibilityOf(WorldObject
* target
)
17643 if(HaveAtClient(target
))
17645 if(!target
->isVisibleForInState(this,true))
17647 target
->DestroyForPlayer(this);
17648 m_clientGUIDs
.erase(target
->GetGUID());
17650 #ifdef MANGOS_DEBUG
17651 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17652 sLog
.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
17658 if(target
->isVisibleForInState(this,false))
17660 target
->SendUpdateToPlayer(this);
17661 if(target
->GetTypeId()!=TYPEID_GAMEOBJECT
||!((GameObject
*)target
)->IsTransport())
17662 m_clientGUIDs
.insert(target
->GetGUID());
17664 #ifdef MANGOS_DEBUG
17665 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17666 sLog
.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
17669 // target aura duration for caster show only if target exist at caster client
17670 // send data at target visibility change (adding to client)
17671 if(target
!=this && target
->isType(TYPEMASK_UNIT
))
17672 SendAurasForTarget((Unit
*)target
);
17674 if(target
->GetTypeId()==TYPEID_UNIT
&& ((Creature
*)target
)->isAlive())
17675 ((Creature
*)target
)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17681 inline void UpdateVisibilityOf_helper(std::set
<uint64
>& s64
, T
* target
)
17683 s64
.insert(target
->GetGUID());
17687 inline void UpdateVisibilityOf_helper(std::set
<uint64
>& s64
, GameObject
* target
)
17689 if(!target
->IsTransport())
17690 s64
.insert(target
->GetGUID());
17694 void Player::UpdateVisibilityOf(T
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
)
17696 if(HaveAtClient(target
))
17698 if(!target
->isVisibleForInState(this,true))
17700 target
->BuildOutOfRangeUpdateBlock(&data
);
17701 m_clientGUIDs
.erase(target
->GetGUID());
17703 #ifdef MANGOS_DEBUG
17704 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17705 sLog
.outDebug("Object %u (Type: %u, Entry: %u) is out of range for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),target
->GetEntry(),GetGUIDLow(),GetDistance(target
));
17711 if(target
->isVisibleForInState(this,false))
17713 visibleNow
.insert(target
);
17714 target
->BuildUpdate(data_updates
);
17715 target
->BuildCreateUpdateBlockForPlayer(&data
, this);
17716 UpdateVisibilityOf_helper(m_clientGUIDs
,target
);
17718 #ifdef MANGOS_DEBUG
17719 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17720 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
));
17726 template void Player::UpdateVisibilityOf(Player
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17727 template void Player::UpdateVisibilityOf(Creature
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17728 template void Player::UpdateVisibilityOf(Corpse
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17729 template void Player::UpdateVisibilityOf(GameObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17730 template void Player::UpdateVisibilityOf(DynamicObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17732 void Player::InitPrimaryProffesions()
17734 SetFreePrimaryProffesions(sWorld
.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL
));
17737 void Player::SendComboPoints()
17739 Unit
*combotarget
= ObjectAccessor::GetUnit(*this, m_comboTarget
);
17742 WorldPacket
data(SMSG_UPDATE_COMBO_POINTS
, combotarget
->GetPackGUID().size()+1);
17743 data
.append(combotarget
->GetPackGUID());
17744 data
<< uint8(m_comboPoints
);
17745 GetSession()->SendPacket(&data
);
17749 void Player::AddComboPoints(Unit
* target
, int8 count
)
17754 // without combo points lost (duration checked in aura)
17755 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
17757 if(target
->GetGUID() == m_comboTarget
)
17759 m_comboPoints
+= count
;
17764 if(Unit
* target2
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
17765 target2
->RemoveComboPointHolder(GetGUIDLow());
17767 m_comboTarget
= target
->GetGUID();
17768 m_comboPoints
= count
;
17770 target
->AddComboPointHolder(GetGUIDLow());
17773 if (m_comboPoints
> 5) m_comboPoints
= 5;
17774 if (m_comboPoints
< 0) m_comboPoints
= 0;
17779 void Player::ClearComboPoints()
17784 // without combopoints lost (duration checked in aura)
17785 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
17791 if(Unit
* target
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
17792 target
->RemoveComboPointHolder(GetGUIDLow());
17797 void Player::SetGroup(Group
*group
, int8 subgroup
)
17803 // never use SetGroup without a subgroup unless you specify NULL for group
17804 assert(subgroup
>= 0);
17805 m_group
.link(group
, this);
17806 m_group
.setSubGroup((uint8
)subgroup
);
17810 void Player::SendInitialPacketsBeforeAddToMap()
17812 WorldPacket
data(SMSG_SET_REST_START_OBSOLETE
, 4);
17813 data
<< uint32(0); // unknown, may be rest state time or experience
17814 GetSession()->SendPacket(&data
);
17817 data
.Initialize(SMSG_BINDPOINTUPDATE
, 5*4);
17818 data
<< m_homebindX
<< m_homebindY
<< m_homebindZ
;
17819 data
<< (uint32
) m_homebindMapId
;
17820 data
<< (uint32
) m_homebindZoneId
;
17821 GetSession()->SendPacket(&data
);
17823 // SMSG_SET_PROFICIENCY
17824 // SMSG_UPDATE_AURA_DURATION
17827 data
.Initialize(SMSG_TUTORIAL_FLAGS
, 8*4);
17828 for (int i
= 0; i
< 8; ++i
)
17829 data
<< uint32( GetTutorialInt(i
) );
17830 GetSession()->SendPacket(&data
);
17832 SendInitialSpells();
17834 data
.Initialize(SMSG_SEND_UNLEARN_SPELLS
, 4);
17835 data
<< uint32(0); // count, for(count) uint32;
17836 GetSession()->SendPacket(&data
);
17838 SendInitialActionButtons();
17839 m_reputationMgr
.SendInitialReputations();
17840 m_achievementMgr
.SendAllAchievementData();
17843 uint32 newzone
, newarea
;
17844 GetZoneAndAreaId(newzone
,newarea
);
17845 UpdateZone(newzone
,newarea
); // also call SendInitWorldStates();
17847 // SMSG_SET_AURA_SINGLE
17849 data
.Initialize(SMSG_LOGIN_SETTIMESPEED
, 8);
17850 data
<< uint32(secsToTimeBitFields(sWorld
.GetGameTime()));
17851 data
<< (float)0.01666667f
; // game speed
17852 GetSession()->SendPacket( &data
);
17854 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17855 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
) || isInFlight())
17856 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2
);
17861 void Player::SendInitialPacketsAfterAddToMap()
17863 WorldPacket
data(SMSG_TIME_SYNC_REQ
, 4); // new 2.0.x, enable movement
17864 data
<< uint32(0x00000000); // on blizz it increments periodically
17865 GetSession()->SendPacket(&data
);
17867 CastSpell(this, 836, true); // LOGINEFFECT
17869 // set some aura effects that send packet to player client after add player to map
17870 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17871 // same auras state lost at far teleport, send it one more time in this case also
17872 static const AuraType auratypes
[] =
17874 SPELL_AURA_MOD_FEAR
, SPELL_AURA_TRANSFORM
, SPELL_AURA_WATER_WALK
,
17875 SPELL_AURA_FEATHER_FALL
, SPELL_AURA_HOVER
, SPELL_AURA_SAFE_FALL
,
17876 SPELL_AURA_FLY
, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
, SPELL_AURA_NONE
17878 for(AuraType
const* itr
= &auratypes
[0]; itr
&& itr
[0] != SPELL_AURA_NONE
; ++itr
)
17880 Unit::AuraList
const& auraList
= GetAurasByType(*itr
);
17881 if(!auraList
.empty())
17882 auraList
.front()->ApplyModifier(true,true);
17885 if(HasAuraType(SPELL_AURA_MOD_STUN
))
17886 SetMovement(MOVE_ROOT
);
17888 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17889 if(HasAuraType(SPELL_AURA_MOD_ROOT
))
17891 WorldPacket
data2(SMSG_FORCE_MOVE_ROOT
, 10);
17892 data2
.append(GetPackGUID());
17893 data2
<< (uint32
)2;
17894 SendMessageToSet(&data2
,true);
17897 SendAurasForTarget(this);
17898 SendEnchantmentDurations(); // must be after add to map
17899 SendItemDurations(); // must be after add to map
17902 void Player::SendUpdateToOutOfRangeGroupMembers()
17904 if (m_groupUpdateMask
== GROUP_UPDATE_FLAG_NONE
)
17906 if(Group
* group
= GetGroup())
17907 group
->UpdatePlayerOutOfRange(this);
17909 m_groupUpdateMask
= GROUP_UPDATE_FLAG_NONE
;
17910 m_auraUpdateMask
= 0;
17911 if(Pet
*pet
= GetPet())
17912 pet
->ResetAuraUpdateMask();
17915 void Player::SendTransferAborted(uint32 mapid
, uint8 reason
, uint8 arg
)
17917 WorldPacket
data(SMSG_TRANSFER_ABORTED
, 4+2);
17918 data
<< uint32(mapid
);
17919 data
<< uint8(reason
); // transfer abort reason
17922 case TRANSFER_ABORT_INSUF_EXPAN_LVL
:
17923 case TRANSFER_ABORT_DIFFICULTY
:
17924 case TRANSFER_ABORT_UNIQUE_MESSAGE
:
17925 data
<< uint8(arg
);
17928 GetSession()->SendPacket(&data
);
17931 void Player::SendInstanceResetWarning(uint32 mapid
, uint32 time
)
17933 // type of warning, based on the time remaining until reset
17936 type
= RAID_INSTANCE_WELCOME
;
17937 else if(time
> 900 && time
<= 3600)
17938 type
= RAID_INSTANCE_WARNING_HOURS
;
17939 else if(time
> 300 && time
<= 900)
17940 type
= RAID_INSTANCE_WARNING_MIN
;
17942 type
= RAID_INSTANCE_WARNING_MIN_SOON
;
17943 WorldPacket
data(SMSG_RAID_INSTANCE_MESSAGE
, 4+4+4);
17944 data
<< uint32(type
);
17945 data
<< uint32(mapid
);
17946 data
<< uint32(time
);
17947 GetSession()->SendPacket(&data
);
17950 void Player::ApplyEquipCooldown( Item
* pItem
)
17952 for(int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
17954 _Spell
const& spellData
= pItem
->GetProto()->Spells
[i
];
17957 if( !spellData
.SpellId
)
17960 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
17961 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
)
17964 AddSpellCooldown(spellData
.SpellId
, pItem
->GetEntry(), time(NULL
) + 30);
17966 WorldPacket
data(SMSG_ITEM_COOLDOWN
, 12);
17967 data
<< pItem
->GetGUID();
17968 data
<< uint32(spellData
.SpellId
);
17969 GetSession()->SendPacket(&data
);
17973 void Player::resetSpells()
17975 // not need after this call
17976 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS
))
17978 m_atLoginFlags
= m_atLoginFlags
& ~AT_LOGIN_RESET_SPELLS
;
17979 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS
), GetGUIDLow());
17982 // make full copy of map (spells removed and marked as deleted at another spell remove
17983 // and we can't use original map for safe iterative with visit each spell at loop end
17984 PlayerSpellMap smap
= GetSpellMap();
17986 for(PlayerSpellMap::const_iterator iter
= smap
.begin();iter
!= smap
.end(); ++iter
)
17987 removeSpell(iter
->first
); // only iter->first can be accessed, object by iter->second can be deleted already
17989 learnDefaultSpells();
17990 learnQuestRewardedSpells();
17993 void Player::learnDefaultSpells()
17995 // learn default race/class spells
17996 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(),getClass());
17997 for (PlayerCreateInfoSpells::const_iterator itr
= info
->spell
.begin(); itr
!=info
->spell
.end(); ++itr
)
17999 uint32 tspell
= *itr
;
18000 sLog
.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell
);
18001 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
18002 addSpell(tspell
,true,true,true,false);
18003 else // but send in normal spell in game learn case
18004 learnSpell(tspell
,true);
18008 void Player::learnQuestRewardedSpells(Quest
const* quest
)
18010 uint32 spell_id
= quest
->GetRewSpellCast();
18012 // skip quests without rewarded spell
18016 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
18020 // check learned spells state
18021 bool found
= false;
18022 for(int i
=0; i
< 3; ++i
)
18024 if(spellInfo
->Effect
[i
] == SPELL_EFFECT_LEARN_SPELL
&& !HasSpell(spellInfo
->EffectTriggerSpell
[i
]))
18031 // skip quests with not teaching spell or already known spell
18035 // prevent learn non first rank unknown profession and second specialization for same profession)
18036 uint32 learned_0
= spellInfo
->EffectTriggerSpell
[0];
18037 if( spellmgr
.GetSpellRank(learned_0
) > 1 && !HasSpell(learned_0
) )
18039 // not have first rank learned (unlearned prof?)
18040 uint32 first_spell
= spellmgr
.GetFirstSpellInChain(learned_0
);
18041 if( !HasSpell(first_spell
) )
18044 SpellEntry
const *learnedInfo
= sSpellStore
.LookupEntry(learned_0
);
18049 if(learnedInfo
->Effect
[0]==SPELL_EFFECT_TRADE_SKILL
&& learnedInfo
->Effect
[1]==0)
18051 // search other specialization for same prof
18052 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
18054 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->first
==learned_0
)
18057 SpellEntry
const *itrInfo
= sSpellStore
.LookupEntry(itr
->first
);
18061 // compare only specializations
18062 if(itrInfo
->Effect
[0]!=SPELL_EFFECT_TRADE_SKILL
|| itrInfo
->Effect
[1]!=0)
18065 // compare same chain spells
18066 if(spellmgr
.GetFirstSpellInChain(itr
->first
) != first_spell
)
18069 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18070 if(!spellmgr
.IsHighRankOfSpell(learned_0
,itr
->first
))
18076 CastSpell( this, spell_id
, true);
18079 void Player::learnQuestRewardedSpells()
18081 // learn spells received from quest completing
18082 for(QuestStatusMap::const_iterator itr
= mQuestStatus
.begin(); itr
!= mQuestStatus
.end(); ++itr
)
18084 // skip no rewarded quests
18085 if(!itr
->second
.m_rewarded
)
18088 Quest
const* quest
= objmgr
.GetQuestTemplate(itr
->first
);
18092 learnQuestRewardedSpells(quest
);
18096 void Player::learnSkillRewardedSpells(uint32 skill_id
, uint32 skill_value
)
18098 uint32 raceMask
= getRaceMask();
18099 uint32 classMask
= getClassMask();
18100 for (uint32 j
=0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
18102 SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
);
18103 if (!pAbility
|| pAbility
->skillId
!=skill_id
|| pAbility
->learnOnGetSkill
!= ABILITY_LEARNED_ON_GET_PROFESSION_SKILL
)
18105 // Check race if set
18106 if (pAbility
->racemask
&& !(pAbility
->racemask
& raceMask
))
18108 // Check class if set
18109 if (pAbility
->classmask
&& !(pAbility
->classmask
& classMask
))
18112 if (sSpellStore
.LookupEntry(pAbility
->spellId
))
18114 // need unlearn spell
18115 if (skill_value
< pAbility
->req_skill_value
)
18116 removeSpell(pAbility
->spellId
);
18118 else if (!IsInWorld())
18119 addSpell(pAbility
->spellId
,true,true,true,false);
18121 learnSpell(pAbility
->spellId
,true);
18126 void Player::SendAurasForTarget(Unit
*target
)
18128 if(target
->GetVisibleAuras()->empty()) // speedup things
18131 WorldPacket
data(SMSG_AURA_UPDATE_ALL
);
18132 data
.append(target
->GetPackGUID());
18134 Unit::VisibleAuraMap
const *visibleAuras
= target
->GetVisibleAuras();
18135 for(Unit::VisibleAuraMap::const_iterator itr
= visibleAuras
->begin(); itr
!= visibleAuras
->end(); ++itr
)
18137 for(uint32 j
= 0; j
< 3; ++j
)
18139 if(Aura
*aura
= target
->GetAura(itr
->second
, j
))
18141 data
<< uint8(aura
->GetAuraSlot());
18142 data
<< uint32(aura
->GetId());
18146 uint8 auraFlags
= aura
->GetAuraFlags();
18148 data
<< uint8(auraFlags
);
18150 data
<< uint8(aura
->GetAuraLevel());
18152 data
<< uint8(aura
->GetAuraCharges());
18154 if(!(auraFlags
& AFLAG_NOT_CASTER
))
18156 data
<< uint8(0); // packed GUID of someone (caster?)
18159 if(auraFlags
& AFLAG_DURATION
) // include aura duration
18161 data
<< uint32(aura
->GetAuraMaxDuration());
18162 data
<< uint32(aura
->GetAuraDuration());
18170 GetSession()->SendPacket(&data
);
18173 void Player::SetDailyQuestStatus( uint32 quest_id
)
18175 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
18177 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
18179 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
18180 m_lastDailyQuestTime
= time(NULL
); // last daily quest time
18181 m_DailyQuestChanged
= true;
18187 void Player::ResetDailyQuestStatus()
18189 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
18190 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
18192 // DB data deleted in caller
18193 m_DailyQuestChanged
= false;
18194 m_lastDailyQuestTime
= 0;
18197 BattleGround
* Player::GetBattleGround() const
18199 if(GetBattleGroundId()==0)
18202 return sBattleGroundMgr
.GetBattleGround(GetBattleGroundId(), m_bgTypeID
);
18205 bool Player::InArena() const
18207 BattleGround
*bg
= GetBattleGround();
18208 if(!bg
|| !bg
->isArena())
18214 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId
) const
18216 // get a template bg instead of running one
18217 BattleGround
*bg
= sBattleGroundMgr
.GetBattleGroundTemplate(bgTypeId
);
18221 if(getLevel() < bg
->GetMinLevel() || getLevel() > bg
->GetMaxLevel())
18227 BGQueueIdBasedOnLevel
Player::GetBattleGroundQueueIdFromLevel(BattleGroundTypeId bgTypeId
) const
18229 //returned to hardcoded version of this function, because there is no way to code it dynamic
18230 uint32 level
= getLevel();
18231 if( bgTypeId
== BATTLEGROUND_AV
)
18234 uint32 queue_id
= (level
/ 10) - 1; // for ranges 0 - 19, 20 - 29, 30 - 39, 40 - 49, 50 - 59, 60 - 69, 70 -79, 80
18235 if( queue_id
>= MAX_BATTLEGROUND_QUEUES
)
18237 sLog
.outError("BattleGround: too high queue_id %u this shouldn't happen", queue_id
);
18238 return QUEUE_ID_MAX_LEVEL_80
;
18240 return BGQueueIdBasedOnLevel(queue_id
);
18243 float Player::GetReputationPriceDiscount( Creature
const* pCreature
) const
18245 FactionTemplateEntry
const* vendor_faction
= pCreature
->getFactionTemplateEntry();
18246 if(!vendor_faction
|| !vendor_faction
->faction
)
18249 ReputationRank rank
= GetReputationRank(vendor_faction
->faction
);
18250 if(rank
<= REP_NEUTRAL
)
18253 return 1.0f
- 0.05f
* (rank
- REP_NEUTRAL
);
18256 bool Player::IsSpellFitByClassAndRace( uint32 spell_id
) const
18258 uint32 racemask
= getRaceMask();
18259 uint32 classmask
= getClassMask();
18261 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
18262 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
18266 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
18268 // skip wrong race skills
18269 if( _spell_idx
->second
->racemask
&& (_spell_idx
->second
->racemask
& racemask
) == 0)
18272 // skip wrong class skills
18273 if( _spell_idx
->second
->classmask
&& (_spell_idx
->second
->classmask
& classmask
) == 0)
18282 bool Player::HasQuestForGO(int32 GOId
) const
18284 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
18286 uint32 questid
= GetQuestSlotQuestId(i
);
18287 if ( questid
== 0 )
18290 QuestStatusMap::const_iterator qs_itr
= mQuestStatus
.find(questid
);
18291 if(qs_itr
== mQuestStatus
.end())
18294 QuestStatusData
const& qs
= qs_itr
->second
;
18296 if (qs
.m_status
== QUEST_STATUS_INCOMPLETE
)
18298 Quest
const* qinfo
= objmgr
.GetQuestTemplate(questid
);
18302 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
18305 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
18307 if (qinfo
->ReqCreatureOrGOId
[j
]>=0) //skip non GO case
18310 if((-1)*GOId
== qinfo
->ReqCreatureOrGOId
[j
] && qs
.m_creatureOrGOcount
[j
] < qinfo
->ReqCreatureOrGOCount
[j
])
18318 void Player::UpdateForQuestsGO()
18320 if(m_clientGUIDs
.empty())
18324 WorldPacket packet
;
18325 for(ClientGUIDs::const_iterator itr
=m_clientGUIDs
.begin(); itr
!=m_clientGUIDs
.end(); ++itr
)
18327 if(IS_GAMEOBJECT_GUID(*itr
))
18329 GameObject
*obj
= HashMapHolder
<GameObject
>::Find(*itr
);
18331 obj
->BuildValuesUpdateBlockForPlayer(&udata
,this);
18334 udata
.BuildPacket(&packet
);
18335 GetSession()->SendPacket(&packet
);
18338 void Player::SummonIfPossible(bool agree
)
18342 m_summon_expire
= 0;
18346 // expire and auto declined
18347 if(m_summon_expire
< time(NULL
))
18350 // stop taxi flight at summon
18353 GetMotionMaster()->MovementExpired();
18354 m_taxi
.ClearTaxiDestinations();
18357 // drop flag at summon
18358 // 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
18359 if(BattleGround
*bg
= GetBattleGround())
18360 bg
->EventPlayerDroppedFlag(this);
18362 m_summon_expire
= 0;
18364 TeleportTo(m_summon_mapid
, m_summon_x
, m_summon_y
, m_summon_z
,GetOrientation());
18367 void Player::RemoveItemDurations( Item
*item
)
18369 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); ++itr
)
18373 m_itemDuration
.erase(itr
);
18379 void Player::AddItemDurations( Item
*item
)
18381 if(item
->GetUInt32Value(ITEM_FIELD_DURATION
))
18383 m_itemDuration
.push_back(item
);
18384 item
->SendTimeUpdate(this);
18388 void Player::AutoUnequipOffhandIfNeed()
18390 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
18394 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
18395 if (CanTitanGrip() || (offItem
->GetProto()->InventoryType
!= INVTYPE_2HWEAPON
&& !IsTwoHandUsed()))
18398 ItemPosCountVec off_dest
;
18399 uint8 off_msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false );
18400 if( off_msg
== EQUIP_ERR_OK
)
18402 RemoveItem(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
, true);
18403 StoreItem( off_dest
, offItem
, true );
18408 mi
.AddItem(offItem
->GetGUIDLow(), offItem
->GetEntry(), offItem
);
18409 MoveItemFromInventory(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
, true);
18410 CharacterDatabase
.BeginTransaction();
18411 offItem
->DeleteFromInventoryDB(); // deletes item from character's inventory
18412 offItem
->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
18413 CharacterDatabase
.CommitTransaction();
18415 std::string subject
= GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM
);
18416 WorldSession::SendMailTo(this, MAIL_NORMAL
, MAIL_STATIONERY_GM
, GetGUIDLow(), GetGUIDLow(), subject
, 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
);
18420 bool Player::HasItemFitToSpellReqirements(SpellEntry
const* spellInfo
, Item
const* ignoreItem
)
18422 if(spellInfo
->EquippedItemClass
< 0)
18425 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18426 // for optimize check 2 used cases only
18427 switch(spellInfo
->EquippedItemClass
)
18429 case ITEM_CLASS_WEAPON
:
18431 for(int i
= EQUIPMENT_SLOT_MAINHAND
; i
< EQUIPMENT_SLOT_TABARD
; ++i
)
18432 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
18433 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18437 case ITEM_CLASS_ARMOR
:
18439 // tabard not have dependent spells
18440 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_MAINHAND
; ++i
)
18441 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
18442 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18445 // shields can be equipped to offhand slot
18446 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
))
18447 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18450 // ranged slot can have some armor subclasses
18451 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_RANGED
))
18452 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18458 sLog
.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo
->EquippedItemClass
);
18465 bool Player::CanNoReagentCast(SpellEntry
const* spellInfo
) const
18467 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18468 if (spellInfo
->AttributesEx5
& SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
&&
18469 HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PREPARATION
))
18472 // Check no reagent use mask
18473 uint64 noReagentMask_0_1
= GetUInt64Value(PLAYER_NO_REAGENT_COST_1
);
18474 uint32 noReagentMask_2
= GetUInt64Value(PLAYER_NO_REAGENT_COST_1
+2);
18475 if (spellInfo
->SpellFamilyFlags
& noReagentMask_0_1
||
18476 spellInfo
->SpellFamilyFlags2
& noReagentMask_2
)
18482 void Player::RemoveItemDependentAurasAndCasts( Item
* pItem
)
18484 AuraMap
& auras
= GetAuras();
18485 for(AuraMap::const_iterator itr
= auras
.begin(); itr
!= auras
.end(); )
18487 Aura
* aura
= itr
->second
;
18489 // skip passive (passive item dependent spells work in another way) and not self applied auras
18490 SpellEntry
const* spellInfo
= aura
->GetSpellProto();
18491 if(aura
->IsPassive() || aura
->GetCasterGUID()!=GetGUID())
18497 // skip if not item dependent or have alternative item
18498 if(HasItemFitToSpellReqirements(spellInfo
,pItem
))
18504 // no alt item, remove aura, restart check
18505 RemoveAurasDueToSpell(aura
->GetId());
18506 itr
= auras
.begin();
18509 // currently casted spells can be dependent from item
18510 for (uint32 i
= 0; i
< CURRENT_MAX_SPELL
; ++i
)
18512 if( m_currentSpells
[i
] && m_currentSpells
[i
]->getState()!=SPELL_STATE_DELAYED
&&
18513 !HasItemFitToSpellReqirements(m_currentSpells
[i
]->m_spellInfo
,pItem
) )
18518 uint32
Player::GetResurrectionSpellId()
18520 // search priceless resurrection possibilities
18522 uint32 spell_id
= 0;
18523 AuraList
const& dummyAuras
= GetAurasByType(SPELL_AURA_DUMMY
);
18524 for(AuraList::const_iterator itr
= dummyAuras
.begin(); itr
!= dummyAuras
.end(); ++itr
)
18526 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18527 if( prio
< 2 && (*itr
)->GetSpellProto()->SpellVisual
[0] == 99 && (*itr
)->GetSpellProto()->SpellIconID
== 92 )
18529 switch((*itr
)->GetId())
18531 case 20707: spell_id
= 3026; break; // rank 1
18532 case 20762: spell_id
= 20758; break; // rank 2
18533 case 20763: spell_id
= 20759; break; // rank 3
18534 case 20764: spell_id
= 20760; break; // rank 4
18535 case 20765: spell_id
= 20761; break; // rank 5
18536 case 27239: spell_id
= 27240; break; // rank 6
18537 case 47883: spell_id
= 47882; break; // rank 7
18539 sLog
.outError("Unhandled spell %u: S.Resurrection",(*itr
)->GetId());
18545 // Twisting Nether // prio: 2 (max)
18546 else if((*itr
)->GetId()==23701 && roll_chance_i(10))
18553 // Reincarnation (passive spell) // prio: 1
18554 if(prio
< 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18560 // Used in triggers for check "Only to targets that grant experience or honor" req
18561 bool Player::isHonorOrXPTarget(Unit
* pVictim
)
18563 uint32 v_level
= pVictim
->getLevel();
18564 uint32 k_grey
= MaNGOS::XP::GetGrayLevel(getLevel());
18566 // Victim level less gray level
18567 if(v_level
<=k_grey
)
18570 if(pVictim
->GetTypeId() == TYPEID_UNIT
)
18572 if (((Creature
*)pVictim
)->isTotem() ||
18573 ((Creature
*)pVictim
)->isPet() ||
18574 ((Creature
*)pVictim
)->GetCreatureInfo()->flags_extra
& CREATURE_FLAG_EXTRA_NO_XP_AT_KILL
)
18580 bool Player::RewardPlayerAndGroupAtKill(Unit
* pVictim
)
18582 bool PvP
= pVictim
->isCharmedOwnedByPlayerOrPlayer();
18584 // prepare data for near group iteration (PvP and !PvP cases)
18586 bool honored_kill
= false;
18588 if(Group
*pGroup
= GetGroup())
18591 uint32 sum_level
= 0;
18592 Player
* member_with_max_level
= NULL
;
18593 Player
* not_gray_member_with_max_level
= NULL
;
18595 pGroup
->GetDataForXPAtKill(pVictim
,count
,sum_level
,member_with_max_level
,not_gray_member_with_max_level
);
18597 if(member_with_max_level
)
18599 /// not get Xp in PvP or no not gray players in group
18600 xp
= (PvP
|| !not_gray_member_with_max_level
) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level
, pVictim
);
18602 /// skip in check PvP case (for speed, not used)
18603 bool is_raid
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsRaid() && pGroup
->isRaidGroup();
18604 bool is_dungeon
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsDungeon();
18605 float group_rate
= MaNGOS::XP::xp_in_group_rate(count
,is_raid
);
18607 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
18609 Player
* pGroupGuy
= itr
->getSource();
18613 if(!pGroupGuy
->IsAtGroupRewardDistance(pVictim
))
18614 continue; // member (alive or dead) or his corpse at req. distance
18616 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18617 if(pGroupGuy
->isAlive() && pGroupGuy
->RewardHonor(pVictim
,count
) && pGroupGuy
==this)
18618 honored_kill
= true;
18620 // xp and reputation only in !PvP case
18623 float rate
= group_rate
* float(pGroupGuy
->getLevel()) / sum_level
;
18625 // if is in dungeon then all receive full reputation at kill
18626 // rewarded any alive/dead/near_corpse group member
18627 pGroupGuy
->RewardReputation(pVictim
,is_dungeon
? 1.0f
: rate
);
18629 // XP updated only for alive group member
18630 if(pGroupGuy
->isAlive() && not_gray_member_with_max_level
&&
18631 pGroupGuy
->getLevel() <= not_gray_member_with_max_level
->getLevel())
18633 uint32 itr_xp
= (member_with_max_level
== not_gray_member_with_max_level
) ? uint32(xp
*rate
) : uint32((xp
*rate
/2)+1);
18635 pGroupGuy
->GiveXP(itr_xp
, pVictim
);
18636 if(Pet
* pet
= pGroupGuy
->GetPet())
18637 pet
->GivePetXP(itr_xp
/2);
18640 // quest objectives updated only for alive group member or dead but with not released body
18641 if(pGroupGuy
->isAlive()|| !pGroupGuy
->GetCorpse())
18643 // normal creature (not pet/etc) can be only in !PvP case
18644 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
18645 pGroupGuy
->KilledMonster(pVictim
->GetEntry(), pVictim
->GetGUID());
18651 else // if (!pGroup)
18653 xp
= PvP
? 0 : MaNGOS::XP::Gain(this, pVictim
);
18655 // honor can be in PvP and !PvP (racial leader) cases
18656 if(RewardHonor(pVictim
,1))
18657 honored_kill
= true;
18659 // xp and reputation only in !PvP case
18662 RewardReputation(pVictim
,1);
18663 GiveXP(xp
, pVictim
);
18665 if(Pet
* pet
= GetPet())
18666 pet
->GivePetXP(xp
);
18668 // normal creature (not pet/etc) can be only in !PvP case
18669 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
18670 KilledMonster(pVictim
->GetEntry(),pVictim
->GetGUID());
18673 return xp
|| honored_kill
;
18676 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id
, WorldObject
* pRewardSource
)
18678 uint64 creature_guid
= pRewardSource
->GetTypeId()==TYPEID_UNIT
? pRewardSource
->GetGUID() : uint64(0);
18680 // prepare data for near group iteration
18681 if(Group
*pGroup
= GetGroup())
18683 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
18685 Player
* pGroupGuy
= itr
->getSource();
18689 if(!pGroupGuy
->IsAtGroupRewardDistance(pRewardSource
))
18690 continue; // member (alive or dead) or his corpse at req. distance
18692 // quest objectives updated only for alive group member or dead but with not released body
18693 if(pGroupGuy
->isAlive()|| !pGroupGuy
->GetCorpse())
18694 pGroupGuy
->KilledMonster(creature_id
, creature_guid
);
18697 else // if (!pGroup)
18698 KilledMonster(creature_id
, creature_guid
);
18701 bool Player::IsAtGroupRewardDistance(WorldObject
const* pRewardSource
) const
18703 if (pRewardSource
->IsWithinDistInMap(this,sWorld
.getConfig(CONFIG_GROUP_XP_DISTANCE
)))
18709 Corpse
* corpse
= GetCorpse();
18713 return pRewardSource
->IsWithinDistInMap(corpse
,sWorld
.getConfig(CONFIG_GROUP_XP_DISTANCE
));
18716 uint32
Player::GetBaseWeaponSkillValue (WeaponAttackType attType
) const
18718 Item
* item
= GetWeaponForAttack(attType
,true);
18720 // unarmed only with base attack
18721 if(attType
!= BASE_ATTACK
&& !item
)
18724 // weapon skill or (unarmed for base attack)
18725 uint32 skill
= item
? item
->GetSkill() : uint32(SKILL_UNARMED
);
18726 return GetBaseSkillValue(skill
);
18729 void Player::ResurectUsingRequestData()
18731 /// Teleport before resurrecting, otherwise the player might get attacked from creatures near his corpse
18732 TeleportTo(m_resurrectMap
, m_resurrectX
, m_resurrectY
, m_resurrectZ
, GetOrientation());
18734 ResurrectPlayer(0.0f
,false);
18736 if(GetMaxHealth() > m_resurrectHealth
)
18737 SetHealth( m_resurrectHealth
);
18739 SetHealth( GetMaxHealth() );
18741 if(GetMaxPower(POWER_MANA
) > m_resurrectMana
)
18742 SetPower(POWER_MANA
, m_resurrectMana
);
18744 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
) );
18746 SetPower(POWER_RAGE
, 0 );
18748 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
) );
18750 SpawnCorpseBones();
18753 void Player::SetClientControl(Unit
* target
, uint8 allowMove
)
18755 WorldPacket
data(SMSG_CLIENT_CONTROL_UPDATE
, target
->GetPackGUID().size()+1);
18756 data
.append(target
->GetPackGUID());
18757 data
<< uint8(allowMove
);
18758 GetSession()->SendPacket(&data
);
18761 void Player::UpdateZoneDependentAuras( uint32 newZone
)
18763 // remove new continent flight forms
18764 if( !IsAllowUseFlyMountsHere() )
18766 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
);
18767 RemoveSpellsCausingAura(SPELL_AURA_FLY
);
18770 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
18771 SpellAreaForAreaMapBounds saBounds
= spellmgr
.GetSpellAreaForAreaMapBounds(newZone
);
18772 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
18773 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,newZone
,0))
18774 if( !HasAura(itr
->second
->spellId
,0) )
18775 CastSpell(this,itr
->second
->spellId
,true);
18778 void Player::UpdateAreaDependentAuras( uint32 newArea
)
18780 // remove auras from spells with area limitations
18781 for(AuraMap::iterator iter
= m_Auras
.begin(); iter
!= m_Auras
.end();)
18783 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18784 if(spellmgr
.GetSpellAllowedInLocationError(iter
->second
->GetSpellProto(),GetMapId(),m_zoneUpdateId
,newArea
,this) != SPELL_CAST_OK
)
18790 // some auras applied at subzone enter
18791 SpellAreaForAreaMapBounds saBounds
= spellmgr
.GetSpellAreaForAreaMapBounds(newArea
);
18792 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
18793 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,m_zoneUpdateId
,newArea
))
18794 if( !HasAura(itr
->second
->spellId
,0) )
18795 CastSpell(this,itr
->second
->spellId
,true);
18798 uint32
Player::GetCorpseReclaimDelay(bool pvp
) const
18800 if( pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18801 !pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18803 return copseReclaimDelay
[0];
18806 time_t now
= time(NULL
);
18807 // 0..2 full period
18808 uint32 count
= (now
< m_deathExpireTime
) ? (m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
: 0;
18809 return copseReclaimDelay
[count
];
18812 void Player::UpdateCorpseReclaimDelay()
18814 bool pvp
= m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
;
18816 if( pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18817 !pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18820 time_t now
= time(NULL
);
18821 if(now
< m_deathExpireTime
)
18823 // full and partly periods 1..3
18824 uint32 count
= (m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
+1;
18825 if(count
< MAX_DEATH_COUNT
)
18826 m_deathExpireTime
= now
+(count
+1)*DEATH_EXPIRE_STEP
;
18828 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
;
18831 m_deathExpireTime
= now
+DEATH_EXPIRE_STEP
;
18834 void Player::SendCorpseReclaimDelay(bool load
)
18836 Corpse
* corpse
= GetCorpse();
18843 if(corpse
->GetGhostTime() > m_deathExpireTime
)
18846 bool pvp
= corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
;
18849 if( pvp
&& sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18850 !pvp
&& sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18852 count
= (m_deathExpireTime
-corpse
->GetGhostTime())/DEATH_EXPIRE_STEP
;
18853 if(count
>=MAX_DEATH_COUNT
)
18854 count
= MAX_DEATH_COUNT
-1;
18859 time_t expected_time
= corpse
->GetGhostTime()+copseReclaimDelay
[count
];
18861 time_t now
= time(NULL
);
18862 if(now
>= expected_time
)
18865 delay
= expected_time
-now
;
18868 delay
= GetCorpseReclaimDelay(corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
);
18870 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
18871 WorldPacket
data(SMSG_CORPSE_RECLAIM_DELAY
, 4);
18872 data
<< uint32(delay
*IN_MILISECONDS
);
18873 GetSession()->SendPacket( &data
);
18876 Player
* Player::GetNextRandomRaidMember(float radius
)
18878 Group
*pGroup
= GetGroup();
18882 std::vector
<Player
*> nearMembers
;
18883 nearMembers
.reserve(pGroup
->GetMembersCount());
18885 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
18887 Player
* Target
= itr
->getSource();
18889 // IsHostileTo check duel and controlled by enemy
18890 if( Target
&& Target
!= this && IsWithinDistInMap(Target
, radius
) &&
18891 !Target
->HasInvisibilityAura() && !IsHostileTo(Target
) )
18892 nearMembers
.push_back(Target
);
18895 if (nearMembers
.empty())
18898 uint32 randTarget
= urand(0,nearMembers
.size()-1);
18899 return nearMembers
[randTarget
];
18902 PartyResult
Player::CanUninviteFromGroup() const
18904 const Group
* grp
= GetGroup();
18906 return PARTY_RESULT_YOU_NOT_IN_GROUP
;
18908 if(!grp
->IsLeader(GetGUID()) && !grp
->IsAssistant(GetGUID()))
18909 return PARTY_RESULT_YOU_NOT_LEADER
;
18911 if(InBattleGround())
18912 return PARTY_RESULT_INVITE_RESTRICTED
;
18914 return PARTY_RESULT_OK
;
18917 void Player::SetBattleGroundRaid(Group
* group
, int8 subgroup
)
18919 //we must move references from m_group to m_originalGroup
18920 SetOriginalGroup(GetGroup(), GetSubGroup());
18923 m_group
.link(group
, this);
18924 m_group
.setSubGroup((uint8
)subgroup
);
18927 void Player::RemoveFromBattleGroundRaid()
18929 //remove existing reference
18931 if( Group
* group
= GetOriginalGroup() )
18933 m_group
.link(group
, this);
18934 m_group
.setSubGroup(GetOriginalSubGroup());
18936 SetOriginalGroup(NULL
);
18939 void Player::SetOriginalGroup(Group
*group
, int8 subgroup
)
18941 if( group
== NULL
)
18942 m_originalGroup
.unlink();
18945 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
18946 assert(subgroup
>= 0);
18947 m_originalGroup
.link(group
, this);
18948 m_originalGroup
.setSubGroup((uint8
)subgroup
);
18952 void Player::UpdateUnderwaterState( Map
* m
, float x
, float y
, float z
)
18954 LiquidData liquid_status
;
18955 ZLiquidStatus res
= m
->getLiquidStatus(x
, y
, z
, MAP_ALL_LIQUIDS
, &liquid_status
);
18958 m_MirrorTimerFlags
&= ~(UNDERWATER_INWATER
|UNDERWATER_INLAVA
|UNDERWATER_INSLIME
|UNDERWARER_INDARKWATER
);
18959 // Small hack for enable breath in WMO
18961 m_MirrorTimerFlags
|=UNDERWATER_INWATER
;
18965 // All liquids type - check under water position
18966 if (liquid_status
.type
&(MAP_LIQUID_TYPE_WATER
|MAP_LIQUID_TYPE_OCEAN
|MAP_LIQUID_TYPE_MAGMA
|MAP_LIQUID_TYPE_SLIME
))
18968 if ( res
& LIQUID_MAP_UNDER_WATER
)
18969 m_MirrorTimerFlags
|= UNDERWATER_INWATER
;
18971 m_MirrorTimerFlags
&= ~UNDERWATER_INWATER
;
18974 // Allow travel in dark water on taxi or transport
18975 if ((liquid_status
.type
& MAP_LIQUID_TYPE_DARK_WATER
) && !isInFlight() && !GetTransport())
18976 m_MirrorTimerFlags
|= UNDERWARER_INDARKWATER
;
18978 m_MirrorTimerFlags
&= ~UNDERWARER_INDARKWATER
;
18980 // in lava check, anywhere in lava level
18981 if (liquid_status
.type
&MAP_LIQUID_TYPE_MAGMA
)
18983 if (res
& (LIQUID_MAP_UNDER_WATER
|LIQUID_MAP_IN_WATER
|LIQUID_MAP_WATER_WALK
))
18984 m_MirrorTimerFlags
|= UNDERWATER_INLAVA
;
18986 m_MirrorTimerFlags
&= ~UNDERWATER_INLAVA
;
18988 // in slime check, anywhere in slime level
18989 if (liquid_status
.type
&MAP_LIQUID_TYPE_SLIME
)
18991 if (res
& (LIQUID_MAP_UNDER_WATER
|LIQUID_MAP_IN_WATER
|LIQUID_MAP_WATER_WALK
))
18992 m_MirrorTimerFlags
|= UNDERWATER_INSLIME
;
18994 m_MirrorTimerFlags
&= ~UNDERWATER_INSLIME
;
18998 void Player::SetCanParry( bool value
)
19000 if(m_canParry
==value
)
19003 m_canParry
= value
;
19004 UpdateParryPercentage();
19007 void Player::SetCanBlock( bool value
)
19009 if(m_canBlock
==value
)
19012 m_canBlock
= value
;
19013 UpdateBlockPercentage();
19016 bool ItemPosCount::isContainedIn(ItemPosCountVec
const& vec
) const
19018 for(ItemPosCountVec::const_iterator itr
= vec
.begin(); itr
!= vec
.end();++itr
)
19019 if(itr
->pos
== pos
)
19025 bool Player::CanUseBattleGroundObject()
19027 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
19028 // maybe gameobject code should handle that ForceReaction usage
19029 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
19030 return ( //InBattleGround() && // in battleground - not need, check in other cases
19031 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
19032 //player cannot use object when he is invulnerable (immune)
19033 !isTotalImmune() && // not totally immune
19034 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
19035 !HasStealthAura() && // not stealthed
19036 !HasInvisibilityAura() && // not invisible
19037 !HasAura(SPELL_RECENTLY_DROPPED_FLAG
, 0) && // can't pickup
19038 isAlive() // live player
19042 bool Player::CanCaptureTowerPoint()
19044 return ( !HasStealthAura() && // not stealthed
19045 !HasInvisibilityAura() && // not invisible
19046 isAlive() // live player
19050 uint32
Player::GetBarberShopCost(uint8 newhairstyle
, uint8 newhaircolor
, uint8 newfacialhair
)
19052 uint32 level
= getLevel();
19054 if(level
> GT_MAX_LEVEL
)
19055 level
= GT_MAX_LEVEL
; // max level in this dbc
19057 uint8 hairstyle
= GetByteValue(PLAYER_BYTES
, 2);
19058 uint8 haircolor
= GetByteValue(PLAYER_BYTES
, 3);
19059 uint8 facialhair
= GetByteValue(PLAYER_BYTES_2
, 0);
19061 if((hairstyle
== newhairstyle
) && (haircolor
== newhaircolor
) && (facialhair
== newfacialhair
))
19064 GtBarberShopCostBaseEntry
const *bsc
= sGtBarberShopCostBaseStore
.LookupEntry(level
- 1);
19066 if(!bsc
) // shouldn't happen
19071 if(hairstyle
!= newhairstyle
)
19072 cost
+= bsc
->cost
; // full price
19074 if((haircolor
!= newhaircolor
) && (hairstyle
== newhairstyle
))
19075 cost
+= bsc
->cost
* 0.5f
; // +1/2 of price
19077 if(facialhair
!= newfacialhair
)
19078 cost
+= bsc
->cost
* 0.75f
; // +3/4 of price
19080 return uint32(cost
);
19083 void Player::InitGlyphsForLevel()
19085 for(uint32 i
= 0; i
< sGlyphSlotStore
.GetNumRows(); ++i
)
19086 if(GlyphSlotEntry
const * gs
= sGlyphSlotStore
.LookupEntry(i
))
19088 SetGlyphSlot(gs
->Order
- 1, gs
->Id
);
19090 uint32 level
= getLevel();
19093 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19095 value
|= (0x01 | 0x02);
19105 SetUInt32Value(PLAYER_GLYPHS_ENABLED
, value
);
19108 void Player::EnterVehicle(Vehicle
*vehicle
)
19110 VehicleEntry
const *ve
= sVehicleStore
.LookupEntry(vehicle
->GetVehicleId());
19114 VehicleSeatEntry
const *veSeat
= sVehicleSeatStore
.LookupEntry(ve
->m_seatID
[0]);
19118 vehicle
->SetCharmerGUID(GetGUID());
19119 vehicle
->RemoveFlag(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_SPELLCLICK
);
19120 vehicle
->SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_UNK_24
);
19121 vehicle
->setFaction(getFaction());
19123 SetCharm(vehicle
); // charm
19124 SetFarSightGUID(vehicle
->GetGUID()); // set view
19126 SetClientControl(vehicle
, 1); // redirect controls to vehicle
19128 WorldPacket
data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA
, 0);
19129 GetSession()->SendPacket(&data
);
19131 data
.Initialize(MSG_MOVE_TELEPORT_ACK
, 30);
19132 data
.append(GetPackGUID());
19133 data
<< uint32(0); // counter?
19134 data
<< uint32(MOVEMENTFLAG_ONTRANSPORT
); // transport
19135 data
<< uint16(0); // special flags
19136 data
<< uint32(getMSTime()); // time
19137 data
<< vehicle
->GetPositionX(); // x
19138 data
<< vehicle
->GetPositionY(); // y
19139 data
<< vehicle
->GetPositionZ(); // z
19140 data
<< vehicle
->GetOrientation(); // o
19141 // transport part, TODO: load/calculate seat offsets
19142 data
<< uint64(vehicle
->GetGUID()); // transport guid
19143 data
<< float(veSeat
->m_attachmentOffsetX
); // transport offsetX
19144 data
<< float(veSeat
->m_attachmentOffsetY
); // transport offsetY
19145 data
<< float(veSeat
->m_attachmentOffsetZ
); // transport offsetZ
19146 data
<< float(0); // transport orientation
19147 data
<< uint32(getMSTime()); // transport time
19148 data
<< uint8(0); // seat
19149 // end of transport part
19150 data
<< uint32(0); // fall time
19151 GetSession()->SendPacket(&data
);
19153 data
.Initialize(SMSG_PET_SPELLS
, 8+4+4+4+4*10+1+1);
19154 data
<< uint64(vehicle
->GetGUID());
19155 data
<< uint32(0x00000000);
19156 data
<< uint32(0x00000000);
19157 data
<< uint32(0x00000101);
19159 for(uint32 i
= 0; i
< 10; ++i
)
19160 data
<< uint16(0) << uint8(0) << uint8(i
+8);
19164 GetSession()->SendPacket(&data
);
19167 void Player::ExitVehicle(Vehicle
*vehicle
)
19169 vehicle
->SetCharmerGUID(0);
19170 vehicle
->SetFlag(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_SPELLCLICK
);
19171 vehicle
->RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_UNK_24
);
19172 vehicle
->setFaction((GetTeam() == ALLIANCE
) ? vehicle
->GetCreatureInfo()->faction_A
: vehicle
->GetCreatureInfo()->faction_H
);
19175 SetFarSightGUID(0);
19177 SetClientControl(vehicle
, 0);
19179 WorldPacket
data(MSG_MOVE_TELEPORT_ACK
, 30);
19180 data
.append(GetPackGUID());
19181 data
<< uint32(0); // counter?
19182 data
<< uint32(MOVEMENTFLAG_FLY_UNK1
); // fly unk
19183 data
<< uint16(0x40); // special flags
19184 data
<< uint32(getMSTime()); // time
19185 data
<< vehicle
->GetPositionX(); // x
19186 data
<< vehicle
->GetPositionY(); // y
19187 data
<< vehicle
->GetPositionZ(); // z
19188 data
<< vehicle
->GetOrientation(); // o
19189 data
<< uint32(0); // fall time
19190 GetSession()->SendPacket(&data
);
19192 data
.Initialize(SMSG_PET_SPELLS
, 8+4);
19195 GetSession()->SendPacket(&data
);
19197 // only for flyable vehicles?
19198 CastSpell(this, 45472, true); // Parachute
19201 bool Player::isTotalImmune()
19203 AuraList
const& immune
= GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY
);
19205 uint32 immuneMask
= 0;
19206 for(AuraList::const_iterator itr
= immune
.begin(); itr
!= immune
.end(); ++itr
)
19208 immuneMask
|= (*itr
)->GetModifier()->m_miscvalue
;
19209 if( immuneMask
& SPELL_SCHOOL_MASK_ALL
) // total immunity
19215 bool Player::HasTitle(uint32 bitIndex
)
19217 if (bitIndex
> 128)
19220 uint32 fieldIndexOffset
= bitIndex
/32;
19221 uint32 flag
= 1 << (bitIndex
%32);
19222 return HasFlag(PLAYER__FIELD_KNOWN_TITLES
+fieldIndexOffset
, flag
);
19225 void Player::SetTitle(CharTitlesEntry
const* title
)
19227 uint32 fieldIndexOffset
= title
->bit_index
/32;
19228 uint32 flag
= 1 << (title
->bit_index
%32);
19229 SetFlag(PLAYER__FIELD_KNOWN_TITLES
+fieldIndexOffset
, flag
);
19232 void Player::ConvertRune(uint8 index
, uint8 newType
)
19234 SetCurrentRune(index
, newType
);
19236 WorldPacket
data(SMSG_CONVERT_RUNE
, 2);
19237 data
<< uint8(index
);
19238 data
<< uint8(newType
);
19239 GetSession()->SendPacket(&data
);
19242 void Player::ResyncRunes(uint8 count
)
19244 WorldPacket
data(SMSG_RESYNC_RUNES
, count
* 2);
19245 for(uint32 i
= 0; i
< count
; ++i
)
19247 data
<< uint8(GetCurrentRune(i
)); // rune type
19248 data
<< uint8(255 - (GetRuneCooldown(i
) * 51)); // passed cooldown time (0-255)
19250 GetSession()->SendPacket(&data
);
19253 void Player::AddRunePower(uint8 index
)
19255 WorldPacket
data(SMSG_ADD_RUNE_POWER
, 4);
19256 data
<< uint32(1 << index
); // mask (0x00-0x3F probably)
19257 GetSession()->SendPacket(&data
);
19260 void Player::InitRunes()
19262 if(getClass() != CLASS_DEATH_KNIGHT
)
19265 m_runes
= new Runes
;
19267 m_runes
->runeState
= 0;
19269 for(uint32 i
= 0; i
< MAX_RUNES
; ++i
)
19271 SetBaseRune(i
, i
/ 2); // init base types
19272 SetCurrentRune(i
, i
/ 2); // init current types
19273 SetRuneCooldown(i
, 0); // reset cooldowns
19274 m_runes
->SetRuneState(i
);
19277 for(uint32 i
= 0; i
< NUM_RUNE_TYPES
; ++i
)
19278 SetFloatValue(PLAYER_RUNE_REGEN_1
+ i
, 0.1f
);
19281 void Player::AutoStoreLoot(uint8 bag
, uint8 slot
, uint32 loot_id
, LootStore
const& store
, bool broadcast
)
19284 loot
.FillLoot (loot_id
,store
,this,true);
19286 uint32 max_slot
= loot
.GetMaxSlotInLootFor(this);
19287 for(uint32 i
= 0; i
< max_slot
; ++i
)
19289 LootItem
* lootItem
= loot
.LootItemInSlot(i
,this);
19291 ItemPosCountVec dest
;
19292 uint8 msg
= CanStoreNewItem (bag
,slot
,dest
,lootItem
->itemid
,lootItem
->count
);
19293 if(msg
!= EQUIP_ERR_OK
&& slot
!= NULL_SLOT
)
19294 msg
= CanStoreNewItem( bag
, NULL_SLOT
,dest
,lootItem
->itemid
,lootItem
->count
);
19295 if( msg
!= EQUIP_ERR_OK
&& bag
!= NULL_BAG
)
19296 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
,dest
,lootItem
->itemid
,lootItem
->count
);
19297 if(msg
!= EQUIP_ERR_OK
)
19299 SendEquipError( msg
, NULL
, NULL
);
19303 Item
* pItem
= StoreNewItem (dest
,lootItem
->itemid
,true,lootItem
->randomPropertyId
);
19304 SendNewItem(pItem
, lootItem
->count
, false, false, broadcast
);
19308 uint32
Player::CalculateTalentsPoints() const
19310 uint32 base_talent
= getLevel() < 10 ? 0 : uint32((getLevel()-9)*sWorld
.getRate(RATE_TALENT
));
19312 if(getClass() != CLASS_DEATH_KNIGHT
)
19313 return base_talent
;
19315 uint32 talentPointsForLevel
=
19316 (getLevel() < 56 ? 0 : uint32((getLevel()-55)*sWorld
.getRate(RATE_TALENT
)))
19317 + m_questRewardTalentCount
;
19319 if(talentPointsForLevel
> base_talent
)
19320 talentPointsForLevel
= base_talent
;
19322 return talentPointsForLevel
;
19325 bool Player::IsAllowUseFlyMountsHere() const
19327 if (isGameMaster())
19330 uint32 v_map
= GetVirtualMapForMapAndZone(GetMapId(), GetZoneId());
19331 return v_map
== 530 || v_map
== 571 && HasSpell(54197);
19334 void Player::learnSpellHighRank(uint32 spellid
)
19336 learnSpell(spellid
,false);
19338 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
19339 for(SpellChainMapNext::const_iterator itr
= nextMap
.lower_bound(spellid
); itr
!= nextMap
.upper_bound(spellid
); ++itr
)
19340 learnSpellHighRank(itr
->second
);
19343 void Player::_LoadSkills()
19345 // Note: skill data itself loaded from `data` field. This is only cleanup part of load
19347 // reset skill modifiers and set correct unlearn flags
19348 for (uint32 i
= 0; i
< PLAYER_MAX_SKILLS
; ++i
)
19350 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
19352 // set correct unlearn bit
19353 uint32 id
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
19356 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
19357 if(!pSkill
) continue;
19359 // enable unlearn button for primary professions only
19360 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
19361 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
19363 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
19365 // set fixed skill ranges
19366 switch(GetSkillRangeType(pSkill
,false))
19368 case SKILL_RANGE_LANGUAGE
: // 300..300
19369 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(300,300));
19371 case SKILL_RANGE_MONO
: // 1..1, grey monolite bar
19372 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(1,1));
19378 uint32 vskill
= SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
19379 learnSkillRewardedSpells(id
, vskill
);
19382 // special settings
19383 if(getClass()==CLASS_DEATH_KNIGHT
)
19385 uint32 base_level
= std::min(getLevel(),sWorld
.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL
));
19388 uint32 base_skill
= (base_level
-1)*5; // 270 at starting level 55
19390 base_skill
= 1; // skill mast be known and then > 0 in any case
19392 if(GetPureSkillValue (SKILL_FIRST_AID
) < base_skill
)
19393 SetSkill(SKILL_FIRST_AID
,base_skill
, base_skill
);
19394 if(GetPureSkillValue (SKILL_AXES
) < base_skill
)
19395 SetSkill(SKILL_AXES
, base_skill
,base_skill
);
19396 if(GetPureSkillValue (SKILL_DEFENSE
) < base_skill
)
19397 SetSkill(SKILL_DEFENSE
, base_skill
,base_skill
);
19398 if(GetPureSkillValue (SKILL_POLEARMS
) < base_skill
)
19399 SetSkill(SKILL_POLEARMS
, base_skill
,base_skill
);
19400 if(GetPureSkillValue (SKILL_SWORDS
) < base_skill
)
19401 SetSkill(SKILL_SWORDS
, base_skill
,base_skill
);
19402 if(GetPureSkillValue (SKILL_2H_AXES
) < base_skill
)
19403 SetSkill(SKILL_2H_AXES
, base_skill
,base_skill
);
19404 if(GetPureSkillValue (SKILL_2H_SWORDS
) < base_skill
)
19405 SetSkill(SKILL_2H_SWORDS
, base_skill
,base_skill
);
19406 if(GetPureSkillValue (SKILL_UNARMED
) < base_skill
)
19407 SetSkill(SKILL_UNARMED
, base_skill
,base_skill
);
19411 uint32
Player::GetPhaseMaskForSpawn() const
19413 uint32 phase
= PHASEMASK_NORMAL
;
19414 if(!isGameMaster())
19415 phase
= GetPhaseMask();
19418 AuraList
const& phases
= GetAurasByType(SPELL_AURA_PHASE
);
19419 if(!phases
.empty())
19420 phase
= phases
.front()->GetMiscValue();
19423 // some aura phases include 1 normal map in addition to phase itself
19424 if(uint32 n_phase
= phase
& ~PHASEMASK_NORMAL
)
19427 return PHASEMASK_NORMAL
;
19430 uint8
Player::CanEquipUniqueItem(Item
* pItem
, uint8 eslot
, uint32 limit_count
) const
19432 ItemPrototype
const* pProto
= pItem
->GetProto();
19434 // proto based limitations
19435 if(uint8 res
= CanEquipUniqueItem(pProto
,eslot
,limit_count
))
19438 // check unique-equipped on gems
19439 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
19441 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
19444 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
19448 ItemPrototype
const* pGem
= objmgr
.GetItemPrototype(enchantEntry
->GemID
);
19452 // include for check equip another gems with same limit category for not equipped item (and then not counted)
19453 uint32 gem_limit_count
= !pItem
->IsEquipped() && pGem
->ItemLimitCategory
19454 ? pItem
->GetGemCountWithLimitCategory(pGem
->ItemLimitCategory
) : 1;
19456 if(uint8 res
= CanEquipUniqueItem(pGem
, eslot
,gem_limit_count
))
19460 return EQUIP_ERR_OK
;
19463 uint8
Player::CanEquipUniqueItem( ItemPrototype
const* itemProto
, uint8 except_slot
, uint32 limit_count
) const
19465 // check unique-equipped on item
19466 if (itemProto
->Flags
& ITEM_FLAGS_UNIQUE_EQUIPPED
)
19468 // there is an equip limit on this item
19469 if(HasItemOrGemWithIdEquipped(itemProto
->ItemId
,1,except_slot
))
19470 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
19473 // check unique-equipped limit
19474 if (itemProto
->ItemLimitCategory
)
19476 ItemLimitCategoryEntry
const* limitEntry
= sItemLimitCategoryStore
.LookupEntry(itemProto
->ItemLimitCategory
);
19478 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
19480 if(limit_count
> limitEntry
->maxCount
)
19481 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
; // attempt add too many limit category items (gems)
19483 // there is an equip limit on this item
19484 if(HasItemOrGemWithLimitCategoryEquipped(itemProto
->ItemLimitCategory
,limitEntry
->maxCount
-limit_count
+1,except_slot
))
19485 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
19488 return EQUIP_ERR_OK
;
19491 void Player::HandleFall(MovementInfo
const& movementInfo
)
19493 // calculate total z distance of the fall
19494 float z_diff
= m_lastFallZ
- movementInfo
.z
;
19495 sLog
.outDebug("zDiff = %f", z_diff
);
19497 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
19498 // 14.57 can be calculated by resolving damageperc formula below to 0
19499 if (z_diff
>= 14.57f
&& !isDead() && !isGameMaster() &&
19500 !HasAuraType(SPELL_AURA_HOVER
) && !HasAuraType(SPELL_AURA_FEATHER_FALL
) &&
19501 !HasAuraType(SPELL_AURA_FLY
) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL
) )
19503 //Safe fall, fall height reduction
19504 int32 safe_fall
= GetTotalAuraModifier(SPELL_AURA_SAFE_FALL
);
19506 float damageperc
= 0.018f
*(z_diff
-safe_fall
)-0.2426f
;
19510 uint32 damage
= (uint32
)(damageperc
* GetMaxHealth()*sWorld
.getRate(RATE_DAMAGE_FALL
));
19512 float height
= movementInfo
.z
;
19513 UpdateGroundPositionZ(movementInfo
.x
,movementInfo
.y
,height
);
19517 //Prevent fall damage from being more than the player maximum health
19518 if (damage
> GetMaxHealth())
19519 damage
= GetMaxHealth();
19522 if (GetDummyAura(43621))
19523 damage
= GetMaxHealth()/2;
19525 EnvironmentalDamage(DAMAGE_FALL
, damage
);
19527 // recheck alive, might have died of EnvironmentalDamage
19529 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING
, uint32(z_diff
*100));
19532 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
19533 DEBUG_LOG("FALLDAMAGE z=%f sz=%f pZ=%f FallTime=%d mZ=%f damage=%d SF=%d" , movementInfo
.z
, height
, GetPositionZ(), movementInfo
.fallTime
, height
, damage
, safe_fall
);
19538 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type
, uint32 miscvalue1
/*=0*/, uint32 miscvalue2
/*=0*/, Unit
*unit
/*=NULL*/, uint32 time
/*=0*/ )
19540 GetAchievementMgr().UpdateAchievementCriteria(type
, miscvalue1
,miscvalue2
,unit
,time
);
19543 void Player::LearnTalent(uint32 talentId
, uint32 talentRank
)
19545 uint32 CurTalentPoints
= GetFreeTalentPoints();
19547 if(CurTalentPoints
== 0)
19550 if (talentRank
>= MAX_TALENT_RANK
)
19553 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry( talentId
);
19558 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentInfo
->TalentTab
);
19563 // prevent learn talent for different class (cheating)
19564 if( (getClassMask() & talentTabInfo
->ClassMask
) == 0 )
19567 // find current max talent rank
19568 int32 curtalent_maxrank
= 0;
19569 for(int32 k
= MAX_TALENT_RANK
-1; k
> -1; --k
)
19571 if(talentInfo
->RankID
[k
] && HasSpell(talentInfo
->RankID
[k
]))
19573 curtalent_maxrank
= k
+ 1;
19578 // we already have same or higher talent rank learned
19579 if(curtalent_maxrank
>= (talentRank
+ 1))
19582 // check if we have enough talent points
19583 if(CurTalentPoints
< (talentRank
- curtalent_maxrank
+ 1))
19586 // Check if it requires another talent
19587 if (talentInfo
->DependsOn
> 0)
19589 if(TalentEntry
const *depTalentInfo
= sTalentStore
.LookupEntry(talentInfo
->DependsOn
))
19591 bool hasEnoughRank
= false;
19592 for (int i
= talentInfo
->DependsOnRank
; i
< MAX_TALENT_RANK
; ++i
)
19594 if (depTalentInfo
->RankID
[i
] != 0)
19595 if (HasSpell(depTalentInfo
->RankID
[i
]))
19596 hasEnoughRank
= true;
19598 if (!hasEnoughRank
)
19603 // Find out how many points we have in this field
19604 uint32 spentPoints
= 0;
19606 uint32 tTab
= talentInfo
->TalentTab
;
19607 if (talentInfo
->Row
> 0)
19609 unsigned int numRows
= sTalentStore
.GetNumRows();
19610 for (unsigned int i
= 0; i
< numRows
; ++i
) // Loop through all talents.
19612 // Someday, someone needs to revamp
19613 const TalentEntry
*tmpTalent
= sTalentStore
.LookupEntry(i
);
19614 if (tmpTalent
) // the way talents are tracked
19616 if (tmpTalent
->TalentTab
== tTab
)
19618 for (int j
= 0; j
< MAX_TALENT_RANK
; ++j
)
19620 if (tmpTalent
->RankID
[j
] != 0)
19622 if (HasSpell(tmpTalent
->RankID
[j
]))
19624 spentPoints
+= j
+ 1;
19633 // not have required min points spent in talent tree
19634 if(spentPoints
< (talentInfo
->Row
* MAX_TALENT_RANK
))
19637 // spell not set in talent.dbc
19638 uint32 spellid
= talentInfo
->RankID
[talentRank
];
19641 sLog
.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId
, talentRank
);
19646 if(HasSpell(spellid
))
19649 // learn! (other talent ranks will unlearned at learning)
19650 learnSpell(spellid
, false);
19651 sLog
.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId
, talentRank
, spellid
);
19653 // update free talent points
19654 SetFreeTalentPoints(CurTalentPoints
- (talentRank
- curtalent_maxrank
+ 1));
19657 void Player::LearnPetTalent(uint64 petGuid
, uint32 talentId
, uint32 talentRank
)
19659 Pet
*pet
= GetPet();
19664 if(petGuid
!= pet
->GetGUID())
19667 uint32 CurTalentPoints
= pet
->GetFreeTalentPoints();
19669 if(CurTalentPoints
== 0)
19672 if (talentRank
>= MAX_PET_TALENT_RANK
)
19675 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry(talentId
);
19680 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry(talentInfo
->TalentTab
);
19685 CreatureInfo
const *ci
= pet
->GetCreatureInfo();
19690 CreatureFamilyEntry
const *pet_family
= sCreatureFamilyStore
.LookupEntry(ci
->family
);
19695 if(pet_family
->petTalentType
< 0) // not hunter pet
19698 // prevent learn talent for different family (cheating)
19699 if(!((1 << pet_family
->petTalentType
) & talentTabInfo
->petTalentMask
))
19702 // find current max talent rank
19703 int32 curtalent_maxrank
= 0;
19704 for(int32 k
= MAX_TALENT_RANK
-1; k
> -1; --k
)
19706 if(talentInfo
->RankID
[k
] && pet
->HasSpell(talentInfo
->RankID
[k
]))
19708 curtalent_maxrank
= k
+ 1;
19713 // we already have same or higher talent rank learned
19714 if(curtalent_maxrank
>= (talentRank
+ 1))
19717 // check if we have enough talent points
19718 if(CurTalentPoints
< (talentRank
- curtalent_maxrank
+ 1))
19721 // Check if it requires another talent
19722 if (talentInfo
->DependsOn
> 0)
19724 if(TalentEntry
const *depTalentInfo
= sTalentStore
.LookupEntry(talentInfo
->DependsOn
))
19726 bool hasEnoughRank
= false;
19727 for (int i
= talentInfo
->DependsOnRank
; i
< MAX_TALENT_RANK
; ++i
)
19729 if (depTalentInfo
->RankID
[i
] != 0)
19730 if (pet
->HasSpell(depTalentInfo
->RankID
[i
]))
19731 hasEnoughRank
= true;
19733 if (!hasEnoughRank
)
19738 // Find out how many points we have in this field
19739 uint32 spentPoints
= 0;
19741 uint32 tTab
= talentInfo
->TalentTab
;
19742 if (talentInfo
->Row
> 0)
19744 unsigned int numRows
= sTalentStore
.GetNumRows();
19745 for (unsigned int i
= 0; i
< numRows
; ++i
) // Loop through all talents.
19747 // Someday, someone needs to revamp
19748 const TalentEntry
*tmpTalent
= sTalentStore
.LookupEntry(i
);
19749 if (tmpTalent
) // the way talents are tracked
19751 if (tmpTalent
->TalentTab
== tTab
)
19753 for (int j
= 0; j
< MAX_TALENT_RANK
; ++j
)
19755 if (tmpTalent
->RankID
[j
] != 0)
19757 if (pet
->HasSpell(tmpTalent
->RankID
[j
]))
19759 spentPoints
+= j
+ 1;
19768 // not have required min points spent in talent tree
19769 if(spentPoints
< (talentInfo
->Row
* MAX_PET_TALENT_RANK
))
19772 // spell not set in talent.dbc
19773 uint32 spellid
= talentInfo
->RankID
[talentRank
];
19776 sLog
.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId
, talentRank
);
19781 if(pet
->HasSpell(spellid
))
19784 // learn! (other talent ranks will unlearned at learning)
19785 pet
->learnSpell(spellid
);
19786 sLog
.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId
, talentRank
, spellid
);
19788 // update free talent points
19789 pet
->SetFreeTalentPoints(CurTalentPoints
- (talentRank
- curtalent_maxrank
+ 1));
19792 void Player::UpdateKnownCurrencies(uint32 itemId
, bool apply
)
19794 if(CurrencyTypesEntry
const* ctEntry
= sCurrencyTypesStore
.LookupEntry(itemId
))
19797 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES
,(1LL << (ctEntry
->BitIndex
-1)));
19799 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES
,(1LL << (ctEntry
->BitIndex
-1)));
19803 void Player::UpdateFallInformationIfNeed( MovementInfo
const& minfo
,uint16 opcode
)
19805 if (m_lastFallTime
>= minfo
.fallTime
|| m_lastFallZ
<=minfo
.z
|| opcode
== MSG_MOVE_FALL_LAND
)
19806 SetFallInformation(minfo
.fallTime
, minfo
.z
);
19809 void Player::UnsummonPetTemporaryIfAny()
19811 Pet
* pet
= GetPet();
19815 if(!m_temporaryUnsummonedPetNumber
&& pet
->isControlled() && !pet
->isTemporarySummoned() )
19817 m_temporaryUnsummonedPetNumber
= pet
->GetCharmInfo()->GetPetNumber();
19818 m_oldpetspell
= pet
->GetUInt32Value(UNIT_CREATED_BY_SPELL
);
19821 RemovePet(pet
, PET_SAVE_AS_CURRENT
);
19824 void Player::ResummonPetTemporaryUnSummonedIfAny()
19826 if(!m_temporaryUnsummonedPetNumber
)
19829 // not resummon in not appropriate state
19830 if(IsPetNeedBeTemporaryUnsummoned())
19836 Pet
* NewPet
= new Pet
;
19837 if(!NewPet
->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber
, true))
19840 m_temporaryUnsummonedPetNumber
= 0;