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 // capital and taxi hub masks
134 case RACE_HUMAN
: SetTaximaskNode(2); break; // Human
135 case RACE_ORC
: SetTaximaskNode(23); break; // Orc
136 case RACE_DWARF
: SetTaximaskNode(6); break; // Dwarf
137 case RACE_NIGHTELF
: SetTaximaskNode(26);
138 SetTaximaskNode(27); break; // Night Elf
139 case RACE_UNDEAD_PLAYER
: SetTaximaskNode(11); break;// Undead
140 case RACE_TAUREN
: SetTaximaskNode(22); break; // Tauren
141 case RACE_GNOME
: SetTaximaskNode(6); break; // Gnome
142 case RACE_TROLL
: SetTaximaskNode(23); break; // Troll
143 case RACE_BLOODELF
: SetTaximaskNode(82); break; // Blood Elf
144 case RACE_DRAENEI
: SetTaximaskNode(94); break; // Draenei
149 case CLASS_DEATH_KNIGHT
: // TODO: figure out initial known nodes
153 // new continent starting masks (It will be accessible only at new map)
154 switch(Player::TeamForRace(race
))
156 case ALLIANCE
: SetTaximaskNode(100); break;
157 case HORDE
: SetTaximaskNode(99); break;
159 // level dependent taxi hubs
161 SetTaximaskNode(213); //Shattered Sun Staging Area
164 void PlayerTaxi::LoadTaxiMask(const char* data
)
166 Tokens tokens
= StrSplit(data
, " ");
169 Tokens::iterator iter
;
170 for (iter
= tokens
.begin(), index
= 0;
171 (index
< TaxiMaskSize
) && (iter
!= tokens
.end()); ++iter
, ++index
)
173 // load and set bits only for existed taxi nodes
174 m_taximask
[index
] = sTaxiNodesMask
[index
] & uint32(atol((*iter
).c_str()));
178 void PlayerTaxi::AppendTaximaskTo( ByteBuffer
& data
, bool all
)
182 for (uint8 i
=0; i
<TaxiMaskSize
; i
++)
183 data
<< uint32(sTaxiNodesMask
[i
]); // all existed nodes
187 for (uint8 i
=0; i
<TaxiMaskSize
; i
++)
188 data
<< uint32(m_taximask
[i
]); // known nodes
192 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string
& values
, uint32 team
)
194 ClearTaxiDestinations();
196 Tokens tokens
= StrSplit(values
," ");
198 for(Tokens::iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
)
200 uint32 node
= uint32(atol(iter
->c_str()));
201 AddTaxiDestination(node
);
204 if(m_TaxiDestinations
.empty())
208 if(m_TaxiDestinations
.size() < 2)
211 for(size_t i
= 1; i
< m_TaxiDestinations
.size(); ++i
)
215 objmgr
.GetTaxiPath(m_TaxiDestinations
[i
-1],m_TaxiDestinations
[i
],path
,cost
);
220 // can't load taxi path without mount set (quest taxi path?)
221 if(!objmgr
.GetTaxiMount(GetTaxiSource(),team
))
227 std::string
PlayerTaxi::SaveTaxiDestinationsToString()
229 if(m_TaxiDestinations
.empty())
232 std::ostringstream ss
;
234 for(size_t i
=0; i
< m_TaxiDestinations
.size(); ++i
)
235 ss
<< m_TaxiDestinations
[i
] << " ";
240 uint32
PlayerTaxi::GetCurrentTaxiPath() const
242 if(m_TaxiDestinations
.size() < 2)
248 objmgr
.GetTaxiPath(m_TaxiDestinations
[0],m_TaxiDestinations
[1],path
,cost
);
253 std::ostringstream
& operator<< (std::ostringstream
& ss
, PlayerTaxi
const& taxi
)
256 for(int i
= 0; i
< TaxiMaskSize
; ++i
)
257 ss
<< taxi
.m_taximask
[i
] << " ";
262 //== Player ====================================================
264 const int32
Player::ReputationRank_Length
[MAX_REPUTATION_RANK
] = {36000, 3000, 3000, 3000, 6000, 12000, 21000, 1000};
266 UpdateMask
Player::updateVisualBits
;
268 Player::Player (WorldSession
*session
): Unit(), m_achievementMgr(this)
275 m_objectType
|= TYPEMASK_PLAYER
;
276 m_objectTypeId
= TYPEID_PLAYER
;
278 m_valuesCount
= PLAYER_END
;
285 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER
)
286 SetAcceptTicket(true);
288 // players always accept
289 if(GetSession()->GetSecurity() == SEC_PLAYER
)
290 SetAcceptWhispers(true);
298 m_usedTalentCount
= 0;
299 m_questRewardTalentCount
= 0;
302 m_weaponChangeTimer
= 0;
305 m_zoneUpdateTimer
= 0;
309 m_nextSave
= sWorld
.getConfig(CONFIG_INTERVAL_SAVE
);
311 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
312 // this must help in case next save after mass player load after server startup
313 m_nextSave
= urand(m_nextSave
/2,m_nextSave
*3/2);
315 clearResurrectRequestData();
317 m_SpellModRemoveCount
= 0;
319 memset(m_items
, 0, sizeof(Item
*)*PLAYER_SLOTS_COUNT
);
323 // group is initialized in the reference constructor
324 SetGroupInvite(NULL
);
325 m_groupUpdateMask
= 0;
326 m_auraUpdateMask
= 0;
330 m_GuildIdInvited
= 0;
331 m_ArenaTeamIdInvited
= 0;
333 m_atLoginFlags
= AT_LOGIN_NONE
;
342 PlayerTalkClass
= new PlayerMenu( GetSession() );
343 m_currentBuybackSlot
= BUYBACK_SLOT_START
;
345 for ( int aX
= 0 ; aX
< 8 ; aX
++ )
346 m_Tutorials
[ aX
] = 0x00;
347 m_TutorialsChanged
= false;
349 m_DailyQuestChanged
= false;
350 m_lastDailyQuestTime
= 0;
353 m_weaponChangeTimer
= 0;
354 for (int i
=0; i
<MAX_TIMERS
; i
++)
355 m_MirrorTimer
[i
] = DISABLED_MIRROR_TIMER
;
357 m_MirrorTimerFlags
= UNDERWATER_NONE
;
358 m_MirrorTimerFlagsLast
= UNDERWATER_NONE
;
364 m_deathExpireTime
= 0;
368 m_DetectInvTimer
= 1*IN_MILISECONDS
;
370 m_bgBattleGroundID
= 0;
371 m_bgTypeID
= BATTLEGROUND_TYPE_NONE
;
372 for (int j
=0; j
< PLAYER_MAX_BATTLEGROUND_QUEUES
; j
++)
374 m_bgBattleGroundQueueID
[j
].bgQueueTypeId
= BATTLEGROUND_QUEUE_NONE
;
375 m_bgBattleGroundQueueID
[j
].invitedToInstance
= 0;
379 m_logintime
= time(NULL
);
380 m_Last_tick
= m_logintime
;
381 m_WeaponProficiency
= 0;
382 m_ArmorProficiency
= 0;
385 m_canDualWield
= false;
386 m_canTitanGrip
= false;
389 m_temporaryUnsummonedPetNumber
= 0;
390 //cache for UNIT_CREATED_BY_SPELL to allow
391 //returning reagents for temporarily removed pets
392 //when dying/logging out
395 ////////////////////Rest System/////////////////////
402 rest_type
=REST_TYPE_NO
;
403 ////////////////////Rest System/////////////////////
405 m_mailsLoaded
= false;
406 m_mailsUpdated
= false;
408 m_nextMailDelivereTime
= 0;
410 m_resetTalentsCost
= 0;
411 m_resetTalentsTime
= 0;
412 m_itemUpdateQueueBlocked
= false;
414 for (int i
= 0; i
< MAX_MOVE_TYPE
; ++i
)
415 m_forced_speed_changes
[i
] = 0;
419 /////////////////// Instance System /////////////////////
422 m_InstanceValid
= true;
423 m_dungeonDifficulty
= DIFFICULTY_NORMAL
;
427 for (int i
= 0; i
< BASEMOD_END
; i
++)
429 m_auraBaseMod
[i
][FLAT_MOD
] = 0.0f
;
430 m_auraBaseMod
[i
][PCT_MOD
] = 1.0f
;
433 for (int i
= 0; i
< MAX_COMBAT_RATING
; i
++)
434 m_baseRatingValue
[i
] = 0;
436 m_baseSpellDamage
= 0;
437 m_baseSpellHealing
= 0;
442 m_lastHonorUpdateTime
= time(NULL
);
451 //Default movement to run mode
452 m_unit_movement_flags
= 0;
457 m_bgAfkReportedTimer
= 0;
458 m_contestedPvPTimer
= 0;
460 m_declinedname
= NULL
;
466 CleanupsBeforeDelete();
468 // it must be unloaded already in PlayerLogout and accessed only for loggined player
471 // Note: buy back item already deleted from DB when player was saved
472 for(int i
= 0; i
< PLAYER_SLOTS_COUNT
; ++i
)
479 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
482 //all mailed items should be deleted, also all mail should be deallocated
483 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
486 for (ItemMap::iterator iter
= mMitems
.begin(); iter
!= mMitems
.end(); ++iter
)
487 delete iter
->second
; //if item is duplicated... then server may crash ... but that item should be deallocated
489 delete PlayerTalkClass
;
493 m_transport
->RemovePassenger(this);
496 for(size_t x
= 0; x
< ItemSetEff
.size(); x
++)
498 delete ItemSetEff
[x
];
500 // clean up player-instance binds, may unload some instance saves
501 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
502 for(BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
503 itr
->second
.save
->RemovePlayer(this);
505 delete m_declinedname
;
509 void Player::CleanupsBeforeDelete()
511 if(m_uint32Values
) // only for fully created Object
514 DuelComplete(DUEL_INTERUPTED
);
516 Unit::CleanupsBeforeDelete();
519 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
)
521 //FIXME: outfitId not used in player creating
523 Object::_Create(guidlow
, 0, HIGHGUID_PLAYER
);
527 PlayerInfo
const* info
= objmgr
.GetPlayerInfo(race
, class_
);
530 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
534 for (int i
= 0; i
< PLAYER_SLOTS_COUNT
; i
++)
540 SetMapId(info
->mapId
);
541 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
);
543 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(class_
);
546 sLog
.outError("Class %u not found in DBC (Wrong DBC files?)",class_
);
550 uint8 powertype
= cEntry
->powerType
;
552 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, DEFAULT_WORLD_OBJECT_SIZE
);
553 SetFloatValue(UNIT_FIELD_COMBATREACH
, 1.5f
);
558 SetDisplayId(info
->displayId_f
);
559 SetNativeDisplayId(info
->displayId_f
);
562 SetDisplayId(info
->displayId_m
);
563 SetNativeDisplayId(info
->displayId_m
);
566 sLog
.outError("Invalid gender %u for player",gender
);
571 setFactionForRace(m_race
);
573 uint32 RaceClassGender
= ( race
) | ( class_
<< 8 ) | ( gender
<< 16 );
575 SetUInt32Value(UNIT_FIELD_BYTES_0
, ( RaceClassGender
| ( powertype
<< 24 ) ) );
576 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_PVP
);
577 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
);
578 SetFlag(UNIT_FIELD_FLAGS_2
, UNIT_FLAG2_REGENERATE_POWER
);
579 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
); // fix cast time showed in spell tooltip on client
580 SetFloatValue(UNIT_FIELD_HOVERHEIGHT
, 1.0f
); // default for players in 3.0.3
582 // -1 is default value
583 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX
, uint32(-1));
585 SetUInt32Value(PLAYER_BYTES
, (skin
| (face
<< 8) | (hairStyle
<< 16) | (hairColor
<< 24)));
586 SetUInt32Value(PLAYER_BYTES_2
, (facialHair
| (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
587 SetByteValue(PLAYER_BYTES_3
, 0, gender
);
589 SetUInt32Value( PLAYER_GUILDID
, 0 );
590 SetUInt32Value( PLAYER_GUILDRANK
, 0 );
591 SetUInt32Value( PLAYER_GUILD_TIMESTAMP
, 0 );
593 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES
, 0 ); // 0=disabled
594 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1
, 0 ); // 0=disabled
595 SetUInt32Value( PLAYER_CHOSEN_TITLE
, 0 );
596 SetUInt32Value( PLAYER_FIELD_KILLS
, 0 );
597 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 0 );
598 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION
, 0 );
599 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0 );
601 // set starting level
602 uint32 start_level
= getClass() != CLASS_DEATH_KNIGHT
603 ? sWorld
.getConfig(CONFIG_START_PLAYER_LEVEL
)
604 : sWorld
.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL
);
606 if (GetSession()->GetSecurity() >= SEC_MODERATOR
)
608 uint32 gm_level
= sWorld
.getConfig(CONFIG_START_GM_LEVEL
);
609 if(gm_level
> start_level
)
610 start_level
= gm_level
;
613 SetUInt32Value(UNIT_FIELD_LEVEL
, start_level
);
617 SetUInt32Value (PLAYER_FIELD_COINAGE
, sWorld
.getConfig(CONFIG_START_PLAYER_MONEY
));
618 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_START_HONOR_POINTS
));
619 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_START_ARENA_POINTS
));
622 m_Last_tick
= time(NULL
);
623 m_Played_time
[0] = 0;
624 m_Played_time
[1] = 0;
626 // base stats and related field values
628 InitTaxiNodesForLevel();
629 InitGlyphsForLevel();
630 InitTalentForLevel();
631 InitPrimaryProffesions(); // to max set before any spell added
633 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
634 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
635 SetHealth(GetMaxHealth());
636 if (getPowerType()==POWER_MANA
)
638 UpdateMaxPower(POWER_MANA
); // Update max Mana (for add bonus from intellect)
639 SetPower(POWER_MANA
,GetMaxPower(POWER_MANA
));
642 if(getPowerType() == POWER_RUNIC_POWER
)
644 SetPower(POWER_RUNE
, 8);
645 SetMaxPower(POWER_RUNE
, 8);
646 SetPower(POWER_RUNIC_POWER
, 0);
647 SetMaxPower(POWER_RUNIC_POWER
, 1000);
651 learnDefaultSpells();
653 // original action bar
654 std::list
<uint16
>::const_iterator action_itr
[4];
655 for(int i
=0; i
<4; i
++)
656 action_itr
[i
] = info
->action
[i
].begin();
658 for (; action_itr
[0]!=info
->action
[0].end() && action_itr
[1]!=info
->action
[1].end();)
661 for(int i
=0; i
<4 ;i
++)
662 taction
[i
] = (*action_itr
[i
]);
664 addActionButton((uint8
)taction
[0], taction
[1], (uint8
)taction
[2], (uint8
)taction
[3]);
666 for(int i
=0; i
<4 ;i
++)
671 CharStartOutfitEntry
const* oEntry
= NULL
;
672 for (uint32 i
= 1; i
< sCharStartOutfitStore
.GetNumRows(); ++i
)
674 if(CharStartOutfitEntry
const* entry
= sCharStartOutfitStore
.LookupEntry(i
))
676 if(entry
->RaceClassGender
== RaceClassGender
)
686 for(int j
= 0; j
< MAX_OUTFIT_ITEMS
; ++j
)
688 if(oEntry
->ItemId
[j
] <= 0)
691 uint32 item_id
= oEntry
->ItemId
[j
];
694 // Hack for not existed item id in dbc 3.0.3
698 ItemPrototype
const* iProto
= objmgr
.GetItemPrototype(item_id
);
701 sLog
.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id
,getRace(),getClass());
705 // max stack by default (mostly 1), 1 for infinity stackable
706 uint32 count
= iProto
->Stackable
> 0 ? uint32(iProto
->Stackable
) : 1;
708 if(iProto
->Class
==ITEM_CLASS_CONSUMABLE
&& iProto
->SubClass
==ITEM_SUBCLASS_FOOD
)
710 switch(iProto
->Spells
[0].SpellCategory
)
713 if(iProto
->Stackable
> 4)
717 if(iProto
->Stackable
> 2)
723 StoreNewItemInBestSlots(item_id
, count
);
727 for (PlayerCreateInfoItems::const_iterator item_id_itr
= info
->item
.begin(); item_id_itr
!=info
->item
.end(); ++item_id_itr
++)
728 StoreNewItemInBestSlots(item_id_itr
->item_id
, item_id_itr
->item_amount
);
730 // bags and main-hand weapon must equipped at this moment
731 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
732 // or ammo not equipped in special bag
733 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
735 if(Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
738 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
739 uint8 msg
= CanEquipItem( NULL_SLOT
, eDest
, pItem
, false );
740 if( msg
== EQUIP_ERR_OK
)
742 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
743 EquipItem( eDest
, pItem
, true);
745 // move other items to more appropriate slots (ammo not equipped in special bag)
748 ItemPosCountVec sDest
;
749 msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, sDest
, pItem
, false );
750 if( msg
== EQUIP_ERR_OK
)
752 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
753 pItem
= StoreItem( sDest
, pItem
, true);
756 // if this is ammo then use it
757 uint8 msg
= CanUseAmmo( pItem
->GetEntry() );
758 if( msg
== EQUIP_ERR_OK
)
759 SetAmmo( pItem
->GetEntry() );
763 // all item positions resolved
768 bool Player::StoreNewItemInBestSlots(uint32 titem_id
, uint32 titem_amount
)
770 sLog
.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id
, titem_amount
);
772 // attempt equip by one
773 while(titem_amount
> 0)
776 uint8 msg
= CanEquipNewItem( NULL_SLOT
, eDest
, titem_id
, false );
777 if( msg
!= EQUIP_ERR_OK
)
780 EquipNewItem( eDest
, titem_id
, true);
781 AutoUnequipOffhandIfNeed();
785 if(titem_amount
== 0)
786 return true; // equipped
789 ItemPosCountVec sDest
;
790 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
791 uint8 msg
= CanStoreNewItem( INVENTORY_SLOT_BAG_0
, NULL_SLOT
, sDest
, titem_id
, titem_amount
);
792 if( msg
== EQUIP_ERR_OK
)
794 StoreNewItem( sDest
, titem_id
, true, Item::GenerateItemRandomPropertyId(titem_id
) );
795 return true; // stored
798 // item can't be added
799 sLog
.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id
,getRace(),getClass(),msg
);
803 void Player::SendMirrorTimer(MirrorTimerType Type
, uint32 MaxValue
, uint32 CurrentValue
, int32 Regen
)
805 if (MaxValue
== DISABLED_MIRROR_TIMER
)
807 if (CurrentValue
!=DISABLED_MIRROR_TIMER
)
808 StopMirrorTimer(Type
);
811 WorldPacket
data(SMSG_START_MIRROR_TIMER
, (21));
812 data
<< (uint32
)Type
;
813 data
<< CurrentValue
;
817 data
<< (uint32
)0; // spell id
818 GetSession()->SendPacket( &data
);
821 void Player::StopMirrorTimer(MirrorTimerType Type
)
823 m_MirrorTimer
[Type
] = DISABLED_MIRROR_TIMER
;
824 WorldPacket
data(SMSG_STOP_MIRROR_TIMER
, 4);
825 data
<< (uint32
)Type
;
826 GetSession()->SendPacket( &data
);
829 void Player::EnvironmentalDamage(uint64 guid
, EnviromentalDamage type
, uint32 damage
)
831 if(!isAlive() || isGameMaster())
834 // Absorb, resist some environmental damage type
837 if (type
== DAMAGE_LAVA
)
838 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE
, DIRECT_DAMAGE
, damage
, &absorb
, &resist
);
839 else if (type
== DAMAGE_SLIME
)
840 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE
, DIRECT_DAMAGE
, damage
, &absorb
, &resist
);
842 damage
-=absorb
+resist
;
844 WorldPacket
data(SMSG_ENVIRONMENTALDAMAGELOG
, (21));
845 data
<< (uint64
)guid
;
846 data
<< (uint8
)(type
!=DAMAGE_FALL_TO_VOID
? type
: DAMAGE_FALL
);
847 data
<< (uint32
)damage
;
848 data
<< (uint32
)absorb
; // absorb
849 data
<< (uint32
)resist
; // resist
850 SendMessageToSet(&data
, true);
852 DealDamage(this, damage
, NULL
, SELF_DAMAGE
, SPELL_SCHOOL_MASK_NORMAL
, NULL
, false);
856 if(type
==DAMAGE_FALL
) // DealDamage not apply item durability loss at self damage
858 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
859 DurabilityLossAll(0.10f
,false);
860 // durability lost message
861 WorldPacket
data(SMSG_DURABILITY_DAMAGE_DEATH
, 0);
862 GetSession()->SendPacket(&data
);
865 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM
, 1, type
);
869 int32
Player::getMaxTimer(MirrorTimerType timer
)
874 return MINUTE
*IN_MILISECONDS
;
877 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING
) || GetSession()->GetSecurity() >= sWorld
.getConfig(CONFIG_DISABLE_BREATHING
))
878 return DISABLED_MIRROR_TIMER
;
879 int32 UnderWaterTime
= 3*MINUTE
*IN_MILISECONDS
;
880 AuraList
const& mModWaterBreathing
= GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING
);
881 for(AuraList::const_iterator i
= mModWaterBreathing
.begin(); i
!= mModWaterBreathing
.end(); ++i
)
882 UnderWaterTime
= uint32(UnderWaterTime
* (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
);
883 return UnderWaterTime
;
888 return DISABLED_MIRROR_TIMER
;
889 return 1*IN_MILISECONDS
;
897 void Player::UpdateMirrorTimers()
899 // Desync flags for update on next HandleDrowning
900 if (m_MirrorTimerFlags
)
901 m_MirrorTimerFlagsLast
= ~m_MirrorTimerFlags
;
904 void Player::HandleDrowning(uint32 time_diff
)
906 if (!m_MirrorTimerFlags
)
910 if (m_MirrorTimerFlags
& UNDERWATER_INWATER
)
912 // Breath timer not activated - activate it
913 if (m_MirrorTimer
[BREATH_TIMER
] == DISABLED_MIRROR_TIMER
)
915 m_MirrorTimer
[BREATH_TIMER
] = getMaxTimer(BREATH_TIMER
);
916 SendMirrorTimer(BREATH_TIMER
, m_MirrorTimer
[BREATH_TIMER
], m_MirrorTimer
[BREATH_TIMER
], -1);
918 else // If activated - do tick
920 m_MirrorTimer
[BREATH_TIMER
]-=time_diff
;
921 // Timer limit - need deal damage
922 if (m_MirrorTimer
[BREATH_TIMER
] < 0)
924 m_MirrorTimer
[BREATH_TIMER
]+= 1*IN_MILISECONDS
;
925 // Calculate and deal damage
926 // TODO: Check this formula
927 uint32 damage
= GetMaxHealth() / 5 + urand(0, getLevel()-1);
928 EnvironmentalDamage(GetGUID(), DAMAGE_DROWNING
, damage
);
930 else if (!(m_MirrorTimerFlagsLast
& UNDERWATER_INWATER
)) // Update time in client if need
931 SendMirrorTimer(BREATH_TIMER
, getMaxTimer(BREATH_TIMER
), m_MirrorTimer
[BREATH_TIMER
], -1);
934 else if (m_MirrorTimer
[BREATH_TIMER
] != DISABLED_MIRROR_TIMER
) // Regen timer
936 int32 UnderWaterTime
= getMaxTimer(BREATH_TIMER
);
938 m_MirrorTimer
[BREATH_TIMER
]+=10*time_diff
;
939 if (m_MirrorTimer
[BREATH_TIMER
] >= UnderWaterTime
|| !isAlive())
940 StopMirrorTimer(BREATH_TIMER
);
941 else if (m_MirrorTimerFlagsLast
& UNDERWATER_INWATER
)
942 SendMirrorTimer(BREATH_TIMER
, UnderWaterTime
, m_MirrorTimer
[BREATH_TIMER
], 10);
946 if (m_MirrorTimerFlags
& UNDERWARER_INDARKWATER
)
948 // Fatigue timer not activated - activate it
949 if (m_MirrorTimer
[FATIGUE_TIMER
] == DISABLED_MIRROR_TIMER
)
951 m_MirrorTimer
[FATIGUE_TIMER
] = getMaxTimer(FATIGUE_TIMER
);
952 SendMirrorTimer(FATIGUE_TIMER
, m_MirrorTimer
[FATIGUE_TIMER
], m_MirrorTimer
[FATIGUE_TIMER
], -1);
956 m_MirrorTimer
[FATIGUE_TIMER
]-=time_diff
;
957 // Timer limit - need deal damage or teleport ghost to graveyard
958 if (m_MirrorTimer
[FATIGUE_TIMER
] < 0)
960 m_MirrorTimer
[FATIGUE_TIMER
]+= 1*IN_MILISECONDS
;
961 if (isAlive()) // Calculate and deal damage
963 uint32 damage
= GetMaxHealth() / 5 + urand(0, getLevel()-1);
964 EnvironmentalDamage(GetGUID(), DAMAGE_EXHAUSTED
, damage
);
966 else if (HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
)) // Teleport ghost to graveyard
969 else if (!(m_MirrorTimerFlagsLast
& UNDERWARER_INDARKWATER
))
970 SendMirrorTimer(FATIGUE_TIMER
, getMaxTimer(FATIGUE_TIMER
), m_MirrorTimer
[FATIGUE_TIMER
], -1);
973 else if (m_MirrorTimer
[FATIGUE_TIMER
] != DISABLED_MIRROR_TIMER
) // Regen timer
975 int32 DarkWaterTime
= getMaxTimer(FATIGUE_TIMER
);
976 m_MirrorTimer
[FATIGUE_TIMER
]+=10*time_diff
;
977 if (m_MirrorTimer
[FATIGUE_TIMER
] >= DarkWaterTime
|| !isAlive())
978 StopMirrorTimer(FATIGUE_TIMER
);
979 else if (m_MirrorTimerFlagsLast
& UNDERWARER_INDARKWATER
)
980 SendMirrorTimer(FATIGUE_TIMER
, DarkWaterTime
, m_MirrorTimer
[FATIGUE_TIMER
], 10);
983 if (m_MirrorTimerFlags
& (UNDERWATER_INLAVA
|UNDERWATER_INSLIME
))
985 // Breath timer not activated - activate it
986 if (m_MirrorTimer
[FIRE_TIMER
] == DISABLED_MIRROR_TIMER
)
987 m_MirrorTimer
[FIRE_TIMER
] = getMaxTimer(FIRE_TIMER
);
990 m_MirrorTimer
[FIRE_TIMER
]-=time_diff
;
991 if (m_MirrorTimer
[FIRE_TIMER
] < 0)
993 m_MirrorTimer
[FIRE_TIMER
]+= 1*IN_MILISECONDS
;
994 // Calculate and deal damage
995 // TODO: Check this formula
996 uint32 damage
= urand(600, 700);
997 if (m_MirrorTimerFlags
&UNDERWATER_INLAVA
)
998 EnvironmentalDamage(GetGUID(), DAMAGE_LAVA
, damage
);
1000 EnvironmentalDamage(GetGUID(), DAMAGE_SLIME
, damage
);
1005 m_MirrorTimer
[FIRE_TIMER
] = DISABLED_MIRROR_TIMER
;
1007 // Recheck timers flag
1008 m_MirrorTimerFlags
&=~UNDERWATER_EXIST_TIMERS
;
1009 for (int i
= 0; i
< MAX_TIMERS
; ++i
)
1010 if (m_MirrorTimer
[i
]!=DISABLED_MIRROR_TIMER
)
1012 m_MirrorTimerFlags
|=UNDERWATER_EXIST_TIMERS
;
1015 m_MirrorTimerFlagsLast
= m_MirrorTimerFlags
;
1018 ///The player sobers by 256 every 10 seconds
1019 void Player::HandleSobering()
1023 uint32 drunk
= (m_drunk
<= 256) ? 0 : (m_drunk
- 256);
1024 SetDrunkValue(drunk
);
1027 DrunkenState
Player::GetDrunkenstateByValue(uint16 value
)
1030 return DRUNKEN_SMASHED
;
1032 return DRUNKEN_DRUNK
;
1034 return DRUNKEN_TIPSY
;
1035 return DRUNKEN_SOBER
;
1038 void Player::SetDrunkValue(uint16 newDrunkenValue
, uint32 itemId
)
1040 uint32 oldDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
1042 m_drunk
= newDrunkenValue
;
1043 SetUInt32Value(PLAYER_BYTES_3
,(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFF0001) | (m_drunk
& 0xFFFE));
1045 uint32 newDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
1047 // special drunk invisibility detection
1048 if(newDrunkenState
>= DRUNKEN_DRUNK
)
1049 m_detectInvisibilityMask
|= (1<<6);
1051 m_detectInvisibilityMask
&= ~(1<<6);
1053 if(newDrunkenState
== oldDrunkenState
)
1056 WorldPacket
data(SMSG_CROSSED_INEBRIATION_THRESHOLD
, (8+4+4));
1057 data
<< uint64(GetGUID());
1058 data
<< uint32(newDrunkenState
);
1059 data
<< uint32(itemId
);
1061 SendMessageToSet(&data
, true);
1064 void Player::Update( uint32 p_time
)
1070 if(m_nextMailDelivereTime
&& m_nextMailDelivereTime
<= time(NULL
))
1075 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1076 m_nextMailDelivereTime
= 0;
1079 Unit::Update( p_time
);
1081 // update player only attacks
1082 if(uint32 ranged_att
= getAttackTimer(RANGED_ATTACK
))
1084 setAttackTimer(RANGED_ATTACK
, (p_time
>= ranged_att
? 0 : ranged_att
- p_time
) );
1087 if(uint32 off_att
= getAttackTimer(OFF_ATTACK
))
1089 setAttackTimer(OFF_ATTACK
, (p_time
>= off_att
? 0 : off_att
- p_time
) );
1092 time_t now
= time (NULL
);
1096 UpdateContestedPvP(p_time
);
1098 UpdateDuelFlag(now
);
1100 CheckDuelDistance(now
);
1102 UpdateAfkReport(now
);
1104 CheckExploreSystem();
1106 // Update items that have just a limited lifetime
1107 if (now
>m_Last_tick
)
1108 UpdateItemDuration(uint32(now
- m_Last_tick
));
1110 if (!m_timedquests
.empty())
1112 std::set
<uint32
>::iterator iter
= m_timedquests
.begin();
1113 while (iter
!= m_timedquests
.end())
1115 QuestStatusData
& q_status
= mQuestStatus
[*iter
];
1116 if( q_status
.m_timer
<= p_time
)
1118 uint32 quest_id
= *iter
;
1119 ++iter
; // current iter will be removed in FailTimedQuest
1120 FailTimedQuest( quest_id
);
1124 q_status
.m_timer
-= p_time
;
1125 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
1131 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING
))
1133 Unit
*pVictim
= getVictim();
1134 if( !IsNonMeleeSpellCasted(false) && pVictim
)
1136 // default combat reach 10
1137 // TODO add weapon,skill check
1139 float pldistance
= ATTACK_DISTANCE
;
1141 if (isAttackReady(BASE_ATTACK
))
1143 if(!IsWithinDistInMap(pVictim
, pldistance
))
1145 setAttackTimer(BASE_ATTACK
,100);
1146 if(m_swingErrorMsg
!= 1) // send single time (client auto repeat)
1148 SendAttackSwingNotInRange();
1149 m_swingErrorMsg
= 1;
1152 //120 degrees of radiant range
1153 else if( !HasInArc( 2*M_PI
/3, pVictim
))
1155 setAttackTimer(BASE_ATTACK
,100);
1156 if(m_swingErrorMsg
!= 2) // send single time (client auto repeat)
1158 SendAttackSwingBadFacingAttack();
1159 m_swingErrorMsg
= 2;
1164 m_swingErrorMsg
= 0; // reset swing error state
1166 // prevent base and off attack in same time, delay attack at 0.2 sec
1167 if(haveOffhandWeapon())
1169 uint32 off_att
= getAttackTimer(OFF_ATTACK
);
1170 if(off_att
< ATTACK_DISPLAY_DELAY
)
1171 setAttackTimer(OFF_ATTACK
,ATTACK_DISPLAY_DELAY
);
1173 AttackerStateUpdate(pVictim
, BASE_ATTACK
);
1174 resetAttackTimer(BASE_ATTACK
);
1178 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK
))
1180 if(!IsWithinDistInMap(pVictim
, pldistance
))
1182 setAttackTimer(OFF_ATTACK
,100);
1184 else if( !HasInArc( 2*M_PI
/3, pVictim
))
1186 setAttackTimer(OFF_ATTACK
,100);
1190 // prevent base and off attack in same time, delay attack at 0.2 sec
1191 uint32 base_att
= getAttackTimer(BASE_ATTACK
);
1192 if(base_att
< ATTACK_DISPLAY_DELAY
)
1193 setAttackTimer(BASE_ATTACK
,ATTACK_DISPLAY_DELAY
);
1195 AttackerStateUpdate(pVictim
, OFF_ATTACK
);
1196 resetAttackTimer(OFF_ATTACK
);
1200 Unit
*owner
= pVictim
->GetOwner();
1201 Unit
*u
= owner
? owner
: pVictim
;
1202 if(u
->IsPvP() && (!duel
|| duel
->opponent
!= u
))
1205 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT
);
1210 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
))
1212 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1214 int time_inn
= time(NULL
)-GetTimeInnEnter();
1215 if (time_inn
>= 10) //freeze update
1217 float bubble
= 0.125*sWorld
.getRate(RATE_REST_INGAME
);
1218 //speed collect rest bonus (section/in hour)
1219 SetRestBonus( GetRestBonus()+ time_inn
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
1220 UpdateInnerTime(time(NULL
));
1225 if(m_regenTimer
> 0)
1227 if(p_time
>= m_regenTimer
)
1230 m_regenTimer
-= p_time
;
1233 if (m_weaponChangeTimer
> 0)
1235 if(p_time
>= m_weaponChangeTimer
)
1236 m_weaponChangeTimer
= 0;
1238 m_weaponChangeTimer
-= p_time
;
1241 if (m_zoneUpdateTimer
> 0)
1243 if(p_time
>= m_zoneUpdateTimer
)
1245 uint32 newzone
, newarea
;
1246 GetZoneAndAreaId(newzone
,newarea
);
1248 if( m_zoneUpdateId
!= newzone
)
1249 UpdateZone(newzone
,newarea
); // also update area
1252 // use area updates as well
1253 // needed for free far all arenas for example
1254 if( m_areaUpdateId
!= newarea
)
1255 UpdateArea(newarea
);
1257 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
1261 m_zoneUpdateTimer
-= p_time
;
1269 if (m_deathState
== JUST_DIED
)
1276 if(p_time
>= m_nextSave
)
1278 // m_nextSave reseted in SaveToDB call
1280 sLog
.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1284 m_nextSave
-= p_time
;
1288 //Handle Water/drowning
1289 HandleDrowning(p_time
);
1291 //Handle detect stealth players
1292 if (m_DetectInvTimer
> 0)
1294 if (p_time
>= m_DetectInvTimer
)
1296 m_DetectInvTimer
= 3000;
1297 HandleStealthedUnitsDetection();
1300 m_DetectInvTimer
-= p_time
;
1304 if (now
> m_Last_tick
)
1306 uint32 elapsed
= uint32(now
- m_Last_tick
);
1307 m_Played_time
[0] += elapsed
; // Total played time
1308 m_Played_time
[1] += elapsed
; // Level played time
1314 m_drunkTimer
+= p_time
;
1316 if (m_drunkTimer
> 10*IN_MILISECONDS
)
1320 // not auto-free ghost from body in instances
1321 if(m_deathTimer
> 0 && !GetBaseMap()->Instanceable())
1323 if(p_time
>= m_deathTimer
)
1330 m_deathTimer
-= p_time
;
1333 UpdateEnchantTime(p_time
);
1334 UpdateHomebindTime(p_time
);
1337 SendUpdateToOutOfRangeGroupMembers();
1339 Pet
* pet
= GetPet();
1340 if(pet
&& !IsWithinDistInMap(pet
, OWNER_MAX_DISTANCE
) && (GetCharmGUID() && (pet
->GetGUID() != GetCharmGUID())))
1342 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
, true);
1347 void Player::setDeathState(DeathState s
)
1349 uint32 ressSpellId
= 0;
1351 bool cur
= isAlive();
1353 if(s
== JUST_DIED
&& cur
)
1355 // drunken state is cleared on death
1357 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1360 clearResurrectRequestData();
1362 // remove form before other mods to prevent incorrect stats calculation
1363 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId
);
1365 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1366 RemovePet(NULL
, PET_SAVE_NOT_IN_SLOT
, true);
1368 // remove uncontrolled pets
1372 // save value before aura remove in Unit::setDeathState
1373 ressSpellId
= GetUInt32Value(PLAYER_SELF_RES_SPELL
);
1377 ressSpellId
= GetResurrectionSpellId();
1378 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP
, 1);
1379 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH
, 1);
1380 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON
, 1);
1382 Unit::setDeathState(s
);
1384 // restore resurrection spell id for player after aura remove
1385 if(s
== JUST_DIED
&& cur
&& ressSpellId
)
1386 SetUInt32Value(PLAYER_SELF_RES_SPELL
, ressSpellId
);
1388 if(isAlive() && !cur
)
1390 //clear aura case after resurrection by another way (spells will be applied before next death)
1391 SetUInt32Value(PLAYER_SELF_RES_SPELL
, 0);
1393 // restore default warrior stance
1394 if(getClass()== CLASS_WARRIOR
)
1395 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
1399 void Player::BuildEnumData( QueryResult
* result
, WorldPacket
* p_data
)
1401 Field
*fields
= result
->Fetch();
1403 *p_data
<< uint64(GetGUID());
1406 *p_data
<< uint8(getRace());
1407 uint8 pClass
= getClass();
1408 *p_data
<< uint8(pClass
);
1409 *p_data
<< uint8(getGender());
1411 uint32 bytes
= GetUInt32Value(PLAYER_BYTES
);
1412 *p_data
<< uint8(bytes
);
1413 *p_data
<< uint8(bytes
>> 8);
1414 *p_data
<< uint8(bytes
>> 16);
1415 *p_data
<< uint8(bytes
>> 24);
1417 bytes
= GetUInt32Value(PLAYER_BYTES_2
);
1418 *p_data
<< uint8(bytes
);
1420 *p_data
<< uint8(getLevel()); // player level
1421 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1422 uint32 zoneId
= MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY(),GetPositionZ());
1423 sLog
.outDebug("Player::BuildEnumData: m:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId
);
1424 *p_data
<< uint32(zoneId
);
1425 *p_data
<< uint32(GetMapId());
1427 *p_data
<< GetPositionX();
1428 *p_data
<< GetPositionY();
1429 *p_data
<< GetPositionZ();
1432 *p_data
<< (result
? fields
[13].GetUInt32() : 0);
1434 uint32 char_flags
= 0;
1435 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
1436 char_flags
|= CHARACTER_FLAG_HIDE_HELM
;
1437 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
1438 char_flags
|= CHARACTER_FLAG_HIDE_CLOAK
;
1439 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
))
1440 char_flags
|= CHARACTER_FLAG_GHOST
;
1441 if(HasAtLoginFlag(AT_LOGIN_RENAME
))
1442 char_flags
|= CHARACTER_FLAG_RENAME
;
1443 if(sWorld
.getConfig(CONFIG_DECLINED_NAMES_USED
) && (fields
[14].GetCppString() != ""))
1444 char_flags
|= CHARACTER_FLAG_DECLINED
;
1446 *p_data
<< uint32(char_flags
); // character flags
1447 // character customize (flags?)
1448 *p_data
<< uint32(HasAtLoginFlag(AT_LOGIN_CUSTOMIZE
) ? 1 : 0);
1449 *p_data
<< uint8(1); // unknown
1453 uint32 petDisplayId
= 0;
1454 uint32 petLevel
= 0;
1455 uint32 petFamily
= 0;
1457 // show pet at selection character in character list only for non-ghost character
1458 if(result
&& isAlive() && (pClass
== CLASS_WARLOCK
|| pClass
== CLASS_HUNTER
))
1460 uint32 entry
= fields
[10].GetUInt32();
1461 CreatureInfo
const* cInfo
= sCreatureStorage
.LookupEntry
<CreatureInfo
>(entry
);
1464 petDisplayId
= fields
[11].GetUInt32();
1465 petLevel
= fields
[12].GetUInt32();
1466 petFamily
= cInfo
->family
;
1470 *p_data
<< uint32(petDisplayId
);
1471 *p_data
<< uint32(petLevel
);
1472 *p_data
<< uint32(petFamily
);
1475 for (uint8 slot
= 0; slot
< EQUIPMENT_SLOT_END
; slot
++)
1477 uint32 visualbase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
1478 uint32 item_id
= GetUInt32Value(visualbase
);
1479 const ItemPrototype
* proto
= objmgr
.GetItemPrototype(item_id
);
1480 SpellItemEnchantmentEntry
const *enchant
= NULL
;
1482 for(uint8 enchantSlot
= PERM_ENCHANTMENT_SLOT
; enchantSlot
<=TEMP_ENCHANTMENT_SLOT
; enchantSlot
++)
1484 uint32 enchantId
= GetUInt32Value(visualbase
+1+enchantSlot
);
1485 if(enchant
= sSpellItemEnchantmentStore
.LookupEntry(enchantId
))
1491 *p_data
<< uint32(proto
->DisplayInfoID
);
1492 *p_data
<< uint8(proto
->InventoryType
);
1493 *p_data
<< uint32(enchant
? enchant
->aura_id
: 0);
1497 *p_data
<< uint32(0);
1498 *p_data
<< uint8(0);
1499 *p_data
<< uint32(0); // enchant?
1502 *p_data
<< uint32(0); // first bag display id
1503 *p_data
<< uint8(0); // first bag inventory type
1504 *p_data
<< uint32(0); // enchant?
1507 bool Player::ToggleAFK()
1509 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1511 bool state
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1513 // afk player not allowed in battleground
1514 if(state
&& InBattleGround())
1515 LeaveBattleground();
1520 bool Player::ToggleDND()
1522 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1524 return HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1527 uint8
Player::chatTag() const
1544 bool Player::TeleportTo(uint32 mapid
, float x
, float y
, float z
, float orientation
, uint32 options
)
1546 if(!MapManager::IsValidMapCoord(mapid
, x
, y
, z
, orientation
))
1548 sLog
.outError("TeleportTo: invalid map %d or absent instance template.", mapid
);
1552 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1553 Pet
* pet
= GetPet();
1555 MapEntry
const* mEntry
= sMapStore
.LookupEntry(mapid
);
1557 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1558 // don't let gm level > 1 either
1559 if(!InBattleGround() && mEntry
->IsBattleGroundOrArena())
1562 // client without expansion support
1563 if(GetSession()->Expansion() < mEntry
->Expansion())
1565 sLog
.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid
);
1568 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1570 SendTransferAborted(mapid
, TRANSFER_ABORT_INSUF_EXPAN_LVL
, mEntry
->Expansion());
1572 return false; // normal client can't teleport to this map...
1576 sLog
.outDebug("Player %s is being teleported to map %u", GetName(), mapid
);
1579 // if we were on a transport, leave
1580 if (!(options
& TELE_TO_NOT_LEAVE_TRANSPORT
) && m_transport
)
1582 m_transport
->RemovePassenger(this);
1584 m_movementInfo
.t_x
= 0.0f
;
1585 m_movementInfo
.t_y
= 0.0f
;
1586 m_movementInfo
.t_z
= 0.0f
;
1587 m_movementInfo
.t_o
= 0.0f
;
1588 m_movementInfo
.t_time
= 0;
1591 SetSemaphoreTeleport(true);
1593 // The player was ported to another map and looses the duel immediately.
1594 // We have to perform this check before the teleport, otherwise the
1595 // ObjectAccessor won't find the flag.
1596 if (duel
&& GetMapId()!=mapid
)
1598 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER
));
1600 DuelComplete(DUEL_FLED
);
1603 // reset movement flags at teleport, because player will continue move with these flags after teleport
1604 SetUnitMovementFlags(0);
1606 if ((GetMapId() == mapid
) && (!m_transport
))
1608 // prepare zone change detect
1609 uint32 old_zone
= GetZoneId();
1612 if(!GetSession()->PlayerLogout())
1615 BuildTeleportAckMsg(&data
, x
, y
, z
, orientation
);
1616 GetSession()->SendPacket(&data
);
1617 SetPosition( x
, y
, z
, orientation
, true);
1620 // this will be used instead of the current location in SaveToDB
1621 m_teleport_dest
= WorldLocation(mapid
, x
, y
, z
, orientation
);
1623 SetFallInformation(0, z
);
1625 //BuildHeartBeatMsg(&data);
1626 //SendMessageToSet(&data, true);
1627 if (!(options
& TELE_TO_NOT_UNSUMMON_PET
))
1629 //same map, only remove pet if out of range
1630 if(pet
&& !IsWithinDistInMap(pet
, OWNER_MAX_DISTANCE
))
1632 if(pet
->isControlled() && !pet
->isTemporarySummoned() )
1633 m_temporaryUnsummonedPetNumber
= pet
->GetCharmInfo()->GetPetNumber();
1635 m_temporaryUnsummonedPetNumber
= 0;
1637 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
);
1641 if(!(options
& TELE_TO_NOT_LEAVE_COMBAT
))
1644 if (!(options
& TELE_TO_NOT_UNSUMMON_PET
))
1647 if(pet
&& m_temporaryUnsummonedPetNumber
)
1649 Pet
* NewPet
= new Pet
;
1650 if(!NewPet
->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber
, true))
1653 m_temporaryUnsummonedPetNumber
= 0;
1657 uint32 newzone
, newarea
;
1658 GetZoneAndAreaId(newzone
,newarea
);
1660 if(!GetSession()->PlayerLogout())
1662 // don't reset teleport semaphore while logging out, otherwise m_teleport_dest won't be used in Player::SaveToDB
1663 SetSemaphoreTeleport(false);
1665 UpdateZone(newzone
,newarea
);
1669 if(old_zone
!= newzone
)
1672 if(pvpInfo
.inHostileArea
)
1673 CastSpell(this, 2479, true);
1678 // far teleport to another map
1679 Map
* oldmap
= IsInWorld() ? GetMap() : NULL
;
1680 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1682 // Check enter rights before map getting to avoid creating instance copy for player
1683 // this check not dependent from map instance copy and same for all instance copies of selected map
1684 if (!MapManager::Instance().CanPlayerEnter(mapid
, this))
1686 SetSemaphoreTeleport(false);
1690 // If the map is not created, assume it is possible to enter it.
1691 // It will be created in the WorldPortAck.
1692 Map
*map
= MapManager::Instance().FindMap(mapid
);
1693 if (!map
|| map
->CanEnter(this))
1699 ResetContestedPvP();
1701 // remove player from battleground on far teleport (when changing maps)
1702 if(BattleGround
const* bg
= GetBattleGround())
1704 // Note: at battleground join battleground id set before teleport
1705 // and we already will found "current" battleground
1706 // just need check that this is targeted map or leave
1707 if(bg
->GetMapId() != mapid
)
1708 LeaveBattleground(false); // don't teleport to entry point
1711 // remove pet on map change
1714 //leaving map -> delete pet right away (doing this later will cause problems)
1715 if(pet
->isControlled() && !pet
->isTemporarySummoned())
1716 m_temporaryUnsummonedPetNumber
= pet
->GetCharmInfo()->GetPetNumber();
1718 m_temporaryUnsummonedPetNumber
= 0;
1720 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
);
1723 // remove all dyn objects
1724 RemoveAllDynObjects();
1726 // stop spellcasting
1727 // not attempt interrupt teleportation spell at caster teleport
1728 if(!(options
& TELE_TO_SPELL
))
1729 if(IsNonMeleeSpellCasted(true))
1730 InterruptNonMeleeSpells(true);
1732 if(!GetSession()->PlayerLogout())
1734 // send transfer packets
1735 WorldPacket
data(SMSG_TRANSFER_PENDING
, (4+4+4));
1736 data
<< uint32(mapid
);
1739 data
<< m_transport
->GetEntry() << GetMapId();
1741 GetSession()->SendPacket(&data
);
1743 data
.Initialize(SMSG_NEW_WORLD
, (20));
1746 data
<< (uint32
)mapid
<< m_movementInfo
.t_x
<< m_movementInfo
.t_y
<< m_movementInfo
.t_z
<< m_movementInfo
.t_o
;
1750 data
<< (uint32
)mapid
<< (float)x
<< (float)y
<< (float)z
<< (float)orientation
;
1752 GetSession()->SendPacket( &data
);
1753 SendSavedInstances();
1755 // remove from old map now
1756 if(oldmap
) oldmap
->Remove(this, false);
1759 // new final coordinates
1763 float final_o
= orientation
;
1767 final_x
+= m_movementInfo
.t_x
;
1768 final_y
+= m_movementInfo
.t_y
;
1769 final_z
+= m_movementInfo
.t_z
;
1770 final_o
+= m_movementInfo
.t_o
;
1773 m_teleport_dest
= WorldLocation(mapid
, final_x
, final_y
, final_z
, final_o
);
1774 SetFallInformation(0, final_z
);
1775 // if the player is saved before worldportack (at logout for example)
1776 // this will be used instead of the current location in SaveToDB
1778 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP
);
1780 // move packet sent by client always after far teleport
1781 // SetPosition(final_x, final_y, final_z, final_o, true);
1784 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1792 void Player::AddToWorld()
1794 ///- Do not add/remove the player from the object storage
1795 ///- It will crash when updating the ObjectAccessor
1796 ///- The player should only be added when logging in
1799 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; i
++)
1802 m_items
[i
]->AddToWorld();
1806 void Player::RemoveFromWorld()
1811 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1813 UnsummonAllTotems();
1818 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; i
++)
1821 m_items
[i
]->RemoveFromWorld();
1824 ///- Do not add/remove the player from the object storage
1825 ///- It will crash when updating the ObjectAccessor
1826 ///- The player should only be removed when logging out
1827 Unit::RemoveFromWorld();
1830 void Player::RewardRage( uint32 damage
, uint32 weaponSpeedHitFactor
, bool attacker
)
1834 float rageconversion
= ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1838 addRage
= ((damage
/rageconversion
*7.5 + weaponSpeedHitFactor
)/2);
1840 // talent who gave more rage on attack
1841 addRage
*= 1.0f
+ GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT
) / 100.0f
;
1845 addRage
= damage
/rageconversion
*2.5;
1847 // Berserker Rage effect
1848 if(HasAura(18499,0))
1852 addRage
*= sWorld
.getRate(RATE_POWER_RAGE_INCOME
);
1854 ModifyPower(POWER_RAGE
, uint32(addRage
*10));
1857 void Player::RegenerateAll()
1859 if (m_regenTimer
!= 0)
1861 uint32 regenDelay
= 2000;
1863 // Not in combat or they have regeneration
1864 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) ||
1865 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
) || IsPolymorphed() )
1868 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN
))
1870 Regenerate(POWER_RAGE
);
1871 if(getClass() == CLASS_DEATH_KNIGHT
)
1872 Regenerate(POWER_RUNIC_POWER
);
1876 Regenerate( POWER_ENERGY
);
1878 Regenerate( POWER_MANA
);
1880 if(getClass() == CLASS_DEATH_KNIGHT
)
1881 Regenerate( POWER_RUNE
);
1883 m_regenTimer
= regenDelay
;
1886 void Player::Regenerate(Powers power
)
1888 uint32 curValue
= GetPower(power
);
1889 uint32 maxValue
= GetMaxPower(power
);
1891 float addvalue
= 0.0f
;
1897 bool recentCast
= IsUnderLastManaUseEffect();
1898 float ManaIncreaseRate
= sWorld
.getRate(RATE_POWER_MANA
);
1901 // Mangos Updates Mana in intervals of 2s, which is correct
1902 addvalue
= GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER
) * ManaIncreaseRate
* 2.00f
;
1906 addvalue
= GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER
) * ManaIncreaseRate
* 2.00f
;
1909 case POWER_RAGE
: // Regenerate rage
1911 float RageDecreaseRate
= sWorld
.getRate(RATE_POWER_RAGE_LOSS
);
1912 addvalue
= 30 * RageDecreaseRate
; // 3 rage by tick
1914 case POWER_ENERGY
: // Regenerate energy (rogue)
1917 case POWER_RUNIC_POWER
:
1919 float RunicPowerDecreaseRate
= sWorld
.getRate(RATE_POWER_RUNICPOWER_LOSS
);
1920 addvalue
= 30 * RunicPowerDecreaseRate
; // 3 RunicPower by tick
1924 for(uint32 i
= 0; i
< MAX_RUNES
; ++i
)
1925 if(uint8 cd
= GetRuneCooldown(i
)) // if we have cooldown, reduce it...
1926 SetRuneCooldown(i
, cd
- 1); // ... by 2 sec (because update is every 2 sec)
1929 case POWER_HAPPINESS
:
1933 // Mana regen calculated in Player::UpdateManaRegen()
1934 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1935 if(power
!= POWER_MANA
)
1937 AuraList
const& ModPowerRegenPCTAuras
= GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT
);
1938 for(AuraList::const_iterator i
= ModPowerRegenPCTAuras
.begin(); i
!= ModPowerRegenPCTAuras
.end(); ++i
)
1939 if ((*i
)->GetModifier()->m_miscvalue
== power
)
1940 addvalue
*= ((*i
)->GetModifier()->m_amount
+ 100) / 100.0f
;
1943 if (power
!= POWER_RAGE
&& power
!= POWER_RUNIC_POWER
)
1945 curValue
+= uint32(addvalue
);
1946 if (curValue
> maxValue
)
1947 curValue
= maxValue
;
1951 if(curValue
<= uint32(addvalue
))
1954 curValue
-= uint32(addvalue
);
1956 SetPower(power
, curValue
);
1959 void Player::RegenerateHealth()
1961 uint32 curValue
= GetHealth();
1962 uint32 maxValue
= GetMaxHealth();
1964 if (curValue
>= maxValue
) return;
1966 float HealthIncreaseRate
= sWorld
.getRate(RATE_HEALTH
);
1968 float addvalue
= 0.0f
;
1971 if ( IsPolymorphed() )
1972 addvalue
= GetMaxHealth()/3;
1973 // normal regen case (maybe partly in combat case)
1974 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) )
1976 addvalue
= OCTRegenHPPerSpirit()* HealthIncreaseRate
;
1979 AuraList
const& mModHealthRegenPct
= GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT
);
1980 for(AuraList::const_iterator i
= mModHealthRegenPct
.begin(); i
!= mModHealthRegenPct
.end(); ++i
)
1981 addvalue
*= (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
;
1983 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
))
1984 addvalue
*= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) / 100.0f
;
1990 // always regeneration bonus (including combat)
1991 addvalue
+= GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
);
1996 ModifyHealth(int32(addvalue
));
1999 bool Player::CanInteractWithNPCs(bool alive
) const
2001 if(alive
&& !isAlive())
2009 bool Player::IsUnderWater() const
2011 return IsInWater() &&
2012 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2015 void Player::SetInWater(bool apply
)
2017 if(m_isInWater
==apply
)
2020 //define player in water by opcodes
2021 //move player's guid into HateOfflineList of those mobs
2022 //which can't swim and move guid back into ThreatList when
2024 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2025 m_isInWater
= apply
;
2027 // remove auras that need water/land
2028 RemoveAurasWithInterruptFlags(apply
? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER
: AURA_INTERRUPT_FLAG_NOT_UNDERWATER
);
2030 getHostilRefManager().updateThreatTables();
2033 void Player::SetGameMaster(bool on
)
2037 m_ExtraFlags
|= PLAYER_EXTRA_GM_ON
;
2039 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
2041 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
2042 ResetContestedPvP();
2044 getHostilRefManager().setOnlineOfflineState(false);
2047 SetPhaseMask(PHASEMASK_ANYWHERE
,false); // see and visible in all phases
2052 AuraList
const& phases
= GetAurasByType(SPELL_AURA_PHASE
);
2053 SetPhaseMask(!phases
.empty() ? phases
.front()->GetMiscValue() : PHASEMASK_NORMAL
,false);
2055 m_ExtraFlags
&= ~ PLAYER_EXTRA_GM_ON
;
2056 setFactionForRace(getRace());
2057 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
2059 // restore FFA PvP Server state
2060 if(sWorld
.IsFFAPvPRealm())
2061 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
2063 // restore FFA PvP area state, remove not allowed for GM mounts
2064 UpdateArea(m_areaUpdateId
);
2066 getHostilRefManager().setOnlineOfflineState(true);
2069 ObjectAccessor::UpdateVisibilityForPlayer(this);
2072 void Player::SetGMVisible(bool on
)
2076 m_ExtraFlags
&= ~PLAYER_EXTRA_GM_INVISIBLE
; //remove flag
2078 // Reapply stealth/invisibility if active or show if not any
2079 if(HasAuraType(SPELL_AURA_MOD_STEALTH
))
2080 SetVisibility(VISIBILITY_GROUP_STEALTH
);
2081 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY
))
2082 SetVisibility(VISIBILITY_GROUP_INVISIBILITY
);
2084 SetVisibility(VISIBILITY_ON
);
2088 m_ExtraFlags
|= PLAYER_EXTRA_GM_INVISIBLE
; //add flag
2090 SetAcceptWhispers(false);
2091 SetGameMaster(true);
2093 SetVisibility(VISIBILITY_OFF
);
2097 bool Player::IsGroupVisibleFor(Player
* p
) const
2099 switch(sWorld
.getConfig(CONFIG_GROUP_VISIBILITY
))
2101 default: return IsInSameGroupWith(p
);
2102 case 1: return IsInSameRaidWith(p
);
2103 case 2: return GetTeam()==p
->GetTeam();
2107 bool Player::IsInSameGroupWith(Player
const* p
) const
2109 return p
==this || GetGroup() != NULL
&&
2110 GetGroup() == p
->GetGroup() &&
2111 GetGroup()->SameSubGroup((Player
*)this, (Player
*)p
);
2114 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2115 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2116 void Player::UninviteFromGroup()
2118 Group
* group
= GetGroupInvite();
2122 group
->RemoveInvite(this);
2124 if(group
->GetMembersCount() <= 1) // group has just 1 member => disband
2126 if(group
->IsCreated())
2128 group
->Disband(true);
2129 objmgr
.RemoveGroup(group
);
2132 group
->RemoveAllInvites();
2138 void Player::RemoveFromGroup(Group
* group
, uint64 guid
)
2142 if (group
->RemoveMember(guid
, 0) <= 1)
2144 // group->Disband(); already disbanded in RemoveMember
2145 objmgr
.RemoveGroup(group
);
2147 // removemember sets the player's group pointer to NULL
2152 void Player::SendLogXPGain(uint32 GivenXP
, Unit
* victim
, uint32 RestXP
)
2154 WorldPacket
data(SMSG_LOG_XPGAIN
, 21);
2155 data
<< uint64(victim
? victim
->GetGUID() : 0); // guid
2156 data
<< uint32(GivenXP
+RestXP
); // given experience
2157 data
<< uint8(victim
? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2160 data
<< uint32(GivenXP
); // experience without rested bonus
2161 data
<< float(1); // 1 - none 0 - 100% group bonus output
2163 data
<< uint8(0); // new 2.4.0
2164 GetSession()->SendPacket(&data
);
2167 void Player::GiveXP(uint32 xp
, Unit
* victim
)
2175 uint32 level
= getLevel();
2177 // XP to money conversion processed in Player::RewardQuest
2178 if(level
>= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
2181 // handle SPELL_AURA_MOD_XP_PCT auras
2182 Unit::AuraList
const& ModXPPctAuras
= GetAurasByType(SPELL_AURA_MOD_XP_PCT
);
2183 for(Unit::AuraList::const_iterator i
= ModXPPctAuras
.begin();i
!= ModXPPctAuras
.end(); ++i
)
2184 xp
= uint32(xp
*(1.0f
+ (*i
)->GetModifier()->m_amount
/ 100.0f
));
2186 // XP resting bonus for kill
2187 uint32 rested_bonus_xp
= victim
? GetXPRestBonus(xp
) : 0;
2189 SendLogXPGain(xp
,victim
,rested_bonus_xp
);
2191 uint32 curXP
= GetUInt32Value(PLAYER_XP
);
2192 uint32 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2193 uint32 newXP
= curXP
+ xp
+ rested_bonus_xp
;
2195 while( newXP
>= nextLvlXP
&& level
< sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
2199 if ( level
< sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
2200 GiveLevel(level
+ 1);
2203 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2206 SetUInt32Value(PLAYER_XP
, newXP
);
2209 // Update player to next level
2210 // Current player experience not update (must be update by caller)
2211 void Player::GiveLevel(uint32 level
)
2213 if ( level
== getLevel() )
2216 PlayerLevelInfo info
;
2217 objmgr
.GetPlayerLevelInfo(getRace(),getClass(),level
,&info
);
2219 PlayerClassLevelInfo classInfo
;
2220 objmgr
.GetPlayerClassLevelInfo(getClass(),level
,&classInfo
);
2222 // send levelup info to client
2223 WorldPacket
data(SMSG_LEVELUP_INFO
, (4+4+MAX_POWERS
*4+MAX_STATS
*4));
2224 data
<< uint32(level
);
2225 data
<< uint32(int32(classInfo
.basehealth
) - int32(GetCreateHealth()));
2226 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2227 data
<< uint32(int32(classInfo
.basemana
) - int32(GetCreateMana()));
2235 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
) // Stats loop (0-4)
2236 data
<< uint32(int32(info
.stats
[i
]) - GetCreateStat(Stats(i
)));
2238 GetSession()->SendPacket(&data
);
2240 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, objmgr
.GetXPForLevel(level
));
2242 //update level, max level of skills
2243 if(getLevel()!= level
)
2244 m_Played_time
[1] = 0; // Level Played Time reset
2246 UpdateSkillsForLevel ();
2248 // save base values (bonuses already included in stored stats
2249 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2250 SetCreateStat(Stats(i
), info
.stats
[i
]);
2252 SetCreateHealth(classInfo
.basehealth
);
2253 SetCreateMana(classInfo
.basemana
);
2255 InitTalentForLevel();
2256 InitTaxiNodesForLevel();
2257 InitGlyphsForLevel();
2261 // set current level health and mana/energy to maximum after applying all mods.
2262 SetHealth(GetMaxHealth());
2263 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2264 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2265 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2266 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2267 SetPower(POWER_FOCUS
, 0);
2268 SetPower(POWER_HAPPINESS
, 0);
2270 // give level to summoned pet
2271 Pet
* pet
= GetPet();
2272 if(pet
&& pet
->getPetType()==SUMMON_PET
)
2273 pet
->GivePetLevel(level
);
2274 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL
);
2277 void Player::InitTalentForLevel()
2279 uint32 level
= getLevel();
2280 // talents base at level diff ( talents = level - 9 but some can be used already)
2283 // Remove all talent points
2284 if(m_usedTalentCount
> 0) // Free any used talents
2287 SetFreeTalentPoints(0);
2292 uint32 talentPointsForLevel
= CalculateTalentsPoints();
2294 // if used more that have then reset
2295 if(m_usedTalentCount
> talentPointsForLevel
)
2297 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR
)
2300 SetFreeTalentPoints(0);
2302 // else update amount of free points
2304 SetFreeTalentPoints(talentPointsForLevel
-m_usedTalentCount
);
2308 void Player::InitStatsForLevel(bool reapplyMods
)
2310 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2311 _RemoveAllStatBonuses();
2313 PlayerClassLevelInfo classInfo
;
2314 objmgr
.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo
);
2316 PlayerLevelInfo info
;
2317 objmgr
.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info
);
2319 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL
, sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) );
2320 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, objmgr
.GetXPForLevel(getLevel()));
2322 UpdateSkillsForLevel ();
2324 // set default cast time multiplier
2325 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
);
2327 // reset size before reapply auras
2328 SetFloatValue(OBJECT_FIELD_SCALE_X
,1.0f
);
2330 // save base values (bonuses already included in stored stats
2331 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2332 SetCreateStat(Stats(i
), info
.stats
[i
]);
2334 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2335 SetStat(Stats(i
), info
.stats
[i
]);
2337 SetCreateHealth(classInfo
.basehealth
);
2340 SetCreateMana(classInfo
.basemana
);
2342 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2346 //reset rating fields values
2347 for(uint16 index
= PLAYER_FIELD_COMBAT_RATING_1
; index
< PLAYER_FIELD_COMBAT_RATING_1
+ MAX_COMBAT_RATING
; ++index
)
2348 SetUInt32Value(index
, 0);
2350 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS
,0);
2351 for (int i
= 0; i
< 7; i
++)
2353 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG
+i
, 0);
2354 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS
+i
, 0);
2355 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT
+i
, 1.00f
);
2358 //reset attack power, damage and attack speed fields
2359 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
, 2000.0f
);
2360 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
+ 1, 2000.0f
); // offhand attack time
2361 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME
, 2000.0f
);
2363 SetFloatValue(UNIT_FIELD_MINDAMAGE
, 0.0f
);
2364 SetFloatValue(UNIT_FIELD_MAXDAMAGE
, 0.0f
);
2365 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
, 0.0f
);
2366 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
, 0.0f
);
2367 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
, 0.0f
);
2368 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
, 0.0f
);
2370 SetInt32Value(UNIT_FIELD_ATTACK_POWER
, 0 );
2371 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS
, 0 );
2372 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER
,0.0f
);
2373 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER
, 0 );
2374 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS
,0 );
2375 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER
,0.0f
);
2377 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2378 SetFloatValue(PLAYER_CRIT_PERCENTAGE
,0.0f
);
2379 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE
,0.0f
);
2380 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE
,0.0f
);
2382 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2383 for (uint8 i
= 0; i
< 7; ++i
)
2384 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1
+i
, 0.0f
);
2386 SetFloatValue(PLAYER_PARRY_PERCENTAGE
, 0.0f
);
2387 SetFloatValue(PLAYER_BLOCK_PERCENTAGE
, 0.0f
);
2388 SetUInt32Value(PLAYER_SHIELD_BLOCK
, 0);
2391 SetFloatValue(PLAYER_DODGE_PERCENTAGE
, 0.0f
);
2393 // set armor (resistance 0) to original value (create_agility*2)
2394 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2395 SetResistanceBuffMods(SpellSchools(0), true, 0.0f
);
2396 SetResistanceBuffMods(SpellSchools(0), false, 0.0f
);
2397 // set other resistance to original value (0)
2398 for (int i
= 1; i
< MAX_SPELL_SCHOOL
; i
++)
2400 SetResistance(SpellSchools(i
), 0);
2401 SetResistanceBuffMods(SpellSchools(i
), true, 0.0f
);
2402 SetResistanceBuffMods(SpellSchools(i
), false, 0.0f
);
2405 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE
,0);
2406 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE
,0);
2407 for(int i
= 0; i
< MAX_SPELL_SCHOOL
; ++i
)
2409 SetFloatValue(UNIT_FIELD_POWER_COST_MODIFIER
+i
,0.0f
);
2410 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER
+i
,0.0f
);
2412 // Reset no reagent cost field
2413 for(int i
= 0; i
< 3; i
++)
2414 SetUInt32Value(PLAYER_NO_REAGENT_COST_1
+ i
, 0);
2415 // Init data for form but skip reapply item mods for form
2416 InitDataForForm(reapplyMods
);
2419 for (int i
= POWER_MANA
; i
< MAX_POWERS
; i
++)
2420 SetMaxPower(Powers(i
), uint32(GetCreatePowers(Powers(i
))));
2422 SetMaxHealth(classInfo
.basehealth
); // stamina bonus will applied later
2424 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2425 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID
, 0);
2427 // cleanup unit flags (will be re-applied if need at aura load).
2428 RemoveFlag( UNIT_FIELD_FLAGS
,
2429 UNIT_FLAG_NON_ATTACKABLE
| UNIT_FLAG_DISABLE_MOVE
| UNIT_FLAG_NOT_ATTACKABLE_1
|
2430 UNIT_FLAG_PET_IN_COMBAT
| UNIT_FLAG_SILENCED
| UNIT_FLAG_PACIFIED
|
2431 UNIT_FLAG_STUNNED
| UNIT_FLAG_IN_COMBAT
| UNIT_FLAG_DISARMED
|
2432 UNIT_FLAG_CONFUSED
| UNIT_FLAG_FLEEING
| UNIT_FLAG_NOT_SELECTABLE
|
2433 UNIT_FLAG_SKINNABLE
| UNIT_FLAG_MOUNT
| UNIT_FLAG_TAXI_FLIGHT
);
2434 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
); // must be set
2436 SetFlag(UNIT_FIELD_FLAGS_2
,UNIT_FLAG2_REGENERATE_POWER
);// must be set
2438 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2439 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
| PLAYER_FLAGS_DND
| PLAYER_FLAGS_GM
| PLAYER_FLAGS_GHOST
);
2441 RemoveStandFlags(UNIT_STAND_FLAGS_ALL
); // one form stealth modified bytes
2442 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
| UNIT_BYTE2_FLAG_SANCTUARY
);
2444 // restore if need some important flags
2445 SetUInt32Value(PLAYER_FIELD_BYTES2
, 0 ); // flags empty by default
2447 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2448 _ApplyAllStatBonuses();
2450 // set current level health and mana/energy to maximum after applying all mods.
2451 SetHealth(GetMaxHealth());
2452 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2453 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2454 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2455 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2456 SetPower(POWER_FOCUS
, 0);
2457 SetPower(POWER_HAPPINESS
, 0);
2458 SetPower(POWER_RUNIC_POWER
, 0);
2461 void Player::SendInitialSpells()
2463 time_t curTime
= time(NULL
);
2464 time_t infTime
= curTime
+ MONTH
/2;
2466 uint16 spellCount
= 0;
2468 WorldPacket
data(SMSG_INITIAL_SPELLS
, (1+2+4*m_spells
.size()+2+m_spellCooldowns
.size()*(2+2+2+4+4)));
2471 size_t countPos
= data
.wpos();
2472 data
<< uint16(spellCount
); // spell count placeholder
2474 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2476 if(itr
->second
->state
== PLAYERSPELL_REMOVED
)
2479 if(!itr
->second
->active
|| itr
->second
->disabled
)
2482 data
<< uint16(itr
->first
);
2483 data
<< uint16(0); // it's not slot id
2488 data
.put
<uint16
>(countPos
,spellCount
); // write real count value
2490 uint16 spellCooldowns
= m_spellCooldowns
.size();
2491 data
<< uint16(spellCooldowns
);
2492 for(SpellCooldowns::const_iterator itr
=m_spellCooldowns
.begin(); itr
!=m_spellCooldowns
.end(); ++itr
)
2494 SpellEntry
const *sEntry
= sSpellStore
.LookupEntry(itr
->first
);
2498 // not send infinity cooldown
2499 if(itr
->second
.end
> infTime
)
2502 data
<< uint16(itr
->first
);
2504 time_t cooldown
= 0;
2505 if(itr
->second
.end
> curTime
)
2506 cooldown
= (itr
->second
.end
-curTime
)*IN_MILISECONDS
;
2508 data
<< uint16(itr
->second
.itemid
); // cast item id
2509 data
<< uint16(sEntry
->Category
); // spell category
2510 if(sEntry
->Category
) // may be wrong, but anyway better than nothing...
2512 data
<< uint32(0); // cooldown
2513 data
<< uint32(cooldown
); // category cooldown
2517 data
<< uint32(cooldown
); // cooldown
2518 data
<< uint32(0); // category cooldown
2522 GetSession()->SendPacket(&data
);
2524 sLog
.outDetail( "CHARACTER: Sent Initial Spells" );
2527 void Player::RemoveMail(uint32 id
)
2529 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
2531 if ((*itr
)->messageID
== id
)
2533 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2540 void Player::SendMailResult(uint32 mailId
, uint32 mailAction
, uint32 mailError
, uint32 equipError
, uint32 item_guid
, uint32 item_count
)
2542 WorldPacket
data(SMSG_SEND_MAIL_RESULT
, (4+4+4+(mailError
== MAIL_ERR_BAG_FULL
?4:(mailAction
== MAIL_ITEM_TAKEN
?4+4:0))));
2543 data
<< (uint32
) mailId
;
2544 data
<< (uint32
) mailAction
;
2545 data
<< (uint32
) mailError
;
2546 if ( mailError
== MAIL_ERR_BAG_FULL
)
2547 data
<< (uint32
) equipError
;
2548 else if( mailAction
== MAIL_ITEM_TAKEN
)
2550 data
<< (uint32
) item_guid
; // item guid low?
2551 data
<< (uint32
) item_count
; // item count?
2553 GetSession()->SendPacket(&data
);
2556 void Player::SendNewMail()
2558 // deliver undelivered mail
2559 WorldPacket
data(SMSG_RECEIVED_MAIL
, 4);
2561 GetSession()->SendPacket(&data
);
2564 void Player::UpdateNextMailTimeAndUnreads()
2566 // calculate next delivery time (min. from non-delivered mails
2567 // and recalculate unReadMail
2568 time_t cTime
= time(NULL
);
2569 m_nextMailDelivereTime
= 0;
2571 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
2573 if((*itr
)->deliver_time
> cTime
)
2575 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> (*itr
)->deliver_time
)
2576 m_nextMailDelivereTime
= (*itr
)->deliver_time
;
2578 else if(((*itr
)->checked
& MAIL_CHECK_MASK_READ
) == 0)
2583 void Player::AddNewMailDeliverTime(time_t deliver_time
)
2585 if(deliver_time
<= time(NULL
)) // ready now
2590 else // not ready and no have ready mails
2592 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> deliver_time
)
2593 m_nextMailDelivereTime
= deliver_time
;
2597 bool Player::addSpell(uint32 spell_id
, bool active
, bool learning
, bool dependent
, bool disabled
)
2599 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
2602 // do character spell book cleanup (all characters)
2603 if(!IsInWorld() && !learning
) // spell load case
2605 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id
);
2606 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2609 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id
);
2614 if(!SpellMgr::IsSpellValid(spellInfo
,this,false))
2616 // do character spell book cleanup (all characters)
2617 if(!IsInWorld() && !learning
) // spell load case
2619 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id
);
2620 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2623 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id
);
2628 PlayerSpellState state
= learning
? PLAYERSPELL_NEW
: PLAYERSPELL_UNCHANGED
;
2630 bool dependent_set
= false;
2631 bool disabled_case
= false;
2632 bool superceded_old
= false;
2634 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2635 if (itr
!= m_spells
.end())
2637 uint32 next_active_spell_id
= 0;
2638 // fix activate state for non-stackable low rank (and find next spell for !active case)
2639 if(!SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
2641 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
2642 for(SpellChainMapNext::const_iterator next_itr
= nextMap
.lower_bound(spell_id
); next_itr
!= nextMap
.upper_bound(spell_id
); ++next_itr
)
2644 if(HasSpell(next_itr
->second
))
2646 // high rank already known so this must !active
2648 next_active_spell_id
= next_itr
->second
;
2654 // not do anything if already known in expected state
2655 if(itr
->second
->state
!= PLAYERSPELL_REMOVED
&& itr
->second
->active
== active
&&
2656 itr
->second
->dependent
== dependent
&& itr
->second
->disabled
== disabled
)
2658 if(!IsInWorld() && !learning
) // explicitly load from DB and then exist in it already and set correctly
2659 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2664 // dependent spell known as not dependent, overwrite state
2665 if (itr
->second
->state
!= PLAYERSPELL_REMOVED
&& !itr
->second
->dependent
&& dependent
)
2667 itr
->second
->dependent
= dependent
;
2668 if (itr
->second
->state
!= PLAYERSPELL_NEW
)
2669 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2670 dependent_set
= true;
2673 // update active state for known spell
2674 if(itr
->second
->active
!= active
&& itr
->second
->state
!= PLAYERSPELL_REMOVED
&& !itr
->second
->disabled
)
2676 itr
->second
->active
= active
;
2678 if(!IsInWorld() && !learning
&& !dependent_set
) // explicitly load from DB and then exist in it already and set correctly
2679 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2680 else if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2681 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2685 if (IsPassiveSpell(spell_id
) && IsNeedCastPassiveSpellAtLearn(spellInfo
))
2686 CastSpell (this,spell_id
,true);
2688 else if(IsInWorld())
2690 if(next_active_spell_id
)
2692 // update spell ranks in spellbook and action bar
2693 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2694 data
<< uint16(spell_id
);
2695 data
<< uint16(next_active_spell_id
);
2696 GetSession()->SendPacket( &data
);
2700 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
2701 data
<< uint16(spell_id
);
2702 GetSession()->SendPacket(&data
);
2706 return active
; // learn (show in spell book if active now)
2709 if(itr
->second
->disabled
!= disabled
&& itr
->second
->state
!= PLAYERSPELL_REMOVED
)
2711 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2712 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2713 itr
->second
->disabled
= disabled
;
2718 disabled_case
= true;
2720 else switch(itr
->second
->state
)
2722 case PLAYERSPELL_UNCHANGED
: // known saved spell
2724 case PLAYERSPELL_REMOVED
: // re-learning removed not saved spell
2727 m_spells
.erase(itr
);
2728 state
= PLAYERSPELL_CHANGED
;
2729 break; // need re-add
2731 default: // known not saved yet spell (new or modified)
2733 // can be in case spell loading but learned at some previous spell loading
2734 if(!IsInWorld() && !learning
&& !dependent_set
)
2735 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2742 if(!disabled_case
) // skip new spell adding if spell already known (disabled spells case)
2744 // talent: unlearn all other talent ranks (high and low)
2745 if(TalentSpellPos
const* talentPos
= GetTalentSpellPos(spell_id
))
2747 if(TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry( talentPos
->talent_id
))
2749 for(int i
=0; i
<5; ++i
)
2751 // skip learning spell and no rank spell case
2752 uint32 rankSpellId
= talentInfo
->RankID
[i
];
2753 if(!rankSpellId
|| rankSpellId
==spell_id
)
2756 removeSpell(rankSpellId
);
2760 // non talent spell: learn low ranks (recursive call)
2761 else if(uint32 prev_spell
= spellmgr
.GetPrevSpellInChain(spell_id
))
2763 if(!IsInWorld() || disabled
) // at spells loading, no output, but allow save
2764 addSpell(prev_spell
,active
,true,true,disabled
);
2765 else // at normal learning
2766 learnSpell(prev_spell
,true);
2769 PlayerSpell
*newspell
= new PlayerSpell
;
2770 newspell
->state
= state
;
2771 newspell
->active
= active
;
2772 newspell
->dependent
= dependent
;
2773 newspell
->disabled
= disabled
;
2775 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2776 if(newspell
->active
&& !newspell
->disabled
&& !SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
2778 for( PlayerSpellMap::iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2780 if(itr
->second
->state
== PLAYERSPELL_REMOVED
) continue;
2781 SpellEntry
const *i_spellInfo
= sSpellStore
.LookupEntry(itr
->first
);
2782 if(!i_spellInfo
) continue;
2784 if( spellmgr
.IsRankSpellDueToSpell(spellInfo
,itr
->first
) )
2786 if(itr
->second
->active
)
2788 if(spellmgr
.IsHighRankOfSpell(spell_id
,itr
->first
))
2790 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2792 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2793 data
<< uint16(itr
->first
);
2794 data
<< uint16(spell_id
);
2795 GetSession()->SendPacket( &data
);
2798 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2799 itr
->second
->active
= false;
2800 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2801 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2802 superceded_old
= true; // new spell replace old in action bars and spell book.
2804 else if(spellmgr
.IsHighRankOfSpell(itr
->first
,spell_id
))
2806 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2808 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2809 data
<< uint16(spell_id
);
2810 data
<< uint16(itr
->first
);
2811 GetSession()->SendPacket( &data
);
2814 // mark new spell as disable (not learned yet for client and will not learned)
2815 newspell
->active
= false;
2816 if(newspell
->state
!= PLAYERSPELL_NEW
)
2817 newspell
->state
= PLAYERSPELL_CHANGED
;
2824 m_spells
[spell_id
] = newspell
;
2826 // return false if spell disabled
2827 if (newspell
->disabled
)
2831 uint32 talentCost
= GetTalentSpellCost(spell_id
);
2833 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2834 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2835 if( talentCost
> 0 && IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_LEARN_SPELL
) )
2837 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2838 CastSpell(this, spell_id
, true);
2840 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2841 else if (IsPassiveSpell(spell_id
))
2843 if(IsNeedCastPassiveSpellAtLearn(spellInfo
))
2844 CastSpell(this, spell_id
, true);
2846 else if( IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_SKILL_STEP
) )
2848 CastSpell(this, spell_id
, true);
2852 // update used talent points count
2853 m_usedTalentCount
+= talentCost
;
2855 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2856 if(uint32 freeProfs
= GetFreePrimaryProffesionPoints())
2858 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
2859 SetFreePrimaryProffesions(freeProfs
-1);
2862 // add dependent skills
2863 uint16 maxskill
= GetMaxSkillValueForLevel();
2865 SpellLearnSkillNode
const* spellLearnSkill
= spellmgr
.GetSpellLearnSkill(spell_id
);
2869 uint32 skill_value
= GetPureSkillValue(spellLearnSkill
->skill
);
2870 uint32 skill_max_value
= GetPureMaxSkillValue(spellLearnSkill
->skill
);
2872 if(skill_value
< spellLearnSkill
->value
)
2873 skill_value
= spellLearnSkill
->value
;
2875 uint32 new_skill_max_value
= spellLearnSkill
->maxvalue
== 0 ? maxskill
: spellLearnSkill
->maxvalue
;
2877 if(skill_max_value
< new_skill_max_value
)
2878 skill_max_value
= new_skill_max_value
;
2880 SetSkill(spellLearnSkill
->skill
,skill_value
,skill_max_value
);
2884 // not ranked skills
2885 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
2886 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
2888 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
2890 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
2894 if(HasSkill(pSkill
->id
))
2897 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
2898 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2899 (pSkill
->id
==SKILL_LOCKPICKING
|| pSkill
->id
==SKILL_RUNEFORGING
) && _spell_idx
->second
->max_value
==0 )
2901 switch(GetSkillRangeType(pSkill
,_spell_idx
->second
->racemask
!=0))
2903 case SKILL_RANGE_LANGUAGE
:
2904 SetSkill(pSkill
->id
, 300, 300 );
2906 case SKILL_RANGE_LEVEL
:
2907 SetSkill(pSkill
->id
, 1, GetMaxSkillValueForLevel() );
2909 case SKILL_RANGE_MONO
:
2910 SetSkill(pSkill
->id
, 1, 1 );
2919 // learn dependent spells
2920 SpellLearnSpellMap::const_iterator spell_begin
= spellmgr
.GetBeginSpellLearnSpell(spell_id
);
2921 SpellLearnSpellMap::const_iterator spell_end
= spellmgr
.GetEndSpellLearnSpell(spell_id
);
2923 for(SpellLearnSpellMap::const_iterator itr
= spell_begin
; itr
!= spell_end
; ++itr
)
2925 if(!itr
->second
.autoLearned
)
2927 if(!IsInWorld() || !itr
->second
.active
) // at spells loading, no output, but allow save
2928 addSpell(itr
->second
.spell
,itr
->second
.active
,true,true,false);
2929 else // at normal learning
2930 learnSpell(itr
->second
.spell
,true);
2936 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL
);
2937 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS
);
2940 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2941 return active
&& !disabled
&& !superceded_old
;
2944 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry
const* spellInfo
) const
2946 bool need_cast
= false;
2948 switch(spellInfo
->Id
)
2950 // some spells not have stance data expacted cast at form change or present
2951 case 5420: need_cast
= (m_form
== FORM_TREE
); break;
2952 case 5419: need_cast
= (m_form
== FORM_TRAVEL
); break;
2953 case 7376: need_cast
= (m_form
== FORM_DEFENSIVESTANCE
); break;
2954 case 7381: need_cast
= (m_form
== FORM_BERSERKERSTANCE
); break;
2955 case 21156: need_cast
= (m_form
== FORM_BATTLESTANCE
); break;
2956 case 21178: need_cast
= (m_form
== FORM_BEAR
|| m_form
== FORM_DIREBEAR
); break;
2957 case 33948: need_cast
= (m_form
== FORM_FLIGHT
); break;
2958 case 34764: need_cast
= (m_form
== FORM_FLIGHT
); break;
2959 case 40121: need_cast
= (m_form
== FORM_FLIGHT_EPIC
); break;
2960 case 40122: need_cast
= (m_form
== FORM_FLIGHT_EPIC
); break;
2961 // another spells have proper stance data
2962 default: need_cast
= !spellInfo
->Stances
|| m_form
!= 0 && (spellInfo
->Stances
& (1<<(m_form
-1))); break;
2965 //Check CasterAuraStates
2966 return need_cast
&& (!spellInfo
->CasterAuraState
|| HasAuraState(AuraState(spellInfo
->CasterAuraState
)));
2969 void Player::learnSpell(uint32 spell_id
, bool dependent
)
2971 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2973 bool disabled
= (itr
!= m_spells
.end()) ? itr
->second
->disabled
: false;
2974 bool active
= disabled
? itr
->second
->active
: true;
2976 bool learning
= addSpell(spell_id
,active
,true,dependent
,false);
2978 // learn all disabled higher ranks (recursive)
2981 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
2982 for(SpellChainMapNext::const_iterator i
= nextMap
.lower_bound(spell_id
); i
!= nextMap
.upper_bound(spell_id
); ++i
)
2984 PlayerSpellMap::iterator iter
= m_spells
.find(i
->second
);
2985 if (iter
!= m_spells
.end() && iter
->second
->disabled
)
2986 learnSpell(i
->second
,false);
2990 // prevent duplicated entires in spell book, also not send if not in world (loading)
2991 if(!learning
|| !IsInWorld ())
2994 WorldPacket
data(SMSG_LEARNED_SPELL
, 4);
2995 data
<< uint32(spell_id
);
2996 GetSession()->SendPacket(&data
);
2999 void Player::removeSpell(uint32 spell_id
, bool disabled
, bool update_action_bar_for_low_rank
)
3001 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
3002 if (itr
== m_spells
.end())
3005 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| disabled
&& itr
->second
->disabled
)
3008 // unlearn non talent higher ranks (recursive)
3009 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
3010 for(SpellChainMapNext::const_iterator itr2
= nextMap
.lower_bound(spell_id
); itr2
!= nextMap
.upper_bound(spell_id
); ++itr2
)
3011 if(HasSpell(itr2
->second
) && !GetTalentSpellPos(itr2
->second
))
3012 removeSpell(itr2
->second
,disabled
);
3014 bool cur_active
= itr
->second
->active
;
3015 bool cur_dependent
= itr
->second
->dependent
;
3019 itr
->second
->disabled
= disabled
;
3020 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
3021 itr
->second
->state
= PLAYERSPELL_CHANGED
;
3025 if(itr
->second
->state
== PLAYERSPELL_NEW
)
3028 m_spells
.erase(itr
);
3031 itr
->second
->state
= PLAYERSPELL_REMOVED
;
3034 RemoveAurasDueToSpell(spell_id
);
3037 if(PetAura
const* petSpell
= spellmgr
.GetPetAura(spell_id
))
3038 RemovePetAura(petSpell
);
3040 // free talent points
3041 uint32 talentCosts
= GetTalentSpellCost(spell_id
);
3044 if(talentCosts
< m_usedTalentCount
)
3045 m_usedTalentCount
-= talentCosts
;
3047 m_usedTalentCount
= 0;
3050 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3051 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
3053 uint32 freeProfs
= GetFreePrimaryProffesionPoints()+1;
3054 if(freeProfs
<= sWorld
.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL
))
3055 SetFreePrimaryProffesions(freeProfs
);
3058 // remove dependent skill
3059 SpellLearnSkillNode
const* spellLearnSkill
= spellmgr
.GetSpellLearnSkill(spell_id
);
3062 uint32 prev_spell
= spellmgr
.GetPrevSpellInChain(spell_id
);
3063 if(!prev_spell
) // first rank, remove skill
3064 SetSkill(spellLearnSkill
->skill
,0,0);
3067 // search prev. skill setting by spell ranks chain
3068 SpellLearnSkillNode
const* prevSkill
= spellmgr
.GetSpellLearnSkill(prev_spell
);
3069 while(!prevSkill
&& prev_spell
)
3071 prev_spell
= spellmgr
.GetPrevSpellInChain(prev_spell
);
3072 prevSkill
= spellmgr
.GetSpellLearnSkill(spellmgr
.GetFirstSpellInChain(prev_spell
));
3075 if(!prevSkill
) // not found prev skill setting, remove skill
3076 SetSkill(spellLearnSkill
->skill
,0,0);
3077 else // set to prev. skill setting values
3079 uint32 skill_value
= GetPureSkillValue(prevSkill
->skill
);
3080 uint32 skill_max_value
= GetPureMaxSkillValue(prevSkill
->skill
);
3082 if(skill_value
> prevSkill
->value
)
3083 skill_value
= prevSkill
->value
;
3085 uint32 new_skill_max_value
= prevSkill
->maxvalue
== 0 ? GetMaxSkillValueForLevel() : prevSkill
->maxvalue
;
3087 if(skill_max_value
> new_skill_max_value
)
3088 skill_max_value
= new_skill_max_value
;
3090 SetSkill(prevSkill
->skill
,skill_value
,skill_max_value
);
3097 // not ranked skills
3098 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
3099 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
3101 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
3103 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
3107 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
3108 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3109 (pSkill
->id
==SKILL_LOCKPICKING
|| pSkill
->id
==SKILL_RUNEFORGING
) && _spell_idx
->second
->max_value
==0 )
3111 // not reset skills for professions and racial abilities
3112 if( (pSkill
->categoryId
==SKILL_CATEGORY_SECONDARY
|| pSkill
->categoryId
==SKILL_CATEGORY_PROFESSION
) &&
3113 (IsProfessionSkill(pSkill
->id
) || _spell_idx
->second
->racemask
!=0) )
3116 SetSkill(pSkill
->id
, 0, 0 );
3121 // remove dependent spells
3122 SpellLearnSpellMap::const_iterator spell_begin
= spellmgr
.GetBeginSpellLearnSpell(spell_id
);
3123 SpellLearnSpellMap::const_iterator spell_end
= spellmgr
.GetEndSpellLearnSpell(spell_id
);
3125 for(SpellLearnSpellMap::const_iterator itr2
= spell_begin
; itr2
!= spell_end
; ++itr2
)
3126 removeSpell(itr2
->second
.spell
, disabled
);
3128 // activate lesser rank in spellbook/action bar, and cast it if need
3129 bool prev_activate
= false;
3131 if(uint32 prev_id
= spellmgr
.GetPrevSpellInChain (spell_id
))
3133 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
3135 // if talent then lesser rank also talent and need learn
3137 learnSpell (prev_id
,false);
3138 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3139 else if(cur_active
&& !SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
3141 // need manually update dependence state (learn spell ignore like attempts)
3142 PlayerSpellMap::iterator prev_itr
= m_spells
.find(prev_id
);
3143 if (prev_itr
!= m_spells
.end())
3145 if(prev_itr
->second
->dependent
!= cur_dependent
)
3147 prev_itr
->second
->dependent
= cur_dependent
;
3148 if(prev_itr
->second
->state
!= PLAYERSPELL_NEW
)
3149 prev_itr
->second
->state
= PLAYERSPELL_CHANGED
;
3152 // now re-learn if need re-activate
3153 if(cur_active
&& !prev_itr
->second
->active
)
3155 if(addSpell(prev_id
,true,false,prev_itr
->second
->dependent
,prev_itr
->second
->disabled
))
3157 if(update_action_bar_for_low_rank
)
3159 // downgrade spell ranks in spellbook and action bar
3160 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
3161 data
<< uint16(spell_id
);
3162 data
<< uint16(prev_id
);
3163 GetSession()->SendPacket( &data
);
3164 prev_activate
= true;
3172 // remove from spell book if not replaced by lesser rank
3175 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
3176 data
<< uint16(spell_id
);
3177 GetSession()->SendPacket(&data
);
3181 void Player::RemoveArenaSpellCooldowns()
3183 // remove cooldowns on spells that has < 15 min CD
3184 SpellCooldowns::iterator itr
, next
;
3185 // iterate spell cooldowns
3186 for(itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); itr
= next
)
3190 SpellEntry
const * entry
= sSpellStore
.LookupEntry(itr
->first
);
3191 // check if spellentry is present and if the cooldown is less than 15 mins
3193 entry
->RecoveryTime
<= 15 * MINUTE
* IN_MILISECONDS
&&
3194 entry
->CategoryRecoveryTime
<= 15 * MINUTE
* IN_MILISECONDS
)
3197 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, (4+8));
3198 data
<< uint32(itr
->first
);
3200 GetSession()->SendPacket(&data
);
3202 m_spellCooldowns
.erase(itr
);
3207 void Player::RemoveAllSpellCooldown()
3209 if(!m_spellCooldowns
.empty())
3211 for(SpellCooldowns::const_iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); ++itr
)
3213 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, (4+8));
3214 data
<< uint32(itr
->first
);
3215 data
<< uint64(GetGUID());
3216 GetSession()->SendPacket(&data
);
3218 m_spellCooldowns
.clear();
3222 void Player::_LoadSpellCooldowns(QueryResult
*result
)
3224 // some cooldowns can be already set at aura loading...
3226 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3230 time_t curTime
= time(NULL
);
3234 Field
*fields
= result
->Fetch();
3236 uint32 spell_id
= fields
[0].GetUInt32();
3237 uint32 item_id
= fields
[1].GetUInt32();
3238 time_t db_time
= (time_t)fields
[2].GetUInt64();
3240 if(!sSpellStore
.LookupEntry(spell_id
))
3242 sLog
.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id
);
3246 // skip outdated cooldown
3247 if(db_time
<= curTime
)
3250 AddSpellCooldown(spell_id
, item_id
, db_time
);
3252 sLog
.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id
, item_id
, uint32(db_time
-curTime
));
3254 while( result
->NextRow() );
3260 void Player::_SaveSpellCooldowns()
3262 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3264 time_t curTime
= time(NULL
);
3265 time_t infTime
= curTime
+ MONTH
/2;
3267 // remove outdated and save active
3268 for(SpellCooldowns::iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end();)
3270 if(itr
->second
.end
<= curTime
)
3271 m_spellCooldowns
.erase(itr
++);
3272 else if(itr
->second
.end
<= infTime
) // not save locked cooldowns, it will be reset or set at reload
3274 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
));
3282 uint32
Player::resetTalentsCost() const
3284 // The first time reset costs 1 gold
3285 if(m_resetTalentsCost
< 1*GOLD
)
3288 else if(m_resetTalentsCost
< 5*GOLD
)
3290 // After that it increases in increments of 5 gold
3291 else if(m_resetTalentsCost
< 10*GOLD
)
3295 uint32 months
= (sWorld
.GetGameTime() - m_resetTalentsTime
)/MONTH
;
3298 // This cost will be reduced by a rate of 5 gold per month
3299 int32 new_cost
= int32(m_resetTalentsCost
) - 5*GOLD
*months
;
3300 // to a minimum of 10 gold.
3301 return (new_cost
< 10*GOLD
? 10*GOLD
: new_cost
);
3305 // After that it increases in increments of 5 gold
3306 int32 new_cost
= m_resetTalentsCost
+ 5*GOLD
;
3307 // until it hits a cap of 50 gold.
3308 if(new_cost
> 50*GOLD
)
3315 bool Player::resetTalents(bool no_cost
)
3317 // not need after this call
3318 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS
))
3320 m_atLoginFlags
= m_atLoginFlags
& ~AT_LOGIN_RESET_TALENTS
;
3321 CharacterDatabase
.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS
), GetGUIDLow());
3324 uint32 talentPointsForLevel
= CalculateTalentsPoints();
3326 if (m_usedTalentCount
== 0)
3328 SetFreeTalentPoints(talentPointsForLevel
);
3336 cost
= resetTalentsCost();
3338 if (GetMoney() < cost
)
3340 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, 0, 0, 0);
3345 for (unsigned int i
= 0; i
< sTalentStore
.GetNumRows(); i
++)
3347 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry(i
);
3349 if (!talentInfo
) continue;
3351 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentInfo
->TalentTab
);
3356 // unlearn only talents for character class
3357 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3358 // to prevent unexpected lost normal learned spell skip another class talents
3359 if( (getClassMask() & talentTabInfo
->ClassMask
) == 0 )
3362 for (int j
= 0; j
< 5; j
++)
3364 for(PlayerSpellMap::iterator itr
= GetSpellMap().begin(); itr
!= GetSpellMap().end();)
3366 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->second
->disabled
)
3372 // remove learned spells (all ranks)
3373 uint32 itrFirstId
= spellmgr
.GetFirstSpellInChain(itr
->first
);
3375 // unlearn if first rank is talent or learned by talent
3376 if (itrFirstId
== talentInfo
->RankID
[j
] || spellmgr
.IsSpellLearnToSpell(talentInfo
->RankID
[j
],itrFirstId
))
3378 removeSpell(itr
->first
,!IsPassiveSpell(itr
->first
));
3379 itr
= GetSpellMap().begin();
3388 SetFreeTalentPoints(talentPointsForLevel
);
3392 ModifyMoney(-(int32
)cost
);
3393 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS
, cost
);
3395 m_resetTalentsCost
= cost
;
3396 m_resetTalentsTime
= time(NULL
);
3399 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3400 RemovePet(NULL
,PET_SAVE_NOT_IN_SLOT
, true);
3404 m_canTitanGrip
= false;
3405 if(sWorld
.getConfig(CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET
))
3406 AutoUnequipOffhandIfNeed();
3412 Mail
* Player::GetMail(uint32 id
)
3414 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
3416 if ((*itr
)->messageID
== id
)
3424 void Player::_SetCreateBits(UpdateMask
*updateMask
, Player
*target
) const
3428 Object::_SetCreateBits(updateMask
, target
);
3432 for(uint16 index
= 0; index
< m_valuesCount
; index
++)
3434 if(GetUInt32Value(index
) != 0 && updateVisualBits
.GetBit(index
))
3435 updateMask
->SetBit(index
);
3440 void Player::_SetUpdateBits(UpdateMask
*updateMask
, Player
*target
) const
3444 Object::_SetUpdateBits(updateMask
, target
);
3448 Object::_SetUpdateBits(updateMask
, target
);
3449 *updateMask
&= updateVisualBits
;
3453 void Player::InitVisibleBits()
3455 updateVisualBits
.SetCount(PLAYER_END
);
3457 updateVisualBits
.SetBit(OBJECT_FIELD_GUID
);
3458 updateVisualBits
.SetBit(OBJECT_FIELD_TYPE
);
3459 updateVisualBits
.SetBit(OBJECT_FIELD_ENTRY
);
3460 updateVisualBits
.SetBit(OBJECT_FIELD_SCALE_X
);
3461 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 0);
3462 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 1);
3463 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 0);
3464 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 1);
3465 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 0);
3466 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 1);
3467 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 0);
3468 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 1);
3469 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 0);
3470 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 1);
3471 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_0
);
3472 updateVisualBits
.SetBit(UNIT_FIELD_HEALTH
);
3473 updateVisualBits
.SetBit(UNIT_FIELD_POWER1
);
3474 updateVisualBits
.SetBit(UNIT_FIELD_POWER2
);
3475 updateVisualBits
.SetBit(UNIT_FIELD_POWER3
);
3476 updateVisualBits
.SetBit(UNIT_FIELD_POWER4
);
3477 updateVisualBits
.SetBit(UNIT_FIELD_POWER5
);
3478 updateVisualBits
.SetBit(UNIT_FIELD_POWER6
);
3479 updateVisualBits
.SetBit(UNIT_FIELD_POWER7
);
3480 updateVisualBits
.SetBit(UNIT_FIELD_MAXHEALTH
);
3481 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER1
);
3482 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER2
);
3483 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER3
);
3484 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER4
);
3485 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER5
);
3486 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER6
);
3487 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER7
);
3488 updateVisualBits
.SetBit(UNIT_FIELD_LEVEL
);
3489 updateVisualBits
.SetBit(UNIT_FIELD_FACTIONTEMPLATE
);
3490 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 0);
3491 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 1);
3492 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 2);
3493 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS
);
3494 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS_2
);
3495 updateVisualBits
.SetBit(UNIT_FIELD_AURASTATE
);
3496 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 0);
3497 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 1);
3498 updateVisualBits
.SetBit(UNIT_FIELD_BOUNDINGRADIUS
);
3499 updateVisualBits
.SetBit(UNIT_FIELD_COMBATREACH
);
3500 updateVisualBits
.SetBit(UNIT_FIELD_DISPLAYID
);
3501 updateVisualBits
.SetBit(UNIT_FIELD_NATIVEDISPLAYID
);
3502 updateVisualBits
.SetBit(UNIT_FIELD_MOUNTDISPLAYID
);
3503 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_1
);
3504 updateVisualBits
.SetBit(UNIT_FIELD_PETNUMBER
);
3505 updateVisualBits
.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP
);
3506 updateVisualBits
.SetBit(UNIT_DYNAMIC_FLAGS
);
3507 updateVisualBits
.SetBit(UNIT_CHANNEL_SPELL
);
3508 updateVisualBits
.SetBit(UNIT_MOD_CAST_SPEED
);
3509 updateVisualBits
.SetBit(UNIT_FIELD_BASE_MANA
);
3510 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_2
);
3511 updateVisualBits
.SetBit(UNIT_FIELD_HOVERHEIGHT
);
3513 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 0);
3514 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 1);
3515 updateVisualBits
.SetBit(PLAYER_FLAGS
);
3516 updateVisualBits
.SetBit(PLAYER_GUILDID
);
3517 updateVisualBits
.SetBit(PLAYER_GUILDRANK
);
3518 updateVisualBits
.SetBit(PLAYER_BYTES
);
3519 updateVisualBits
.SetBit(PLAYER_BYTES_2
);
3520 updateVisualBits
.SetBit(PLAYER_BYTES_3
);
3521 updateVisualBits
.SetBit(PLAYER_DUEL_TEAM
);
3522 updateVisualBits
.SetBit(PLAYER_GUILD_TIMESTAMP
);
3524 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3525 for(uint16 i
= PLAYER_QUEST_LOG_1_1
; i
< PLAYER_QUEST_LOG_25_2
; i
+= 4)
3526 updateVisualBits
.SetBit(i
);
3528 // Players visible items are not inventory stuff
3529 for(uint16 i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
3531 uint32 offset
= i
* MAX_VISIBLE_ITEM_OFFSET
;
3534 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR
+ 0 + offset
);
3535 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR
+ 1 + offset
);
3538 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_0
+ 0 + offset
);
3540 // item enchantments
3541 for(uint8 j
= 0; j
< MAX_ENCHANTMENT_SLOT
; ++j
)
3542 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_0
+ 1 + j
+ offset
);
3544 // random properties
3545 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ offset
);
3546 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_SEED
+ offset
);
3547 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_PAD
+ offset
);
3550 updateVisualBits
.SetBit(PLAYER_CHOSEN_TITLE
);
3553 void Player::BuildCreateUpdateBlockForPlayer( UpdateData
*data
, Player
*target
) const
3555 for(int i
= 0; i
< EQUIPMENT_SLOT_END
; i
++)
3557 if(m_items
[i
] == NULL
)
3560 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3565 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
3567 if(m_items
[i
] == NULL
)
3570 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3572 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
3574 if(m_items
[i
] == NULL
)
3577 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3581 Unit::BuildCreateUpdateBlockForPlayer( data
, target
);
3584 void Player::DestroyForPlayer( Player
*target
) const
3586 Unit::DestroyForPlayer( target
);
3588 for(int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
3590 if(m_items
[i
] == NULL
)
3593 m_items
[i
]->DestroyForPlayer( target
);
3598 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
3600 if(m_items
[i
] == NULL
)
3603 m_items
[i
]->DestroyForPlayer( target
);
3605 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
3607 if(m_items
[i
] == NULL
)
3610 m_items
[i
]->DestroyForPlayer( target
);
3615 bool Player::HasSpell(uint32 spell
) const
3617 PlayerSpellMap::const_iterator itr
= m_spells
.find(spell
);
3618 return (itr
!= m_spells
.end() && itr
->second
->state
!= PLAYERSPELL_REMOVED
&&
3619 !itr
->second
->disabled
);
3622 bool Player::HasActiveSpell(uint32 spell
) const
3624 PlayerSpellMap::const_iterator itr
= m_spells
.find(spell
);
3625 return (itr
!= m_spells
.end() && itr
->second
->state
!= PLAYERSPELL_REMOVED
&&
3626 itr
->second
->active
&& !itr
->second
->disabled
);
3629 TrainerSpellState
Player::GetTrainerSpellState(TrainerSpell
const* trainer_spell
) const
3632 return TRAINER_SPELL_RED
;
3634 if (!trainer_spell
->learnedSpell
)
3635 return TRAINER_SPELL_RED
;
3638 if(HasSpell(trainer_spell
->learnedSpell
))
3639 return TRAINER_SPELL_GRAY
;
3641 // check race/class requirement
3642 if(!IsSpellFitByClassAndRace(trainer_spell
->learnedSpell
))
3643 return TRAINER_SPELL_RED
;
3645 // check level requirement
3646 if(getLevel() < trainer_spell
->reqLevel
)
3647 return TRAINER_SPELL_RED
;
3649 if(SpellChainNode
const* spell_chain
= spellmgr
.GetSpellChainNode(trainer_spell
->learnedSpell
))
3651 // check prev.rank requirement
3652 if(spell_chain
->prev
&& !HasSpell(spell_chain
->prev
))
3653 return TRAINER_SPELL_RED
;
3655 // check additional spell requirement
3656 if(spell_chain
->req
&& !HasSpell(spell_chain
->req
))
3657 return TRAINER_SPELL_RED
;
3660 // check skill requirement
3661 if(trainer_spell
->reqSkill
&& GetBaseSkillValue(trainer_spell
->reqSkill
) < trainer_spell
->reqSkillValue
)
3662 return TRAINER_SPELL_RED
;
3664 // exist, already checked at loading
3665 SpellEntry
const* spell
= sSpellStore
.LookupEntry(trainer_spell
->learnedSpell
);
3667 // secondary prof. or not prof. spell
3668 uint32 skill
= spell
->EffectMiscValue
[1];
3670 if(spell
->Effect
[1] != SPELL_EFFECT_SKILL
|| !IsPrimaryProfessionSkill(skill
))
3671 return TRAINER_SPELL_GREEN
;
3673 // check primary prof. limit
3674 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell
->Id
) && GetFreePrimaryProffesionPoints() == 0)
3675 return TRAINER_SPELL_RED
;
3677 return TRAINER_SPELL_GREEN
;
3680 void Player::DeleteFromDB(uint64 playerguid
, uint32 accountId
, bool updateRealmChars
)
3682 uint32 guid
= GUID_LOPART(playerguid
);
3684 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3685 // bones will be deleted by corpse/bones deleting thread shortly
3686 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid
);
3688 // remove from guild
3689 uint32 guildId
= GetGuildIdFromDB(playerguid
);
3692 Guild
* guild
= objmgr
.GetGuildById(guildId
);
3694 guild
->DelMember(guid
);
3697 // remove from arena teams
3698 LeaveAllArenaTeams(playerguid
);
3700 // the player was uninvited already on logout so just remove from group
3701 QueryResult
*resultGroup
= CharacterDatabase
.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid
);
3704 uint64 leaderGuid
= MAKE_NEW_GUID((*resultGroup
)[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
3706 Group
* group
= objmgr
.GetGroupByLeader(leaderGuid
);
3709 RemoveFromGroup(group
, playerguid
);
3713 // remove signs from petitions (also remove petitions if owner);
3714 RemovePetitionsAndSigns(playerguid
, 10);
3716 // return back all mails with COD and Item 0 1 2 3 4 5 6
3717 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
);
3722 Field
*fields
= resultMail
->Fetch();
3724 uint32 mail_id
= fields
[0].GetUInt32();
3725 uint16 mailTemplateId
= fields
[1].GetUInt16();
3726 uint32 sender
= fields
[2].GetUInt32();
3727 std::string subject
= fields
[3].GetCppString();
3728 uint32 itemTextId
= fields
[4].GetUInt32();
3729 uint32 money
= fields
[5].GetUInt32();
3730 bool has_items
= fields
[6].GetBool();
3732 //we can return mail now
3733 //so firstly delete the old one
3734 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id
);
3739 // data needs to be at first place for Item::LoadFromDB
3740 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
);
3745 Field
*fields2
= resultItems
->Fetch();
3747 uint32 item_guidlow
= fields2
[1].GetUInt32();
3748 uint32 item_template
= fields2
[2].GetUInt32();
3750 ItemPrototype
const* itemProto
= objmgr
.GetItemPrototype(item_template
);
3753 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow
);
3757 Item
*pItem
= NewItemOrBag(itemProto
);
3758 if(!pItem
->LoadFromDB(item_guidlow
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
),resultItems
))
3760 pItem
->FSetState(ITEM_REMOVED
);
3761 pItem
->SaveToDB(); // it also deletes item object !
3765 mi
.AddItem(item_guidlow
, item_template
, pItem
);
3767 while (resultItems
->NextRow());
3773 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id
);
3775 uint32 pl_account
= objmgr
.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
3777 WorldSession::SendReturnToSender(MAIL_NORMAL
, pl_account
, guid
, sender
, subject
, itemTextId
, &mi
, money
, mailTemplateId
);
3779 while (resultMail
->NextRow());
3784 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3785 // Get guids of character's pets, will deleted in transaction
3786 QueryResult
*resultPets
= CharacterDatabase
.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid
);
3788 // NOW we can finally clear other DB data related to character
3789 CharacterDatabase
.BeginTransaction();
3794 Field
*fields3
= resultPets
->Fetch();
3795 uint32 petguidlow
= fields3
[0].GetUInt32();
3796 Pet::DeleteFromDB(petguidlow
);
3797 } while (resultPets
->NextRow());
3801 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",guid
);
3802 CharacterDatabase
.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid
);
3803 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid
);
3804 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid
);
3805 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid
);
3806 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid
);
3807 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid
);
3808 CharacterDatabase
.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid
);
3809 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid
);
3810 CharacterDatabase
.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid
);
3811 CharacterDatabase
.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid
);
3812 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid
);
3813 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid
);
3814 CharacterDatabase
.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid
);
3815 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid
);
3816 CharacterDatabase
.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid
,guid
);
3817 CharacterDatabase
.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid
);
3818 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid
);
3819 CharacterDatabase
.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid
);
3820 CharacterDatabase
.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid
);
3821 CharacterDatabase
.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid
);
3822 CharacterDatabase
.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid
);
3823 CharacterDatabase
.CommitTransaction();
3825 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3826 if(updateRealmChars
) sWorld
.UpdateRealmCharCount(accountId
);
3829 void Player::SetMovement(PlayerMovementType pType
)
3834 case MOVE_ROOT
: data
.Initialize(SMSG_FORCE_MOVE_ROOT
, GetPackGUID().size()+4); break;
3835 case MOVE_UNROOT
: data
.Initialize(SMSG_FORCE_MOVE_UNROOT
, GetPackGUID().size()+4); break;
3836 case MOVE_WATER_WALK
: data
.Initialize(SMSG_MOVE_WATER_WALK
, GetPackGUID().size()+4); break;
3837 case MOVE_LAND_WALK
: data
.Initialize(SMSG_MOVE_LAND_WALK
, GetPackGUID().size()+4); break;
3839 sLog
.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType
);
3842 data
.append(GetPackGUID());
3844 GetSession()->SendPacket( &data
);
3848 - a resurrectable corpse must not be loaded for the player (only bones)
3849 - the player must be in world
3851 void Player::BuildPlayerRepop()
3853 WorldPacket
data(SMSG_PRE_RESURRECT
, GetPackGUID().size());
3854 data
.append(GetPackGUID());
3855 GetSession()->SendPacket(&data
);
3857 if(getRace() == RACE_NIGHTELF
)
3858 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)
3859 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3861 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3862 // there must be SMSG.STOP_MIRROR_TIMER
3863 // there we must send 888 opcode
3865 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3868 sLog
.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3872 // create a corpse and place it at the player's location
3874 Corpse
*corpse
= GetCorpse();
3877 sLog
.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3880 GetMap()->Add(corpse
);
3882 // convert player body to ghost
3885 SetMovement(MOVE_WATER_WALK
);
3886 if(!GetSession()->isLogingOut())
3887 SetMovement(MOVE_UNROOT
);
3889 // BG - remove insignia related
3890 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_SKINNABLE
);
3892 SendCorpseReclaimDelay();
3894 // to prevent cheating
3895 corpse
->ResetGhostTime();
3897 StopMirrorTimers(); //disable timers(bars)
3899 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, (float)1.0); //see radius of death player?
3901 // set and clear other
3902 SetByteValue(UNIT_FIELD_BYTES_1
, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND
);
3905 void Player::SendDelayResponse(const uint32 ml_seconds
)
3907 //FIXME: is this delay time arg really need? 50msec by default in code
3908 WorldPacket
data( SMSG_QUERY_TIME_RESPONSE
, 4+4 );
3909 data
<< (uint32
)time(NULL
);
3911 GetSession()->SendPacket( &data
);
3914 void Player::ResurrectPlayer(float restore_percent
, bool applySickness
)
3916 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // remove spirit healer position
3921 GetSession()->SendPacket(&data
);
3923 // speed change, land walk
3925 // remove death flag + set aura
3926 SetByteValue(UNIT_FIELD_BYTES_1
, 3, 0x00);
3927 if(getRace() == RACE_NIGHTELF
)
3928 RemoveAurasDueToSpell(20584); // speed bonuses
3929 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3931 setDeathState(ALIVE
);
3933 SetMovement(MOVE_LAND_WALK
);
3934 SetMovement(MOVE_UNROOT
);
3938 // set health/powers (0- will be set in caller)
3939 if(restore_percent
>0.0f
)
3941 SetHealth(uint32(GetMaxHealth()*restore_percent
));
3942 SetPower(POWER_MANA
, uint32(GetMaxPower(POWER_MANA
)*restore_percent
));
3943 SetPower(POWER_RAGE
, 0);
3944 SetPower(POWER_ENERGY
, uint32(GetMaxPower(POWER_ENERGY
)*restore_percent
));
3947 // trigger update zone for alive state zone updates
3948 uint32 newzone
, newarea
;
3949 GetZoneAndAreaId(newzone
,newarea
);
3950 UpdateZone(newzone
,newarea
);
3952 // update visibility
3953 ObjectAccessor::UpdateVisibilityForPlayer(this);
3958 //Characters from level 1-10 are not affected by resurrection sickness.
3959 //Characters from level 11-19 will suffer from one minute of sickness
3960 //for each level they are above 10.
3961 //Characters level 20 and up suffer from ten minutes of sickness.
3962 int32 startLevel
= sWorld
.getConfig(CONFIG_DEATH_SICKNESS_LEVEL
);
3964 if(int32(getLevel()) >= startLevel
)
3966 // set resurrection sickness
3967 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,true);
3969 // not full duration
3970 if(int32(getLevel()) < startLevel
+9)
3972 int32 delta
= (int32(getLevel()) - startLevel
+ 1)*MINUTE
;
3974 for(int i
=0; i
< 3; ++i
)
3976 if(Aura
* Aur
= GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,i
))
3978 Aur
->SetAuraDuration(delta
*IN_MILISECONDS
);
3979 Aur
->SendAuraUpdate(false);
3986 void Player::KillPlayer()
3988 SetMovement(MOVE_ROOT
);
3990 StopMirrorTimers(); //disable timers(bars)
3992 setDeathState(CORPSE
);
3993 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
3995 SetFlag(UNIT_DYNAMIC_FLAGS
, 0x00);
3996 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, !sMapStore
.LookupEntry(GetMapId())->Instanceable());
3998 // 6 minutes until repop at graveyard
3999 m_deathTimer
= 6*MINUTE
*IN_MILISECONDS
;
4001 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4003 // don't create corpse at this moment, player might be falling
4005 // update visibility
4006 ObjectAccessor::UpdateObjectVisibility(this);
4009 void Player::CreateCorpse()
4011 // prevent existence 2 corpse for player
4014 uint32 _uf
, _pb
, _pb2
, _cfb1
, _cfb2
;
4016 Corpse
*corpse
= new Corpse( (m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
) ? CORPSE_RESURRECTABLE_PVP
: CORPSE_RESURRECTABLE_PVE
);
4019 if(!corpse
->Create(objmgr
.GenerateLowGuid(HIGHGUID_CORPSE
), this))
4025 _uf
= GetUInt32Value(UNIT_FIELD_BYTES_0
);
4026 _pb
= GetUInt32Value(PLAYER_BYTES
);
4027 _pb2
= GetUInt32Value(PLAYER_BYTES_2
);
4029 uint8 race
= (uint8
)(_uf
);
4030 uint8 skin
= (uint8
)(_pb
);
4031 uint8 face
= (uint8
)(_pb
>> 8);
4032 uint8 hairstyle
= (uint8
)(_pb
>> 16);
4033 uint8 haircolor
= (uint8
)(_pb
>> 24);
4034 uint8 facialhair
= (uint8
)(_pb2
);
4036 _cfb1
= ((0x00) | (race
<< 8) | (getGender() << 16) | (skin
<< 24));
4037 _cfb2
= ((face
) | (hairstyle
<< 8) | (haircolor
<< 16) | (facialhair
<< 24));
4039 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_1
, _cfb1
);
4040 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_2
, _cfb2
);
4042 uint32 flags
= CORPSE_FLAG_UNK2
;
4043 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
4044 flags
|= CORPSE_FLAG_HIDE_HELM
;
4045 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
4046 flags
|= CORPSE_FLAG_HIDE_CLOAK
;
4047 if(InBattleGround() && !InArena())
4048 flags
|= CORPSE_FLAG_LOOTABLE
; // to be able to remove insignia
4049 corpse
->SetUInt32Value( CORPSE_FIELD_FLAGS
, flags
);
4051 corpse
->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID
, GetNativeDisplayId() );
4053 corpse
->SetUInt32Value( CORPSE_FIELD_GUILD
, GetGuildId() );
4056 uint16 iIventoryType
;
4058 for (int i
= 0; i
< EQUIPMENT_SLOT_END
; i
++)
4062 iDisplayID
= m_items
[i
]->GetProto()->DisplayInfoID
;
4063 iIventoryType
= (uint16
)m_items
[i
]->GetProto()->InventoryType
;
4065 _cfi
= (uint16(iDisplayID
)) | (iIventoryType
)<< 24;
4066 corpse
->SetUInt32Value(CORPSE_FIELD_ITEM
+ i
,_cfi
);
4070 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4071 const MapEntry
*entry
= sMapStore
.LookupEntry(corpse
->GetMapId());
4073 if(entry
->map_type
!= MAP_BATTLEGROUND
)
4076 // register for player, but not show
4077 ObjectAccessor::Instance().AddCorpse(corpse
);
4080 void Player::SpawnCorpseBones()
4082 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4083 SaveToDB(); // prevent loading as ghost without corpse
4086 Corpse
* Player::GetCorpse() const
4088 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4091 void Player::DurabilityLossAll(double percent
, bool inventory
)
4093 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
4094 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4095 DurabilityLoss(pItem
,percent
);
4099 // bags not have durability
4100 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4102 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
4103 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4104 DurabilityLoss(pItem
,percent
);
4106 // keys not have durability
4107 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
4109 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
4110 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4111 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
4112 if(Item
* pItem
= GetItemByPos( i
, j
))
4113 DurabilityLoss(pItem
,percent
);
4117 void Player::DurabilityLoss(Item
* item
, double percent
)
4122 uint32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4127 uint32 pDurabilityLoss
= uint32(pMaxDurability
*percent
);
4129 if(pDurabilityLoss
< 1 )
4130 pDurabilityLoss
= 1;
4132 DurabilityPointsLoss(item
,pDurabilityLoss
);
4135 void Player::DurabilityPointsLossAll(int32 points
, bool inventory
)
4137 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
4138 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4139 DurabilityPointsLoss(pItem
,points
);
4143 // bags not have durability
4144 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4146 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
4147 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4148 DurabilityPointsLoss(pItem
,points
);
4150 // keys not have durability
4151 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
4153 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
4154 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4155 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
4156 if(Item
* pItem
= GetItemByPos( i
, j
))
4157 DurabilityPointsLoss(pItem
,points
);
4161 void Player::DurabilityPointsLoss(Item
* item
, int32 points
)
4163 int32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4164 int32 pOldDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4165 int32 pNewDurability
= pOldDurability
- points
;
4167 if (pNewDurability
< 0)
4169 else if (pNewDurability
> pMaxDurability
)
4170 pNewDurability
= pMaxDurability
;
4172 if (pOldDurability
!= pNewDurability
)
4174 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4175 if ( pNewDurability
== 0 && pOldDurability
> 0 && item
->IsEquipped())
4176 _ApplyItemMods(item
,item
->GetSlot(), false);
4178 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, pNewDurability
);
4180 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4181 if ( pNewDurability
> 0 && pOldDurability
== 0 && item
->IsEquipped())
4182 _ApplyItemMods(item
,item
->GetSlot(), true);
4184 item
->SetState(ITEM_CHANGED
, this);
4188 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot
)
4190 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
))
4191 DurabilityPointsLoss(pItem
,1);
4194 uint32
Player::DurabilityRepairAll(bool cost
, float discountMod
, bool guildBank
)
4196 uint32 TotalCost
= 0;
4197 // equipped, backpack, bags itself
4198 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
4199 TotalCost
+= DurabilityRepair(( (INVENTORY_SLOT_BAG_0
<< 8) | i
),cost
,discountMod
, guildBank
);
4201 // bank, buyback and keys not repaired
4203 // items in inventory bags
4204 for(int j
= INVENTORY_SLOT_BAG_START
; j
< INVENTORY_SLOT_BAG_END
; j
++)
4205 for(int i
= 0; i
< MAX_BAG_SIZE
; i
++)
4206 TotalCost
+= DurabilityRepair(( (j
<< 8) | i
),cost
,discountMod
, guildBank
);
4210 uint32
Player::DurabilityRepair(uint16 pos
, bool cost
, float discountMod
, bool guildBank
)
4212 Item
* item
= GetItemByPos(pos
);
4214 uint32 TotalCost
= 0;
4218 uint32 maxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4222 uint32 curDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4226 uint32 LostDurability
= maxDurability
- curDurability
;
4227 if(LostDurability
>0)
4229 ItemPrototype
const *ditemProto
= item
->GetProto();
4231 DurabilityCostsEntry
const *dcost
= sDurabilityCostsStore
.LookupEntry(ditemProto
->ItemLevel
);
4234 sLog
.outError("ERROR: RepairDurability: Wrong item lvl %u", ditemProto
->ItemLevel
);
4238 uint32 dQualitymodEntryId
= (ditemProto
->Quality
+1)*2;
4239 DurabilityQualityEntry
const *dQualitymodEntry
= sDurabilityQualityStore
.LookupEntry(dQualitymodEntryId
);
4240 if(!dQualitymodEntry
)
4242 sLog
.outError("ERROR: RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId
);
4246 uint32 dmultiplier
= dcost
->multiplier
[ItemSubClassToDurabilityMultiplierId(ditemProto
->Class
,ditemProto
->SubClass
)];
4247 uint32 costs
= uint32(LostDurability
*dmultiplier
*double(dQualitymodEntry
->quality_mod
));
4249 costs
= uint32(costs
* discountMod
);
4251 if (costs
==0) //fix for ITEM_QUALITY_ARTIFACT
4256 if (GetGuildId()==0)
4258 DEBUG_LOG("You are not member of a guild");
4262 Guild
*pGuild
= objmgr
.GetGuildById(GetGuildId());
4266 if (!pGuild
->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR
))
4268 DEBUG_LOG("You do not have rights to withdraw for repairs");
4272 if (pGuild
->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs
)
4274 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4278 if (pGuild
->GetGuildBankMoney() < costs
)
4280 DEBUG_LOG("There is not enough money in bank");
4284 pGuild
->MemberMoneyWithdraw(costs
, GetGUIDLow());
4287 else if (GetMoney() < costs
)
4289 DEBUG_LOG("You do not have enough money");
4293 ModifyMoney( -int32(costs
) );
4297 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, maxDurability
);
4298 item
->SetState(ITEM_CHANGED
, this);
4300 // reapply mods for total broken and repaired item if equipped
4301 if(IsEquipmentPos(pos
) && !curDurability
)
4302 _ApplyItemMods(item
,pos
& 255, true);
4306 void Player::RepopAtGraveyard()
4308 // note: this can be called also when the player is alive
4309 // for example from WorldSession::HandleMovementOpcodes
4311 AreaTableEntry
const *zone
= GetAreaEntryByAreaID(GetAreaId());
4313 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4314 if(!isAlive() && zone
&& zone
->flags
& AREA_FLAG_NEED_FLY
|| GetTransport())
4316 ResurrectPlayer(0.5f
);
4320 WorldSafeLocsEntry
const *ClosestGrave
= NULL
;
4322 // Special handle for battleground maps
4323 if( BattleGround
*bg
= GetBattleGround() )
4324 ClosestGrave
= bg
->GetClosestGraveYard(this);
4326 ClosestGrave
= objmgr
.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4328 // stop countdown until repop
4331 // if no grave found, stay at the current location
4332 // and don't show spirit healer location
4335 TeleportTo(ClosestGrave
->map_id
, ClosestGrave
->x
, ClosestGrave
->y
, ClosestGrave
->z
, GetOrientation());
4336 if(isDead()) // not send if alive, because it used in TeleportTo()
4338 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // show spirit healer position on minimap
4339 data
<< ClosestGrave
->map_id
;
4340 data
<< ClosestGrave
->x
;
4341 data
<< ClosestGrave
->y
;
4342 data
<< ClosestGrave
->z
;
4343 GetSession()->SendPacket(&data
);
4348 void Player::JoinedChannel(Channel
*c
)
4350 m_channels
.push_back(c
);
4353 void Player::LeftChannel(Channel
*c
)
4355 m_channels
.remove(c
);
4358 void Player::CleanupChannels()
4360 while(!m_channels
.empty())
4362 Channel
* ch
= *m_channels
.begin();
4363 m_channels
.erase(m_channels
.begin()); // remove from player's channel list
4364 ch
->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4365 if (ChannelMgr
* cMgr
= channelMgr(GetTeam()))
4366 cMgr
->LeftChannel(ch
->GetName()); // deleted channel if empty
4369 sLog
.outDebug("Player: channels cleaned up!");
4372 void Player::UpdateLocalChannels(uint32 newZone
)
4374 if(m_channels
.empty())
4377 AreaTableEntry
const* current_zone
= GetAreaEntryByAreaID(newZone
);
4381 ChannelMgr
* cMgr
= channelMgr(GetTeam());
4385 std::string current_zone_name
= current_zone
->area_name
[GetSession()->GetSessionDbcLocale()];
4387 for(JoinedChannelsList::iterator i
= m_channels
.begin(), next
; i
!= m_channels
.end(); i
= next
)
4391 // skip non built-in channels
4392 if(!(*i
)->IsConstant())
4395 ChatChannelsEntry
const* ch
= GetChannelEntryFor((*i
)->GetChannelId());
4399 if((ch
->flags
& 4) == 4) // global channel without zone name in pattern
4403 char new_channel_name_buf
[100];
4404 snprintf(new_channel_name_buf
,100,ch
->pattern
[m_session
->GetSessionDbcLocale()],current_zone_name
.c_str());
4405 Channel
* new_channel
= cMgr
->GetJoinChannel(new_channel_name_buf
,ch
->ChannelID
);
4407 if((*i
)!=new_channel
)
4409 new_channel
->Join(GetGUID(),""); // will output Changed Channel: N. Name
4411 // leave old channel
4412 (*i
)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4413 std::string name
= (*i
)->GetName(); // store name, (*i)erase in LeftChannel
4414 LeftChannel(*i
); // remove from player's channel list
4415 cMgr
->LeftChannel(name
); // delete if empty
4418 sLog
.outDebug("Player: channels cleaned up!");
4421 void Player::LeaveLFGChannel()
4423 for(JoinedChannelsList::iterator i
= m_channels
.begin(); i
!= m_channels
.end(); ++i
)
4427 (*i
)->Leave(GetGUID());
4433 void Player::UpdateDefense()
4435 uint32 defense_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_DEFENSE
);
4437 if(UpdateSkill(SKILL_DEFENSE
,defense_skill_gain
))
4439 // update dependent from defense skill part
4440 UpdateDefenseBonusesMod();
4444 void Player::HandleBaseModValue(BaseModGroup modGroup
, BaseModType modType
, float amount
, bool apply
)
4446 if(modGroup
>= BASEMOD_END
|| modType
>= MOD_END
)
4448 sLog
.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4457 m_auraBaseMod
[modGroup
][modType
] += apply
? amount
: -amount
;
4460 if(amount
<= -100.0f
)
4463 val
= (100.0f
+ amount
) / 100.0f
;
4464 m_auraBaseMod
[modGroup
][modType
] *= apply
? val
: (1.0f
/val
);
4468 if(!CanModifyStats())
4473 case CRIT_PERCENTAGE
: UpdateCritPercentage(BASE_ATTACK
); break;
4474 case RANGED_CRIT_PERCENTAGE
: UpdateCritPercentage(RANGED_ATTACK
); break;
4475 case OFFHAND_CRIT_PERCENTAGE
: UpdateCritPercentage(OFF_ATTACK
); break;
4476 case SHIELD_BLOCK_VALUE
: UpdateShieldBlockValue(); break;
4481 float Player::GetBaseModValue(BaseModGroup modGroup
, BaseModType modType
) const
4483 if(modGroup
>= BASEMOD_END
|| modType
> MOD_END
)
4485 sLog
.outError("ERROR: trial to access non existed BaseModGroup or wrong BaseModType!");
4489 if(modType
== PCT_MOD
&& m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4492 return m_auraBaseMod
[modGroup
][modType
];
4495 float Player::GetTotalBaseModValue(BaseModGroup modGroup
) const
4497 if(modGroup
>= BASEMOD_END
)
4499 sLog
.outError("ERROR: wrong BaseModGroup in GetTotalBaseModValue()!");
4503 if(m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4506 return m_auraBaseMod
[modGroup
][FLAT_MOD
] * m_auraBaseMod
[modGroup
][PCT_MOD
];
4509 uint32
Player::GetShieldBlockValue() const
4511 BaseModGroup modGroup
= SHIELD_BLOCK_VALUE
;
4513 float value
= GetTotalBaseModValue(modGroup
) + GetStat(STAT_STRENGTH
) * 0.5f
- 10;
4515 value
= (value
< 0) ? 0 : value
;
4517 return uint32(value
);
4520 float Player::GetMeleeCritFromAgility()
4522 uint32 level
= getLevel();
4523 uint32 pclass
= getClass();
4525 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4527 GtChanceToMeleeCritBaseEntry
const *critBase
= sGtChanceToMeleeCritBaseStore
.LookupEntry(pclass
-1);
4528 GtChanceToMeleeCritEntry
const *critRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4529 if (critBase
==NULL
|| critRatio
==NULL
)
4532 float crit
=critBase
->base
+ GetStat(STAT_AGILITY
)*critRatio
->ratio
;
4536 float Player::GetDodgeFromAgility()
4538 // Table for base dodge values
4539 float dodge_base
[MAX_CLASSES
] = {
4541 0.00652f
, // Paladin
4548 0.02011f
, // Warlock
4552 // Crit/agility to dodge/agility coefficient multipliers
4553 float crit_to_dodge
[MAX_CLASSES
] = {
4567 uint32 level
= getLevel();
4568 uint32 pclass
= getClass();
4570 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4572 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4573 GtChanceToMeleeCritEntry
const *dodgeRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4574 if (dodgeRatio
==NULL
|| pclass
> MAX_CLASSES
)
4577 float dodge
=dodge_base
[pclass
-1] + GetStat(STAT_AGILITY
) * dodgeRatio
->ratio
* crit_to_dodge
[pclass
-1];
4578 return dodge
*100.0f
;
4581 float Player::GetSpellCritFromIntellect()
4583 uint32 level
= getLevel();
4584 uint32 pclass
= getClass();
4586 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4588 GtChanceToSpellCritBaseEntry
const *critBase
= sGtChanceToSpellCritBaseStore
.LookupEntry(pclass
-1);
4589 GtChanceToSpellCritEntry
const *critRatio
= sGtChanceToSpellCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4590 if (critBase
==NULL
|| critRatio
==NULL
)
4593 float crit
=critBase
->base
+ GetStat(STAT_INTELLECT
)*critRatio
->ratio
;
4597 float Player::GetRatingCoefficient(CombatRating cr
) const
4599 uint32 level
= getLevel();
4601 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4603 GtCombatRatingsEntry
const *Rating
= sGtCombatRatingsStore
.LookupEntry(cr
*GT_MAX_LEVEL
+level
-1);
4605 return 1.0f
; // By default use minimum coefficient (not must be called)
4607 return Rating
->ratio
;
4610 float Player::GetRatingBonusValue(CombatRating cr
) const
4612 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
)) / GetRatingCoefficient(cr
);
4615 uint32
Player::GetMeleeCritDamageReduction(uint32 damage
) const
4617 float melee
= GetRatingBonusValue(CR_CRIT_TAKEN_MELEE
)*2.0f
;
4618 if (melee
>25.0f
) melee
= 25.0f
;
4619 return uint32 (melee
* damage
/100.0f
);
4622 uint32
Player::GetRangedCritDamageReduction(uint32 damage
) const
4624 float ranged
= GetRatingBonusValue(CR_CRIT_TAKEN_RANGED
)*2.0f
;
4625 if (ranged
>25.0f
) ranged
=25.0f
;
4626 return uint32 (ranged
* damage
/100.0f
);
4629 uint32
Player::GetSpellCritDamageReduction(uint32 damage
) const
4631 float spell
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
)*2.0f
;
4632 // In wow script resilience limited to 25%
4635 return uint32 (spell
* damage
/ 100.0f
);
4638 uint32
Player::GetDotDamageReduction(uint32 damage
) const
4640 float spellDot
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
);
4641 // Dot resilience not limited (limit it by 100%)
4642 if (spellDot
> 100.0f
)
4644 return uint32 (spellDot
* damage
/ 100.0f
);
4647 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType
) const
4652 return GetUInt32Value(PLAYER_EXPERTISE
) / 4.0f
;
4654 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE
) / 4.0f
;
4661 float Player::OCTRegenHPPerSpirit()
4663 uint32 level
= getLevel();
4664 uint32 pclass
= getClass();
4666 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4668 GtOCTRegenHPEntry
const *baseRatio
= sGtOCTRegenHPStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4669 GtRegenHPPerSptEntry
const *moreRatio
= sGtRegenHPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4670 if (baseRatio
==NULL
|| moreRatio
==NULL
)
4673 // Formula from PaperDollFrame script
4674 float spirit
= GetStat(STAT_SPIRIT
);
4675 float baseSpirit
= spirit
;
4676 if (baseSpirit
>50) baseSpirit
= 50;
4677 float moreSpirit
= spirit
- baseSpirit
;
4678 float regen
= baseSpirit
* baseRatio
->ratio
+ moreSpirit
* moreRatio
->ratio
;
4682 float Player::OCTRegenMPPerSpirit()
4684 uint32 level
= getLevel();
4685 uint32 pclass
= getClass();
4687 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4689 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4690 GtRegenMPPerSptEntry
const *moreRatio
= sGtRegenMPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4691 if (moreRatio
==NULL
)
4694 // Formula get from PaperDollFrame script
4695 float spirit
= GetStat(STAT_SPIRIT
);
4696 float regen
= spirit
* moreRatio
->ratio
;
4700 void Player::ApplyRatingMod(CombatRating cr
, int32 value
, bool apply
)
4702 m_baseRatingValue
[cr
]+=(apply
? value
: -value
);
4704 int32 amount
= uint32(m_baseRatingValue
[cr
]);
4705 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4706 // stat used stored in miscValueB for this aura
4707 AuraList
const& modRatingFromStat
= GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT
);
4708 for(AuraList::const_iterator i
= modRatingFromStat
.begin();i
!= modRatingFromStat
.end(); ++i
)
4709 if ((*i
)->GetMiscValue() & (1<<cr
))
4710 amount
+= int32(GetStat(Stats((*i
)->GetMiscBValue())) * (*i
)->GetModifier()->m_amount
/ 100.0f
);
4713 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
, uint32(amount
));
4715 float RatingCoeffecient
= GetRatingCoefficient(cr
);
4716 float RatingChange
= 0.0f
;
4718 bool affectStats
= CanModifyStats();
4722 case CR_WEAPON_SKILL
: // Implemented in Unit::RollMeleeOutcomeAgainst
4723 case CR_DEFENSE_SKILL
:
4724 UpdateDefenseBonusesMod();
4727 UpdateDodgePercentage();
4730 UpdateParryPercentage();
4733 UpdateBlockPercentage();
4736 UpdateMeleeHitChances();
4739 UpdateRangedHitChances();
4742 UpdateSpellHitChances();
4747 UpdateCritPercentage(BASE_ATTACK
);
4748 UpdateCritPercentage(OFF_ATTACK
);
4751 case CR_CRIT_RANGED
:
4753 UpdateCritPercentage(RANGED_ATTACK
);
4757 UpdateAllSpellCritChances();
4759 case CR_HIT_TAKEN_MELEE
: // Implemented in Unit::MeleeMissChanceCalc
4760 case CR_HIT_TAKEN_RANGED
:
4762 case CR_HIT_TAKEN_SPELL
: // Implemented in Unit::MagicSpellHitResult
4764 case CR_CRIT_TAKEN_MELEE
: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4765 case CR_CRIT_TAKEN_RANGED
:
4767 case CR_CRIT_TAKEN_SPELL
: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4769 case CR_HASTE_MELEE
:
4770 RatingChange
= value
/ RatingCoeffecient
;
4771 ApplyAttackTimePercentMod(BASE_ATTACK
,RatingChange
,apply
);
4772 ApplyAttackTimePercentMod(OFF_ATTACK
,RatingChange
,apply
);
4774 case CR_HASTE_RANGED
:
4775 RatingChange
= value
/ RatingCoeffecient
;
4776 ApplyAttackTimePercentMod(RANGED_ATTACK
, RatingChange
, apply
);
4778 case CR_HASTE_SPELL
:
4779 RatingChange
= value
/ RatingCoeffecient
;
4780 ApplyCastTimePercentMod(RatingChange
,apply
);
4782 case CR_WEAPON_SKILL_MAINHAND
: // Implemented in Unit::RollMeleeOutcomeAgainst
4783 case CR_WEAPON_SKILL_OFFHAND
:
4784 case CR_WEAPON_SKILL_RANGED
:
4789 UpdateExpertise(BASE_ATTACK
);
4790 UpdateExpertise(OFF_ATTACK
);
4796 void Player::SetRegularAttackTime()
4798 for(int i
= 0; i
< MAX_ATTACK
; ++i
)
4800 Item
*tmpitem
= GetWeaponForAttack(WeaponAttackType(i
));
4801 if(tmpitem
&& !tmpitem
->IsBroken())
4803 ItemPrototype
const *proto
= tmpitem
->GetProto();
4805 SetAttackTime(WeaponAttackType(i
), proto
->Delay
);
4807 SetAttackTime(WeaponAttackType(i
), BASE_ATTACK_TIME
);
4812 //skill+step, checking for max value
4813 bool Player::UpdateSkill(uint32 skill_id
, uint32 step
)
4819 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4820 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill_id
)
4823 if(i
>=PLAYER_MAX_SKILLS
)
4826 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4827 uint32 value
= SKILL_VALUE(data
);
4828 uint32 max
= SKILL_MAX(data
);
4830 if ((!max
) || (!value
) || (value
>= max
))
4833 if (value
*512 < max
*urand(0,512))
4835 uint32 new_value
= value
+step
;
4839 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,max
));
4840 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
);
4847 inline int SkillGainChance(uint32 SkillValue
, uint32 GrayLevel
, uint32 GreenLevel
, uint32 YellowLevel
)
4849 if ( SkillValue
>= GrayLevel
)
4850 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREY
)*10;
4851 if ( SkillValue
>= GreenLevel
)
4852 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREEN
)*10;
4853 if ( SkillValue
>= YellowLevel
)
4854 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_YELLOW
)*10;
4855 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_ORANGE
)*10;
4858 bool Player::UpdateCraftSkill(uint32 spellid
)
4860 sLog
.outDebug("UpdateCraftSkill spellid %d", spellid
);
4862 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spellid
);
4863 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spellid
);
4865 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
4867 if(_spell_idx
->second
->skillId
)
4869 uint32 SkillValue
= GetPureSkillValue(_spell_idx
->second
->skillId
);
4871 // Alchemy Discoveries here
4872 SpellEntry
const* spellEntry
= sSpellStore
.LookupEntry(spellid
);
4873 if(spellEntry
&& spellEntry
->Mechanic
==MECHANIC_DISCOVERY
)
4875 if(uint32 discoveredSpell
= GetSkillDiscoverySpell(_spell_idx
->second
->skillId
, spellid
, this))
4876 learnSpell(discoveredSpell
,false);
4879 uint32 craft_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_CRAFTING
);
4881 return UpdateSkillPro(_spell_idx
->second
->skillId
, SkillGainChance(SkillValue
,
4882 _spell_idx
->second
->max_value
,
4883 (_spell_idx
->second
->max_value
+ _spell_idx
->second
->min_value
)/2,
4884 _spell_idx
->second
->min_value
),
4891 bool Player::UpdateGatherSkill(uint32 SkillId
, uint32 SkillValue
, uint32 RedLevel
, uint32 Multiplicator
)
4893 sLog
.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId
, SkillValue
, RedLevel
);
4895 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
4897 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4900 case SKILL_HERBALISM
:
4901 case SKILL_LOCKPICKING
:
4902 case SKILL_JEWELCRAFTING
:
4903 case SKILL_INSCRIPTION
:
4904 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4905 case SKILL_SKINNING
:
4906 if( sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)==0)
4907 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4909 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)), gathering_skill_gain
);
4911 if (sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)==0)
4912 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4914 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)),gathering_skill_gain
);
4919 bool Player::UpdateFishingSkill()
4921 sLog
.outDebug("UpdateFishingSkill");
4923 uint32 SkillValue
= GetPureSkillValue(SKILL_FISHING
);
4925 int32 chance
= SkillValue
< 75 ? 100 : 2500/(SkillValue
-50);
4927 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
4929 return UpdateSkillPro(SKILL_FISHING
,chance
*10,gathering_skill_gain
);
4932 // levels sync. with spell requirement for skill levels to learn
4933 // bonus abilities in sSkillLineAbilityStore
4934 // Used only to avoid scan DBC at each skill grow
4935 static uint32 bonusSkillLevels
[] = {75,150,225,300,375,450};
4937 bool Player::UpdateSkillPro(uint16 SkillId
, int32 Chance
, uint32 step
)
4939 sLog
.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId
, Chance
/10.0);
4943 if(Chance
<= 0) // speedup in 0 chance case
4945 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
4950 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4951 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i
))) == SkillId
) break;
4952 if ( i
>= PLAYER_MAX_SKILLS
)
4955 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4956 uint16 SkillValue
= SKILL_VALUE(data
);
4957 uint16 MaxValue
= SKILL_MAX(data
);
4959 if ( !MaxValue
|| !SkillValue
|| SkillValue
>= MaxValue
)
4962 int32 Roll
= irand(1,1000);
4964 if ( Roll
<= Chance
)
4966 uint32 new_value
= SkillValue
+step
;
4967 if(new_value
> MaxValue
)
4968 new_value
= MaxValue
;
4970 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,MaxValue
));
4971 for(uint32
* bsl
= &bonusSkillLevels
[0]; *bsl
; ++bsl
)
4973 if((SkillValue
< *bsl
&& new_value
>= *bsl
))
4975 learnSkillRewardedSpells( SkillId
, new_value
);
4979 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
);
4980 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance
/10.0);
4984 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
4988 void Player::UpdateWeaponSkill (WeaponAttackType attType
)
4990 // no skill gain in pvp
4991 Unit
*pVictim
= getVictim();
4992 if(pVictim
&& pVictim
->GetTypeId() == TYPEID_PLAYER
)
4996 return; // always maximized SKILL_FERAL_COMBAT in fact
4998 if(m_form
== FORM_TREE
)
4999 return; // use weapon but not skill up
5001 uint32 weapon_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_WEAPON
);
5007 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
5010 UpdateSkill(SKILL_UNARMED
,weapon_skill_gain
);
5011 else if(tmpitem
->GetProto()->SubClass
!= ITEM_SUBCLASS_WEAPON_FISHING_POLE
)
5012 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
5018 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
5020 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
5024 UpdateAllCritPercentages();
5027 void Player::UpdateCombatSkills(Unit
*pVictim
, WeaponAttackType attType
, bool defence
)
5029 uint32 plevel
= getLevel(); // if defense than pVictim == attacker
5030 uint32 greylevel
= MaNGOS::XP::GetGrayLevel(plevel
);
5031 uint32 moblevel
= pVictim
->getLevelForTarget(this);
5032 if(moblevel
< greylevel
)
5035 if (moblevel
> plevel
+ 5)
5036 moblevel
= plevel
+ 5;
5038 uint32 lvldif
= moblevel
- greylevel
;
5042 uint32 skilldif
= 5 * plevel
- (defence
? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType
));
5046 float chance
= float(3 * lvldif
* skilldif
) / plevel
;
5049 if(getClass() == CLASS_WARRIOR
|| getClass() == CLASS_ROGUE
)
5050 chance
*= 0.1f
* GetStat(STAT_INTELLECT
);
5053 chance
= chance
< 1.0f
? 1.0f
: chance
; //minimum chance to increase skill is 1%
5055 if(roll_chance_f(chance
))
5060 UpdateWeaponSkill(attType
);
5066 void Player::ModifySkillBonus(uint32 skillid
,int32 val
, bool talent
)
5068 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5069 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skillid
)
5071 uint32 bonus_val
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5072 int16 temp_bonus
= SKILL_TEMP_BONUS(bonus_val
);
5073 int16 perm_bonus
= SKILL_PERM_BONUS(bonus_val
);
5075 if(talent
) // permanent bonus stored in high part
5076 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
,perm_bonus
+val
));
5077 else // temporary/item bonus stored in low part
5078 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
+val
,perm_bonus
));
5083 void Player::UpdateSkillsForLevel()
5085 uint16 maxconfskill
= sWorld
.GetConfigMaxSkillValue();
5086 uint32 maxSkill
= GetMaxSkillValueForLevel();
5088 bool alwaysMaxSkill
= sWorld
.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL
);
5090 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5091 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5093 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
5095 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(pskill
);
5099 if(GetSkillRangeType(pSkill
,false) != SKILL_RANGE_LEVEL
)
5102 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
5103 uint32 max
= SKILL_MAX(data
);
5104 uint32 val
= SKILL_VALUE(data
);
5106 /// update only level dependent max skill values
5109 /// miximize skill always
5111 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(maxSkill
,maxSkill
));
5112 /// update max skill value if current max skill not maximized
5113 else if(max
!= maxconfskill
)
5114 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(val
,maxSkill
));
5119 void Player::UpdateSkillsToMaxSkillsForLevel()
5121 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5122 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5124 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
5125 if( IsProfessionOrRidingSkill(pskill
))
5127 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
5129 uint32 max
= SKILL_MAX(data
);
5132 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(max
,max
));
5134 if(pskill
== SKILL_DEFENSE
)
5135 UpdateDefenseBonusesMod();
5139 // This functions sets a skill line value (and adds if doesn't exist yet)
5140 // To "remove" a skill line, set it's values to zero
5141 void Player::SetSkill(uint32 id
, uint16 currVal
, uint16 maxVal
)
5147 for (; i
< PLAYER_MAX_SKILLS
; i
++)
5148 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == id
) break;
5150 if(i
<PLAYER_MAX_SKILLS
) //has skill
5154 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
5155 learnSkillRewardedSpells(id
, currVal
);
5156 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
);
5160 // clear skill fields
5161 SetUInt32Value(PLAYER_SKILL_INDEX(i
),0);
5162 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),0);
5163 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
5165 // remove all spells that related to this skill
5166 for (uint32 j
=0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
5167 if(SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
))
5168 if (pAbility
->skillId
==id
)
5169 removeSpell(spellmgr
.GetFirstSpellInChain(pAbility
->spellId
));
5172 else if(currVal
) //add
5174 for (i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5175 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5177 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
5180 sLog
.outError("Skill not found in SkillLineStore: skill #%u", id
);
5183 // enable unlearn button for primary professions only
5184 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
5185 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
5187 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
5188 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
5189 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
);
5191 // apply skill bonuses
5192 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
5194 // temporary bonuses
5195 AuraList
const& mModSkill
= GetAurasByType(SPELL_AURA_MOD_SKILL
);
5196 for(AuraList::const_iterator i
= mModSkill
.begin(); i
!= mModSkill
.end(); ++i
)
5197 if ((*i
)->GetModifier()->m_miscvalue
== int32(id
))
5198 (*i
)->ApplyModifier(true);
5200 // permanent bonuses
5201 AuraList
const& mModSkillTalent
= GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT
);
5202 for(AuraList::const_iterator i
= mModSkillTalent
.begin(); i
!= mModSkillTalent
.end(); ++i
)
5203 if ((*i
)->GetModifier()->m_miscvalue
== int32(id
))
5204 (*i
)->ApplyModifier(true);
5206 // Learn all spells for skill
5207 learnSkillRewardedSpells(id
, currVal
);
5213 bool Player::HasSkill(uint32 skill
) const
5215 if(!skill
)return false;
5216 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5218 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5226 uint16
Player::GetSkillValue(uint32 skill
) const
5231 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5233 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5235 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5237 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5238 result
+= SKILL_TEMP_BONUS(bonus
);
5239 result
+= SKILL_PERM_BONUS(bonus
);
5240 return result
< 0 ? 0 : result
;
5246 uint16
Player::GetMaxSkillValue(uint32 skill
) const
5249 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5251 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5253 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5255 int32 result
= int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5256 result
+= SKILL_TEMP_BONUS(bonus
);
5257 result
+= SKILL_PERM_BONUS(bonus
);
5258 return result
< 0 ? 0 : result
;
5264 uint16
Player::GetPureMaxSkillValue(uint32 skill
) const
5267 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5269 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5271 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5277 uint16
Player::GetBaseSkillValue(uint32 skill
) const
5280 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5282 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5284 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5285 result
+= SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5286 return result
< 0 ? 0 : result
;
5292 uint16
Player::GetPureSkillValue(uint32 skill
) const
5295 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5297 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5299 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5305 int16
Player::GetSkillPermBonusValue(uint32 skill
) const
5310 for (int i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
5312 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5314 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5321 int16
Player::GetSkillTempBonusValue(uint32 skill
) const
5326 for (int i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
5328 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5330 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5337 void Player::SendInitialActionButtons()
5339 sLog
.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5341 WorldPacket
data(SMSG_ACTION_BUTTONS
, (MAX_ACTION_BUTTONS
*4));
5342 for(int button
= 0; button
< MAX_ACTION_BUTTONS
; ++button
)
5344 ActionButtonList::const_iterator itr
= m_actionButtons
.find(button
);
5345 if(itr
!= m_actionButtons
.end() && itr
->second
.uState
!= ACTIONBUTTON_DELETED
)
5347 data
<< uint16(itr
->second
.action
);
5348 data
<< uint8(itr
->second
.misc
);
5349 data
<< uint8(itr
->second
.type
);
5357 GetSession()->SendPacket( &data
);
5358 sLog
.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5361 bool Player::addActionButton(const uint8 button
, const uint16 action
, const uint8 type
, const uint8 misc
)
5363 if(button
>= MAX_ACTION_BUTTONS
)
5365 sLog
.outError( "Action %u not added into button %u for player %s: button must be < 132", action
, button
, GetName() );
5369 // check cheating with adding non-known spells to action bar
5370 if(type
==ACTION_BUTTON_SPELL
)
5372 if(!sSpellStore
.LookupEntry(action
))
5374 sLog
.outError( "Action %u not added into button %u for player %s: spell not exist", action
, button
, GetName() );
5378 if(!HasSpell(action
))
5380 sLog
.outError( "Action %u not added into button %u for player %s: player don't known this spell", action
, button
, GetName() );
5385 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5387 if (buttonItr
==m_actionButtons
.end())
5388 { // just add new button
5389 m_actionButtons
[button
] = ActionButton(action
,type
,misc
);
5392 { // change state of current button
5393 ActionButtonUpdateState uState
= buttonItr
->second
.uState
;
5394 buttonItr
->second
= ActionButton(action
,type
,misc
);
5395 if (uState
!= ACTIONBUTTON_NEW
) buttonItr
->second
.uState
= ACTIONBUTTON_CHANGED
;
5398 sLog
.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action
, button
);
5402 void Player::removeActionButton(uint8 button
)
5404 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5405 if (buttonItr
==m_actionButtons
.end())
5408 if(buttonItr
->second
.uState
==ACTIONBUTTON_NEW
)
5409 m_actionButtons
.erase(buttonItr
); // new and not saved
5411 buttonItr
->second
.uState
= ACTIONBUTTON_DELETED
; // saved, will deleted at next save
5413 sLog
.outDetail( "Action Button '%u' Removed from Player '%u'", button
, GetGUIDLow() );
5416 void Player::SetDontMove(bool dontMove
)
5418 m_dontMove
= dontMove
;
5421 bool Player::SetPosition(float x
, float y
, float z
, float orientation
, bool teleport
)
5423 // prevent crash when a bad coord is sent by the client
5424 if(!MaNGOS::IsValidMapCoord(x
,y
,z
,orientation
))
5426 sLog
.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x
,y
,z
,orientation
,teleport
,GetGUIDLow());
5432 const float old_x
= GetPositionX();
5433 const float old_y
= GetPositionY();
5434 const float old_z
= GetPositionZ();
5435 const float old_r
= GetOrientation();
5437 if( teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
|| old_r
!= orientation
)
5439 if (teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
)
5440 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE
| AURA_INTERRUPT_FLAG_TURNING
);
5442 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING
);
5444 // move and update visible state if need
5445 m
->PlayerRelocation(this, x
, y
, z
, orientation
);
5447 // reread after Map::Relocation
5454 if(GetGroup() && (old_x
!= x
|| old_y
!= y
))
5455 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION
);
5458 // code block for underwater state update
5459 UpdateUnderwaterState(m
, x
, y
, z
);
5461 CheckExploreSystem();
5466 void Player::SaveRecallPosition()
5468 m_recallMap
= GetMapId();
5469 m_recallX
= GetPositionX();
5470 m_recallY
= GetPositionY();
5471 m_recallZ
= GetPositionZ();
5472 m_recallO
= GetOrientation();
5475 void Player::SendMessageToSet(WorldPacket
*data
, bool self
)
5477 GetMap()->MessageBroadcast(this, data
, self
);
5480 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
)
5482 GetMap()->MessageDistBroadcast(this, data
, dist
, self
);
5485 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
, bool own_team_only
)
5487 GetMap()->MessageDistBroadcast(this, data
, dist
, self
,own_team_only
);
5490 void Player::SendDirectMessage(WorldPacket
*data
)
5492 GetSession()->SendPacket(data
);
5495 void Player::CheckExploreSystem()
5503 uint16 areaFlag
=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5504 if(areaFlag
==0xffff)
5506 int offset
= areaFlag
/ 32;
5510 sLog
.outError("ERROR: 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
);
5514 uint32 val
= (uint32
)(1 << (areaFlag
% 32));
5515 uint32 currFields
= GetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
);
5517 if( !(currFields
& val
) )
5519 SetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
, (uint32
)(currFields
| val
));
5521 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA
);
5523 AreaTableEntry
const *p
= GetAreaEntryByAreaFlagAndMap(areaFlag
,GetMapId());
5526 sLog
.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5528 else if(p
->area_level
> 0)
5530 uint32 area
= p
->ID
;
5531 if (getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
5533 SendExplorationExperience(area
,0);
5537 int32 diff
= int32(getLevel()) - p
->area_level
;
5541 XP
= uint32(objmgr
.GetBaseXP(getLevel()+5)*sWorld
.getRate(RATE_XP_EXPLORE
));
5545 int32 exploration_percent
= (100-((diff
-5)*5));
5546 if (exploration_percent
> 100)
5547 exploration_percent
= 100;
5548 else if (exploration_percent
< 0)
5549 exploration_percent
= 0;
5551 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*exploration_percent
/100*sWorld
.getRate(RATE_XP_EXPLORE
));
5555 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*sWorld
.getRate(RATE_XP_EXPLORE
));
5559 SendExplorationExperience(area
,XP
);
5561 sLog
.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area
);
5566 uint32
Player::TeamForRace(uint8 race
)
5568 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5571 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5575 switch(rEntry
->TeamID
)
5577 case 7: return ALLIANCE
;
5578 case 1: return HORDE
;
5581 sLog
.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race
),rEntry
->TeamID
);
5585 uint32
Player::getFactionForRace(uint8 race
)
5587 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5590 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5594 return rEntry
->FactionID
;
5597 void Player::setFactionForRace(uint8 race
)
5599 m_team
= TeamForRace(race
);
5600 setFaction( getFactionForRace(race
) );
5603 void Player::UpdateReputation() const
5605 sLog
.outDetail( "WORLD: Player::UpdateReputation" );
5607 for(FactionStateList::const_iterator itr
= m_factions
.begin(); itr
!= m_factions
.end(); ++itr
)
5609 SendFactionState(&(itr
->second
));
5613 void Player::SendFactionState(FactionState
const* faction
) const
5615 if(faction
->Flags
& FACTION_FLAG_VISIBLE
) //If faction is visible then update it
5617 WorldPacket
data(SMSG_SET_FACTION_STANDING
, (16)); // last check 2.4.0
5618 data
<< (float) 0; // unk 2.4.0
5619 data
<< (uint8
) 0; // wotlk 8634
5620 data
<< (uint32
) 1; // count
5622 data
<< (uint32
) faction
->ReputationListID
;
5623 data
<< (uint32
) faction
->Standing
;
5625 GetSession()->SendPacket(&data
);
5629 void Player::SendInitialReputations()
5631 WorldPacket
data(SMSG_INITIALIZE_FACTIONS
, (4+128*5));
5632 data
<< uint32 (0x00000080);
5636 for (FactionStateList::const_iterator itr
= m_factions
.begin(); itr
!= m_factions
.end(); ++itr
)
5638 // fill in absent fields
5639 for (; a
!= itr
->first
; a
++)
5641 data
<< uint8 (0x00);
5642 data
<< uint32 (0x00000000);
5645 // fill in encountered data
5646 data
<< uint8 (itr
->second
.Flags
);
5647 data
<< uint32 (itr
->second
.Standing
);
5652 // fill in absent fields
5653 for (; a
!= 128; a
++)
5655 data
<< uint8 (0x00);
5656 data
<< uint32 (0x00000000);
5659 GetSession()->SendPacket(&data
);
5662 FactionState
const* Player::GetFactionState( FactionEntry
const* factionEntry
) const
5664 FactionStateList::const_iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5665 if (itr
!= m_factions
.end())
5666 return &itr
->second
;
5671 void Player::SetFactionAtWar(FactionState
* faction
, bool atWar
)
5673 // not allow declare war to own faction
5674 if(atWar
&& (faction
->Flags
& FACTION_FLAG_PEACE_FORCED
) )
5678 if(((faction
->Flags
& FACTION_FLAG_AT_WAR
) != 0) == atWar
)
5682 faction
->Flags
|= FACTION_FLAG_AT_WAR
;
5684 faction
->Flags
&= ~FACTION_FLAG_AT_WAR
;
5686 faction
->Changed
= true;
5689 void Player::SetFactionInactive(FactionState
* faction
, bool inactive
)
5691 // always invisible or hidden faction can't be inactive
5692 if(inactive
&& ((faction
->Flags
& (FACTION_FLAG_INVISIBLE_FORCED
|FACTION_FLAG_HIDDEN
)) || !(faction
->Flags
& FACTION_FLAG_VISIBLE
) ) )
5696 if(((faction
->Flags
& FACTION_FLAG_INACTIVE
) != 0) == inactive
)
5700 faction
->Flags
|= FACTION_FLAG_INACTIVE
;
5702 faction
->Flags
&= ~FACTION_FLAG_INACTIVE
;
5704 faction
->Changed
= true;
5707 void Player::SetFactionVisibleForFactionTemplateId(uint32 FactionTemplateId
)
5709 FactionTemplateEntry
const*factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5711 if(!factionTemplateEntry
)
5714 if(factionTemplateEntry
->faction
)
5715 SetFactionVisibleForFactionId(factionTemplateEntry
->faction
);
5718 void Player::SetFactionVisibleForFactionId(uint32 FactionId
)
5720 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(FactionId
);
5724 if(factionEntry
->reputationListID
< 0)
5727 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5728 if (itr
== m_factions
.end())
5731 SetFactionVisible(&itr
->second
);
5734 void Player::SetFactionVisible(FactionState
* faction
)
5736 // always invisible or hidden faction can't be make visible
5737 if(faction
->Flags
& (FACTION_FLAG_INVISIBLE_FORCED
|FACTION_FLAG_HIDDEN
))
5741 if(faction
->Flags
& FACTION_FLAG_VISIBLE
)
5744 faction
->Flags
|= FACTION_FLAG_VISIBLE
;
5745 faction
->Changed
= true;
5747 if(!m_session
->PlayerLoading())
5749 // make faction visible in reputation list at client
5750 WorldPacket
data(SMSG_SET_FACTION_VISIBLE
, 4);
5751 data
<< faction
->ReputationListID
;
5752 GetSession()->SendPacket(&data
);
5756 void Player::SetInitialFactions()
5758 for(unsigned int i
= 1; i
< sFactionStore
.GetNumRows(); i
++)
5760 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(i
);
5762 if( factionEntry
&& (factionEntry
->reputationListID
>= 0))
5764 FactionState newFaction
;
5765 newFaction
.ID
= factionEntry
->ID
;
5766 newFaction
.ReputationListID
= factionEntry
->reputationListID
;
5767 newFaction
.Standing
= 0;
5768 newFaction
.Flags
= GetDefaultReputationFlags(factionEntry
);
5769 newFaction
.Changed
= true;
5771 m_factions
[newFaction
.ReputationListID
] = newFaction
;
5776 uint32
Player::GetDefaultReputationFlags(const FactionEntry
*factionEntry
) const
5781 uint32 raceMask
= getRaceMask();
5782 uint32 classMask
= getClassMask();
5783 for (int i
=0; i
< 4; i
++)
5785 if( (factionEntry
->BaseRepRaceMask
[i
] & raceMask
) &&
5786 (factionEntry
->BaseRepClassMask
[i
]==0 ||
5787 (factionEntry
->BaseRepClassMask
[i
] & classMask
) ) )
5788 return factionEntry
->ReputationFlags
[i
];
5793 int32
Player::GetBaseReputation(const FactionEntry
*factionEntry
) const
5798 uint32 raceMask
= getRaceMask();
5799 uint32 classMask
= getClassMask();
5800 for (int i
=0; i
< 4; i
++)
5802 if( (factionEntry
->BaseRepRaceMask
[i
] & raceMask
) &&
5803 (factionEntry
->BaseRepClassMask
[i
]==0 ||
5804 (factionEntry
->BaseRepClassMask
[i
] & classMask
) ) )
5805 return factionEntry
->BaseRepValue
[i
];
5808 // in faction.dbc exist factions with (RepListId >=0, listed in character reputation list) with all BaseRepRaceMask[i]==0
5812 int32
Player::GetReputation(uint32 faction_id
) const
5814 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(faction_id
);
5818 sLog
.outError("Player::GetReputation: Can't get reputation of %s for unknown faction (faction template id) #%u.",GetName(), faction_id
);
5822 return GetReputation(factionEntry
);
5825 int32
Player::GetReputation(const FactionEntry
*factionEntry
) const
5827 // Faction without recorded reputation. Just ignore.
5831 FactionStateList::const_iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5832 if (itr
!= m_factions
.end())
5833 return GetBaseReputation(factionEntry
) + itr
->second
.Standing
;
5838 ReputationRank
Player::GetReputationRank(uint32 faction
) const
5840 FactionEntry
const*factionEntry
= sFactionStore
.LookupEntry(faction
);
5842 return MIN_REPUTATION_RANK
;
5844 return GetReputationRank(factionEntry
);
5847 ReputationRank
Player::ReputationToRank(int32 standing
) const
5849 int32 Limit
= Reputation_Cap
+ 1;
5850 for (int i
= MAX_REPUTATION_RANK
-1; i
>= MIN_REPUTATION_RANK
; --i
)
5852 Limit
-= ReputationRank_Length
[i
];
5853 if (standing
>= Limit
)
5854 return ReputationRank(i
);
5856 return MIN_REPUTATION_RANK
;
5859 ReputationRank
Player::GetReputationRank(const FactionEntry
*factionEntry
) const
5861 int32 Reputation
= GetReputation(factionEntry
);
5862 return ReputationToRank(Reputation
);
5865 ReputationRank
Player::GetBaseReputationRank(const FactionEntry
*factionEntry
) const
5867 int32 Reputation
= GetBaseReputation(factionEntry
);
5868 return ReputationToRank(Reputation
);
5871 bool Player::ModifyFactionReputation(uint32 FactionTemplateId
, int32 DeltaReputation
)
5873 FactionTemplateEntry
const* factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5875 if(!factionTemplateEntry
)
5877 sLog
.outError("Player::ModifyFactionReputation: Can't update reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId
);
5881 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(factionTemplateEntry
->faction
);
5883 // Faction without recorded reputation. Just ignore.
5887 return ModifyFactionReputation(factionEntry
, DeltaReputation
);
5890 bool Player::ModifyFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5892 SimpleFactionsList
const* flist
= GetFactionTeamList(factionEntry
->ID
);
5896 for (SimpleFactionsList::const_iterator itr
= flist
->begin();itr
!= flist
->end();++itr
)
5898 FactionEntry
const *factionEntryCalc
= sFactionStore
.LookupEntry(*itr
);
5899 if(factionEntryCalc
)
5900 res
= ModifyOneFactionReputation(factionEntryCalc
, standing
);
5905 return ModifyOneFactionReputation(factionEntry
, standing
);
5908 bool Player::ModifyOneFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5910 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5911 if (itr
!= m_factions
.end())
5913 int32 BaseRep
= GetBaseReputation(factionEntry
);
5914 int32 new_rep
= BaseRep
+ itr
->second
.Standing
+ standing
;
5916 if (new_rep
> Reputation_Cap
)
5917 new_rep
= Reputation_Cap
;
5919 if (new_rep
< Reputation_Bottom
)
5920 new_rep
= Reputation_Bottom
;
5922 if(ReputationToRank(new_rep
) <= REP_HOSTILE
)
5923 SetFactionAtWar(&itr
->second
,true);
5925 itr
->second
.Standing
= new_rep
- BaseRep
;
5926 itr
->second
.Changed
= true;
5928 SetFactionVisible(&itr
->second
);
5930 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
5932 if(uint32 questid
= GetQuestSlotQuestId(i
))
5934 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
5935 if( qInfo
&& qInfo
->GetRepObjectiveFaction() == factionEntry
->ID
)
5937 QuestStatusData
& q_status
= mQuestStatus
[questid
];
5938 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
5940 if(GetReputation(factionEntry
) >= qInfo
->GetRepObjectiveValue())
5941 if ( CanCompleteQuest( questid
) )
5942 CompleteQuest( questid
);
5944 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
5946 if(GetReputation(factionEntry
) < qInfo
->GetRepObjectiveValue())
5947 IncompleteQuest( questid
);
5952 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION
);
5953 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION
);
5954 SendFactionState(&(itr
->second
));
5961 bool Player::SetFactionReputation(uint32 FactionTemplateId
, int32 standing
)
5963 FactionTemplateEntry
const* factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5965 if(!factionTemplateEntry
)
5967 sLog
.outError("Player::SetFactionReputation: Can't set reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId
);
5971 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(factionTemplateEntry
->faction
);
5973 // Faction without recorded reputation. Just ignore.
5977 return SetFactionReputation(factionEntry
, standing
);
5980 bool Player::SetFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5982 SimpleFactionsList
const* flist
= GetFactionTeamList(factionEntry
->ID
);
5986 for (SimpleFactionsList::const_iterator itr
= flist
->begin();itr
!= flist
->end();++itr
)
5988 FactionEntry
const *factionEntryCalc
= sFactionStore
.LookupEntry(*itr
);
5989 if(factionEntryCalc
)
5990 res
= SetOneFactionReputation(factionEntryCalc
, standing
);
5995 return SetOneFactionReputation(factionEntry
, standing
);
5998 bool Player::SetOneFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
6000 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
6001 if (itr
!= m_factions
.end())
6003 if (standing
> Reputation_Cap
)
6004 standing
= Reputation_Cap
;
6006 if (standing
< Reputation_Bottom
)
6007 standing
= Reputation_Bottom
;
6009 int32 BaseRep
= GetBaseReputation(factionEntry
);
6010 itr
->second
.Standing
= standing
- BaseRep
;
6011 itr
->second
.Changed
= true;
6013 SetFactionVisible(&itr
->second
);
6015 if(ReputationToRank(standing
) <= REP_HOSTILE
)
6016 SetFactionAtWar(&itr
->second
,true);
6018 SendFactionState(&(itr
->second
));
6019 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION
);
6020 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION
);
6026 //Calculate total reputation percent player gain with quest/creature level
6027 int32
Player::CalculateReputationGain(uint32 creatureOrQuestLevel
, int32 rep
, bool for_quest
)
6029 // for grey creature kill received 20%, in other case 100.
6030 int32 percent
= (!for_quest
&& (creatureOrQuestLevel
<= MaNGOS::XP::GetGrayLevel(getLevel()))) ? 20 : 100;
6032 int32 repMod
= GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN
);
6034 percent
+= rep
> 0 ? repMod
: -repMod
;
6039 return int32(sWorld
.getRate(RATE_REPUTATION_GAIN
)*rep
*percent
/100);
6042 //Calculates how many reputation points player gains in victim's enemy factions
6043 void Player::RewardReputation(Unit
*pVictim
, float rate
)
6045 if(!pVictim
|| pVictim
->GetTypeId() == TYPEID_PLAYER
)
6048 ReputationOnKillEntry
const* Rep
= objmgr
.GetReputationOnKilEntry(((Creature
*)pVictim
)->GetCreatureInfo()->Entry
);
6053 if(Rep
->repfaction1
&& (!Rep
->team_dependent
|| GetTeam()==ALLIANCE
))
6055 int32 donerep1
= CalculateReputationGain(pVictim
->getLevel(),Rep
->repvalue1
,false);
6056 donerep1
= int32(donerep1
*rate
);
6057 FactionEntry
const *factionEntry1
= sFactionStore
.LookupEntry(Rep
->repfaction1
);
6058 uint32 current_reputation_rank1
= GetReputationRank(factionEntry1
);
6059 if(factionEntry1
&& current_reputation_rank1
<= Rep
->reputation_max_cap1
)
6060 ModifyFactionReputation(factionEntry1
, donerep1
);
6062 // Wiki: Team factions value divided by 2
6063 if(Rep
->is_teamaward1
)
6065 FactionEntry
const *team1_factionEntry
= sFactionStore
.LookupEntry(factionEntry1
->team
);
6066 if(team1_factionEntry
)
6067 ModifyFactionReputation(team1_factionEntry
, donerep1
/ 2);
6071 if(Rep
->repfaction2
&& (!Rep
->team_dependent
|| GetTeam()==HORDE
))
6073 int32 donerep2
= CalculateReputationGain(pVictim
->getLevel(),Rep
->repvalue2
,false);
6074 donerep2
= int32(donerep2
*rate
);
6075 FactionEntry
const *factionEntry2
= sFactionStore
.LookupEntry(Rep
->repfaction2
);
6076 uint32 current_reputation_rank2
= GetReputationRank(factionEntry2
);
6077 if(factionEntry2
&& current_reputation_rank2
<= Rep
->reputation_max_cap2
)
6078 ModifyFactionReputation(factionEntry2
, donerep2
);
6080 // Wiki: Team factions value divided by 2
6081 if(Rep
->is_teamaward2
)
6083 FactionEntry
const *team2_factionEntry
= sFactionStore
.LookupEntry(factionEntry2
->team
);
6084 if(team2_factionEntry
)
6085 ModifyFactionReputation(team2_factionEntry
, donerep2
/ 2);
6090 //Calculate how many reputation points player gain with the quest
6091 void Player::RewardReputation(Quest
const *pQuest
)
6093 // quest reputation reward/loss
6094 for(int i
= 0; i
< QUEST_REPUTATIONS_COUNT
; ++i
)
6096 if(pQuest
->RewRepFaction
[i
] && pQuest
->RewRepValue
[i
] )
6098 int32 rep
= CalculateReputationGain(GetQuestLevel(pQuest
),pQuest
->RewRepValue
[i
],true);
6099 FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(pQuest
->RewRepFaction
[i
]);
6101 ModifyFactionReputation(factionEntry
, rep
);
6105 // TODO: implement reputation spillover
6108 void Player::UpdateArenaFields(void)
6110 /* arena calcs go here */
6113 void Player::UpdateHonorFields()
6115 /// called when rewarding honor and at each save
6116 uint64 now
= time(NULL
);
6117 uint64 today
= uint64(time(NULL
) / DAY
) * DAY
;
6119 if(m_lastHonorUpdateTime
< today
)
6121 uint64 yesterday
= today
- DAY
;
6123 uint16 kills_today
= PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS
));
6125 // update yesterday's contribution
6126 if(m_lastHonorUpdateTime
>= yesterday
)
6128 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
));
6130 // this is the first update today, reset today's contribution
6131 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, 0);
6132 SetUInt32Value(PLAYER_FIELD_KILLS
, MAKE_PAIR32(0,kills_today
));
6136 // no honor/kills yesterday or today, reset
6137 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0);
6138 SetUInt32Value(PLAYER_FIELD_KILLS
, 0);
6142 m_lastHonorUpdateTime
= now
;
6145 ///Calculate the amount of honor gained based on the victim
6146 ///and the size of the group for which the honor is divided
6147 ///An exact honor value can also be given (overriding the calcs)
6148 bool Player::RewardHonor(Unit
*uVictim
, uint32 groupsize
, float honor
)
6150 // do not reward honor in arenas, but enable onkill spellproc
6153 if(!uVictim
|| uVictim
== this || uVictim
->GetTypeId() != TYPEID_PLAYER
)
6156 if( GetBGTeam() == ((Player
*)uVictim
)->GetBGTeam() )
6162 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
6163 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE
))
6166 uint64 victim_guid
= 0;
6167 uint32 victim_rank
= 0;
6169 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
6170 UpdateHonorFields();
6174 if(!uVictim
|| uVictim
== this || uVictim
->HasAuraType(SPELL_AURA_NO_PVP_CREDIT
))
6177 victim_guid
= uVictim
->GetGUID();
6179 if( uVictim
->GetTypeId() == TYPEID_PLAYER
)
6181 Player
*pVictim
= (Player
*)uVictim
;
6183 if( GetTeam() == pVictim
->GetTeam() && !sWorld
.IsFFAPvPRealm() )
6186 float f
= 1; //need for total kills (?? need more info)
6188 uint32 k_level
= getLevel();
6189 uint32 v_level
= pVictim
->getLevel();
6192 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6194 // [1..14] Alliance honor titles and player name
6195 // [15..28] Horde honor titles and player name
6196 // [29..38] Other title and player name
6198 uint32 victim_title
= pVictim
->GetUInt32Value(PLAYER_CHOSEN_TITLE
);
6199 // Get Killer titles, CharTitlesEntry::bit_index
6201 // title[1..14] -> rank[5..18]
6202 // title[15..28] -> rank[5..18]
6203 // title[other] -> 0
6204 if (victim_title
== 0)
6205 victim_guid
= 0; // Don't show HK: <rank> message, only log.
6206 else if (victim_title
< 15)
6207 victim_rank
= victim_title
+ 4;
6208 else if (victim_title
< 29)
6209 victim_rank
= victim_title
- 14 + 4;
6211 victim_guid
= 0; // Don't show HK: <rank> message, only log.
6214 k_grey
= MaNGOS::XP::GetGrayLevel(k_level
);
6219 float diff_level
= (k_level
== k_grey
) ? 1 : ((float(v_level
) - float(k_grey
)) / (float(k_level
) - float(k_grey
)));
6221 int32 v_rank
=1; //need more info
6223 honor
= ((f
* diff_level
* (190 + v_rank
*10))/6);
6224 honor
*= ((float)k_level
) / 70.0f
; //factor of dependence on levels of the killer
6226 // count the number of playerkills in one day
6227 ApplyModUInt32Value(PLAYER_FIELD_KILLS
, 1, true);
6228 // and those in a lifetime
6229 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 1, true);
6233 Creature
*cVictim
= (Creature
*)uVictim
;
6235 if (!cVictim
->isRacialLeader())
6238 honor
= 100; // ??? need more info
6239 victim_rank
= 19; // HK: Leader
6243 if (uVictim
!= NULL
)
6245 honor
*= sWorld
.getRate(RATE_HONOR
);
6250 honor
*= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6253 // honor - for show honor points in log
6254 // victim_guid - for show victim name in log
6255 // victim_rank [1..4] HK: <dishonored rank>
6256 // victim_rank [5..19] HK: <alliance\horde rank>
6257 // victim_rank [0,20+] HK: <>
6258 WorldPacket
data(SMSG_PVP_CREDIT
,4+8+4);
6259 data
<< (uint32
) honor
;
6260 data
<< (uint64
) victim_guid
;
6261 data
<< (uint32
) victim_rank
;
6263 GetSession()->SendPacket(&data
);
6266 ModifyHonorPoints(int32(honor
));
6268 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, uint32(honor
), true);
6272 void Player::ModifyHonorPoints( int32 value
)
6276 if (GetHonorPoints() > sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
))
6277 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) + value
);
6279 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() > uint32(-value
) ? GetHonorPoints() + value
: 0);
6282 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() < sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) - value
? GetHonorPoints() + value
: sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
));
6285 void Player::ModifyArenaPoints( int32 value
)
6289 if (GetArenaPoints() > sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
))
6290 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) + value
);
6292 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() > uint32(-value
) ? GetArenaPoints() + value
: 0);
6295 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() < sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) - value
? GetArenaPoints() + value
: sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
));
6298 uint32
Player::GetGuildIdFromDB(uint64 guid
)
6300 QueryResult
* result
= CharacterDatabase
.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid
));
6304 uint32 id
= result
->Fetch()[0].GetUInt32();
6309 uint32
Player::GetRankFromDB(uint64 guid
)
6311 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid
) );
6314 uint32 v
= result
->Fetch()[0].GetUInt32();
6322 uint32
Player::GetArenaTeamIdFromDB(uint64 guid
, uint8 type
)
6324 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
);
6328 uint32 id
= (*result
)[0].GetUInt32();
6333 uint32
Player::GetZoneIdFromDB(uint64 guid
)
6335 uint32 guidLow
= GUID_LOPART(guid
);
6336 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow
);
6339 Field
* fields
= result
->Fetch();
6340 uint32 zone
= fields
[0].GetUInt32();
6345 // stored zone is zero, use generic and slow zone detection
6346 result
= CharacterDatabase
.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow
);
6349 fields
= result
->Fetch();
6350 uint32 map
= fields
[0].GetUInt32();
6351 float posx
= fields
[1].GetFloat();
6352 float posy
= fields
[2].GetFloat();
6353 float posz
= fields
[3].GetFloat();
6356 zone
= MapManager::Instance().GetZoneId(map
,posx
,posy
,posz
);
6358 CharacterDatabase
.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone
, guidLow
);
6364 void Player::UpdateArea(uint32 newArea
)
6366 // FFA_PVP flags are area and not zone id dependent
6367 // so apply them accordingly
6368 m_areaUpdateId
= newArea
;
6370 AreaTableEntry
const* area
= GetAreaEntryByAreaID(newArea
);
6372 if(area
&& (area
->flags
& AREA_FLAG_ARENA
))
6375 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6379 // remove ffa flag only if not ffapvp realm
6380 // removal in sanctuaries and capitals is handled in zone update
6381 if(HasByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
) && !sWorld
.IsFFAPvPRealm())
6382 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6385 UpdateAreaDependentAuras(newArea
);
6388 void Player::UpdateZone(uint32 newZone
, uint32 newArea
)
6390 if(m_zoneUpdateId
!= newZone
)
6391 SendInitWorldStates(newZone
, newArea
); // only if really enters to new zone, not just area change, works strange...
6393 m_zoneUpdateId
= newZone
;
6394 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
6396 // zone changed, so area changed as well, update it
6397 UpdateArea(newArea
);
6399 AreaTableEntry
const* zone
= GetAreaEntryByAreaID(newZone
);
6403 if (sWorld
.getConfig(CONFIG_WEATHER
))
6405 Weather
*wth
= sWorld
.FindWeather(zone
->ID
);
6408 wth
->SendWeatherUpdateToPlayer(this);
6412 if(!sWorld
.AddWeather(zone
->ID
))
6414 // send fine weather packet to remove old zone's weather
6415 Weather::SendFineWeatherUpdateToPlayer(this);
6420 pvpInfo
.inHostileArea
=
6421 GetTeam() == ALLIANCE
&& zone
->team
== AREATEAM_HORDE
||
6422 GetTeam() == HORDE
&& zone
->team
== AREATEAM_ALLY
||
6423 sWorld
.IsPvPRealm() && zone
->team
== AREATEAM_NONE
||
6424 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6426 if(pvpInfo
.inHostileArea
) // in hostile area
6428 if(!IsPvP() || pvpInfo
.endTimer
!= 0)
6429 UpdatePvP(true, true);
6431 else // in friendly area
6433 if(IsPvP() && !HasFlag(PLAYER_FLAGS
,PLAYER_FLAGS_IN_PVP
) && pvpInfo
.endTimer
== 0)
6434 pvpInfo
.endTimer
= time(0); // start toggle-off
6437 if(zone
->flags
& AREA_FLAG_SANCTUARY
) // in sanctuary
6439 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_SANCTUARY
);
6440 if(sWorld
.IsFFAPvPRealm())
6441 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6445 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_SANCTUARY
);
6448 if(zone
->flags
& AREA_FLAG_CAPITAL
) // in capital city
6450 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6451 SetRestType(REST_TYPE_IN_CITY
);
6452 InnEnter(time(0),GetMapId(),0,0,0);
6454 if(sWorld
.IsFFAPvPRealm())
6455 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6457 else // anywhere else
6459 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6461 if(GetRestType()==REST_TYPE_IN_TAVERN
) // has been in tavern. Is still in?
6463 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6465 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6466 SetRestType(REST_TYPE_NO
);
6468 if(sWorld
.IsFFAPvPRealm())
6469 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6472 else // not in tavern (leave city then)
6474 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6475 SetRestType(REST_TYPE_NO
);
6477 // Set player to FFA PVP when not in rested environment.
6478 if(sWorld
.IsFFAPvPRealm())
6479 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6484 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6485 // if player resurrected at teleport this will be applied in resurrect code
6487 DestroyZoneLimitedItem( true, newZone
);
6489 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6490 AutoUnequipOffhandIfNeed();
6492 // recent client version not send leave/join channel packets for built-in local channels
6493 UpdateLocalChannels( newZone
);
6497 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE
);
6499 UpdateZoneDependentAuras(newZone
);
6502 //If players are too far way of duel flag... then player loose the duel
6503 void Player::CheckDuelDistance(time_t currTime
)
6508 uint64 duelFlagGUID
= GetUInt64Value(PLAYER_DUEL_ARBITER
);
6509 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, duelFlagGUID
);
6513 if(duel
->outOfBound
== 0)
6515 if(!IsWithinDistInMap(obj
, 50))
6517 duel
->outOfBound
= currTime
;
6519 WorldPacket
data(SMSG_DUEL_OUTOFBOUNDS
, 0);
6520 GetSession()->SendPacket(&data
);
6525 if(IsWithinDistInMap(obj
, 40))
6527 duel
->outOfBound
= 0;
6529 WorldPacket
data(SMSG_DUEL_INBOUNDS
, 0);
6530 GetSession()->SendPacket(&data
);
6532 else if(currTime
>= (duel
->outOfBound
+10))
6534 DuelComplete(DUEL_FLED
);
6539 void Player::DuelComplete(DuelCompleteType type
)
6541 // duel not requested
6545 WorldPacket
data(SMSG_DUEL_COMPLETE
, (1));
6546 data
<< (uint8
)((type
!= DUEL_INTERUPTED
) ? 1 : 0);
6547 GetSession()->SendPacket(&data
);
6548 duel
->opponent
->GetSession()->SendPacket(&data
);
6550 if(type
!= DUEL_INTERUPTED
)
6552 data
.Initialize(SMSG_DUEL_WINNER
, (1+20)); // we guess size
6553 data
<< (uint8
)((type
==DUEL_WON
) ? 0 : 1); // 0 = just won; 1 = fled
6554 data
<< duel
->opponent
->GetName();
6556 SendMessageToSet(&data
,true);
6559 // cool-down duel spell
6560 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6567 GetSession()->SendPacket(&data);
6568 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6569 data<<duel->opponent->GetGUID();
6573 duel->opponent->GetSession()->SendPacket(&data);*/
6575 //Remove Duel Flag object
6576 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER
));
6578 duel
->initiator
->RemoveGameObject(obj
,true);
6581 std::vector
<uint32
> auras2remove
;
6582 AuraMap
const& vAuras
= duel
->opponent
->GetAuras();
6583 for (AuraMap::const_iterator i
= vAuras
.begin(); i
!= vAuras
.end(); ++i
)
6585 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6586 auras2remove
.push_back(i
->second
->GetId());
6589 for(size_t i
=0; i
<auras2remove
.size(); i
++)
6590 duel
->opponent
->RemoveAurasDueToSpell(auras2remove
[i
]);
6592 auras2remove
.clear();
6593 AuraMap
const& auras
= GetAuras();
6594 for (AuraMap::const_iterator i
= auras
.begin(); i
!= auras
.end(); ++i
)
6596 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == duel
->opponent
->GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6597 auras2remove
.push_back(i
->second
->GetId());
6599 for(size_t i
=0; i
<auras2remove
.size(); i
++)
6600 RemoveAurasDueToSpell(auras2remove
[i
]);
6602 // cleanup combo points
6603 if(GetComboTarget()==duel
->opponent
->GetGUID())
6605 else if(GetComboTarget()==duel
->opponent
->GetPetGUID())
6608 if(duel
->opponent
->GetComboTarget()==GetGUID())
6609 duel
->opponent
->ClearComboPoints();
6610 else if(duel
->opponent
->GetComboTarget()==GetPetGUID())
6611 duel
->opponent
->ClearComboPoints();
6614 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6615 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6616 duel
->opponent
->SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6617 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6619 delete duel
->opponent
->duel
;
6620 duel
->opponent
->duel
= NULL
;
6625 //---------------------------------------------------------//
6627 void Player::_ApplyItemMods(Item
*item
, uint8 slot
,bool apply
)
6629 if(slot
>= INVENTORY_SLOT_BAG_END
|| !item
)
6632 // not apply/remove mods for broken item
6633 if(item
->IsBroken())
6636 ItemPrototype
const *proto
= item
->GetProto();
6641 sLog
.outDetail("applying mods for item %u ",item
->GetGUIDLow());
6643 uint32 attacktype
= Player::GetAttackBySlot(slot
);
6644 if(attacktype
< MAX_ATTACK
)
6645 _ApplyWeaponDependentAuraMods(item
,WeaponAttackType(attacktype
),apply
);
6647 _ApplyItemBonuses(proto
,slot
,apply
);
6649 if( slot
==EQUIPMENT_SLOT_RANGED
)
6650 _ApplyAmmoBonuses();
6652 ApplyItemEquipSpell(item
,apply
);
6653 ApplyEnchantment(item
, apply
);
6655 if(proto
->Socket
[0].Color
) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6656 CorrectMetaGemEnchants(slot
, apply
);
6658 sLog
.outDebug("_ApplyItemMods complete.");
6661 void Player::_ApplyItemBonuses(ItemPrototype
const *proto
, uint8 slot
, bool apply
)
6663 if(slot
>= INVENTORY_SLOT_BAG_END
|| !proto
)
6666 for (int i
= 0; i
< MAX_ITEM_PROTO_STATS
; ++i
)
6668 uint32 statType
= 0;
6671 if(proto
->ScalingStatDistribution
)
6673 if(ScalingStatDistributionEntry
const *ssd
= sScalingStatDistributionStore
.LookupEntry(proto
->ScalingStatDistribution
))
6675 statType
= ssd
->StatMod
[i
];
6677 if(uint32 modifier
= ssd
->Modifier
[i
])
6679 uint32 level
= ((getLevel() > ssd
->MaxLevel
) ? ssd
->MaxLevel
: getLevel());
6680 if(ScalingStatValuesEntry
const *ssv
= sScalingStatValuesStore
.LookupEntry(level
))
6682 uint32 multiplier
= ssv
->Multiplier
[proto
->GetScalingStatValuesColumn()];
6683 val
= (multiplier
* modifier
) / 10000;
6690 statType
= proto
->ItemStat
[i
].ItemStatType
;
6691 val
= proto
->ItemStat
[i
].ItemStatValue
;
6700 HandleStatModifier(UNIT_MOD_MANA
, BASE_VALUE
, float(val
), apply
);
6702 case ITEM_MOD_HEALTH
: // modify HP
6703 HandleStatModifier(UNIT_MOD_HEALTH
, BASE_VALUE
, float(val
), apply
);
6705 case ITEM_MOD_AGILITY
: // modify agility
6706 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, BASE_VALUE
, float(val
), apply
);
6707 ApplyStatBuffMod(STAT_AGILITY
, float(val
), apply
);
6709 case ITEM_MOD_STRENGTH
: //modify strength
6710 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, BASE_VALUE
, float(val
), apply
);
6711 ApplyStatBuffMod(STAT_STRENGTH
, float(val
), apply
);
6713 case ITEM_MOD_INTELLECT
: //modify intellect
6714 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, BASE_VALUE
, float(val
), apply
);
6715 ApplyStatBuffMod(STAT_INTELLECT
, float(val
), apply
);
6717 case ITEM_MOD_SPIRIT
: //modify spirit
6718 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, BASE_VALUE
, float(val
), apply
);
6719 ApplyStatBuffMod(STAT_SPIRIT
, float(val
), apply
);
6721 case ITEM_MOD_STAMINA
: //modify stamina
6722 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, BASE_VALUE
, float(val
), apply
);
6723 ApplyStatBuffMod(STAT_STAMINA
, float(val
), apply
);
6725 case ITEM_MOD_DEFENSE_SKILL_RATING
:
6726 ApplyRatingMod(CR_DEFENSE_SKILL
, int32(val
), apply
);
6728 case ITEM_MOD_DODGE_RATING
:
6729 ApplyRatingMod(CR_DODGE
, int32(val
), apply
);
6731 case ITEM_MOD_PARRY_RATING
:
6732 ApplyRatingMod(CR_PARRY
, int32(val
), apply
);
6734 case ITEM_MOD_BLOCK_RATING
:
6735 ApplyRatingMod(CR_BLOCK
, int32(val
), apply
);
6737 case ITEM_MOD_HIT_MELEE_RATING
:
6738 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6740 case ITEM_MOD_HIT_RANGED_RATING
:
6741 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6743 case ITEM_MOD_HIT_SPELL_RATING
:
6744 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6746 case ITEM_MOD_CRIT_MELEE_RATING
:
6747 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6749 case ITEM_MOD_CRIT_RANGED_RATING
:
6750 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6752 case ITEM_MOD_CRIT_SPELL_RATING
:
6753 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6755 case ITEM_MOD_HIT_TAKEN_MELEE_RATING
:
6756 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6758 case ITEM_MOD_HIT_TAKEN_RANGED_RATING
:
6759 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6761 case ITEM_MOD_HIT_TAKEN_SPELL_RATING
:
6762 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6764 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING
:
6765 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6767 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING
:
6768 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6770 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING
:
6771 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6773 case ITEM_MOD_HASTE_MELEE_RATING
:
6774 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6776 case ITEM_MOD_HASTE_RANGED_RATING
:
6777 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6779 case ITEM_MOD_HASTE_SPELL_RATING
:
6780 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6782 case ITEM_MOD_HIT_RATING
:
6783 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6784 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6785 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6787 case ITEM_MOD_CRIT_RATING
:
6788 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6789 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6790 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6792 case ITEM_MOD_HIT_TAKEN_RATING
:
6793 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6794 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6795 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6797 case ITEM_MOD_CRIT_TAKEN_RATING
:
6798 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6799 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6800 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6802 case ITEM_MOD_RESILIENCE_RATING
:
6803 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6804 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6805 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6807 case ITEM_MOD_HASTE_RATING
:
6808 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6809 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6810 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6812 case ITEM_MOD_EXPERTISE_RATING
:
6813 ApplyRatingMod(CR_EXPERTISE
, int32(val
), apply
);
6815 case ITEM_MOD_ATTACK_POWER
:
6816 HandleStatModifier(UNIT_MOD_ATTACK_POWER
, TOTAL_VALUE
, float(val
), apply
);
6817 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(val
), apply
);
6819 case ITEM_MOD_RANGED_ATTACK_POWER
:
6820 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(val
), apply
);
6822 case ITEM_MOD_FERAL_ATTACK_POWER
:
6823 ApplyFeralAPBonus(int32(val
), apply
);
6825 case ITEM_MOD_SPELL_HEALING_DONE
:
6826 ApplySpellHealingBonus(int32(val
), apply
);
6828 case ITEM_MOD_SPELL_DAMAGE_DONE
:
6829 ApplySpellDamageBonus(int32(val
), apply
);
6831 case ITEM_MOD_MANA_REGENERATION
:
6832 ApplyManaRegenBonus(int32(val
), apply
);
6834 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
6835 ApplyRatingMod(CR_ARMOR_PENETRATION
, int32(val
), apply
);
6837 case ITEM_MOD_SPELL_POWER
:
6838 ApplySpellHealingBonus(int32(val
), apply
);
6839 ApplySpellDamageBonus(int32(val
), apply
);
6845 HandleStatModifier(UNIT_MOD_ARMOR
, BASE_VALUE
, float(proto
->Armor
), apply
);
6848 HandleBaseModValue(SHIELD_BLOCK_VALUE
, FLAT_MOD
, float(proto
->Block
), apply
);
6851 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY
, BASE_VALUE
, float(proto
->HolyRes
), apply
);
6854 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE
, BASE_VALUE
, float(proto
->FireRes
), apply
);
6856 if (proto
->NatureRes
)
6857 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE
, BASE_VALUE
, float(proto
->NatureRes
), apply
);
6859 if (proto
->FrostRes
)
6860 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST
, BASE_VALUE
, float(proto
->FrostRes
), apply
);
6862 if (proto
->ShadowRes
)
6863 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW
, BASE_VALUE
, float(proto
->ShadowRes
), apply
);
6865 if (proto
->ArcaneRes
)
6866 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE
, BASE_VALUE
, float(proto
->ArcaneRes
), apply
);
6868 WeaponAttackType attType
= BASE_ATTACK
;
6869 float damage
= 0.0f
;
6871 if( slot
== EQUIPMENT_SLOT_RANGED
&& (
6872 proto
->InventoryType
== INVTYPE_RANGED
|| proto
->InventoryType
== INVTYPE_THROWN
||
6873 proto
->InventoryType
== INVTYPE_RANGEDRIGHT
))
6875 attType
= RANGED_ATTACK
;
6877 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6879 attType
= OFF_ATTACK
;
6882 if (proto
->Damage
[0].DamageMin
> 0 )
6884 damage
= apply
? proto
->Damage
[0].DamageMin
: BASE_MINDAMAGE
;
6885 SetBaseWeaponDamage(attType
, MINDAMAGE
, damage
);
6886 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6889 if (proto
->Damage
[0].DamageMax
> 0 )
6891 damage
= apply
? proto
->Damage
[0].DamageMax
: BASE_MAXDAMAGE
;
6892 SetBaseWeaponDamage(attType
, MAXDAMAGE
, damage
);
6895 // Druids get feral AP bonus from weapon dps
6896 if(getClass() == CLASS_DRUID
)
6898 int32 feral_bonus
= proto
->getFeralBonus();
6899 if (feral_bonus
> 0)
6900 ApplyFeralAPBonus(feral_bonus
, apply
);
6903 if(!IsUseEquipedWeapon(slot
==EQUIPMENT_SLOT_MAINHAND
))
6908 if(slot
== EQUIPMENT_SLOT_RANGED
)
6909 SetAttackTime(RANGED_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6910 else if(slot
==EQUIPMENT_SLOT_MAINHAND
)
6911 SetAttackTime(BASE_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6912 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6913 SetAttackTime(OFF_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6916 if(CanModifyStats() && (damage
|| proto
->Delay
))
6917 UpdateDamagePhysical(attType
);
6920 void Player::_ApplyWeaponDependentAuraMods(Item
*item
,WeaponAttackType attackType
,bool apply
)
6922 AuraList
const& auraCritList
= GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT
);
6923 for(AuraList::const_iterator itr
= auraCritList
.begin(); itr
!=auraCritList
.end();++itr
)
6924 _ApplyWeaponDependentAuraCritMod(item
,attackType
,*itr
,apply
);
6926 AuraList
const& auraDamageFlatList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE
);
6927 for(AuraList::const_iterator itr
= auraDamageFlatList
.begin(); itr
!=auraDamageFlatList
.end();++itr
)
6928 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6930 AuraList
const& auraDamagePCTList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
);
6931 for(AuraList::const_iterator itr
= auraDamagePCTList
.begin(); itr
!=auraDamagePCTList
.end();++itr
)
6932 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6935 void Player::_ApplyWeaponDependentAuraCritMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6937 // generic not weapon specific case processes in aura code
6938 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6941 BaseModGroup mod
= BASEMOD_END
;
6944 case BASE_ATTACK
: mod
= CRIT_PERCENTAGE
; break;
6945 case OFF_ATTACK
: mod
= OFFHAND_CRIT_PERCENTAGE
;break;
6946 case RANGED_ATTACK
: mod
= RANGED_CRIT_PERCENTAGE
; break;
6950 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6952 HandleBaseModValue(mod
, FLAT_MOD
, float (aura
->GetModifier()->m_amount
), apply
);
6956 void Player::_ApplyWeaponDependentAuraDamageMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6958 // ignore spell mods for not wands
6959 Modifier
const* modifier
= aura
->GetModifier();
6960 if((modifier
->m_miscvalue
& SPELL_SCHOOL_MASK_NORMAL
)==0 && (getClassMask() & CLASSMASK_WAND_USERS
)==0)
6963 // generic not weapon specific case processes in aura code
6964 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6967 UnitMods unitMod
= UNIT_MOD_END
;
6970 case BASE_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_MAINHAND
; break;
6971 case OFF_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_OFFHAND
; break;
6972 case RANGED_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_RANGED
; break;
6976 UnitModifierType unitModType
= TOTAL_VALUE
;
6977 switch(modifier
->m_auraname
)
6979 case SPELL_AURA_MOD_DAMAGE_DONE
: unitModType
= TOTAL_VALUE
; break;
6980 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
: unitModType
= TOTAL_PCT
; break;
6984 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6986 HandleStatModifier(unitMod
, unitModType
, float(modifier
->m_amount
),apply
);
6990 void Player::ApplyItemEquipSpell(Item
*item
, bool apply
, bool form_change
)
6995 ItemPrototype
const *proto
= item
->GetProto();
6999 for (int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
7001 _Spell
const& spellData
= proto
->Spells
[i
];
7004 if(!spellData
.SpellId
)
7007 // wrong triggering type
7008 if(apply
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_EQUIP
)
7011 // check if it is valid spell
7012 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellData
.SpellId
);
7016 ApplyEquipSpell(spellproto
,item
,apply
,form_change
);
7020 void Player::ApplyEquipSpell(SpellEntry
const* spellInfo
, Item
* item
, bool apply
, bool form_change
)
7024 // Cannot be used in this stance/form
7025 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
) != SPELL_CAST_OK
)
7028 if(form_change
) // check aura active state from other form
7031 for (int k
=0; k
< 3; ++k
)
7033 spellEffectPair spair
= spellEffectPair(spellInfo
->Id
, k
);
7034 for (AuraMap::iterator iter
= m_Auras
.lower_bound(spair
); iter
!= m_Auras
.upper_bound(spair
); ++iter
)
7036 if(!item
|| iter
->second
->GetCastItemGUID() == item
->GetGUID())
7046 if(found
) // and skip re-cast already active aura at form change
7050 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item
? "item" : "itemset"), spellInfo
->Id
);
7052 CastSpell(this,spellInfo
,true,item
);
7056 if(form_change
) // check aura compatibility
7058 // Cannot be used in this stance/form
7059 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
)==SPELL_CAST_OK
)
7060 return; // and remove only not compatible at form change
7064 RemoveAurasDueToItemSpell(item
,spellInfo
->Id
); // un-apply all spells , not only at-equipped
7066 RemoveAurasDueToSpell(spellInfo
->Id
); // un-apply spell (item set case)
7070 void Player::UpdateEquipSpellsAtFormChange()
7072 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
7074 if(m_items
[i
] && !m_items
[i
]->IsBroken())
7076 ApplyItemEquipSpell(m_items
[i
],false,true); // remove spells that not fit to form
7077 ApplyItemEquipSpell(m_items
[i
],true,true); // add spells that fit form but not active
7081 // item set bonuses not dependent from item broken state
7082 for(size_t setindex
= 0; setindex
< ItemSetEff
.size(); ++setindex
)
7084 ItemSetEffect
* eff
= ItemSetEff
[setindex
];
7088 for(uint32 y
=0;y
<8; ++y
)
7090 SpellEntry
const* spellInfo
= eff
->spells
[y
];
7094 ApplyEquipSpell(spellInfo
,NULL
,false,true); // remove spells that not fit to form
7095 ApplyEquipSpell(spellInfo
,NULL
,true,true); // add spells that fit form but not active
7100 void Player::CastItemCombatSpell(Item
*item
,Unit
* Target
, WeaponAttackType attType
)
7102 if(!item
|| item
->IsBroken())
7105 ItemPrototype
const *proto
= item
->GetProto();
7109 if (!Target
|| Target
== this )
7112 for (int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
7114 _Spell
const& spellData
= proto
->Spells
[i
];
7117 if(!spellData
.SpellId
)
7120 // wrong triggering type
7121 if(spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_CHANCE_ON_HIT
)
7124 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
7127 sLog
.outError("WORLD: unknown Item spellid %i", spellData
.SpellId
);
7131 // not allow proc extra attack spell at extra attack
7132 if( m_extraAttacks
&& IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_ADD_EXTRA_ATTACKS
) )
7135 float chance
= spellInfo
->procChance
;
7137 if(spellData
.SpellPPMRate
)
7139 uint32 WeaponSpeed
= GetAttackTime(attType
);
7140 chance
= GetPPMProcChance(WeaponSpeed
, spellData
.SpellPPMRate
);
7142 else if(chance
> 100.0f
)
7144 chance
= GetWeaponProcChance();
7147 if (roll_chance_f(chance
))
7148 CastSpell(Target
, spellInfo
->Id
, true, item
);
7151 // item combat enchantments
7152 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
7154 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
7155 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
7156 if(!pEnchant
) continue;
7157 for (int s
=0;s
<3;s
++)
7159 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
)
7162 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
7165 sLog
.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
7169 float chance
= pEnchant
->amount
[s
] != 0 ? float(pEnchant
->amount
[s
]) : GetWeaponProcChance();
7170 if (roll_chance_f(chance
))
7172 if(IsPositiveSpell(pEnchant
->spellid
[s
]))
7173 CastSpell(this, pEnchant
->spellid
[s
], true, item
);
7175 CastSpell(Target
, pEnchant
->spellid
[s
], true, item
);
7181 void Player::CastItemUseSpell(Item
*item
,SpellCastTargets
const& targets
,uint8 cast_count
, uint32 glyphIndex
)
7183 ItemPrototype
const* proto
= item
->GetProto();
7184 // special learning case
7185 if(proto
->Spells
[0].SpellId
==SPELL_ID_GENERIC_LEARN
|| proto
->Spells
[0].SpellId
==SPELL_ID_GENERIC_LEARN_PET
)
7187 uint32 learn_spell_id
= proto
->Spells
[0].SpellId
;
7188 uint32 learning_spell_id
= proto
->Spells
[1].SpellId
;
7190 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(learn_spell_id
);
7193 sLog
.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto
->ItemId
, learn_spell_id
);
7194 SendEquipError(EQUIP_ERR_NONE
,item
,NULL
);
7198 Spell
*spell
= new Spell(this, spellInfo
, false);
7199 spell
->m_CastItem
= item
;
7200 spell
->m_cast_count
= cast_count
; //set count of casts
7201 spell
->m_currentBasePoints
[0] = learning_spell_id
;
7202 spell
->prepare(&targets
);
7206 // use triggered flag only for items with many spell casts and for not first cast
7209 // item spells casted at use
7210 for(int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
7212 _Spell
const& spellData
= proto
->Spells
[i
];
7215 if(!spellData
.SpellId
)
7218 // wrong triggering type
7219 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_NO_DELAY_USE
)
7222 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
7225 sLog
.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto
->ItemId
, spellData
.SpellId
);
7229 Spell
*spell
= new Spell(this, spellInfo
, (count
> 0));
7230 spell
->m_CastItem
= item
;
7231 spell
->m_cast_count
= cast_count
; // set count of casts
7232 spell
->m_glyphIndex
= glyphIndex
; // glyph index
7233 spell
->prepare(&targets
);
7238 // Item enchantments spells casted at use
7239 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
7241 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
7242 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
7243 if(!pEnchant
) continue;
7244 for (int s
=0;s
<3;s
++)
7246 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL
)
7249 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
7252 sLog
.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
7256 Spell
*spell
= new Spell(this, spellInfo
, (count
> 0));
7257 spell
->m_CastItem
= item
;
7258 spell
->m_cast_count
= cast_count
; // set count of casts
7259 spell
->m_glyphIndex
= glyphIndex
; // glyph index
7260 spell
->prepare(&targets
);
7267 void Player::_RemoveAllItemMods()
7269 sLog
.outDebug("_RemoveAllItemMods start.");
7271 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
7275 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7279 // item set bonuses not dependent from item broken state
7281 RemoveItemsSetItem(this,proto
);
7283 if(m_items
[i
]->IsBroken())
7286 ApplyItemEquipSpell(m_items
[i
],false);
7287 ApplyEnchantment(m_items
[i
], false);
7291 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
7295 if(m_items
[i
]->IsBroken())
7297 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7301 uint32 attacktype
= Player::GetAttackBySlot(i
);
7302 if(attacktype
< MAX_ATTACK
)
7303 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),false);
7305 _ApplyItemBonuses(proto
,i
, false);
7307 if( i
== EQUIPMENT_SLOT_RANGED
)
7308 _ApplyAmmoBonuses();
7312 sLog
.outDebug("_RemoveAllItemMods complete.");
7315 void Player::_ApplyAllItemMods()
7317 sLog
.outDebug("_ApplyAllItemMods start.");
7319 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
7323 if(m_items
[i
]->IsBroken())
7326 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7330 uint32 attacktype
= Player::GetAttackBySlot(i
);
7331 if(attacktype
< MAX_ATTACK
)
7332 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),true);
7334 _ApplyItemBonuses(proto
,i
, true);
7336 if( i
== EQUIPMENT_SLOT_RANGED
)
7337 _ApplyAmmoBonuses();
7341 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
7345 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7349 // item set bonuses not dependent from item broken state
7351 AddItemsSetItem(this,m_items
[i
]);
7353 if(m_items
[i
]->IsBroken())
7356 ApplyItemEquipSpell(m_items
[i
],true);
7357 ApplyEnchantment(m_items
[i
], true);
7361 sLog
.outDebug("_ApplyAllItemMods complete.");
7364 void Player::_ApplyAmmoBonuses()
7367 uint32 ammo_id
= GetUInt32Value(PLAYER_AMMO_ID
);
7371 float currentAmmoDPS
;
7373 ItemPrototype
const *ammo_proto
= objmgr
.GetItemPrototype( ammo_id
);
7374 if( !ammo_proto
|| ammo_proto
->Class
!=ITEM_CLASS_PROJECTILE
|| !CheckAmmoCompatibility(ammo_proto
))
7375 currentAmmoDPS
= 0.0f
;
7377 currentAmmoDPS
= ammo_proto
->Damage
[0].DamageMin
;
7379 if(currentAmmoDPS
== GetAmmoDPS())
7382 m_ammoDPS
= currentAmmoDPS
;
7384 if(CanModifyStats())
7385 UpdateDamagePhysical(RANGED_ATTACK
);
7388 bool Player::CheckAmmoCompatibility(const ItemPrototype
*ammo_proto
) const
7393 // check ranged weapon
7394 Item
*weapon
= GetWeaponForAttack( RANGED_ATTACK
);
7395 if(!weapon
|| weapon
->IsBroken() )
7398 ItemPrototype
const* weapon_proto
= weapon
->GetProto();
7399 if(!weapon_proto
|| weapon_proto
->Class
!=ITEM_CLASS_WEAPON
)
7402 // check ammo ws. weapon compatibility
7403 switch(weapon_proto
->SubClass
)
7405 case ITEM_SUBCLASS_WEAPON_BOW
:
7406 case ITEM_SUBCLASS_WEAPON_CROSSBOW
:
7407 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_ARROW
)
7410 case ITEM_SUBCLASS_WEAPON_GUN
:
7411 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_BULLET
)
7421 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7422 Called by remove insignia spell effect */
7423 void Player::RemovedInsignia(Player
* looterPlr
)
7425 if (!GetBattleGroundId())
7428 // If not released spirit, do it !
7429 if(m_deathTimer
> 0)
7436 Corpse
*corpse
= GetCorpse();
7440 // We have to convert player corpse to bones, not to be able to resurrect there
7441 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7442 Corpse
*bones
= ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7446 // Now we must make bones lootable, and send player loot
7447 bones
->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS
, CORPSE_DYNFLAG_LOOTABLE
);
7449 // We store the level of our player in the gold field
7450 // We retrieve this information at Player::SendLoot()
7451 bones
->loot
.gold
= getLevel();
7452 bones
->lootRecipient
= looterPlr
;
7453 looterPlr
->SendLoot(bones
->GetGUID(), LOOT_INSIGNIA
);
7462 void Player::SendLootRelease( uint64 guid
)
7464 WorldPacket
data( SMSG_LOOT_RELEASE_RESPONSE
, (8+1) );
7465 data
<< uint64(guid
) << uint8(1);
7466 SendDirectMessage( &data
);
7469 void Player::SendLoot(uint64 guid
, LootType loot_type
)
7471 if (uint64 lguid
= GetLootGUID())
7472 m_session
->DoLootRelease(lguid
);
7475 PermissionTypes permission
= ALL_PERMISSION
;
7477 sLog
.outDebug("Player::SendLoot");
7478 if (IS_GAMEOBJECT_GUID(guid
))
7480 sLog
.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7482 ObjectAccessor::GetGameObject(*this, guid
);
7484 // not check distance for GO in case owned GO (fishing bobber case, for example)
7485 // And permit out of range GO with no owner in case fishing hole
7486 if (!go
|| (loot_type
!= LOOT_FISHINGHOLE
&& (loot_type
!= LOOT_FISHING
|| go
->GetOwnerGUID() != GetGUID()) && !go
->IsWithinDistInMap(this,INTERACTION_DISTANCE
)))
7488 SendLootRelease(guid
);
7494 if(go
->getLootState() == GO_READY
)
7496 uint32 lootid
= go
->GetLootId();
7500 sLog
.outDebug(" if(lootid)");
7502 loot
->FillLoot(lootid
, LootTemplates_Gameobject
, this, false);
7505 if(loot_type
== LOOT_FISHING
)
7506 go
->getFishLoot(loot
,this);
7508 go
->SetLootState(GO_ACTIVATED
);
7511 else if (IS_ITEM_GUID(guid
))
7513 Item
*item
= GetItemByGuid( guid
);
7517 SendLootRelease(guid
);
7521 if(loot_type
== LOOT_DISENCHANTING
)
7525 if(!item
->m_lootGenerated
)
7527 item
->m_lootGenerated
= true;
7529 loot
->FillLoot(item
->GetProto()->DisenchantID
, LootTemplates_Disenchant
, this,true);
7532 else if(loot_type
== LOOT_PROSPECTING
)
7536 if(!item
->m_lootGenerated
)
7538 item
->m_lootGenerated
= true;
7540 loot
->FillLoot(item
->GetEntry(), LootTemplates_Prospecting
, this,true);
7543 else if(loot_type
== LOOT_MILLING
)
7547 if(!item
->m_lootGenerated
)
7549 item
->m_lootGenerated
= true;
7551 loot
->FillLoot(item
->GetEntry(), LootTemplates_Milling
, this,true);
7558 if(!item
->m_lootGenerated
)
7560 item
->m_lootGenerated
= true;
7562 loot
->FillLoot(item
->GetEntry(), LootTemplates_Item
, this,true);
7564 loot
->generateMoneyLoot(item
->GetProto()->MinMoneyLoot
,item
->GetProto()->MaxMoneyLoot
);
7568 else if (IS_CORPSE_GUID(guid
)) // remove insignia
7570 Corpse
*bones
= ObjectAccessor::GetCorpse(*this, guid
);
7572 if (!bones
|| !((loot_type
== LOOT_CORPSE
) || (loot_type
== LOOT_INSIGNIA
)) || (bones
->GetType() != CORPSE_BONES
) )
7574 SendLootRelease(guid
);
7578 loot
= &bones
->loot
;
7580 if (!bones
->lootForBody
)
7582 bones
->lootForBody
= true;
7583 uint32 pLevel
= bones
->loot
.gold
;
7584 bones
->loot
.clear();
7585 // It may need a better formula
7586 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7587 bones
->loot
.gold
= (uint32
)( urand(50, 150) * 0.016f
* pow( ((float)pLevel
)/5.76f
, 2.5f
) * sWorld
.getRate(RATE_DROP_MONEY
) );
7590 if (bones
->lootRecipient
!= this)
7591 permission
= NONE_PERMISSION
;
7595 Creature
*creature
= ObjectAccessor::GetCreature(*this, guid
);
7597 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7598 if (!creature
|| creature
->isAlive()!=(loot_type
== LOOT_PICKPOCKETING
) || !creature
->IsWithinDistInMap(this,INTERACTION_DISTANCE
))
7600 SendLootRelease(guid
);
7604 if(loot_type
== LOOT_PICKPOCKETING
&& IsFriendlyTo(creature
))
7606 SendLootRelease(guid
);
7610 loot
= &creature
->loot
;
7612 if(loot_type
== LOOT_PICKPOCKETING
)
7614 if ( !creature
->lootForPickPocketed
)
7616 creature
->lootForPickPocketed
= true;
7619 if (uint32 lootid
= creature
->GetCreatureInfo()->pickpocketLootId
)
7620 loot
->FillLoot(lootid
, LootTemplates_Pickpocketing
, this, false);
7622 // Generate extra money for pick pocket loot
7623 const uint32 a
= urand(0, creature
->getLevel()/2);
7624 const uint32 b
= urand(0, getLevel()/2);
7625 loot
->gold
= uint32(10 * (a
+ b
) * sWorld
.getRate(RATE_DROP_MONEY
));
7630 // the player whose group may loot the corpse
7631 Player
*recipient
= creature
->GetLootRecipient();
7634 creature
->SetLootRecipient(this);
7638 if (creature
->lootForPickPocketed
)
7640 creature
->lootForPickPocketed
= false;
7644 if(!creature
->lootForBody
)
7646 creature
->lootForBody
= true;
7649 if (uint32 lootid
= creature
->GetCreatureInfo()->lootid
)
7650 loot
->FillLoot(lootid
, LootTemplates_Creature
, recipient
, false);
7652 loot
->generateMoneyLoot(creature
->GetCreatureInfo()->mingold
,creature
->GetCreatureInfo()->maxgold
);
7654 if(Group
* group
= recipient
->GetGroup())
7656 group
->UpdateLooterGuid(creature
,true);
7658 switch (group
->GetLootMethod())
7661 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7662 group
->GroupLoot(recipient
->GetGUID(), loot
, creature
);
7664 case NEED_BEFORE_GREED
:
7665 group
->NeedBeforeGreed(recipient
->GetGUID(), loot
, creature
);
7668 group
->MasterLoot(recipient
->GetGUID(), loot
, creature
);
7676 // possible only if creature->lootForBody && loot->empty() at spell cast check
7677 if (loot_type
== LOOT_SKINNING
)
7680 loot
->FillLoot(creature
->GetCreatureInfo()->SkinLootId
, LootTemplates_Skinning
, this, false);
7682 // set group rights only for loot_type != LOOT_SKINNING
7685 if(Group
* group
= GetGroup())
7687 if( group
== recipient
->GetGroup() )
7689 if(group
->GetLootMethod() == FREE_FOR_ALL
)
7690 permission
= ALL_PERMISSION
;
7691 else if(group
->GetLooterGuid() == GetGUID())
7693 if(group
->GetLootMethod() == MASTER_LOOT
)
7694 permission
= MASTER_PERMISSION
;
7696 permission
= ALL_PERMISSION
;
7699 permission
= GROUP_PERMISSION
;
7702 permission
= NONE_PERMISSION
;
7704 else if(recipient
== this)
7705 permission
= ALL_PERMISSION
;
7707 permission
= NONE_PERMISSION
;
7714 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING, LOOT_INSIGNIA and LOOT_MILLING unsupported by client, sending LOOT_SKINNING instead
7715 if(loot_type
== LOOT_PICKPOCKETING
|| loot_type
== LOOT_DISENCHANTING
|| loot_type
== LOOT_PROSPECTING
|| loot_type
== LOOT_INSIGNIA
|| loot_type
== LOOT_MILLING
)
7716 loot_type
= LOOT_SKINNING
;
7718 if(loot_type
== LOOT_FISHINGHOLE
)
7719 loot_type
= LOOT_FISHING
;
7721 WorldPacket
data(SMSG_LOOT_RESPONSE
, (9+50)); // we guess size
7723 data
<< uint64(guid
);
7724 data
<< uint8(loot_type
);
7725 data
<< LootView(*loot
, this, permission
);
7727 SendDirectMessage(&data
);
7729 // add 'this' player as one of the players that are looting 'loot'
7730 if (permission
!= NONE_PERMISSION
)
7731 loot
->AddLooter(GetGUID());
7733 if ( loot_type
== LOOT_CORPSE
&& !IS_ITEM_GUID(guid
) )
7734 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_LOOTING
);
7737 void Player::SendNotifyLootMoneyRemoved()
7739 WorldPacket
data(SMSG_LOOT_CLEAR_MONEY
, 0);
7740 GetSession()->SendPacket( &data
);
7743 void Player::SendNotifyLootItemRemoved(uint8 lootSlot
)
7745 WorldPacket
data(SMSG_LOOT_REMOVED
, 1);
7746 data
<< uint8(lootSlot
);
7747 GetSession()->SendPacket( &data
);
7750 void Player::SendUpdateWorldState(uint32 Field
, uint32 Value
)
7752 WorldPacket
data(SMSG_UPDATE_WORLD_STATE
, 8);
7755 GetSession()->SendPacket(&data
);
7758 void Player::SendInitWorldStates(uint32 zoneid
, uint32 areaid
)
7760 // data depends on zoneid/mapid...
7761 BattleGround
* bg
= GetBattleGround();
7762 uint16 NumberOfFields
= 0;
7763 uint32 mapid
= GetMapId();
7765 sLog
.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid
, zoneid
);
7767 // may be exist better way to do this...
7790 NumberOfFields
= 41;
7793 NumberOfFields
= 15;
7796 NumberOfFields
= 83;
7799 NumberOfFields
= 16;
7803 NumberOfFields
= 40;
7806 NumberOfFields
= 27;
7809 NumberOfFields
= 39;
7812 NumberOfFields
= 38;
7815 NumberOfFields
= 37;
7820 NumberOfFields
= 11;
7823 NumberOfFields
= 11;
7826 NumberOfFields
= 12;
7830 WorldPacket
data(SMSG_INIT_WORLD_STATES
, (4+4+4+2+(NumberOfFields
*8)));
7831 data
<< uint32(mapid
); // mapid
7832 data
<< uint32(zoneid
); // zone id
7833 data
<< uint32(areaid
); // area id, new 2.1.0
7834 data
<< uint16(NumberOfFields
); // count of uint64 blocks
7835 data
<< uint32(0x8d8) << uint32(0x0); // 1
7836 data
<< uint32(0x8d7) << uint32(0x0); // 2
7837 data
<< uint32(0x8d6) << uint32(0x0); // 3
7838 data
<< uint32(0x8d5) << uint32(0x0); // 4
7839 data
<< uint32(0x8d4) << uint32(0x0); // 5
7840 data
<< uint32(0x8d3) << uint32(0x0); // 6
7841 // 7 1 - Arena season in progress, 0 - end of season
7842 data
<< uint32(0xC77) << uint32(sWorld
.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS
));
7843 // 8 Arena season id
7844 data
<< uint32(0xF3D) << uint32(sWorld
.getConfig(CONFIG_ARENA_SEASON_ID
));
7845 if(mapid
== 530) // Outland
7847 data
<< uint32(0x9bf) << uint32(0x0); // 7
7848 data
<< uint32(0x9bd) << uint32(0xF); // 8
7849 data
<< uint32(0x9bb) << uint32(0xF); // 9
7864 data
<< uint32(0x7ae) << uint32(0x1); // 7
7865 data
<< uint32(0x532) << uint32(0x1); // 8
7866 data
<< uint32(0x531) << uint32(0x0); // 9
7867 data
<< uint32(0x52e) << uint32(0x0); // 10
7868 data
<< uint32(0x571) << uint32(0x0); // 11
7869 data
<< uint32(0x570) << uint32(0x0); // 12
7870 data
<< uint32(0x567) << uint32(0x1); // 13
7871 data
<< uint32(0x566) << uint32(0x1); // 14
7872 data
<< uint32(0x550) << uint32(0x1); // 15
7873 data
<< uint32(0x544) << uint32(0x0); // 16
7874 data
<< uint32(0x536) << uint32(0x0); // 17
7875 data
<< uint32(0x535) << uint32(0x1); // 18
7876 data
<< uint32(0x518) << uint32(0x0); // 19
7877 data
<< uint32(0x517) << uint32(0x0); // 20
7878 data
<< uint32(0x574) << uint32(0x0); // 21
7879 data
<< uint32(0x573) << uint32(0x0); // 22
7880 data
<< uint32(0x572) << uint32(0x0); // 23
7881 data
<< uint32(0x56f) << uint32(0x0); // 24
7882 data
<< uint32(0x56e) << uint32(0x0); // 25
7883 data
<< uint32(0x56d) << uint32(0x0); // 26
7884 data
<< uint32(0x56c) << uint32(0x0); // 27
7885 data
<< uint32(0x56b) << uint32(0x0); // 28
7886 data
<< uint32(0x56a) << uint32(0x1); // 29
7887 data
<< uint32(0x569) << uint32(0x1); // 30
7888 data
<< uint32(0x568) << uint32(0x1); // 13
7889 data
<< uint32(0x565) << uint32(0x0); // 32
7890 data
<< uint32(0x564) << uint32(0x0); // 33
7891 data
<< uint32(0x563) << uint32(0x0); // 34
7892 data
<< uint32(0x562) << uint32(0x0); // 35
7893 data
<< uint32(0x561) << uint32(0x0); // 36
7894 data
<< uint32(0x560) << uint32(0x0); // 37
7895 data
<< uint32(0x55f) << uint32(0x0); // 38
7896 data
<< uint32(0x55e) << uint32(0x0); // 39
7897 data
<< uint32(0x55d) << uint32(0x0); // 40
7898 data
<< uint32(0x3c6) << uint32(0x4); // 41
7899 data
<< uint32(0x3c4) << uint32(0x6); // 42
7900 data
<< uint32(0x3c2) << uint32(0x4); // 43
7901 data
<< uint32(0x516) << uint32(0x1); // 44
7902 data
<< uint32(0x515) << uint32(0x0); // 45
7903 data
<< uint32(0x3b6) << uint32(0x6); // 46
7904 data
<< uint32(0x55c) << uint32(0x0); // 47
7905 data
<< uint32(0x55b) << uint32(0x0); // 48
7906 data
<< uint32(0x55a) << uint32(0x0); // 49
7907 data
<< uint32(0x559) << uint32(0x0); // 50
7908 data
<< uint32(0x558) << uint32(0x0); // 51
7909 data
<< uint32(0x557) << uint32(0x0); // 52
7910 data
<< uint32(0x556) << uint32(0x0); // 53
7911 data
<< uint32(0x555) << uint32(0x0); // 54
7912 data
<< uint32(0x554) << uint32(0x1); // 55
7913 data
<< uint32(0x553) << uint32(0x1); // 56
7914 data
<< uint32(0x552) << uint32(0x1); // 57
7915 data
<< uint32(0x551) << uint32(0x1); // 58
7916 data
<< uint32(0x54f) << uint32(0x0); // 59
7917 data
<< uint32(0x54e) << uint32(0x0); // 60
7918 data
<< uint32(0x54d) << uint32(0x1); // 61
7919 data
<< uint32(0x54c) << uint32(0x0); // 62
7920 data
<< uint32(0x54b) << uint32(0x0); // 63
7921 data
<< uint32(0x545) << uint32(0x0); // 64
7922 data
<< uint32(0x543) << uint32(0x1); // 65
7923 data
<< uint32(0x542) << uint32(0x0); // 66
7924 data
<< uint32(0x540) << uint32(0x0); // 67
7925 data
<< uint32(0x53f) << uint32(0x0); // 68
7926 data
<< uint32(0x53e) << uint32(0x0); // 69
7927 data
<< uint32(0x53d) << uint32(0x0); // 70
7928 data
<< uint32(0x53c) << uint32(0x0); // 71
7929 data
<< uint32(0x53b) << uint32(0x0); // 72
7930 data
<< uint32(0x53a) << uint32(0x1); // 73
7931 data
<< uint32(0x539) << uint32(0x0); // 74
7932 data
<< uint32(0x538) << uint32(0x0); // 75
7933 data
<< uint32(0x537) << uint32(0x0); // 76
7934 data
<< uint32(0x534) << uint32(0x0); // 77
7935 data
<< uint32(0x533) << uint32(0x0); // 78
7936 data
<< uint32(0x530) << uint32(0x0); // 79
7937 data
<< uint32(0x52f) << uint32(0x0); // 80
7938 data
<< uint32(0x52d) << uint32(0x1); // 81
7941 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_WS
)
7942 bg
->FillInitialWorldStates(data
);
7945 data
<< uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7946 data
<< uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7947 data
<< uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7948 data
<< uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7949 data
<< uint32(0x60b) << uint32(0x2); // 11 1547 unk
7950 data
<< uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7951 data
<< uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7952 data
<< uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7956 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_AB
)
7957 bg
->FillInitialWorldStates(data
);
7960 data
<< uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7961 data
<< uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7962 data
<< uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7963 data
<< uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7964 data
<< uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7965 data
<< uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7966 data
<< uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7967 data
<< uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7968 data
<< uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7969 data
<< uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7970 data
<< uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7971 data
<< uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7972 data
<< uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7973 data
<< uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7974 data
<< uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7975 data
<< uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7976 data
<< uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7977 data
<< uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7978 data
<< uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7979 data
<< uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7980 data
<< uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7981 data
<< uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7982 data
<< uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7983 data
<< uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7984 data
<< uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7985 data
<< uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7986 data
<< uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7987 data
<< uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7988 data
<< uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7989 data
<< uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7990 data
<< uint32(0x745) << uint32(0x2); // 37 1861 unk
7991 data
<< uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7995 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_EY
)
7996 bg
->FillInitialWorldStates(data
);
7999 data
<< uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
8000 data
<< uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
8001 data
<< uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
8002 data
<< uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
8003 data
<< uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
8004 data
<< uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
8005 data
<< uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
8006 data
<< uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
8007 data
<< uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
8008 data
<< uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
8009 data
<< uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
8010 data
<< uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
8011 data
<< uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
8012 data
<< uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
8013 data
<< uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
8014 data
<< uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
8015 data
<< uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
8016 data
<< uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
8017 data
<< uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
8018 data
<< uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
8019 data
<< uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
8020 data
<< uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
8021 data
<< uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
8022 data
<< uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
8023 data
<< uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
8024 data
<< uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
8025 data
<< uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
8026 data
<< uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
8027 data
<< uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
8028 data
<< uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
8029 data
<< uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
8030 data
<< uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
8031 // and some more ... unknown
8034 case 3483: // Hellfire Peninsula
8035 data
<< uint32(0x9ba) << uint32(0x1); // 10
8036 data
<< uint32(0x9b9) << uint32(0x1); // 11
8037 data
<< uint32(0x9b5) << uint32(0x0); // 12
8038 data
<< uint32(0x9b4) << uint32(0x1); // 13
8039 data
<< uint32(0x9b3) << uint32(0x0); // 14
8040 data
<< uint32(0x9b2) << uint32(0x0); // 15
8041 data
<< uint32(0x9b1) << uint32(0x1); // 16
8042 data
<< uint32(0x9b0) << uint32(0x0); // 17
8043 data
<< uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
8044 data
<< uint32(0x9ac) << uint32(0x0); // 19
8045 data
<< uint32(0x9a8) << uint32(0x0); // 20
8046 data
<< uint32(0x9a7) << uint32(0x0); // 21
8047 data
<< uint32(0x9a6) << uint32(0x1); // 22
8049 case 3519: // Terokkar Forest
8050 data
<< uint32(0xa41) << uint32(0x0); // 10
8051 data
<< uint32(0xa40) << uint32(0x14); // 11
8052 data
<< uint32(0xa3f) << uint32(0x0); // 12
8053 data
<< uint32(0xa3e) << uint32(0x0); // 13
8054 data
<< uint32(0xa3d) << uint32(0x5); // 14
8055 data
<< uint32(0xa3c) << uint32(0x0); // 15
8056 data
<< uint32(0xa87) << uint32(0x0); // 16
8057 data
<< uint32(0xa86) << uint32(0x0); // 17
8058 data
<< uint32(0xa85) << uint32(0x0); // 18
8059 data
<< uint32(0xa84) << uint32(0x0); // 19
8060 data
<< uint32(0xa83) << uint32(0x0); // 20
8061 data
<< uint32(0xa82) << uint32(0x0); // 21
8062 data
<< uint32(0xa81) << uint32(0x0); // 22
8063 data
<< uint32(0xa80) << uint32(0x0); // 23
8064 data
<< uint32(0xa7e) << uint32(0x0); // 24
8065 data
<< uint32(0xa7d) << uint32(0x0); // 25
8066 data
<< uint32(0xa7c) << uint32(0x0); // 26
8067 data
<< uint32(0xa7b) << uint32(0x0); // 27
8068 data
<< uint32(0xa7a) << uint32(0x0); // 28
8069 data
<< uint32(0xa79) << uint32(0x0); // 29
8070 data
<< uint32(0x9d0) << uint32(0x5); // 30
8071 data
<< uint32(0x9ce) << uint32(0x0); // 31
8072 data
<< uint32(0x9cd) << uint32(0x0); // 32
8073 data
<< uint32(0x9cc) << uint32(0x0); // 33
8074 data
<< uint32(0xa88) << uint32(0x0); // 34
8075 data
<< uint32(0xad0) << uint32(0x0); // 35
8076 data
<< uint32(0xacf) << uint32(0x1); // 36
8078 case 3521: // Zangarmarsh
8079 data
<< uint32(0x9e1) << uint32(0x0); // 10
8080 data
<< uint32(0x9e0) << uint32(0x0); // 11
8081 data
<< uint32(0x9df) << uint32(0x0); // 12
8082 data
<< uint32(0xa5d) << uint32(0x1); // 13
8083 data
<< uint32(0xa5c) << uint32(0x0); // 14
8084 data
<< uint32(0xa5b) << uint32(0x1); // 15
8085 data
<< uint32(0xa5a) << uint32(0x0); // 16
8086 data
<< uint32(0xa59) << uint32(0x1); // 17
8087 data
<< uint32(0xa58) << uint32(0x0); // 18
8088 data
<< uint32(0xa57) << uint32(0x0); // 19
8089 data
<< uint32(0xa56) << uint32(0x0); // 20
8090 data
<< uint32(0xa55) << uint32(0x1); // 21
8091 data
<< uint32(0xa54) << uint32(0x0); // 22
8092 data
<< uint32(0x9e7) << uint32(0x0); // 23
8093 data
<< uint32(0x9e6) << uint32(0x0); // 24
8094 data
<< uint32(0x9e5) << uint32(0x0); // 25
8095 data
<< uint32(0xa00) << uint32(0x0); // 26
8096 data
<< uint32(0x9ff) << uint32(0x1); // 27
8097 data
<< uint32(0x9fe) << uint32(0x0); // 28
8098 data
<< uint32(0x9fd) << uint32(0x0); // 29
8099 data
<< uint32(0x9fc) << uint32(0x1); // 30
8100 data
<< uint32(0x9fb) << uint32(0x0); // 31
8101 data
<< uint32(0xa62) << uint32(0x0); // 32
8102 data
<< uint32(0xa61) << uint32(0x1); // 33
8103 data
<< uint32(0xa60) << uint32(0x1); // 34
8104 data
<< uint32(0xa5f) << uint32(0x0); // 35
8106 case 3698: // Nagrand Arena
8107 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_NA
)
8108 bg
->FillInitialWorldStates(data
);
8111 data
<< uint32(0xa0f) << uint32(0x0); // 7
8112 data
<< uint32(0xa10) << uint32(0x0); // 8
8113 data
<< uint32(0xa11) << uint32(0x0); // 9 show
8116 case 3702: // Blade's Edge Arena
8117 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_BE
)
8118 bg
->FillInitialWorldStates(data
);
8121 data
<< uint32(0x9f0) << uint32(0x0); // 7 gold
8122 data
<< uint32(0x9f1) << uint32(0x0); // 8 green
8123 data
<< uint32(0x9f3) << uint32(0x0); // 9 show
8126 case 3968: // Ruins of Lordaeron
8127 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_RL
)
8128 bg
->FillInitialWorldStates(data
);
8131 data
<< uint32(0xbb8) << uint32(0x0); // 7 gold
8132 data
<< uint32(0xbb9) << uint32(0x0); // 8 green
8133 data
<< uint32(0xbba) << uint32(0x0); // 9 show
8136 case 3703: // Shattrath City
8139 data
<< uint32(0x914) << uint32(0x0); // 7
8140 data
<< uint32(0x913) << uint32(0x0); // 8
8141 data
<< uint32(0x912) << uint32(0x0); // 9
8142 data
<< uint32(0x915) << uint32(0x0); // 10
8145 GetSession()->SendPacket(&data
);
8148 uint32
Player::GetXPRestBonus(uint32 xp
)
8150 uint32 rested_bonus
= (uint32
)GetRestBonus(); // xp for each rested bonus
8152 if(rested_bonus
> xp
) // max rested_bonus == xp or (r+x) = 200% xp
8155 SetRestBonus( GetRestBonus() - rested_bonus
);
8157 sLog
.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp
+rested_bonus
,rested_bonus
,GetRestBonus());
8158 return rested_bonus
;
8161 void Player::SetBindPoint(uint64 guid
)
8163 WorldPacket
data(SMSG_BINDER_CONFIRM
, 8);
8164 data
<< uint64(guid
);
8165 GetSession()->SendPacket( &data
);
8168 void Player::SendTalentWipeConfirm(uint64 guid
)
8170 WorldPacket
data(MSG_TALENT_WIPE_CONFIRM
, (8+4));
8171 data
<< uint64(guid
);
8172 data
<< uint32(resetTalentsCost());
8173 GetSession()->SendPacket( &data
);
8176 void Player::SendPetSkillWipeConfirm()
8178 Pet
* pet
= GetPet();
8181 WorldPacket
data(SMSG_PET_UNLEARN_CONFIRM
, (8+4));
8182 data
<< pet
->GetGUID();
8183 data
<< uint32(pet
->resetTalentsCost());
8184 GetSession()->SendPacket( &data
);
8187 /*********************************************************/
8188 /*** STORAGE SYSTEM ***/
8189 /*********************************************************/
8191 void Player::SetVirtualItemSlot( uint8 i
, Item
* item
)
8196 if(!item
->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT
))
8198 uint32 charges
= item
->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
);
8202 item
->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
,charges
-1);
8203 else if(charges
<= 1)
8205 ApplyEnchantment(item
,TEMP_ENCHANTMENT_SLOT
,false);
8206 item
->ClearEnchantment(TEMP_ENCHANTMENT_SLOT
);
8211 void Player::SetSheath( uint32 sheathed
)
8215 case SHEATH_STATE_UNARMED
: // no prepared weapon
8216 SetVirtualItemSlot(0,NULL
);
8217 SetVirtualItemSlot(1,NULL
);
8218 SetVirtualItemSlot(2,NULL
);
8220 case SHEATH_STATE_MELEE
: // prepared melee weapon
8222 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK
,true));
8223 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK
,true));
8224 SetVirtualItemSlot(2,NULL
);
8226 case SHEATH_STATE_RANGED
: // prepared ranged weapon
8227 SetVirtualItemSlot(0,NULL
);
8228 SetVirtualItemSlot(1,NULL
);
8229 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK
,true));
8232 SetVirtualItemSlot(0,NULL
);
8233 SetVirtualItemSlot(1,NULL
);
8234 SetVirtualItemSlot(2,NULL
);
8237 SetByteValue(UNIT_FIELD_BYTES_2
, 0, sheathed
); // this must visualize Sheath changing for other players...
8240 uint8
Player::FindEquipSlot( ItemPrototype
const* proto
, uint32 slot
, bool swap
) const
8242 uint8 pClass
= getClass();
8245 slots
[0] = NULL_SLOT
;
8246 slots
[1] = NULL_SLOT
;
8247 slots
[2] = NULL_SLOT
;
8248 slots
[3] = NULL_SLOT
;
8249 switch( proto
->InventoryType
)
8252 slots
[0] = EQUIPMENT_SLOT_HEAD
;
8255 slots
[0] = EQUIPMENT_SLOT_NECK
;
8257 case INVTYPE_SHOULDERS
:
8258 slots
[0] = EQUIPMENT_SLOT_SHOULDERS
;
8261 slots
[0] = EQUIPMENT_SLOT_BODY
;
8264 slots
[0] = EQUIPMENT_SLOT_CHEST
;
8267 slots
[0] = EQUIPMENT_SLOT_CHEST
;
8270 slots
[0] = EQUIPMENT_SLOT_WAIST
;
8273 slots
[0] = EQUIPMENT_SLOT_LEGS
;
8276 slots
[0] = EQUIPMENT_SLOT_FEET
;
8278 case INVTYPE_WRISTS
:
8279 slots
[0] = EQUIPMENT_SLOT_WRISTS
;
8282 slots
[0] = EQUIPMENT_SLOT_HANDS
;
8284 case INVTYPE_FINGER
:
8285 slots
[0] = EQUIPMENT_SLOT_FINGER1
;
8286 slots
[1] = EQUIPMENT_SLOT_FINGER2
;
8288 case INVTYPE_TRINKET
:
8289 slots
[0] = EQUIPMENT_SLOT_TRINKET1
;
8290 slots
[1] = EQUIPMENT_SLOT_TRINKET2
;
8293 slots
[0] = EQUIPMENT_SLOT_BACK
;
8295 case INVTYPE_WEAPON
:
8297 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8299 // suggest offhand slot only if know dual wielding
8300 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8302 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
8305 case INVTYPE_SHIELD
:
8306 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8308 case INVTYPE_RANGED
:
8309 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8311 case INVTYPE_2HWEAPON
:
8312 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8313 if (CanDualWield() && CanTitanGrip())
8314 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
8316 case INVTYPE_TABARD
:
8317 slots
[0] = EQUIPMENT_SLOT_TABARD
;
8319 case INVTYPE_WEAPONMAINHAND
:
8320 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8322 case INVTYPE_WEAPONOFFHAND
:
8323 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8325 case INVTYPE_HOLDABLE
:
8326 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8328 case INVTYPE_THROWN
:
8329 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8331 case INVTYPE_RANGEDRIGHT
:
8332 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8335 slots
[0] = INVENTORY_SLOT_BAG_1
;
8336 slots
[1] = INVENTORY_SLOT_BAG_2
;
8337 slots
[2] = INVENTORY_SLOT_BAG_3
;
8338 slots
[3] = INVENTORY_SLOT_BAG_4
;
8342 switch(proto
->SubClass
)
8344 case ITEM_SUBCLASS_ARMOR_LIBRAM
:
8345 if (pClass
== CLASS_PALADIN
)
8346 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8348 case ITEM_SUBCLASS_ARMOR_IDOL
:
8349 if (pClass
== CLASS_DRUID
)
8350 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8352 case ITEM_SUBCLASS_ARMOR_TOTEM
:
8353 if (pClass
== CLASS_SHAMAN
)
8354 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8356 case ITEM_SUBCLASS_ARMOR_MISC
:
8357 if (pClass
== CLASS_WARLOCK
)
8358 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8360 case ITEM_SUBCLASS_ARMOR_SIGIL
:
8361 if (pClass
== CLASS_DEATH_KNIGHT
)
8362 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8371 if( slot
!= NULL_SLOT
)
8373 if( swap
|| !GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
) )
8375 for (int i
= 0; i
< 4; i
++)
8377 if ( slots
[i
] == slot
)
8384 // search free slot at first
8385 for (int i
= 0; i
< 4; i
++)
8387 if ( slots
[i
] != NULL_SLOT
&& !GetItemByPos( INVENTORY_SLOT_BAG_0
, slots
[i
] ) )
8389 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8390 if(slots
[i
]!=EQUIPMENT_SLOT_OFFHAND
|| !IsTwoHandUsed())
8395 // if not found free and can swap return first appropriate from used
8396 for (int i
= 0; i
< 4; i
++)
8398 if ( slots
[i
] != NULL_SLOT
&& swap
)
8407 uint8
Player::CanUnequipItems( uint32 item
, uint32 count
) const
8410 uint32 tempcount
= 0;
8412 uint8 res
= EQUIP_ERR_OK
;
8414 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8416 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8417 if( pItem
&& pItem
->GetEntry() == item
)
8419 uint8 ires
= CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
, false);
8420 if(ires
==EQUIP_ERR_OK
)
8422 tempcount
+= pItem
->GetCount();
8423 if( tempcount
>= count
)
8424 return EQUIP_ERR_OK
;
8430 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8432 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8433 if( pItem
&& pItem
->GetEntry() == item
)
8435 tempcount
+= pItem
->GetCount();
8436 if( tempcount
>= count
)
8437 return EQUIP_ERR_OK
;
8440 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8442 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8443 if( pItem
&& pItem
->GetEntry() == item
)
8445 tempcount
+= pItem
->GetCount();
8446 if( tempcount
>= count
)
8447 return EQUIP_ERR_OK
;
8451 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8453 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8456 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8458 pItem
= GetItemByPos( i
, j
);
8459 if( pItem
&& pItem
->GetEntry() == item
)
8461 tempcount
+= pItem
->GetCount();
8462 if( tempcount
>= count
)
8463 return EQUIP_ERR_OK
;
8469 // not found req. item count and have unequippable items
8473 uint32
Player::GetItemCount( uint32 item
, bool inBankAlso
, Item
* skipItem
) const
8476 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8478 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8479 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8480 count
+= pItem
->GetCount();
8482 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8484 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8485 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8486 count
+= pItem
->GetCount();
8488 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8490 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8492 count
+= pBag
->GetItemCount(item
,skipItem
);
8495 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8497 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8499 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8500 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8501 count
+= pItem
->GetGemCountWithID(item
);
8507 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8509 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8510 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8511 count
+= pItem
->GetCount();
8513 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8515 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8517 count
+= pBag
->GetItemCount(item
,skipItem
);
8520 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8522 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8524 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8525 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8526 count
+= pItem
->GetGemCountWithID(item
);
8534 Item
* Player::GetItemByGuid( uint64 guid
) const
8536 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8538 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8539 if( pItem
&& pItem
->GetGUID() == guid
)
8542 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8544 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8545 if( pItem
&& pItem
->GetGUID() == guid
)
8549 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8551 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8554 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8556 Item
* pItem
= pBag
->GetItemByPos( j
);
8557 if( pItem
&& pItem
->GetGUID() == guid
)
8562 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8564 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8567 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8569 Item
* pItem
= pBag
->GetItemByPos( j
);
8570 if( pItem
&& pItem
->GetGUID() == guid
)
8579 Item
* Player::GetItemByPos( uint16 pos
) const
8581 uint8 bag
= pos
>> 8;
8582 uint8 slot
= pos
& 255;
8583 return GetItemByPos( bag
, slot
);
8586 Item
* Player::GetItemByPos( uint8 bag
, uint8 slot
) const
8588 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< BANK_SLOT_BAG_END
|| slot
>= KEYRING_SLOT_START
&& slot
< QUESTBAG_SLOT_END
) )
8589 return m_items
[slot
];
8590 else if(bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
8591 || bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8593 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8595 return pBag
->GetItemByPos(slot
);
8600 Item
* Player::GetWeaponForAttack(WeaponAttackType attackType
, bool useable
) const
8605 case BASE_ATTACK
: slot
= EQUIPMENT_SLOT_MAINHAND
; break;
8606 case OFF_ATTACK
: slot
= EQUIPMENT_SLOT_OFFHAND
; break;
8607 case RANGED_ATTACK
: slot
= EQUIPMENT_SLOT_RANGED
; break;
8608 default: return NULL
;
8611 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, slot
);
8612 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_WEAPON
)
8618 if( item
->IsBroken() || !IsUseEquipedWeapon(attackType
==BASE_ATTACK
) )
8624 Item
* Player::GetShield(bool useable
) const
8626 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
8627 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_ARMOR
)
8633 if( item
->IsBroken())
8639 uint32
Player::GetAttackBySlot( uint8 slot
)
8643 case EQUIPMENT_SLOT_MAINHAND
: return BASE_ATTACK
;
8644 case EQUIPMENT_SLOT_OFFHAND
: return OFF_ATTACK
;
8645 case EQUIPMENT_SLOT_RANGED
: return RANGED_ATTACK
;
8646 default: return MAX_ATTACK
;
8650 bool Player::HasBankBagSlot( uint8 slot
) const
8652 uint32 maxslot
= GetByteValue(PLAYER_BYTES_2
, 2) + BANK_SLOT_BAG_START
;
8653 if( slot
< maxslot
)
8658 bool Player::IsInventoryPos( uint8 bag
, uint8 slot
)
8660 if( bag
== INVENTORY_SLOT_BAG_0
&& slot
== NULL_SLOT
)
8662 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
) )
8664 if( bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8666 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= KEYRING_SLOT_START
&& slot
< QUESTBAG_SLOT_END
) )
8671 bool Player::IsEquipmentPos( uint8 bag
, uint8 slot
)
8673 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< EQUIPMENT_SLOT_END
) )
8675 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8680 bool Player::IsBankPos( uint8 bag
, uint8 slot
)
8682 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
) )
8684 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8686 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8691 bool Player::IsBagPos( uint16 pos
)
8693 uint8 bag
= pos
>> 8;
8694 uint8 slot
= pos
& 255;
8695 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8697 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8702 bool Player::IsValidPos( uint8 bag
, uint8 slot
)
8708 if (bag
== INVENTORY_SLOT_BAG_0
)
8710 // any post selected
8711 if (slot
== NULL_SLOT
)
8715 if (slot
< EQUIPMENT_SLOT_END
)
8719 if (slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
)
8723 if (slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
)
8727 if (slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_END
)
8731 if (slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
)
8735 if (slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
8741 // bag content slots
8742 if (bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8744 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8748 // any post selected
8749 if (slot
== NULL_SLOT
)
8752 return slot
< pBag
->GetBagSize();
8755 // bank bag content slots
8756 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8758 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8762 // any post selected
8763 if (slot
== NULL_SLOT
)
8766 return slot
< pBag
->GetBagSize();
8774 bool Player::HasItemCount( uint32 item
, uint32 count
, bool inBankAlso
) const
8776 uint32 tempcount
= 0;
8777 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8779 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8780 if( pItem
&& pItem
->GetEntry() == item
)
8782 tempcount
+= pItem
->GetCount();
8783 if( tempcount
>= count
)
8787 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8789 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8790 if( pItem
&& pItem
->GetEntry() == item
)
8792 tempcount
+= pItem
->GetCount();
8793 if( tempcount
>= count
)
8797 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8799 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8801 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8803 Item
* pItem
= GetItemByPos( i
, j
);
8804 if( pItem
&& pItem
->GetEntry() == item
)
8806 tempcount
+= pItem
->GetCount();
8807 if( tempcount
>= count
)
8816 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8818 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8819 if( pItem
&& pItem
->GetEntry() == item
)
8821 tempcount
+= pItem
->GetCount();
8822 if( tempcount
>= count
)
8826 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8828 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8830 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8832 Item
* pItem
= GetItemByPos( i
, j
);
8833 if( pItem
&& pItem
->GetEntry() == item
)
8835 tempcount
+= pItem
->GetCount();
8836 if( tempcount
>= count
)
8847 bool Player::HasItemOrGemWithIdEquipped( uint32 item
, uint32 count
, uint8 except_slot
) const
8849 uint32 tempcount
= 0;
8850 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
8852 if(i
==int(except_slot
))
8855 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8856 if( pItem
&& pItem
->GetEntry() == item
)
8858 tempcount
+= pItem
->GetCount();
8859 if( tempcount
>= count
)
8864 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(item
);
8865 if (pProto
&& pProto
->GemProperties
)
8867 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
8869 if(i
==int(except_slot
))
8872 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8873 if( pItem
&& pItem
->GetProto()->Socket
[0].Color
)
8875 tempcount
+= pItem
->GetGemCountWithID(item
);
8876 if( tempcount
>= count
)
8885 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory
, uint32 count
, uint8 except_slot
) const
8887 uint32 tempcount
= 0;
8888 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
8890 if(i
==int(except_slot
))
8893 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8897 ItemPrototype
const *pProto
= pItem
->GetProto();
8901 if (pProto
->ItemLimitCategory
== limitCategory
)
8903 tempcount
+= pItem
->GetCount();
8904 if( tempcount
>= count
)
8908 if( pProto
->Socket
[0].Color
)
8910 tempcount
+= pItem
->GetGemCountWithLimitCategory(limitCategory
);
8911 if( tempcount
>= count
)
8919 uint8
Player::_CanTakeMoreSimilarItems(uint32 entry
, uint32 count
, Item
* pItem
, uint32
* no_space_count
) const
8921 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
8925 *no_space_count
= count
;
8926 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8930 if(pProto
->MaxCount
<= 0)
8931 return EQUIP_ERR_OK
;
8933 uint32 curcount
= GetItemCount(pProto
->ItemId
,true,pItem
);
8935 if (curcount
+ count
> uint32(pProto
->MaxCount
))
8938 *no_space_count
= count
+curcount
- pProto
->MaxCount
;
8939 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8942 return EQUIP_ERR_OK
;
8945 bool Player::HasItemTotemCategory( uint32 TotemCategory
) const
8948 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8950 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8951 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8954 for(uint8 i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
8956 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8957 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8960 for(uint8 i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8962 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8964 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8966 pItem
= GetItemByPos( i
, j
);
8967 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8975 uint8
Player::_CanStoreItem_InSpecificSlot( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, ItemPrototype
const *pProto
, uint32
& count
, bool swap
, Item
* pSrcItem
) const
8977 Item
* pItem2
= GetItemByPos( bag
, slot
);
8979 // ignore move item (this slot will be empty at move)
8980 if(pItem2
==pSrcItem
)
8985 // empty specific slot - check item fit to slot
8986 if( !pItem2
|| swap
)
8988 if( bag
== INVENTORY_SLOT_BAG_0
)
8991 if(slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_START
+GetMaxKeyringSize() && !(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
))
8992 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8994 // vanitypet case (not use, vanity pets stored as spells)
8995 if(slot
>= VANITYPET_SLOT_START
&& slot
< VANITYPET_SLOT_END
)
8996 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8998 // currencytoken case (disabled until proper implement)
8999 if(slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
&& !(false /*pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS*/))
9000 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9002 // guestbag case (disabled until proper implement)
9003 if(slot
>= QUESTBAG_SLOT_START
&& slot
< QUESTBAG_SLOT_END
&& !(false /*pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS*/))
9004 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9007 if(slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
|| slot
>= PLAYER_SLOT_END
)
9008 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9012 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
9014 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9016 ItemPrototype
const* pBagProto
= pBag
->GetProto();
9018 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9020 if( !ItemCanGoIntoBag(pProto
,pBagProto
) )
9021 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9024 // non empty stack with space
9025 need_space
= pProto
->GetMaxStackSize();
9027 // non empty slot, check item type
9031 if(pItem2
->GetEntry() != pProto
->ItemId
)
9032 return EQUIP_ERR_ITEM_CANT_STACK
;
9035 if(pItem2
->GetCount() >= pProto
->GetMaxStackSize())
9036 return EQUIP_ERR_ITEM_CANT_STACK
;
9038 // free stack space or infinity
9039 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
9042 if(need_space
> count
)
9045 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | slot
, need_space
);
9046 if(!newPosition
.isContainedIn(dest
))
9048 dest
.push_back(newPosition
);
9049 count
-= need_space
;
9051 return EQUIP_ERR_OK
;
9054 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
9056 // skip specific bag already processed in first called _CanStoreItem_InBag
9058 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9060 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
9062 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9064 ItemPrototype
const* pBagProto
= pBag
->GetProto();
9066 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9068 // specialized bag mode or non-specilized
9069 if( non_specialized
!= (pBagProto
->Class
== ITEM_CLASS_CONTAINER
&& pBagProto
->SubClass
== ITEM_SUBCLASS_CONTAINER
) )
9070 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9072 if( !ItemCanGoIntoBag(pProto
,pBagProto
) )
9073 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
9075 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9077 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9081 Item
* pItem2
= GetItemByPos( bag
, j
);
9083 // ignore move item (this slot will be empty at move)
9084 if(pItem2
==pSrcItem
)
9087 // if merge skip empty, if !merge skip non-empty
9088 if((pItem2
!=NULL
)!=merge
)
9093 if(pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->GetMaxStackSize())
9095 uint32 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
9096 if(need_space
> count
)
9099 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
9100 if(!newPosition
.isContainedIn(dest
))
9102 dest
.push_back(newPosition
);
9103 count
-= need_space
;
9106 return EQUIP_ERR_OK
;
9112 uint32 need_space
= pProto
->GetMaxStackSize();
9113 if(need_space
> count
)
9116 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
9117 if(!newPosition
.isContainedIn(dest
))
9119 dest
.push_back(newPosition
);
9120 count
-= need_space
;
9123 return EQUIP_ERR_OK
;
9127 return EQUIP_ERR_OK
;
9130 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
9132 for(uint32 j
= slot_begin
; j
< slot_end
; j
++)
9134 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9135 if(INVENTORY_SLOT_BAG_0
==skip_bag
&& j
==skip_slot
)
9138 Item
* pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, j
);
9140 // ignore move item (this slot will be empty at move)
9141 if(pItem2
==pSrcItem
)
9144 // if merge skip empty, if !merge skip non-empty
9145 if((pItem2
!=NULL
)!=merge
)
9150 if(pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->GetMaxStackSize())
9152 uint32 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
9153 if(need_space
> count
)
9155 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
9156 if(!newPosition
.isContainedIn(dest
))
9158 dest
.push_back(newPosition
);
9159 count
-= need_space
;
9162 return EQUIP_ERR_OK
;
9168 uint32 need_space
= pProto
->GetMaxStackSize();
9169 if(need_space
> count
)
9172 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
9173 if(!newPosition
.isContainedIn(dest
))
9175 dest
.push_back(newPosition
);
9176 count
-= need_space
;
9179 return EQUIP_ERR_OK
;
9183 return EQUIP_ERR_OK
;
9186 uint8
Player::_CanStoreItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, uint32 entry
, uint32 count
, Item
*pItem
, bool swap
, uint32
* no_space_count
) const
9188 sLog
.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, entry
, count
);
9190 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
9194 *no_space_count
= count
;
9195 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
:EQUIP_ERR_ITEM_NOT_FOUND
;
9198 if(pItem
&& pItem
->IsBindedNotWith(GetGUID()))
9201 *no_space_count
= count
;
9202 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9205 // check count of items (skip for auto move for same player from bank)
9206 uint32 no_similar_count
= 0; // can't store this amount similar items
9207 uint8 res
= _CanTakeMoreSimilarItems(entry
,count
,pItem
,&no_similar_count
);
9208 if(res
!=EQUIP_ERR_OK
)
9210 if(count
==no_similar_count
)
9213 *no_space_count
= no_similar_count
;
9216 count
-= no_similar_count
;
9220 if( bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
9222 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
9223 if(res
!=EQUIP_ERR_OK
)
9226 *no_space_count
= count
+ no_similar_count
;
9232 if(no_similar_count
==0)
9233 return EQUIP_ERR_OK
;
9236 *no_space_count
= count
+ no_similar_count
;
9237 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9241 // not specific slot or have space for partly store only in specific slot
9244 if( bag
!= NULL_BAG
)
9246 // search stack in bag for merge to
9247 if( pProto
->Stackable
!= 1 )
9249 if( bag
== INVENTORY_SLOT_BAG_0
) // inventory
9251 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,QUESTBAG_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9252 if(res
!=EQUIP_ERR_OK
)
9255 *no_space_count
= count
+ no_similar_count
;
9261 if(no_similar_count
==0)
9262 return EQUIP_ERR_OK
;
9265 *no_space_count
= count
+ no_similar_count
;
9266 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9269 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9270 if(res
!=EQUIP_ERR_OK
)
9273 *no_space_count
= count
+ no_similar_count
;
9279 if(no_similar_count
==0)
9280 return EQUIP_ERR_OK
;
9283 *no_space_count
= count
+ no_similar_count
;
9284 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9287 else // equipped bag
9289 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
9290 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
9291 if(res
!=EQUIP_ERR_OK
)
9292 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
9294 if(res
!=EQUIP_ERR_OK
)
9297 *no_space_count
= count
+ no_similar_count
;
9303 if(no_similar_count
==0)
9304 return EQUIP_ERR_OK
;
9307 *no_space_count
= count
+ no_similar_count
;
9308 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9313 // search free slot in bag for place to
9314 if( bag
== INVENTORY_SLOT_BAG_0
) // inventory
9316 // search free slot - keyring case
9317 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9319 uint32 keyringSize
= GetMaxKeyringSize();
9320 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9321 if(res
!=EQUIP_ERR_OK
)
9324 *no_space_count
= count
+ no_similar_count
;
9330 if(no_similar_count
==0)
9331 return EQUIP_ERR_OK
;
9334 *no_space_count
= count
+ no_similar_count
;
9335 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9339 // Vanity pet case skipped as not used
9341 /* until proper implementation
9342 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9344 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9345 if(res!=EQUIP_ERR_OK)
9348 *no_space_count = count + no_similar_count;
9354 if(no_similar_count==0)
9355 return EQUIP_ERR_OK;
9358 *no_space_count = count + no_similar_count;
9359 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9363 /* until proper implementation
9364 else if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9366 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9367 if(res!=EQUIP_ERR_OK)
9370 *no_space_count = count + no_similar_count;
9376 if(no_similar_count==0)
9377 return EQUIP_ERR_OK;
9380 *no_space_count = count + no_similar_count;
9381 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9386 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9387 if(res
!=EQUIP_ERR_OK
)
9390 *no_space_count
= count
+ no_similar_count
;
9396 if(no_similar_count
==0)
9397 return EQUIP_ERR_OK
;
9400 *no_space_count
= count
+ no_similar_count
;
9401 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9404 else // equipped bag
9406 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
9407 if(res
!=EQUIP_ERR_OK
)
9408 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
9410 if(res
!=EQUIP_ERR_OK
)
9413 *no_space_count
= count
+ no_similar_count
;
9419 if(no_similar_count
==0)
9420 return EQUIP_ERR_OK
;
9423 *no_space_count
= count
+ no_similar_count
;
9424 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9429 // not specific bag or have space for partly store only in specific bag
9431 // search stack for merge to
9432 if( pProto
->Stackable
!= 1 )
9434 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,QUESTBAG_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9435 if(res
!=EQUIP_ERR_OK
)
9438 *no_space_count
= count
+ no_similar_count
;
9444 if(no_similar_count
==0)
9445 return EQUIP_ERR_OK
;
9448 *no_space_count
= count
+ no_similar_count
;
9449 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9452 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9453 if(res
!=EQUIP_ERR_OK
)
9456 *no_space_count
= count
+ no_similar_count
;
9462 if(no_similar_count
==0)
9463 return EQUIP_ERR_OK
;
9466 *no_space_count
= count
+ no_similar_count
;
9467 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9470 if( pProto
->BagFamily
)
9472 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9474 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
9475 if(res
!=EQUIP_ERR_OK
)
9480 if(no_similar_count
==0)
9481 return EQUIP_ERR_OK
;
9484 *no_space_count
= count
+ no_similar_count
;
9485 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9490 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9492 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
9493 if(res
!=EQUIP_ERR_OK
)
9498 if(no_similar_count
==0)
9499 return EQUIP_ERR_OK
;
9502 *no_space_count
= count
+ no_similar_count
;
9503 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9508 // search free slot - special bag case
9509 if( pProto
->BagFamily
)
9511 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9513 uint32 keyringSize
= GetMaxKeyringSize();
9514 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9515 if(res
!=EQUIP_ERR_OK
)
9518 *no_space_count
= count
+ no_similar_count
;
9524 if(no_similar_count
==0)
9525 return EQUIP_ERR_OK
;
9528 *no_space_count
= count
+ no_similar_count
;
9529 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9533 // Vanity pet case skipped as not used
9535 /* until proper implementation
9536 else if(false pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9538 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9539 if(res!=EQUIP_ERR_OK)
9542 *no_space_count = count + no_similar_count;
9548 if(no_similar_count==0)
9549 return EQUIP_ERR_OK;
9552 *no_space_count = count + no_similar_count;
9553 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9557 /* until proper implementation
9558 else if(false pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9560 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9561 if(res!=EQUIP_ERR_OK)
9564 *no_space_count = count + no_similar_count;
9570 if(no_similar_count==0)
9571 return EQUIP_ERR_OK;
9574 *no_space_count = count + no_similar_count;
9575 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9580 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9582 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
9583 if(res
!=EQUIP_ERR_OK
)
9588 if(no_similar_count
==0)
9589 return EQUIP_ERR_OK
;
9592 *no_space_count
= count
+ no_similar_count
;
9593 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9599 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9600 if(res
!=EQUIP_ERR_OK
)
9603 *no_space_count
= count
+ no_similar_count
;
9609 if(no_similar_count
==0)
9610 return EQUIP_ERR_OK
;
9613 *no_space_count
= count
+ no_similar_count
;
9614 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9617 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9619 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
9620 if(res
!=EQUIP_ERR_OK
)
9625 if(no_similar_count
==0)
9626 return EQUIP_ERR_OK
;
9629 *no_space_count
= count
+ no_similar_count
;
9630 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9635 *no_space_count
= count
+ no_similar_count
;
9637 return EQUIP_ERR_INVENTORY_FULL
;
9640 //////////////////////////////////////////////////////////////////////////
9641 uint8
Player::CanStoreItems( Item
**pItems
,int count
) const
9646 int inv_slot_items
[INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
];
9647 int inv_bags
[INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
][MAX_BAG_SIZE
];
9648 int inv_keys
[KEYRING_SLOT_END
-KEYRING_SLOT_START
];
9649 int inv_tokens
[CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
];
9650 int inv_quests
[QUESTBAG_SLOT_END
-QUESTBAG_SLOT_START
];
9652 memset(inv_slot_items
,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
));
9653 memset(inv_bags
,0,sizeof(int)*(INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
)*MAX_BAG_SIZE
);
9654 memset(inv_keys
,0,sizeof(int)*(KEYRING_SLOT_END
-KEYRING_SLOT_START
));
9655 memset(inv_tokens
,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
));
9656 memset(inv_quests
,0,sizeof(int)*(QUESTBAG_SLOT_END
-QUESTBAG_SLOT_START
));
9658 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
9660 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9662 if (pItem2
&& !pItem2
->IsInTrade())
9664 inv_slot_items
[i
-INVENTORY_SLOT_ITEM_START
] = pItem2
->GetCount();
9668 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
9670 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9672 if (pItem2
&& !pItem2
->IsInTrade())
9674 inv_keys
[i
-KEYRING_SLOT_START
] = pItem2
->GetCount();
9678 // Vanity pet case skipped as not used
9680 for(int i
= CURRENCYTOKEN_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; i
++)
9682 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9684 if (pItem2
&& !pItem2
->IsInTrade())
9686 inv_tokens
[i
-CURRENCYTOKEN_SLOT_START
] = pItem2
->GetCount();
9690 for(int i
= QUESTBAG_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
9692 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9694 if (pItem2
&& !pItem2
->IsInTrade())
9696 inv_quests
[i
-QUESTBAG_SLOT_START
] = pItem2
->GetCount();
9700 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9702 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
9704 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9706 pItem2
= GetItemByPos( i
, j
);
9707 if (pItem2
&& !pItem2
->IsInTrade())
9709 inv_bags
[i
-INVENTORY_SLOT_BAG_START
][j
] = pItem2
->GetCount();
9715 // check free space for all items
9716 for (int k
=0;k
<count
;k
++)
9718 Item
*pItem
= pItems
[k
];
9721 if (!pItem
) continue;
9723 sLog
.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k
+1, pItem
->GetEntry(), pItem
->GetCount());
9724 ItemPrototype
const *pProto
= pItem
->GetProto();
9728 return EQUIP_ERR_ITEM_NOT_FOUND
;
9731 if(pItem
->IsBindedNotWith(GetGUID()))
9732 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9735 ItemPrototype
const *pBagProto
;
9737 // item is 'one item only'
9738 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9739 if(res
!= EQUIP_ERR_OK
)
9742 // search stack for merge to
9743 if( pProto
->Stackable
!= 1 )
9745 bool b_found
= false;
9747 for(int t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_END
; t
++)
9749 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9750 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_keys
[t
-KEYRING_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9752 inv_keys
[t
-KEYRING_SLOT_START
] += pItem
->GetCount();
9757 if (b_found
) continue;
9759 // Vanity pet case skipped as not used
9761 for(int t
= CURRENCYTOKEN_SLOT_START
; t
< CURRENCYTOKEN_SLOT_END
; t
++)
9763 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9764 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9766 inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] += pItem
->GetCount();
9771 if (b_found
) continue;
9773 for(int t
= QUESTBAG_SLOT_START
; t
< QUESTBAG_SLOT_END
; t
++)
9775 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9776 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_quests
[t
-QUESTBAG_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9778 inv_quests
[t
-QUESTBAG_SLOT_START
] += pItem
->GetCount();
9783 if (b_found
) continue;
9785 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; t
++)
9787 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9788 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9790 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] += pItem
->GetCount();
9795 if (b_found
) continue;
9797 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9799 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9802 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9804 pItem2
= GetItemByPos( t
, j
);
9805 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9807 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] += pItem
->GetCount();
9814 if (b_found
) continue;
9818 if( pProto
->BagFamily
)
9820 bool b_found
= false;
9821 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9823 uint32 keyringSize
= GetMaxKeyringSize();
9824 for(uint32 t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_START
+keyringSize
; ++t
)
9826 if( inv_keys
[t
-KEYRING_SLOT_START
] == 0 )
9828 inv_keys
[t
-KEYRING_SLOT_START
] = 1;
9835 if (b_found
) continue;
9837 // Vanity pet case skipped as not used
9839 /* until proper implementation
9840 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9842 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9844 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9846 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9853 if (b_found) continue;
9855 /* until proper implementation
9856 if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9858 for(uint32 t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; ++t)
9860 if( inv_quests[t-QUESTBAG_SLOT_START] == 0 )
9862 inv_quests[t-QUESTBAG_SLOT_START] = 1;
9869 if (b_found) continue;
9872 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9874 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9877 pBagProto
= pBag
->GetProto();
9879 // not plain container check
9880 if( pBagProto
&& (pBagProto
->Class
!= ITEM_CLASS_CONTAINER
|| pBagProto
->SubClass
!= ITEM_SUBCLASS_CONTAINER
) &&
9881 ItemCanGoIntoBag(pProto
,pBagProto
) )
9883 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9885 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9887 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9895 if (b_found
) continue;
9899 bool b_found
= false;
9900 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; t
++)
9902 if( inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] == 0 )
9904 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] = 1;
9909 if (b_found
) continue;
9911 // search free slot in bags
9912 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9914 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9917 pBagProto
= pBag
->GetProto();
9919 // special bag already checked
9920 if( pBagProto
&& (pBagProto
->Class
!= ITEM_CLASS_CONTAINER
|| pBagProto
->SubClass
!= ITEM_SUBCLASS_CONTAINER
))
9923 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9925 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9927 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9935 // no free slot found?
9937 return EQUIP_ERR_INVENTORY_FULL
;
9940 return EQUIP_ERR_OK
;
9943 //////////////////////////////////////////////////////////////////////////
9944 uint8
Player::CanEquipNewItem( uint8 slot
, uint16
&dest
, uint32 item
, bool swap
) const
9947 Item
*pItem
= Item::CreateItem( item
, 1, this );
9950 uint8 result
= CanEquipItem(slot
, dest
, pItem
, swap
);
9955 return EQUIP_ERR_ITEM_NOT_FOUND
;
9958 uint8
Player::CanEquipItem( uint8 slot
, uint16
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
9963 sLog
.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot
, pItem
->GetEntry(), pItem
->GetCount());
9964 ItemPrototype
const *pProto
= pItem
->GetProto();
9967 if(pItem
->IsBindedNotWith(GetGUID()))
9968 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9970 // check count of items (skip for auto move for same player from bank)
9971 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9972 if(res
!= EQUIP_ERR_OK
)
9975 // check this only in game
9978 // May be here should be more stronger checks; STUNNED checked
9979 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9980 if (hasUnitState(UNIT_STAT_STUNNED
))
9981 return EQUIP_ERR_YOU_ARE_STUNNED
;
9983 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9985 // - in-progress arenas
9986 if( !pProto
->CanChangeEquipStateInCombat() )
9989 return EQUIP_ERR_NOT_IN_COMBAT
;
9991 if(BattleGround
* bg
= GetBattleGround())
9992 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
9993 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
9996 if(isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
!= 0)
9997 return EQUIP_ERR_CANT_DO_RIGHT_NOW
; // maybe exist better err
9999 if(IsNonMeleeSpellCasted(false))
10000 return EQUIP_ERR_CANT_DO_RIGHT_NOW
;
10003 uint8 eslot
= FindEquipSlot( pProto
, slot
, swap
);
10004 if( eslot
== NULL_SLOT
)
10005 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
10007 uint8 msg
= CanUseItem( pItem
, not_loading
);
10008 if( msg
!= EQUIP_ERR_OK
)
10010 if( !swap
&& GetItemByPos( INVENTORY_SLOT_BAG_0
, eslot
) )
10011 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE
;
10013 // if swap ignore item (equipped also)
10014 if(uint8 res
= CanEquipUniqueItem(pItem
, swap
? eslot
: NULL_SLOT
))
10017 // check unique-equipped special item classes
10018 if (pProto
->Class
== ITEM_CLASS_QUIVER
)
10020 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
10022 if( Item
* pBag
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
) )
10024 if( ItemPrototype
const* pBagProto
= pBag
->GetProto() )
10026 if( pBagProto
->Class
==pProto
->Class
&& (!swap
|| pBag
->GetSlot() != eslot
) )
10028 if(pBagProto
->SubClass
== ITEM_SUBCLASS_AMMO_POUCH
)
10029 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
;
10031 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER
;
10038 uint32 type
= pProto
->InventoryType
;
10040 if(eslot
== EQUIPMENT_SLOT_OFFHAND
)
10042 if (type
== INVTYPE_WEAPON
|| type
== INVTYPE_WEAPONOFFHAND
)
10044 if(!CanDualWield())
10045 return EQUIP_ERR_CANT_DUAL_WIELD
;
10047 else if (type
== INVTYPE_2HWEAPON
)
10049 if(!CanDualWield() || !CanTitanGrip())
10050 return EQUIP_ERR_CANT_DUAL_WIELD
;
10053 if(IsTwoHandUsed())
10054 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED
;
10057 // equip two-hand weapon case (with possible unequip 2 items)
10058 if( type
== INVTYPE_2HWEAPON
)
10060 if (eslot
== EQUIPMENT_SLOT_OFFHAND
)
10062 if (!CanTitanGrip())
10063 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
10065 else if (eslot
!= EQUIPMENT_SLOT_MAINHAND
)
10066 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
10068 if (!CanTitanGrip())
10070 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
10071 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
10072 ItemPosCountVec off_dest
;
10073 if( offItem
&& (!not_loading
||
10074 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0
) << 8 | EQUIPMENT_SLOT_OFFHAND
,false) != EQUIP_ERR_OK
||
10075 CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false ) != EQUIP_ERR_OK
) )
10076 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_INVENTORY_FULL
;
10079 dest
= ((INVENTORY_SLOT_BAG_0
<< 8) | eslot
);
10080 return EQUIP_ERR_OK
;
10084 return EQUIP_ERR_ITEM_NOT_FOUND
;
10086 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
;
10089 uint8
Player::CanUnequipItem( uint16 pos
, bool swap
) const
10091 // Applied only to equipped items and bank bags
10092 if(!IsEquipmentPos(pos
) && !IsBagPos(pos
))
10093 return EQUIP_ERR_OK
;
10095 Item
* pItem
= GetItemByPos(pos
);
10097 // Applied only to existed equipped item
10099 return EQUIP_ERR_OK
;
10101 sLog
.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos
, pItem
->GetEntry(), pItem
->GetCount());
10103 ItemPrototype
const *pProto
= pItem
->GetProto();
10105 return EQUIP_ERR_ITEM_NOT_FOUND
;
10107 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
10109 // - in-progress arenas
10110 if( !pProto
->CanChangeEquipStateInCombat() )
10113 return EQUIP_ERR_NOT_IN_COMBAT
;
10115 if(BattleGround
* bg
= GetBattleGround())
10116 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
10117 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
10120 if(!swap
&& pItem
->IsBag() && !((Bag
*)pItem
)->IsEmpty())
10121 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS
;
10123 return EQUIP_ERR_OK
;
10126 uint8
Player::CanBankItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
10129 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
10131 uint32 count
= pItem
->GetCount();
10133 sLog
.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), pItem
->GetCount());
10134 ItemPrototype
const *pProto
= pItem
->GetProto();
10136 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
10138 if( pItem
->IsBindedNotWith(GetGUID()) )
10139 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
10141 // check count of items (skip for auto move for same player from bank)
10142 uint8 res
= CanTakeMoreSimilarItems(pItem
);
10143 if(res
!= EQUIP_ERR_OK
)
10146 // in specific slot
10147 if( bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
10149 if( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
10151 if (!pItem
->IsBag())
10152 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
;
10154 Bag
*pBag
= (Bag
*)pItem
;
10155 if( !HasBankBagSlot( slot
) )
10156 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT
;
10158 if( uint8 cantuse
= CanUseItem( pItem
, not_loading
) != EQUIP_ERR_OK
)
10162 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
10163 if(res
!=EQUIP_ERR_OK
)
10167 return EQUIP_ERR_OK
;
10170 // not specific slot or have space for partly store only in specific slot
10173 if( bag
!= NULL_BAG
)
10175 if( pProto
->InventoryType
== INVTYPE_BAG
)
10177 Bag
*pBag
= (Bag
*)pItem
;
10178 if( pBag
&& !pBag
->IsEmpty() )
10179 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
;
10182 // search stack in bag for merge to
10183 if( pProto
->Stackable
!= 1 )
10185 if( bag
== INVENTORY_SLOT_BAG_0
)
10187 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
10188 if(res
!=EQUIP_ERR_OK
)
10192 return EQUIP_ERR_OK
;
10196 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
10197 if(res
!=EQUIP_ERR_OK
)
10198 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
10200 if(res
!=EQUIP_ERR_OK
)
10204 return EQUIP_ERR_OK
;
10208 // search free slot in bag
10209 if( bag
== INVENTORY_SLOT_BAG_0
)
10211 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
10212 if(res
!=EQUIP_ERR_OK
)
10216 return EQUIP_ERR_OK
;
10220 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
10221 if(res
!=EQUIP_ERR_OK
)
10222 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
10224 if(res
!=EQUIP_ERR_OK
)
10228 return EQUIP_ERR_OK
;
10232 // not specific bag or have space for partly store only in specific bag
10234 // search stack for merge to
10235 if( pProto
->Stackable
!= 1 )
10238 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
10239 if(res
!=EQUIP_ERR_OK
)
10243 return EQUIP_ERR_OK
;
10246 if( pProto
->BagFamily
)
10248 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
10250 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
10251 if(res
!=EQUIP_ERR_OK
)
10255 return EQUIP_ERR_OK
;
10259 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
10261 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
10262 if(res
!=EQUIP_ERR_OK
)
10266 return EQUIP_ERR_OK
;
10270 // search free place in special bag
10271 if( pProto
->BagFamily
)
10273 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
10275 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
10276 if(res
!=EQUIP_ERR_OK
)
10280 return EQUIP_ERR_OK
;
10284 // search free space
10285 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
10286 if(res
!=EQUIP_ERR_OK
)
10290 return EQUIP_ERR_OK
;
10292 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
10294 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
10295 if(res
!=EQUIP_ERR_OK
)
10299 return EQUIP_ERR_OK
;
10301 return EQUIP_ERR_BANK_FULL
;
10304 uint8
Player::CanUseItem( Item
*pItem
, bool not_loading
) const
10308 sLog
.outDebug( "STORAGE: CanUseItem item = %u", pItem
->GetEntry());
10309 if( !isAlive() && not_loading
)
10310 return EQUIP_ERR_YOU_ARE_DEAD
;
10311 //if( isStunned() )
10312 // return EQUIP_ERR_YOU_ARE_STUNNED;
10313 ItemPrototype
const *pProto
= pItem
->GetProto();
10316 if( pItem
->IsBindedNotWith(GetGUID()) )
10317 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
10318 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
10319 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
10320 if( pItem
->GetSkill() != 0 )
10322 if( GetSkillValue( pItem
->GetSkill() ) == 0 )
10323 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10325 if( pProto
->RequiredSkill
!= 0 )
10327 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
10328 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10329 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10330 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
10332 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
10333 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10334 if( pProto
->RequiredReputationFaction
&& uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
10335 return EQUIP_ERR_CANT_EQUIP_REPUTATION
;
10336 if( getLevel() < pProto
->RequiredLevel
)
10337 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
10338 return EQUIP_ERR_OK
;
10341 return EQUIP_ERR_ITEM_NOT_FOUND
;
10344 bool Player::CanUseItem( ItemPrototype
const *pProto
)
10346 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10350 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
10352 if( pProto
->RequiredSkill
!= 0 )
10354 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
10356 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10359 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
10361 if( getLevel() < pProto
->RequiredLevel
)
10368 uint8
Player::CanUseAmmo( uint32 item
) const
10370 sLog
.outDebug( "STORAGE: CanUseAmmo item = %u", item
);
10372 return EQUIP_ERR_YOU_ARE_DEAD
;
10373 //if( isStunned() )
10374 // return EQUIP_ERR_YOU_ARE_STUNNED;
10375 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
10378 if( pProto
->InventoryType
!= INVTYPE_AMMO
)
10379 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE
;
10380 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
10381 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
10382 if( pProto
->RequiredSkill
!= 0 )
10384 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
10385 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10386 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10387 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
10389 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
10390 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10391 /*if( GetReputation() < pProto->RequiredReputation )
10392 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10394 if( getLevel() < pProto
->RequiredLevel
)
10395 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
10397 // Requires No Ammo
10398 if(GetDummyAura(46699))
10399 return EQUIP_ERR_BAG_FULL6
;
10401 return EQUIP_ERR_OK
;
10403 return EQUIP_ERR_ITEM_NOT_FOUND
;
10406 void Player::SetAmmo( uint32 item
)
10412 if( GetUInt32Value(PLAYER_AMMO_ID
) == item
)
10418 uint8 msg
= CanUseAmmo( item
);
10419 if( msg
!= EQUIP_ERR_OK
)
10421 SendEquipError( msg
, NULL
, NULL
);
10426 SetUInt32Value(PLAYER_AMMO_ID
, item
);
10428 _ApplyAmmoBonuses();
10431 void Player::RemoveAmmo()
10433 SetUInt32Value(PLAYER_AMMO_ID
, 0);
10437 if(CanModifyStats())
10438 UpdateDamagePhysical(RANGED_ATTACK
);
10441 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10442 Item
* Player::StoreNewItem( ItemPosCountVec
const& dest
, uint32 item
, bool update
,int32 randomPropertyId
)
10445 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); ++itr
)
10446 count
+= itr
->count
;
10448 Item
*pItem
= Item::CreateItem( item
, count
, this );
10451 ItemAddedQuestCheck( item
, count
);
10452 if(randomPropertyId
)
10453 pItem
->SetItemRandomProperties(randomPropertyId
);
10454 pItem
= StoreItem( dest
, pItem
, update
);
10459 Item
* Player::StoreItem( ItemPosCountVec
const& dest
, Item
* pItem
, bool update
)
10464 Item
* lastItem
= pItem
;
10466 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); )
10468 uint16 pos
= itr
->pos
;
10469 uint32 count
= itr
->count
;
10473 if(itr
== dest
.end())
10475 lastItem
= _StoreItem(pos
,pItem
,count
,false,update
);
10479 lastItem
= _StoreItem(pos
,pItem
,count
,true,update
);
10485 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10486 Item
* Player::_StoreItem( uint16 pos
, Item
*pItem
, uint32 count
, bool clone
, bool update
)
10491 uint8 bag
= pos
>> 8;
10492 uint8 slot
= pos
& 255;
10494 sLog
.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), count
);
10496 Item
*pItem2
= GetItemByPos( bag
, slot
);
10501 pItem
= pItem
->CloneItem(count
,this);
10503 pItem
->SetCount(count
);
10508 if( pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10509 pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10510 pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
) )
10511 pItem
->SetBinding( true );
10513 if( bag
== INVENTORY_SLOT_BAG_0
)
10515 m_items
[slot
] = pItem
;
10516 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), pItem
->GetGUID() );
10517 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10518 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10520 pItem
->SetSlot( slot
);
10521 pItem
->SetContainer( NULL
);
10523 if( IsInWorld() && update
)
10525 pItem
->AddToWorld();
10526 pItem
->SendUpdateToPlayer( this );
10529 pItem
->SetState(ITEM_CHANGED
, this);
10533 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
10536 pBag
->StoreItem( slot
, pItem
, update
);
10537 if( IsInWorld() && update
)
10539 pItem
->AddToWorld();
10540 pItem
->SendUpdateToPlayer( this );
10542 pItem
->SetState(ITEM_CHANGED
, this);
10543 pBag
->SetState(ITEM_CHANGED
, this);
10547 AddEnchantmentDurations(pItem
);
10548 AddItemDurations(pItem
);
10554 if( pItem2
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10555 pItem2
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10556 pItem2
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
) )
10557 pItem2
->SetBinding( true );
10559 pItem2
->SetCount( pItem2
->GetCount() + count
);
10560 if( IsInWorld() && update
)
10561 pItem2
->SendUpdateToPlayer( this );
10565 // delete item (it not in any slot currently)
10566 if( IsInWorld() && update
)
10568 pItem
->RemoveFromWorld();
10569 pItem
->DestroyForPlayer( this );
10572 RemoveEnchantmentDurations(pItem
);
10573 RemoveItemDurations(pItem
);
10575 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10576 pItem
->SetState(ITEM_REMOVED
, this);
10578 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10579 AddEnchantmentDurations(pItem2
);
10581 pItem2
->SetState(ITEM_CHANGED
, this);
10587 Item
* Player::EquipNewItem( uint16 pos
, uint32 item
, bool update
)
10589 Item
*pItem
= Item::CreateItem( item
, 1, this );
10592 ItemAddedQuestCheck( item
, 1 );
10593 Item
* retItem
= EquipItem( pos
, pItem
, update
);
10600 Item
* Player::EquipItem( uint16 pos
, Item
*pItem
, bool update
)
10604 AddEnchantmentDurations(pItem
);
10605 AddItemDurations(pItem
);
10607 uint8 bag
= pos
>> 8;
10608 uint8 slot
= pos
& 255;
10610 Item
*pItem2
= GetItemByPos( bag
, slot
);
10614 VisualizeItem( slot
, pItem
);
10618 ItemPrototype
const *pProto
= pItem
->GetProto();
10620 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10621 if(pProto
&& pProto
->ItemSet
)
10622 AddItemsSetItem(this,pItem
);
10624 _ApplyItemMods(pItem
, slot
, true);
10626 if(pProto
&& isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
== 0)
10628 uint32 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s
;
10630 if (getClass() == CLASS_ROGUE
)
10631 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s
;
10633 SpellEntry
const* spellProto
= sSpellStore
.LookupEntry(cooldownSpell
);
10636 sLog
.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell
);
10639 m_weaponChangeTimer
= spellProto
->StartRecoveryTime
;
10641 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+4);
10642 data
<< uint64(GetGUID());
10644 data
<< uint32(cooldownSpell
);
10646 GetSession()->SendPacket(&data
);
10651 if( IsInWorld() && update
)
10653 pItem
->AddToWorld();
10654 pItem
->SendUpdateToPlayer( this );
10657 ApplyEquipCooldown(pItem
);
10659 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
10660 UpdateExpertise(BASE_ATTACK
);
10661 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10662 UpdateExpertise(OFF_ATTACK
);
10666 pItem2
->SetCount( pItem2
->GetCount() + pItem
->GetCount() );
10667 if( IsInWorld() && update
)
10668 pItem2
->SendUpdateToPlayer( this );
10670 // delete item (it not in any slot currently)
10671 //pItem->DeleteFromDB();
10672 if( IsInWorld() && update
)
10674 pItem
->RemoveFromWorld();
10675 pItem
->DestroyForPlayer( this );
10678 RemoveEnchantmentDurations(pItem
);
10679 RemoveItemDurations(pItem
);
10681 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10682 pItem
->SetState(ITEM_REMOVED
, this);
10683 pItem2
->SetState(ITEM_CHANGED
, this);
10685 ApplyEquipCooldown(pItem2
);
10694 void Player::QuickEquipItem( uint16 pos
, Item
*pItem
)
10698 AddEnchantmentDurations(pItem
);
10699 AddItemDurations(pItem
);
10701 uint8 slot
= pos
& 255;
10702 VisualizeItem( slot
, pItem
);
10706 pItem
->AddToWorld();
10707 pItem
->SendUpdateToPlayer( this );
10712 void Player::SetVisibleItemSlot(uint8 slot
, Item
*pItem
)
10714 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10715 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10716 // entry // Size: 1
10717 // inspected enchantments // Size: 6
10719 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10720 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10725 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), pItem
->GetUInt64Value(ITEM_FIELD_CREATOR
));
10727 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
10728 SetUInt32Value(VisibleBase
+ 0, pItem
->GetEntry());
10730 for(int i
= 0; i
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++i
)
10731 SetUInt32Value(VisibleBase
+ 1 + i
, pItem
->GetEnchantmentId(EnchantmentSlot(i
)));
10733 // Use SetInt16Value to prevent set high part to FFFF for negative value
10734 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0, pItem
->GetItemRandomPropertyId());
10735 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), pItem
->GetItemSuffixFactor());
10739 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10741 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
10742 SetUInt32Value(VisibleBase
+ 0, 0);
10744 for(int i
= 0; i
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++i
)
10745 SetUInt32Value(VisibleBase
+ 1 + i
, 0);
10747 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 0 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10748 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10752 void Player::VisualizeItem( uint8 slot
, Item
*pItem
)
10757 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10758 if( pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
|| pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
|| pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
)
10759 pItem
->SetBinding( true );
10761 sLog
.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot
, pItem
->GetEntry());
10763 m_items
[slot
] = pItem
;
10764 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), pItem
->GetGUID() );
10765 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10766 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10767 pItem
->SetSlot( slot
);
10768 pItem
->SetContainer( NULL
);
10770 if( slot
< EQUIPMENT_SLOT_END
)
10771 SetVisibleItemSlot(slot
,pItem
);
10773 pItem
->SetState(ITEM_CHANGED
, this);
10776 void Player::RemoveItem( uint8 bag
, uint8 slot
, bool update
)
10778 // note: removeitem does not actually change the item
10779 // it only takes the item out of storage temporarily
10780 // note2: if removeitem is to be used for delinking
10781 // the item must be removed from the player's updatequeue
10783 Item
*pItem
= GetItemByPos( bag
, slot
);
10786 sLog
.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10788 RemoveEnchantmentDurations(pItem
);
10789 RemoveItemDurations(pItem
);
10791 if( bag
== INVENTORY_SLOT_BAG_0
)
10793 if ( slot
< INVENTORY_SLOT_BAG_END
)
10795 ItemPrototype
const *pProto
= pItem
->GetProto();
10796 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10798 if(pProto
&& pProto
->ItemSet
)
10799 RemoveItemsSetItem(this,pProto
);
10801 _ApplyItemMods(pItem
, slot
, false);
10803 // remove item dependent auras and casts (only weapon and armor slots)
10804 if(slot
< EQUIPMENT_SLOT_END
)
10805 RemoveItemDependentAurasAndCasts(pItem
);
10807 // remove held enchantments
10808 if ( slot
== EQUIPMENT_SLOT_MAINHAND
)
10810 if (pItem
->GetItemSuffixFactor())
10812 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3
);
10813 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4
);
10817 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0
);
10818 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1
);
10823 m_items
[slot
] = NULL
;
10824 SetUInt64Value((uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
*2)), 0);
10826 if ( slot
< EQUIPMENT_SLOT_END
)
10827 SetVisibleItemSlot(slot
,NULL
);
10831 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
10833 pBag
->RemoveItem(slot
, update
);
10835 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10836 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10837 pItem
->SetSlot( NULL_SLOT
);
10838 if( IsInWorld() && update
)
10839 pItem
->SendUpdateToPlayer( this );
10841 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
10842 UpdateExpertise(BASE_ATTACK
);
10843 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10844 UpdateExpertise(OFF_ATTACK
);
10848 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10849 void Player::MoveItemFromInventory(uint8 bag
, uint8 slot
, bool update
)
10851 if(Item
* it
= GetItemByPos(bag
,slot
))
10853 ItemRemovedQuestCheck(it
->GetEntry(),it
->GetCount());
10854 RemoveItem( bag
,slot
,update
);
10855 it
->RemoveFromUpdateQueueOf(this);
10856 if(it
->IsInWorld())
10858 it
->RemoveFromWorld();
10859 it
->DestroyForPlayer( this );
10864 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10865 void Player::MoveItemToInventory(ItemPosCountVec
const& dest
, Item
* pItem
, bool update
, bool in_characterInventoryDB
)
10867 // update quest counters
10868 ItemAddedQuestCheck(pItem
->GetEntry(),pItem
->GetCount());
10871 Item
* pLastItem
= StoreItem( dest
, pItem
, update
);
10873 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10874 if(pLastItem
==pItem
)
10876 // update owner for last item (this can be original item with wrong owner
10877 if(pLastItem
->GetOwnerGUID() != GetGUID())
10878 pLastItem
->SetOwnerGUID(GetGUID());
10880 // if this original item then it need create record in inventory
10881 // in case trade we already have item in other player inventory
10882 pLastItem
->SetState(in_characterInventoryDB
? ITEM_CHANGED
: ITEM_NEW
, this);
10886 void Player::DestroyItem( uint8 bag
, uint8 slot
, bool update
)
10888 Item
*pItem
= GetItemByPos( bag
, slot
);
10891 sLog
.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10893 // start from destroy contained items (only equipped bag can have its)
10894 if (pItem
->IsBag() && pItem
->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10896 for (int i
= 0; i
< MAX_BAG_SIZE
; i
++)
10897 DestroyItem(slot
,i
,update
);
10900 if(pItem
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_WRAPPED
))
10901 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem
->GetGUIDLow());
10903 RemoveEnchantmentDurations(pItem
);
10904 RemoveItemDurations(pItem
);
10906 ItemRemovedQuestCheck( pItem
->GetEntry(), pItem
->GetCount() );
10908 if( bag
== INVENTORY_SLOT_BAG_0
)
10910 SetUInt64Value((uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
*2)), 0);
10912 // equipment and equipped bags can have applied bonuses
10913 if ( slot
< INVENTORY_SLOT_BAG_END
)
10915 ItemPrototype
const *pProto
= pItem
->GetProto();
10917 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10918 if(pProto
&& pProto
->ItemSet
)
10919 RemoveItemsSetItem(this,pProto
);
10921 _ApplyItemMods(pItem
, slot
, false);
10924 if ( slot
< EQUIPMENT_SLOT_END
)
10926 // remove item dependent auras and casts (only weapon and armor slots)
10927 RemoveItemDependentAurasAndCasts(pItem
);
10929 // equipment visual show
10930 SetVisibleItemSlot(slot
,NULL
);
10933 m_items
[slot
] = NULL
;
10935 else if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
))
10936 pBag
->RemoveItem(slot
, update
);
10938 if( IsInWorld() && update
)
10940 pItem
->RemoveFromWorld();
10941 pItem
->DestroyForPlayer(this);
10944 //pItem->SetOwnerGUID(0);
10945 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10946 pItem
->SetSlot( NULL_SLOT
);
10947 pItem
->SetState(ITEM_REMOVED
, this);
10951 void Player::DestroyItemCount( uint32 item
, uint32 count
, bool update
, bool unequip_check
)
10953 sLog
.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item
, count
);
10954 uint32 remcount
= 0;
10957 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
10959 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10961 if (pItem
->GetEntry() == item
)
10963 if (pItem
->GetCount() + remcount
<= count
)
10965 // all items in inventory can unequipped
10966 remcount
+= pItem
->GetCount();
10967 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10969 if (remcount
>=count
)
10974 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10975 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10976 if (IsInWorld() & update
)
10977 pItem
->SendUpdateToPlayer( this );
10978 pItem
->SetState(ITEM_CHANGED
, this);
10984 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
10986 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10988 if (pItem
->GetEntry() == item
)
10990 if (pItem
->GetCount() + remcount
<= count
)
10992 // all keys can be unequipped
10993 remcount
+= pItem
->GetCount();
10994 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10996 if (remcount
>=count
)
11001 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
11002 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
11003 if (IsInWorld() & update
)
11004 pItem
->SendUpdateToPlayer( this );
11005 pItem
->SetState(ITEM_CHANGED
, this);
11012 // in inventory bags
11013 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11015 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11017 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
11019 if(Item
* pItem
= pBag
->GetItemByPos(j
))
11021 if (pItem
->GetEntry() == item
)
11023 // all items in bags can be unequipped
11024 if (pItem
->GetCount() + remcount
<= count
)
11026 remcount
+= pItem
->GetCount();
11027 DestroyItem( i
, j
, update
);
11029 if (remcount
>=count
)
11034 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
11035 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
11036 if (IsInWorld() && update
)
11037 pItem
->SendUpdateToPlayer( this );
11038 pItem
->SetState(ITEM_CHANGED
, this);
11047 // in equipment and bag list
11048 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11050 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11052 if (pItem
&& pItem
->GetEntry() == item
)
11054 if (pItem
->GetCount() + remcount
<= count
)
11056 if (!unequip_check
|| CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
,false) == EQUIP_ERR_OK
)
11058 remcount
+= pItem
->GetCount();
11059 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11061 if (remcount
>=count
)
11067 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
11068 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
11069 if (IsInWorld() & update
)
11070 pItem
->SendUpdateToPlayer( this );
11071 pItem
->SetState(ITEM_CHANGED
, this);
11079 void Player::DestroyZoneLimitedItem( bool update
, uint32 new_zone
)
11081 sLog
.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone
);
11084 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
11085 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11086 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
))
11087 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11089 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
11090 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11091 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
))
11092 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11094 // in inventory bags
11095 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11096 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11097 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
11098 if (Item
* pItem
= pBag
->GetItemByPos(j
))
11099 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
))
11100 DestroyItem( i
, j
, update
);
11102 // in equipment and bag list
11103 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11104 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11105 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
))
11106 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11109 void Player::DestroyConjuredItems( bool update
)
11111 // used when entering arena
11112 // destroys all conjured items
11113 sLog
.outDebug( "STORAGE: DestroyConjuredItems" );
11116 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
11117 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11118 if (pItem
->IsConjuredConsumable())
11119 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11121 // in inventory bags
11122 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11123 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11124 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
11125 if (Item
* pItem
= pBag
->GetItemByPos(j
))
11126 if (pItem
->IsConjuredConsumable())
11127 DestroyItem( i
, j
, update
);
11129 // in equipment and bag list
11130 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11131 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11132 if (pItem
->IsConjuredConsumable())
11133 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11136 void Player::DestroyItemCount( Item
* pItem
, uint32
&count
, bool update
)
11141 sLog
.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem
->GetGUIDLow(),pItem
->GetEntry(), count
);
11143 if( pItem
->GetCount() <= count
)
11145 count
-= pItem
->GetCount();
11147 DestroyItem( pItem
->GetBagSlot(),pItem
->GetSlot(), update
);
11151 ItemRemovedQuestCheck( pItem
->GetEntry(), count
);
11152 pItem
->SetCount( pItem
->GetCount() - count
);
11154 if( IsInWorld() & update
)
11155 pItem
->SendUpdateToPlayer( this );
11156 pItem
->SetState(ITEM_CHANGED
, this);
11160 void Player::SplitItem( uint16 src
, uint16 dst
, uint32 count
)
11162 uint8 srcbag
= src
>> 8;
11163 uint8 srcslot
= src
& 255;
11165 uint8 dstbag
= dst
>> 8;
11166 uint8 dstslot
= dst
& 255;
11168 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
11171 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
11175 // not let split all items (can be only at cheating)
11176 if(pSrcItem
->GetCount() == count
)
11178 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
11182 // not let split more existed items (can be only at cheating)
11183 if(pSrcItem
->GetCount() < count
)
11185 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT
, pSrcItem
, NULL
);
11189 if(pSrcItem
->m_lootGenerated
) // prevent split looting item (item
11191 //best error message found for attempting to split while looting
11192 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
11196 sLog
.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag
, dstslot
, pSrcItem
->GetEntry(), count
);
11197 Item
*pNewItem
= pSrcItem
->CloneItem( count
, this );
11200 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
11204 if( IsInventoryPos( dst
) )
11206 // change item amount before check (for unique max count check)
11207 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11209 ItemPosCountVec dest
;
11210 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pNewItem
, false );
11211 if( msg
!= EQUIP_ERR_OK
)
11214 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11215 SendEquipError( msg
, pSrcItem
, NULL
);
11220 pSrcItem
->SendUpdateToPlayer( this );
11221 pSrcItem
->SetState(ITEM_CHANGED
, this);
11222 StoreItem( dest
, pNewItem
, true);
11224 else if( IsBankPos ( dst
) )
11226 // change item amount before check (for unique max count check)
11227 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11229 ItemPosCountVec dest
;
11230 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pNewItem
, false );
11231 if( msg
!= EQUIP_ERR_OK
)
11234 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11235 SendEquipError( msg
, pSrcItem
, NULL
);
11240 pSrcItem
->SendUpdateToPlayer( this );
11241 pSrcItem
->SetState(ITEM_CHANGED
, this);
11242 BankItem( dest
, pNewItem
, true);
11244 else if( IsEquipmentPos ( dst
) )
11246 // change item amount before check (for unique max count check), provide space for splitted items
11247 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11250 uint8 msg
= CanEquipItem( dstslot
, dest
, pNewItem
, false );
11251 if( msg
!= EQUIP_ERR_OK
)
11254 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11255 SendEquipError( msg
, pSrcItem
, NULL
);
11260 pSrcItem
->SendUpdateToPlayer( this );
11261 pSrcItem
->SetState(ITEM_CHANGED
, this);
11262 EquipItem( dest
, pNewItem
, true);
11263 AutoUnequipOffhandIfNeed();
11267 void Player::SwapItem( uint16 src
, uint16 dst
)
11269 uint8 srcbag
= src
>> 8;
11270 uint8 srcslot
= src
& 255;
11272 uint8 dstbag
= dst
>> 8;
11273 uint8 dstslot
= dst
& 255;
11275 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
11276 Item
*pDstItem
= GetItemByPos( dstbag
, dstslot
);
11281 sLog
.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag
, dstslot
, pSrcItem
->GetEntry());
11285 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD
, pSrcItem
, pDstItem
);
11291 if(pSrcItem
->m_lootGenerated
) // prevent swap looting item
11293 //best error message found for attempting to swap while looting
11294 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pSrcItem
, NULL
);
11298 // check unequip potability for equipped items and bank bags
11299 if(IsEquipmentPos ( src
) || IsBagPos ( src
))
11301 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11302 uint8 msg
= CanUnequipItem( src
, !IsBagPos ( src
) || IsBagPos ( dst
) || pDstItem
&& pDstItem
->IsBag() && ((Bag
*)pDstItem
)->IsEmpty());
11303 if(msg
!= EQUIP_ERR_OK
)
11305 SendEquipError( msg
, pSrcItem
, pDstItem
);
11310 // prevent put equipped/bank bag in self
11311 if( IsBagPos ( src
) && srcslot
== dstbag
)
11313 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
11321 if(pDstItem
->m_lootGenerated
) // prevent swap looting item
11323 //best error message found for attempting to swap while looting
11324 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pDstItem
, NULL
);
11328 // check unequip potability for equipped items and bank bags
11329 if(IsEquipmentPos ( dst
) || IsBagPos ( dst
))
11331 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11332 uint8 msg
= CanUnequipItem( dst
, !IsBagPos ( dst
) || IsBagPos ( src
) || pSrcItem
->IsBag() && ((Bag
*)pSrcItem
)->IsEmpty());
11333 if(msg
!= EQUIP_ERR_OK
)
11335 SendEquipError( msg
, pSrcItem
, pDstItem
);
11341 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
11342 // or swap empty bag with another empty or not empty bag (with items exchange)
11347 if( IsInventoryPos( dst
) )
11349 ItemPosCountVec dest
;
11350 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pSrcItem
, false );
11351 if( msg
!= EQUIP_ERR_OK
)
11353 SendEquipError( msg
, pSrcItem
, NULL
);
11357 RemoveItem(srcbag
, srcslot
, true);
11358 StoreItem( dest
, pSrcItem
, true);
11360 else if( IsBankPos ( dst
) )
11362 ItemPosCountVec dest
;
11363 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pSrcItem
, false);
11364 if( msg
!= EQUIP_ERR_OK
)
11366 SendEquipError( msg
, pSrcItem
, NULL
);
11370 RemoveItem(srcbag
, srcslot
, true);
11371 BankItem( dest
, pSrcItem
, true);
11373 else if( IsEquipmentPos ( dst
) )
11376 uint8 msg
= CanEquipItem( dstslot
, dest
, pSrcItem
, false );
11377 if( msg
!= EQUIP_ERR_OK
)
11379 SendEquipError( msg
, pSrcItem
, NULL
);
11383 RemoveItem(srcbag
, srcslot
, true);
11384 EquipItem( dest
, pSrcItem
, true);
11385 AutoUnequipOffhandIfNeed();
11391 // attempt merge to / fill target item
11392 if(!pSrcItem
->IsBag() && !pDstItem
->IsBag())
11395 ItemPosCountVec sDest
;
11397 if( IsInventoryPos( dst
) )
11398 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
11399 else if( IsBankPos ( dst
) )
11400 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
11401 else if( IsEquipmentPos ( dst
) )
11402 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, false );
11406 // can be merge/fill
11407 if(msg
== EQUIP_ERR_OK
)
11409 if( pSrcItem
->GetCount() + pDstItem
->GetCount() <= pSrcItem
->GetProto()->GetMaxStackSize())
11411 RemoveItem(srcbag
, srcslot
, true);
11413 if( IsInventoryPos( dst
) )
11414 StoreItem( sDest
, pSrcItem
, true);
11415 else if( IsBankPos ( dst
) )
11416 BankItem( sDest
, pSrcItem
, true);
11417 else if( IsEquipmentPos ( dst
) )
11419 EquipItem( eDest
, pSrcItem
, true);
11420 AutoUnequipOffhandIfNeed();
11425 pSrcItem
->SetCount( pSrcItem
->GetCount() + pDstItem
->GetCount() - pSrcItem
->GetProto()->GetMaxStackSize());
11426 pDstItem
->SetCount( pSrcItem
->GetProto()->GetMaxStackSize());
11427 pSrcItem
->SetState(ITEM_CHANGED
, this);
11428 pDstItem
->SetState(ITEM_CHANGED
, this);
11431 pSrcItem
->SendUpdateToPlayer( this );
11432 pDstItem
->SendUpdateToPlayer( this );
11439 // impossible merge/fill, do real swap
11442 // check src->dest move possibility
11443 ItemPosCountVec sDest
;
11445 if( IsInventoryPos( dst
) )
11446 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
11447 else if( IsBankPos( dst
) )
11448 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
11449 else if( IsEquipmentPos( dst
) )
11451 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, true );
11452 if( msg
== EQUIP_ERR_OK
)
11453 msg
= CanUnequipItem( eDest
, true );
11456 if( msg
!= EQUIP_ERR_OK
)
11458 SendEquipError( msg
, pSrcItem
, pDstItem
);
11462 // check dest->src move possibility
11463 ItemPosCountVec sDest2
;
11465 if( IsInventoryPos( src
) )
11466 msg
= CanStoreItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11467 else if( IsBankPos( src
) )
11468 msg
= CanBankItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11469 else if( IsEquipmentPos( src
) )
11471 msg
= CanEquipItem( srcslot
, eDest2
, pDstItem
, true);
11472 if( msg
== EQUIP_ERR_OK
)
11473 msg
= CanUnequipItem( eDest2
, true);
11476 if( msg
!= EQUIP_ERR_OK
)
11478 SendEquipError( msg
, pDstItem
, pSrcItem
);
11482 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11483 if(pSrcItem
->IsBag() && pDstItem
->IsBag())
11485 Bag
* emptyBag
= NULL
;
11486 Bag
* fullBag
= NULL
;
11487 if(((Bag
*)pSrcItem
)->IsEmpty() && !IsBagPos(src
))
11489 emptyBag
= (Bag
*)pSrcItem
;
11490 fullBag
= (Bag
*)pDstItem
;
11492 else if(((Bag
*)pDstItem
)->IsEmpty() && !IsBagPos(dst
))
11494 emptyBag
= (Bag
*)pDstItem
;
11495 fullBag
= (Bag
*)pSrcItem
;
11498 // bag swap (with items exchange) case
11499 if(emptyBag
&& fullBag
)
11501 ItemPrototype
const* emotyProto
= emptyBag
->GetProto();
11505 for(int i
=0; i
< fullBag
->GetBagSize(); ++i
)
11507 Item
*bagItem
= fullBag
->GetItemByPos(i
);
11511 ItemPrototype
const* bagItemProto
= bagItem
->GetProto();
11512 if (!bagItemProto
|| !ItemCanGoIntoBag(bagItemProto
, emotyProto
))
11514 // one from items not go to empry target bag
11515 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
11523 if (count
> emptyBag
->GetBagSize())
11525 // too small targeted bag
11526 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
, pSrcItem
, pDstItem
);
11531 count
= 0; // will pos in new bag
11532 for(int i
=0; i
< fullBag
->GetBagSize(); ++i
)
11534 Item
*bagItem
= fullBag
->GetItemByPos(i
);
11538 fullBag
->RemoveItem(i
, true);
11539 emptyBag
->StoreItem(count
, bagItem
, true);
11540 bagItem
->SetState(ITEM_CHANGED
, this);
11547 // now do moves, remove...
11548 RemoveItem(dstbag
, dstslot
, false);
11549 RemoveItem(srcbag
, srcslot
, false);
11552 if( IsInventoryPos( dst
) )
11553 StoreItem(sDest
, pSrcItem
, true);
11554 else if( IsBankPos( dst
) )
11555 BankItem(sDest
, pSrcItem
, true);
11556 else if( IsEquipmentPos( dst
) )
11557 EquipItem(eDest
, pSrcItem
, true);
11560 if( IsInventoryPos( src
) )
11561 StoreItem(sDest2
, pDstItem
, true);
11562 else if( IsBankPos( src
) )
11563 BankItem(sDest2
, pDstItem
, true);
11564 else if( IsEquipmentPos( src
) )
11565 EquipItem(eDest2
, pDstItem
, true);
11567 AutoUnequipOffhandIfNeed();
11570 void Player::AddItemToBuyBackSlot( Item
*pItem
)
11574 uint32 slot
= m_currentBuybackSlot
;
11575 // if current back slot non-empty search oldest or free
11578 uint32 oldest_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
);
11579 uint32 oldest_slot
= BUYBACK_SLOT_START
;
11581 for(uint32 i
= BUYBACK_SLOT_START
+1; i
< BUYBACK_SLOT_END
; ++i
)
11590 uint32 i_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ i
- BUYBACK_SLOT_START
);
11592 if(oldest_time
> i_time
)
11594 oldest_time
= i_time
;
11600 slot
= oldest_slot
;
11603 RemoveItemFromBuyBackSlot( slot
, true );
11604 sLog
.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem
->GetEntry(), slot
);
11606 m_items
[slot
] = pItem
;
11607 time_t base
= time(NULL
);
11608 uint32 etime
= uint32(base
- m_logintime
+ (30 * 3600));
11609 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11611 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ eslot
* 2, pItem
->GetGUID() );
11612 ItemPrototype
const *pProto
= pItem
->GetProto();
11614 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, pProto
->SellPrice
* pItem
->GetCount() );
11616 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11617 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, (uint32
)etime
);
11619 // move to next (for non filled list is move most optimized choice)
11620 if(m_currentBuybackSlot
< BUYBACK_SLOT_END
-1)
11621 ++m_currentBuybackSlot
;
11625 Item
* Player::GetItemFromBuyBackSlot( uint32 slot
)
11627 sLog
.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot
);
11628 if( slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11629 return m_items
[slot
];
11633 void Player::RemoveItemFromBuyBackSlot( uint32 slot
, bool del
)
11635 sLog
.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot
);
11636 if( slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11638 Item
*pItem
= m_items
[slot
];
11641 pItem
->RemoveFromWorld();
11642 if(del
) pItem
->SetState(ITEM_REMOVED
, this);
11645 m_items
[slot
] = NULL
;
11647 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11648 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ eslot
* 2, 0 );
11649 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11650 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, 0 );
11652 // if current backslot is filled set to now free slot
11653 if(m_items
[m_currentBuybackSlot
])
11654 m_currentBuybackSlot
= slot
;
11658 void Player::SendEquipError( uint8 msg
, Item
* pItem
, Item
*pItem2
)
11660 sLog
.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg
);
11661 WorldPacket
data( SMSG_INVENTORY_CHANGE_FAILURE
, (msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
? 22 : 18) );
11662 data
<< uint8(msg
);
11666 data
<< uint64(pItem
? pItem
->GetGUID() : 0);
11667 data
<< uint64(pItem2
? pItem2
->GetGUID() : 0);
11668 data
<< uint8(0); // not 0 there...
11670 if(msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
)
11675 if(ItemPrototype
const* proto
= pItem
->GetProto())
11676 level
= proto
->RequiredLevel
;
11678 data
<< uint32(level
); // new 2.4.0
11681 GetSession()->SendPacket(&data
);
11684 void Player::SendBuyError( uint8 msg
, Creature
* pCreature
, uint32 item
, uint32 param
)
11686 sLog
.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11687 WorldPacket
data( SMSG_BUY_FAILED
, (8+4+4+1) );
11688 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11689 data
<< uint32(item
);
11691 data
<< uint32(param
);
11692 data
<< uint8(msg
);
11693 GetSession()->SendPacket(&data
);
11696 void Player::SendSellError( uint8 msg
, Creature
* pCreature
, uint64 guid
, uint32 param
)
11698 sLog
.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11699 WorldPacket
data( SMSG_SELL_ITEM
,(8+8+(param
?4:0)+1)); // last check 2.0.10
11700 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11701 data
<< uint64(guid
);
11703 data
<< uint32(param
);
11704 data
<< uint8(msg
);
11705 GetSession()->SendPacket(&data
);
11708 void Player::ClearTrade()
11711 acceptTrade
= false;
11712 for(int i
= 0; i
< TRADE_SLOT_COUNT
; i
++)
11713 tradeItems
[i
] = NULL_SLOT
;
11716 void Player::TradeCancel(bool sendback
)
11720 // send yellow "Trade canceled" message to both traders
11724 ws
->SendCancelTrade();
11725 ws
= pTrader
->GetSession();
11726 if(!ws
->PlayerLogout())
11727 ws
->SendCancelTrade();
11731 pTrader
->ClearTrade();
11732 // prevent loss of reference
11733 pTrader
->pTrader
= NULL
;
11738 void Player::UpdateItemDuration(uint32 time
, bool realtimeonly
)
11740 if(m_itemDuration
.empty())
11743 sLog
.outDebug("Player::UpdateItemDuration(%u,%u)", time
,realtimeonly
);
11745 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); )
11748 ++itr
; // current element can be erased in UpdateDuration
11750 if (realtimeonly
&& item
->GetProto()->Duration
< 0 || !realtimeonly
)
11751 item
->UpdateDuration(this,time
);
11755 void Player::UpdateEnchantTime(uint32 time
)
11757 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11761 if(!itr
->item
->GetEnchantmentId(itr
->slot
))
11763 next
= m_enchantDuration
.erase(itr
);
11765 else if(itr
->leftduration
<= time
)
11767 ApplyEnchantment(itr
->item
,itr
->slot
,false,false);
11768 itr
->item
->ClearEnchantment(itr
->slot
);
11769 next
= m_enchantDuration
.erase(itr
);
11771 else if(itr
->leftduration
> time
)
11773 itr
->leftduration
-= time
;
11779 void Player::AddEnchantmentDurations(Item
*item
)
11781 for(int x
=0;x
<MAX_ENCHANTMENT_SLOT
;++x
)
11783 if(!item
->GetEnchantmentId(EnchantmentSlot(x
)))
11786 uint32 duration
= item
->GetEnchantmentDuration(EnchantmentSlot(x
));
11788 AddEnchantmentDuration(item
,EnchantmentSlot(x
),duration
);
11792 void Player::RemoveEnchantmentDurations(Item
*item
)
11794 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();)
11796 if(itr
->item
== item
)
11798 // save duration in item
11799 item
->SetEnchantmentDuration(EnchantmentSlot(itr
->slot
),itr
->leftduration
);
11800 itr
= m_enchantDuration
.erase(itr
);
11807 void Player::RemoveAllEnchantments(EnchantmentSlot slot
)
11809 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11810 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11813 if(itr
->slot
==slot
)
11815 if(itr
->item
&& itr
->item
->GetEnchantmentId(slot
))
11817 // remove from stats
11818 ApplyEnchantment(itr
->item
,slot
,false,false);
11820 itr
->item
->ClearEnchantment(slot
);
11822 // remove from update list
11823 next
= m_enchantDuration
.erase(itr
);
11829 // remove enchants from inventory items
11830 // NOTE: no need to remove these from stats, since these aren't equipped
11832 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
11834 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11835 if( pItem
&& pItem
->GetEnchantmentId(slot
) )
11836 pItem
->ClearEnchantment(slot
);
11839 // in inventory bags
11840 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11842 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11845 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
11847 Item
* pItem
= pBag
->GetItemByPos(j
);
11848 if( pItem
&& pItem
->GetEnchantmentId(slot
) )
11849 pItem
->ClearEnchantment(slot
);
11855 // duration == 0 will remove item enchant
11856 void Player::AddEnchantmentDuration(Item
*item
,EnchantmentSlot slot
,uint32 duration
)
11861 if(slot
>= MAX_ENCHANTMENT_SLOT
)
11864 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
11866 if(itr
->item
== item
&& itr
->slot
== slot
)
11868 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
11869 m_enchantDuration
.erase(itr
);
11873 if(item
&& duration
> 0 )
11875 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item
->GetGUID(),slot
,uint32(duration
/1000));
11876 m_enchantDuration
.push_back(EnchantDuration(item
,slot
,duration
));
11880 void Player::ApplyEnchantment(Item
*item
,bool apply
)
11882 for(uint32 slot
= 0; slot
< MAX_ENCHANTMENT_SLOT
; ++slot
)
11883 ApplyEnchantment(item
, EnchantmentSlot(slot
), apply
);
11886 void Player::ApplyEnchantment(Item
*item
,EnchantmentSlot slot
,bool apply
, bool apply_dur
, bool ignore_condition
)
11891 if(!item
->IsEquipped())
11894 if(slot
>= MAX_ENCHANTMENT_SLOT
)
11897 uint32 enchant_id
= item
->GetEnchantmentId(slot
);
11901 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
11905 if(!ignore_condition
&& pEnchant
->EnchantmentCondition
&& !((Player
*)this)->EnchantmentFitsRequirements(pEnchant
->EnchantmentCondition
, -1))
11908 for (int s
=0; s
<3; s
++)
11910 uint32 enchant_display_type
= pEnchant
->type
[s
];
11911 uint32 enchant_amount
= pEnchant
->amount
[s
];
11912 uint32 enchant_spell_id
= pEnchant
->spellid
[s
];
11914 switch(enchant_display_type
)
11916 case ITEM_ENCHANTMENT_TYPE_NONE
:
11918 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
:
11919 // processed in Player::CastItemCombatSpell
11921 case ITEM_ENCHANTMENT_TYPE_DAMAGE
:
11922 if (item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
11923 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11924 else if (item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
11925 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11926 else if (item
->GetSlot() == EQUIPMENT_SLOT_RANGED
)
11927 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11929 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL
:
11930 if(enchant_spell_id
)
11934 int32 basepoints
= 0;
11935 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11936 if (item
->GetItemRandomPropertyId())
11938 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11941 // Search enchant_amount
11942 for (int k
=0; k
<3; k
++)
11944 if(item_rand
->enchant_id
[k
] == enchant_id
)
11946 basepoints
= int32((item_rand
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11952 // Cast custom spell vs all equal basepoints getted from enchant_amount
11954 CastCustomSpell(this,enchant_spell_id
,&basepoints
,&basepoints
,&basepoints
,true,item
);
11956 CastSpell(this,enchant_spell_id
,true,item
);
11959 RemoveAurasDueToItemSpell(item
,enchant_spell_id
);
11962 case ITEM_ENCHANTMENT_TYPE_RESISTANCE
:
11963 if (!enchant_amount
)
11965 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11968 for (int k
=0; k
<3; k
++)
11970 if(item_rand
->enchant_id
[k
] == enchant_id
)
11972 enchant_amount
= uint32((item_rand
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11979 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START
+ enchant_spell_id
), TOTAL_VALUE
, float(enchant_amount
), apply
);
11981 case ITEM_ENCHANTMENT_TYPE_STAT
:
11983 if (!enchant_amount
)
11985 ItemRandomSuffixEntry
const *item_rand_suffix
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11986 if(item_rand_suffix
)
11988 for (int k
=0; k
<3; k
++)
11990 if(item_rand_suffix
->enchant_id
[k
] == enchant_id
)
11992 enchant_amount
= uint32((item_rand_suffix
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11999 sLog
.outDebug("Adding %u to stat nb %u",enchant_amount
,enchant_spell_id
);
12000 switch (enchant_spell_id
)
12002 case ITEM_MOD_AGILITY
:
12003 sLog
.outDebug("+ %u AGILITY",enchant_amount
);
12004 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12005 ApplyStatBuffMod(STAT_AGILITY
, enchant_amount
, apply
);
12007 case ITEM_MOD_STRENGTH
:
12008 sLog
.outDebug("+ %u STRENGTH",enchant_amount
);
12009 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12010 ApplyStatBuffMod(STAT_STRENGTH
, enchant_amount
, apply
);
12012 case ITEM_MOD_INTELLECT
:
12013 sLog
.outDebug("+ %u INTELLECT",enchant_amount
);
12014 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12015 ApplyStatBuffMod(STAT_INTELLECT
, enchant_amount
, apply
);
12017 case ITEM_MOD_SPIRIT
:
12018 sLog
.outDebug("+ %u SPIRIT",enchant_amount
);
12019 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12020 ApplyStatBuffMod(STAT_SPIRIT
, enchant_amount
, apply
);
12022 case ITEM_MOD_STAMINA
:
12023 sLog
.outDebug("+ %u STAMINA",enchant_amount
);
12024 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12025 ApplyStatBuffMod(STAT_STAMINA
, enchant_amount
, apply
);
12027 case ITEM_MOD_DEFENSE_SKILL_RATING
:
12028 ((Player
*)this)->ApplyRatingMod(CR_DEFENSE_SKILL
, enchant_amount
, apply
);
12029 sLog
.outDebug("+ %u DEFENCE", enchant_amount
);
12031 case ITEM_MOD_DODGE_RATING
:
12032 ((Player
*)this)->ApplyRatingMod(CR_DODGE
, enchant_amount
, apply
);
12033 sLog
.outDebug("+ %u DODGE", enchant_amount
);
12035 case ITEM_MOD_PARRY_RATING
:
12036 ((Player
*)this)->ApplyRatingMod(CR_PARRY
, enchant_amount
, apply
);
12037 sLog
.outDebug("+ %u PARRY", enchant_amount
);
12039 case ITEM_MOD_BLOCK_RATING
:
12040 ((Player
*)this)->ApplyRatingMod(CR_BLOCK
, enchant_amount
, apply
);
12041 sLog
.outDebug("+ %u SHIELD_BLOCK", enchant_amount
);
12043 case ITEM_MOD_HIT_MELEE_RATING
:
12044 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
12045 sLog
.outDebug("+ %u MELEE_HIT", enchant_amount
);
12047 case ITEM_MOD_HIT_RANGED_RATING
:
12048 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
12049 sLog
.outDebug("+ %u RANGED_HIT", enchant_amount
);
12051 case ITEM_MOD_HIT_SPELL_RATING
:
12052 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
12053 sLog
.outDebug("+ %u SPELL_HIT", enchant_amount
);
12055 case ITEM_MOD_CRIT_MELEE_RATING
:
12056 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
12057 sLog
.outDebug("+ %u MELEE_CRIT", enchant_amount
);
12059 case ITEM_MOD_CRIT_RANGED_RATING
:
12060 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
12061 sLog
.outDebug("+ %u RANGED_CRIT", enchant_amount
);
12063 case ITEM_MOD_CRIT_SPELL_RATING
:
12064 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
12065 sLog
.outDebug("+ %u SPELL_CRIT", enchant_amount
);
12067 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
12069 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
12070 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12072 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
12073 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12075 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
12076 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12078 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
12079 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12081 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
12082 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12084 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
12085 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12087 // case ITEM_MOD_HASTE_MELEE_RATING:
12088 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
12090 // case ITEM_MOD_HASTE_RANGED_RATING:
12091 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
12093 case ITEM_MOD_HASTE_SPELL_RATING
:
12094 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
12096 case ITEM_MOD_HIT_RATING
:
12097 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
12098 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
12099 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
12100 sLog
.outDebug("+ %u HIT", enchant_amount
);
12102 case ITEM_MOD_CRIT_RATING
:
12103 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
12104 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
12105 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
12106 sLog
.outDebug("+ %u CRITICAL", enchant_amount
);
12108 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
12109 // case ITEM_MOD_HIT_TAKEN_RATING:
12110 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
12111 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
12112 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
12114 // case ITEM_MOD_CRIT_TAKEN_RATING:
12115 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
12116 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
12117 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
12119 case ITEM_MOD_RESILIENCE_RATING
:
12120 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, enchant_amount
, apply
);
12121 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, enchant_amount
, apply
);
12122 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, enchant_amount
, apply
);
12123 sLog
.outDebug("+ %u RESILIENCE", enchant_amount
);
12125 case ITEM_MOD_HASTE_RATING
:
12126 ((Player
*)this)->ApplyRatingMod(CR_HASTE_MELEE
, enchant_amount
, apply
);
12127 ((Player
*)this)->ApplyRatingMod(CR_HASTE_RANGED
, enchant_amount
, apply
);
12128 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
12129 sLog
.outDebug("+ %u HASTE", enchant_amount
);
12131 case ITEM_MOD_EXPERTISE_RATING
:
12132 ((Player
*)this)->ApplyRatingMod(CR_EXPERTISE
, enchant_amount
, apply
);
12133 sLog
.outDebug("+ %u EXPERTISE", enchant_amount
);
12135 case ITEM_MOD_ATTACK_POWER
:
12136 HandleStatModifier(UNIT_MOD_ATTACK_POWER
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12137 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12138 sLog
.outDebug("+ %u ATTACK_POWER", enchant_amount
);
12140 case ITEM_MOD_RANGED_ATTACK_POWER
:
12141 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
12142 sLog
.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount
);
12144 case ITEM_MOD_FERAL_ATTACK_POWER
:
12145 ((Player
*)this)->ApplyFeralAPBonus(enchant_amount
, apply
);
12146 sLog
.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount
);
12148 case ITEM_MOD_SPELL_HEALING_DONE
:
12149 ((Player
*)this)->ApplySpellHealingBonus(enchant_amount
, apply
);
12150 sLog
.outDebug("+ %u SPELL_HEALING_DONE", enchant_amount
);
12152 case ITEM_MOD_SPELL_DAMAGE_DONE
:
12153 ((Player
*)this)->ApplySpellDamageBonus(enchant_amount
, apply
);
12154 sLog
.outDebug("+ %u SPELL_DAMAGE_DONE", enchant_amount
);
12156 case ITEM_MOD_MANA_REGENERATION
:
12157 ((Player
*)this)->ApplyManaRegenBonus(enchant_amount
, apply
);
12158 sLog
.outDebug("+ %u MANA_REGENERATION", enchant_amount
);
12160 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
12161 ((Player
*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION
, enchant_amount
, apply
);
12162 sLog
.outDebug("+ %u ARMOR PENETRATION", enchant_amount
);
12164 case ITEM_MOD_SPELL_POWER
:
12165 ((Player
*)this)->ApplySpellHealingBonus(enchant_amount
, apply
);
12166 ((Player
*)this)->ApplySpellDamageBonus(enchant_amount
, apply
);
12167 sLog
.outDebug("+ %u SPELL_POWER", enchant_amount
);
12174 case ITEM_ENCHANTMENT_TYPE_TOTEM
: // Shaman Rockbiter Weapon
12176 if(getClass() == CLASS_SHAMAN
)
12178 float addValue
= 0.0f
;
12179 if(item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
12181 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/1000.0f
);
12182 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, addValue
, apply
);
12184 else if(item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
12186 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/1000.0f
);
12187 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, addValue
, apply
);
12192 case ITEM_ENCHANTMENT_TYPE_USE_SPELL
:
12193 // processed in Player::CastItemUseSpell
12195 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET
:
12199 sLog
.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id
, enchant_display_type
);
12201 } /*switch(enchant_display_type)*/
12204 // visualize enchantment at player and equipped items
12205 if(slot
< MAX_INSPECTED_ENCHANTMENT_SLOT
)
12207 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (item
->GetSlot() * MAX_VISIBLE_ITEM_OFFSET
);
12208 SetUInt32Value(VisibleBase
+ 1 + slot
, apply
? item
->GetEnchantmentId(slot
) : 0);
12216 uint32 duration
= item
->GetEnchantmentDuration(slot
);
12218 AddEnchantmentDuration(item
,slot
,duration
);
12222 // duration == 0 will remove EnchantDuration
12223 AddEnchantmentDuration(item
,slot
,0);
12228 void Player::SendEnchantmentDurations()
12230 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
12232 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr
->item
->GetGUID(),itr
->slot
,uint32(itr
->leftduration
)/1000);
12236 void Player::SendItemDurations()
12238 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end();++itr
)
12240 (*itr
)->SendTimeUpdate(this);
12244 void Player::SendNewItem(Item
*item
, uint32 count
, bool received
, bool created
, bool broadcast
)
12246 if(!item
) // prevent crash
12249 // last check 2.0.10
12250 WorldPacket
data( SMSG_ITEM_PUSH_RESULT
, (8+4+4+4+1+4+4+4+4+4) );
12251 data
<< GetGUID(); // player GUID
12252 data
<< uint32(received
); // 0=looted, 1=from npc
12253 data
<< uint32(created
); // 0=received, 1=created
12254 data
<< uint32(1); // always 0x01 (probably meant to be count of listed items)
12255 data
<< (uint8
)item
->GetBagSlot(); // bagslot
12256 // item slot, but when added to stack: 0xFFFFFFFF
12257 data
<< (uint32
) ((item
->GetCount()==count
) ? item
->GetSlot() : -1);
12258 data
<< uint32(item
->GetEntry()); // item id
12259 data
<< uint32(item
->GetItemSuffixFactor()); // SuffixFactor
12260 data
<< uint32(item
->GetItemRandomPropertyId()); // random item property id
12261 data
<< uint32(count
); // count of items
12262 data
<< GetItemCount(item
->GetEntry()); // count of items in inventory
12264 if (broadcast
&& GetGroup())
12265 GetGroup()->BroadcastPacket(&data
, true);
12267 GetSession()->SendPacket(&data
);
12270 /*********************************************************/
12271 /*** QUEST SYSTEM ***/
12272 /*********************************************************/
12274 void Player::PrepareQuestMenu( uint64 guid
)
12277 QuestRelations
* pObjectQR
;
12278 QuestRelations
* pObjectQIR
;
12279 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
12282 pObject
= (Object
*)pCreature
;
12283 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
12284 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
12288 GameObject
*pGameObject
= ObjectAccessor::GetGameObject(*this, guid
);
12291 pObject
= (Object
*)pGameObject
;
12292 pObjectQR
= &objmgr
.mGOQuestRelations
;
12293 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
12299 QuestMenu
&qm
= PlayerTalkClass
->GetQuestMenu();
12302 for(QuestRelations::const_iterator i
= pObjectQIR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQIR
->upper_bound(pObject
->GetEntry()); ++i
)
12304 uint32 quest_id
= i
->second
;
12305 QuestStatus status
= GetQuestStatus( quest_id
);
12306 if ( status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus( quest_id
) )
12307 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_REWARD_REP
);
12308 else if ( status
== QUEST_STATUS_INCOMPLETE
)
12309 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_INCOMPLETE
);
12310 else if (status
== QUEST_STATUS_AVAILABLE
)
12311 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_CHAT
);
12314 for(QuestRelations::const_iterator i
= pObjectQR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++i
)
12316 uint32 quest_id
= i
->second
;
12317 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
12318 if(!pQuest
) continue;
12320 QuestStatus status
= GetQuestStatus( quest_id
);
12322 if (pQuest
->IsAutoComplete() && CanTakeQuest(pQuest
, false))
12323 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_REWARD_REP
);
12324 else if ( status
== QUEST_STATUS_NONE
&& CanTakeQuest( pQuest
, false ) )
12325 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_AVAILABLE
);
12329 void Player::SendPreparedQuest( uint64 guid
)
12331 QuestMenu
& questMenu
= PlayerTalkClass
->GetQuestMenu();
12332 if( questMenu
.Empty() )
12335 QuestMenuItem
const& qmi0
= questMenu
.GetItem( 0 );
12337 uint32 status
= qmi0
.m_qIcon
;
12339 // single element case
12340 if ( questMenu
.MenuItemCount() == 1 )
12342 // Auto open -- maybe also should verify there is no greeting
12343 uint32 quest_id
= qmi0
.m_qId
;
12344 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
12347 if( status
== DIALOG_STATUS_REWARD_REP
&& !GetQuestRewardStatus( quest_id
) )
12348 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, CanRewardQuest(pQuest
,false), true );
12349 else if( status
== DIALOG_STATUS_INCOMPLETE
)
12350 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, false, true );
12351 // Send completable on repeatable quest if player don't have quest
12352 else if( pQuest
->IsRepeatable() && !pQuest
->IsDaily() )
12353 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, CanCompleteRepeatableQuest(pQuest
), true );
12355 PlayerTalkClass
->SendQuestGiverQuestDetails( pQuest
, guid
, true );
12358 // multiply entries
12364 std::string title
= "";
12365 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
12368 uint32 textid
= pCreature
->GetNpcTextId();
12369 GossipText
const* gossiptext
= objmgr
.GetGossipText(textid
);
12372 qe
._Delay
= 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12373 qe
._Emote
= 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12378 qe
= gossiptext
->Options
[0].Emotes
[0];
12380 if(!gossiptext
->Options
[0].Text_0
.empty())
12382 title
= gossiptext
->Options
[0].Text_0
;
12384 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
12387 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
12390 if (nl
->Text_0
[0].size() > loc_idx
&& !nl
->Text_0
[0][loc_idx
].empty())
12391 title
= nl
->Text_0
[0][loc_idx
];
12397 title
= gossiptext
->Options
[0].Text_1
;
12399 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
12402 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
12405 if (nl
->Text_1
[0].size() > loc_idx
&& !nl
->Text_1
[0][loc_idx
].empty())
12406 title
= nl
->Text_1
[0][loc_idx
];
12412 PlayerTalkClass
->SendQuestGiverQuestList( qe
, title
, guid
);
12416 bool Player::IsActiveQuest( uint32 quest_id
) const
12418 QuestStatusMap::const_iterator itr
= mQuestStatus
.find(quest_id
);
12420 return itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
;
12423 Quest
const * Player::GetNextQuest( uint64 guid
, Quest
const *pQuest
)
12426 QuestRelations
* pObjectQR
;
12427 QuestRelations
* pObjectQIR
;
12429 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
12432 pObject
= (Object
*)pCreature
;
12433 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
12434 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
12438 GameObject
*pGameObject
= ObjectAccessor::GetGameObject(*this, guid
);
12441 pObject
= (Object
*)pGameObject
;
12442 pObjectQR
= &objmgr
.mGOQuestRelations
;
12443 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
12449 uint32 nextQuestID
= pQuest
->GetNextQuestInChain();
12450 for(QuestRelations::const_iterator itr
= pObjectQR
->lower_bound(pObject
->GetEntry()); itr
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++itr
)
12452 if (itr
->second
== nextQuestID
)
12453 return objmgr
.GetQuestTemplate(nextQuestID
);
12459 bool Player::CanSeeStartQuest( Quest
const *pQuest
)
12461 if( SatisfyQuestRace( pQuest
, false ) && SatisfyQuestSkillOrClass( pQuest
, false ) &&
12462 SatisfyQuestExclusiveGroup( pQuest
, false ) && SatisfyQuestReputation( pQuest
, false ) &&
12463 SatisfyQuestPreviousQuest( pQuest
, false ) && SatisfyQuestNextChain( pQuest
, false ) &&
12464 SatisfyQuestPrevChain( pQuest
, false ) && SatisfyQuestDay( pQuest
, false ) )
12466 return getLevel() + sWorld
.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF
) >= pQuest
->GetMinLevel();
12472 bool Player::CanTakeQuest( Quest
const *pQuest
, bool msg
)
12474 return SatisfyQuestStatus( pQuest
, msg
) && SatisfyQuestExclusiveGroup( pQuest
, msg
)
12475 && SatisfyQuestRace( pQuest
, msg
) && SatisfyQuestLevel( pQuest
, msg
)
12476 && SatisfyQuestSkillOrClass( pQuest
, msg
) && SatisfyQuestReputation( pQuest
, msg
)
12477 && SatisfyQuestPreviousQuest( pQuest
, msg
) && SatisfyQuestTimed( pQuest
, msg
)
12478 && SatisfyQuestNextChain( pQuest
, msg
) && SatisfyQuestPrevChain( pQuest
, msg
)
12479 && SatisfyQuestDay( pQuest
, msg
);
12482 bool Player::CanAddQuest( Quest
const *pQuest
, bool msg
)
12484 if( !SatisfyQuestLog( msg
) )
12487 uint32 srcitem
= pQuest
->GetSrcItemId();
12490 uint32 count
= pQuest
->GetSrcItemCount();
12491 ItemPosCountVec dest
;
12492 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
12494 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12495 if( msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
12497 else if( msg
!= EQUIP_ERR_OK
)
12499 SendEquipError( msg
, NULL
, NULL
);
12506 bool Player::CanCompleteQuest( uint32 quest_id
)
12510 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12511 if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
12512 return false; // not allow re-complete quest
12514 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12519 // auto complete quest
12520 if (qInfo
->IsAutoComplete() && CanTakeQuest(qInfo
, false))
12523 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
12526 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12528 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12530 if( qInfo
->ReqItemCount
[i
]!= 0 && q_status
.m_itemcount
[i
] < qInfo
->ReqItemCount
[i
] )
12535 if ( qInfo
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
12537 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12539 if( qInfo
->ReqCreatureOrGOId
[i
] == 0 )
12542 if( qInfo
->ReqCreatureOrGOCount
[i
] != 0 && q_status
.m_creatureOrGOcount
[i
] < qInfo
->ReqCreatureOrGOCount
[i
] )
12547 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT
) && !q_status
.m_explored
)
12550 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && q_status
.m_timer
== 0 )
12553 if ( qInfo
->GetRewOrReqMoney() < 0 )
12555 if ( GetMoney() < uint32(-qInfo
->GetRewOrReqMoney()) )
12559 uint32 repFacId
= qInfo
->GetRepObjectiveFaction();
12560 if ( repFacId
&& GetReputation(repFacId
) < qInfo
->GetRepObjectiveValue() )
12569 bool Player::CanCompleteRepeatableQuest( Quest
const *pQuest
)
12571 // Solve problem that player don't have the quest and try complete it.
12572 // if repeatable she must be able to complete event if player don't have it.
12573 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12574 if( !CanTakeQuest(pQuest
, false) )
12577 if (pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12578 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12579 if( pQuest
->ReqItemId
[i
] && pQuest
->ReqItemCount
[i
] && !HasItemCount(pQuest
->ReqItemId
[i
],pQuest
->ReqItemCount
[i
]) )
12582 if( !CanRewardQuest(pQuest
, false) )
12588 bool Player::CanRewardQuest( Quest
const *pQuest
, bool msg
)
12590 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12591 if(!pQuest
->IsAutoComplete() && GetQuestStatus(pQuest
->GetQuestId()) != QUEST_STATUS_COMPLETE
)
12594 // daily quest can't be rewarded (25 daily quest already completed)
12595 if(!SatisfyQuestDay(pQuest
,true))
12598 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12599 if(GetQuestRewardStatus(pQuest
->GetQuestId()))
12602 // prevent receive reward with quest items in bank
12603 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12605 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12607 if( pQuest
->ReqItemCount
[i
]!= 0 &&
12608 GetItemCount(pQuest
->ReqItemId
[i
]) < pQuest
->ReqItemCount
[i
] )
12611 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, NULL
, NULL
);
12617 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12618 if(pQuest
->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest
->GetRewOrReqMoney()) )
12624 bool Player::CanRewardQuest( Quest
const *pQuest
, uint32 reward
, bool msg
)
12626 // prevent receive reward with quest items in bank or for not completed quest
12627 if(!CanRewardQuest(pQuest
,msg
))
12630 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
12632 if( pQuest
->RewChoiceItemId
[reward
] )
12634 ItemPosCountVec dest
;
12635 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] );
12636 if( res
!= EQUIP_ERR_OK
)
12638 SendEquipError( res
, NULL
, NULL
);
12644 if ( pQuest
->GetRewItemsCount() > 0 )
12646 for (uint32 i
= 0; i
< pQuest
->GetRewItemsCount(); ++i
)
12648 if( pQuest
->RewItemId
[i
] )
12650 ItemPosCountVec dest
;
12651 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] );
12652 if( res
!= EQUIP_ERR_OK
)
12654 SendEquipError( res
, NULL
, NULL
);
12664 void Player::AddQuest( Quest
const *pQuest
, Object
*questGiver
)
12666 uint16 log_slot
= FindQuestSlot( 0 );
12667 assert(log_slot
< MAX_QUEST_LOG_SIZE
);
12669 uint32 quest_id
= pQuest
->GetQuestId();
12671 // if not exist then created with set uState==NEW and rewarded=false
12672 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
12674 // check for repeatable quests status reset
12675 questStatusData
.m_status
= QUEST_STATUS_INCOMPLETE
;
12676 questStatusData
.m_explored
= false;
12678 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12680 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12681 questStatusData
.m_itemcount
[i
] = 0;
12684 if ( pQuest
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
12686 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12687 questStatusData
.m_creatureOrGOcount
[i
] = 0;
12690 GiveQuestSourceItem( pQuest
);
12691 AdjustQuestReqItemCount( pQuest
, questStatusData
);
12693 if( pQuest
->GetRepObjectiveFaction() )
12694 SetFactionVisibleForFactionId(pQuest
->GetRepObjectiveFaction());
12697 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
12699 uint32 limittime
= pQuest
->GetLimitTime();
12701 // shared timed quest
12702 if(questGiver
&& questGiver
->GetTypeId()==TYPEID_PLAYER
)
12703 limittime
= ((Player
*)questGiver
)->getQuestStatusMap()[quest_id
].m_timer
/ IN_MILISECONDS
;
12705 AddTimedQuest( quest_id
);
12706 questStatusData
.m_timer
= limittime
* IN_MILISECONDS
;
12707 qtime
= static_cast<uint32
>(time(NULL
)) + limittime
;
12710 questStatusData
.m_timer
= 0;
12712 SetQuestSlot(log_slot
, quest_id
, qtime
);
12714 if (questStatusData
.uState
!= QUEST_NEW
)
12715 questStatusData
.uState
= QUEST_CHANGED
;
12717 //starting initial quest script
12718 if(questGiver
&& pQuest
->GetQuestStartScript()!=0)
12719 sWorld
.ScriptsStart(sQuestStartScripts
, pQuest
->GetQuestStartScript(), questGiver
, this);
12721 // Some spells applied at quest activation
12722 SpellAreaForQuestMapBounds saBounds
= spellmgr
.GetSpellAreaForQuestMapBounds(quest_id
,true);
12723 if(saBounds
.first
!= saBounds
.second
)
12726 GetZoneAndAreaId(zone
,area
);
12728 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
12729 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,zone
,area
))
12730 if( !HasAura(itr
->second
->spellId
,0) )
12731 CastSpell(this,itr
->second
->spellId
,true);
12734 UpdateForQuestsGO();
12737 void Player::CompleteQuest( uint32 quest_id
)
12741 SetQuestStatus( quest_id
, QUEST_STATUS_COMPLETE
);
12743 uint16 log_slot
= FindQuestSlot( quest_id
);
12744 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12745 SetQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
12747 if(Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
))
12749 if( qInfo
->HasFlag(QUEST_FLAGS_AUTO_REWARDED
) )
12750 RewardQuest(qInfo
,0,this,false);
12752 SendQuestComplete( quest_id
);
12757 void Player::IncompleteQuest( uint32 quest_id
)
12761 SetQuestStatus( quest_id
, QUEST_STATUS_INCOMPLETE
);
12763 uint16 log_slot
= FindQuestSlot( quest_id
);
12764 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12765 RemoveQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
12769 void Player::RewardQuest( Quest
const *pQuest
, uint32 reward
, Object
* questGiver
, bool announce
)
12771 uint32 quest_id
= pQuest
->GetQuestId();
12773 for (int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++ )
12775 if ( pQuest
->ReqItemId
[i
] )
12776 DestroyItemCount( pQuest
->ReqItemId
[i
], pQuest
->ReqItemCount
[i
], true);
12779 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12780 // SetTimedQuest( 0 );
12781 m_timedquests
.erase(pQuest
->GetQuestId());
12783 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
12785 if( pQuest
->RewChoiceItemId
[reward
] )
12787 ItemPosCountVec dest
;
12788 if( CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] ) == EQUIP_ERR_OK
)
12790 Item
* item
= StoreNewItem( dest
, pQuest
->RewChoiceItemId
[reward
], true);
12791 SendNewItem(item
, pQuest
->RewChoiceItemCount
[reward
], true, false);
12796 if ( pQuest
->GetRewItemsCount() > 0 )
12798 for (uint32 i
=0; i
< pQuest
->GetRewItemsCount(); ++i
)
12800 if( pQuest
->RewItemId
[i
] )
12802 ItemPosCountVec dest
;
12803 if( CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] ) == EQUIP_ERR_OK
)
12805 Item
* item
= StoreNewItem( dest
, pQuest
->RewItemId
[i
], true);
12806 SendNewItem(item
, pQuest
->RewItemCount
[i
], true, false);
12812 RewardReputation( pQuest
);
12814 if( pQuest
->GetRewSpellCast() > 0 )
12815 CastSpell( this, pQuest
->GetRewSpellCast(), true);
12816 else if( pQuest
->GetRewSpell() > 0)
12817 CastSpell( this, pQuest
->GetRewSpell(), true);
12819 uint16 log_slot
= FindQuestSlot( quest_id
);
12820 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12821 SetQuestSlot(log_slot
,0);
12823 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12825 // Not give XP in case already completed once repeatable quest
12826 uint32 XP
= q_status
.m_rewarded
? 0 : uint32(pQuest
->XPValue( this )*sWorld
.getRate(RATE_XP_QUEST
));
12828 if ( getLevel() < sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
12829 GiveXP( XP
, NULL
);
12832 uint32 money
= uint32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getRate(RATE_DROP_MONEY
));
12833 ModifyMoney( money
);
12834 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD
, money
);
12837 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12838 if(pQuest
->GetRewOrReqMoney())
12840 ModifyMoney( pQuest
->GetRewOrReqMoney() );
12842 if(pQuest
->GetRewOrReqMoney() > 0)
12843 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD
, pQuest
->GetRewOrReqMoney());
12847 if(pQuest
->GetRewHonorableKills())
12848 RewardHonor(NULL
, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorableKills()));
12851 if(pQuest
->GetCharTitleId())
12853 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
12854 SetTitle(titleEntry
);
12857 if(pQuest
->GetBonusTalents())
12859 m_questRewardTalentCount
+=pQuest
->GetBonusTalents();
12860 InitTalentForLevel();
12863 // Send reward mail
12864 if(pQuest
->GetRewMailTemplateId())
12866 MailMessageType mailType
;
12867 uint32 senderGuidOrEntry
;
12868 switch(questGiver
->GetTypeId())
12871 mailType
= MAIL_CREATURE
;
12872 senderGuidOrEntry
= questGiver
->GetEntry();
12874 case TYPEID_GAMEOBJECT
:
12875 mailType
= MAIL_GAMEOBJECT
;
12876 senderGuidOrEntry
= questGiver
->GetEntry();
12879 mailType
= MAIL_ITEM
;
12880 senderGuidOrEntry
= questGiver
->GetEntry();
12882 case TYPEID_PLAYER
:
12883 mailType
= MAIL_NORMAL
;
12884 senderGuidOrEntry
= questGiver
->GetGUIDLow();
12887 mailType
= MAIL_NORMAL
;
12888 senderGuidOrEntry
= GetGUIDLow();
12892 Loot questMailLoot
;
12894 questMailLoot
.FillLoot(pQuest
->GetQuestId(), LootTemplates_QuestMail
, this,true);
12897 MailItemsInfo mi
; // item list preparing
12899 uint32 max_slot
= questMailLoot
.GetMaxSlotInLootFor(this);
12900 for(uint32 i
= 0; mi
.size() < MAX_MAIL_ITEMS
&& i
< max_slot
; ++i
)
12902 if(LootItem
* lootitem
= questMailLoot
.LootItemInSlot(i
,this))
12904 if(Item
* item
= Item::CreateItem(lootitem
->itemid
,lootitem
->count
,this))
12906 item
->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12907 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
12912 WorldSession::SendMailTo(this, mailType
, MAIL_STATIONERY_NORMAL
, senderGuidOrEntry
, GetGUIDLow(), "", 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
,pQuest
->GetRewMailDelaySecs(),pQuest
->GetRewMailTemplateId());
12915 if(pQuest
->IsDaily())
12917 SetDailyQuestStatus(quest_id
);
12918 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST
, 1);
12921 if ( !pQuest
->IsRepeatable() )
12922 SetQuestStatus(quest_id
, QUEST_STATUS_COMPLETE
);
12924 SetQuestStatus(quest_id
, QUEST_STATUS_NONE
);
12926 q_status
.m_rewarded
= true;
12929 SendQuestReward( pQuest
, XP
, questGiver
);
12931 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12932 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT
);
12933 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST
);
12938 // remove auras from spells with quest reward state limitations
12939 SpellAreaForQuestMapBounds saEndBounds
= spellmgr
.GetSpellAreaForQuestEndMapBounds(quest_id
);
12940 if(saEndBounds
.first
!= saEndBounds
.second
)
12942 GetZoneAndAreaId(zone
,area
);
12944 for(SpellAreaForAreaMap::const_iterator itr
= saEndBounds
.first
; itr
!= saEndBounds
.second
; ++itr
)
12945 if(!itr
->second
->IsFitToRequirements(this,zone
,area
))
12946 RemoveAurasDueToSpell(itr
->second
->spellId
);
12949 // Some spells applied at quest reward
12950 SpellAreaForQuestMapBounds saBounds
= spellmgr
.GetSpellAreaForQuestMapBounds(quest_id
,false);
12951 if(saBounds
.first
!= saBounds
.second
)
12954 GetZoneAndAreaId(zone
,area
);
12956 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
12957 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,zone
,area
))
12958 if( !HasAura(itr
->second
->spellId
,0) )
12959 CastSpell(this,itr
->second
->spellId
,true);
12963 void Player::FailQuest( uint32 quest_id
)
12967 IncompleteQuest( quest_id
);
12969 uint16 log_slot
= FindQuestSlot( quest_id
);
12970 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12972 SetQuestSlotTimer(log_slot
, 1 );
12973 SetQuestSlotState(log_slot
,QUEST_STATE_FAIL
);
12975 SendQuestFailed( quest_id
);
12979 void Player::FailTimedQuest( uint32 quest_id
)
12983 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12985 q_status
.m_timer
= 0;
12986 if (q_status
.uState
!= QUEST_NEW
)
12987 q_status
.uState
= QUEST_CHANGED
;
12989 IncompleteQuest( quest_id
);
12991 uint16 log_slot
= FindQuestSlot( quest_id
);
12992 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12994 SetQuestSlotTimer(log_slot
, 1 );
12995 SetQuestSlotState(log_slot
,QUEST_STATE_FAIL
);
12997 SendQuestTimerFailed( quest_id
);
13001 bool Player::SatisfyQuestSkillOrClass( Quest
const* qInfo
, bool msg
)
13003 int32 zoneOrSort
= qInfo
->GetZoneOrSort();
13004 int32 skillOrClass
= qInfo
->GetSkillOrClass();
13006 // skip zone zoneOrSort and 0 case skillOrClass
13007 if( zoneOrSort
>= 0 && skillOrClass
== 0 )
13010 int32 questSort
= -zoneOrSort
;
13011 uint8 reqSortClass
= ClassByQuestSort(questSort
);
13013 // check class sort cases in zoneOrSort
13014 if( reqSortClass
!= 0 && getClass() != reqSortClass
)
13017 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13022 if( skillOrClass
< 0 )
13024 uint8 reqClass
= -int32(skillOrClass
);
13025 if(getClass() != reqClass
)
13028 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13033 else if( skillOrClass
> 0 )
13035 uint32 reqSkill
= skillOrClass
;
13036 if( GetSkillValue( reqSkill
) < qInfo
->GetRequiredSkillValue() )
13039 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13047 bool Player::SatisfyQuestLevel( Quest
const* qInfo
, bool msg
)
13049 if( getLevel() < qInfo
->GetMinLevel() )
13052 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13058 bool Player::SatisfyQuestLog( bool msg
)
13061 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE
)
13066 WorldPacket
data( SMSG_QUESTLOG_FULL
, 0 );
13067 GetSession()->SendPacket( &data
);
13068 sLog
.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
13073 bool Player::SatisfyQuestPreviousQuest( Quest
const* qInfo
, bool msg
)
13075 // No previous quest (might be first quest in a series)
13076 if( qInfo
->prevQuests
.empty())
13079 for(Quest::PrevQuests::const_iterator iter
= qInfo
->prevQuests
.begin(); iter
!= qInfo
->prevQuests
.end(); ++iter
)
13081 uint32 prevId
= abs(*iter
);
13083 QuestStatusMap::iterator i_prevstatus
= mQuestStatus
.find( prevId
);
13084 Quest
const* qPrevInfo
= objmgr
.GetQuestTemplate(prevId
);
13086 if( qPrevInfo
&& i_prevstatus
!= mQuestStatus
.end() )
13088 // If any of the positive previous quests completed, return true
13089 if( *iter
> 0 && i_prevstatus
->second
.m_rewarded
)
13091 // skip one-from-all exclusive group
13092 if(qPrevInfo
->GetExclusiveGroup() >= 0)
13095 // each-from-all exclusive group ( < 0)
13096 // can be start if only all quests in prev quest exclusive group completed and rewarded
13097 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
13098 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
13100 assert(iter
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
13102 for(; iter
!= end
; ++iter
)
13104 uint32 exclude_Id
= iter
->second
;
13106 // skip checked quest id, only state of other quests in group is interesting
13107 if(exclude_Id
== prevId
)
13110 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
13112 // alternative quest from group also must be completed and rewarded(reported)
13113 if( i_exstatus
== mQuestStatus
.end() || !i_exstatus
->second
.m_rewarded
)
13116 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13122 // If any of the negative previous quests active, return true
13123 if( *iter
< 0 && (i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
13124 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
))))
13126 // skip one-from-all exclusive group
13127 if(qPrevInfo
->GetExclusiveGroup() >= 0)
13130 // each-from-all exclusive group ( < 0)
13131 // can be start if only all quests in prev quest exclusive group active
13132 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
13133 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
13135 assert(iter
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
13137 for(; iter
!= end
; ++iter
)
13139 uint32 exclude_Id
= iter
->second
;
13141 // skip checked quest id, only state of other quests in group is interesting
13142 if(exclude_Id
== prevId
)
13145 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
13147 // alternative quest from group also must be active
13148 if( i_exstatus
== mQuestStatus
.end() ||
13149 i_exstatus
->second
.m_status
!= QUEST_STATUS_INCOMPLETE
&&
13150 (i_prevstatus
->second
.m_status
!= QUEST_STATUS_COMPLETE
|| GetQuestRewardStatus(prevId
)) )
13153 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13162 // Has only positive prev. quests in non-rewarded state
13163 // and negative prev. quests in non-active state
13165 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13170 bool Player::SatisfyQuestRace( Quest
const* qInfo
, bool msg
)
13172 uint32 reqraces
= qInfo
->GetRequiredRaces();
13173 if ( reqraces
== 0 )
13175 if( (reqraces
& getRaceMask()) == 0 )
13178 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE
);
13184 bool Player::SatisfyQuestReputation( Quest
const* qInfo
, bool msg
)
13186 uint32 fIdMin
= qInfo
->GetRequiredMinRepFaction(); //Min required rep
13187 if(fIdMin
&& GetReputation(fIdMin
) < qInfo
->GetRequiredMinRepValue())
13190 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13194 uint32 fIdMax
= qInfo
->GetRequiredMaxRepFaction(); //Max required rep
13195 if(fIdMax
&& GetReputation(fIdMax
) >= qInfo
->GetRequiredMaxRepValue())
13198 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13205 bool Player::SatisfyQuestStatus( Quest
const* qInfo
, bool msg
)
13207 QuestStatusMap::iterator itr
= mQuestStatus
.find( qInfo
->GetQuestId() );
13208 if ( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
)
13211 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON
);
13217 bool Player::SatisfyQuestTimed( Quest
const* qInfo
, bool msg
)
13219 if ( (find(m_timedquests
.begin(), m_timedquests
.end(), qInfo
->GetQuestId()) != m_timedquests
.end()) && qInfo
->HasFlag(QUEST_MANGOS_FLAGS_TIMED
) )
13222 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED
);
13228 bool Player::SatisfyQuestExclusiveGroup( Quest
const* qInfo
, bool msg
)
13230 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
13231 if(qInfo
->GetExclusiveGroup() <= 0)
13234 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qInfo
->GetExclusiveGroup());
13235 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qInfo
->GetExclusiveGroup());
13237 assert(iter
!=end
); // always must be found if qInfo->ExclusiveGroup != 0
13239 for(; iter
!= end
; ++iter
)
13241 uint32 exclude_Id
= iter
->second
;
13243 // skip checked quest id, only state of other quests in group is interesting
13244 if(exclude_Id
== qInfo
->GetQuestId())
13247 // not allow have daily quest if daily quest from exclusive group already recently completed
13248 Quest
const* Nquest
= objmgr
.GetQuestTemplate(exclude_Id
);
13249 if( !SatisfyQuestDay(Nquest
, false) )
13252 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13256 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
13258 // alternative quest already started or completed
13259 if( i_exstatus
!= mQuestStatus
.end()
13260 && (i_exstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
|| i_exstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
13263 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13270 bool Player::SatisfyQuestNextChain( Quest
const* qInfo
, bool msg
)
13272 if(!qInfo
->GetNextQuestInChain())
13275 // next quest in chain already started or completed
13276 QuestStatusMap::iterator itr
= mQuestStatus
.find( qInfo
->GetNextQuestInChain() );
13277 if( itr
!= mQuestStatus
.end()
13278 && (itr
->second
.m_status
== QUEST_STATUS_COMPLETE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
13281 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13285 // check for all quests further up the chain
13286 // only necessary if there are quest chains with more than one quest that can be skipped
13287 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
13291 bool Player::SatisfyQuestPrevChain( Quest
const* qInfo
, bool msg
)
13293 // No previous quest in chain
13294 if( qInfo
->prevChainQuests
.empty())
13297 for(Quest::PrevChainQuests::const_iterator iter
= qInfo
->prevChainQuests
.begin(); iter
!= qInfo
->prevChainQuests
.end(); ++iter
)
13299 uint32 prevId
= *iter
;
13301 QuestStatusMap::iterator i_prevstatus
= mQuestStatus
.find( prevId
);
13303 if( i_prevstatus
!= mQuestStatus
.end() )
13305 // If any of the previous quests in chain active, return false
13306 if( i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
13307 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
)))
13310 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13315 // check for all quests further down the chain
13316 // only necessary if there are quest chains with more than one quest that can be skipped
13317 //if( !SatisfyQuestPrevChain( prevId, msg ) )
13321 // No previous quest in chain active
13325 bool Player::SatisfyQuestDay( Quest
const* qInfo
, bool msg
)
13327 if(!qInfo
->IsDaily())
13330 bool have_slot
= false;
13331 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
13333 uint32 id
= GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
);
13334 if(qInfo
->GetQuestId()==id
)
13344 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING
);
13351 bool Player::GiveQuestSourceItem( Quest
const *pQuest
)
13353 uint32 srcitem
= pQuest
->GetSrcItemId();
13356 uint32 count
= pQuest
->GetSrcItemCount();
13360 ItemPosCountVec dest
;
13361 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
13362 if( msg
== EQUIP_ERR_OK
)
13364 Item
* item
= StoreNewItem(dest
, srcitem
, true);
13365 SendNewItem(item
, count
, true, false);
13368 // player already have max amount required item, just report success
13369 else if( msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
13372 SendEquipError( msg
, NULL
, NULL
);
13379 bool Player::TakeQuestSourceItem( uint32 quest_id
, bool msg
)
13381 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13384 uint32 srcitem
= qInfo
->GetSrcItemId();
13387 uint32 count
= qInfo
->GetSrcItemCount();
13391 // exist one case when destroy source quest item not possible:
13392 // non un-equippable item (equipped non-empty bag, for example)
13393 uint8 res
= CanUnequipItems(srcitem
,count
);
13394 if(res
!= EQUIP_ERR_OK
)
13397 SendEquipError( res
, NULL
, NULL
);
13401 DestroyItemCount(srcitem
, count
, true, true);
13407 bool Player::GetQuestRewardStatus( uint32 quest_id
) const
13409 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13412 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13413 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13414 if( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
13415 && !qInfo
->IsRepeatable() )
13416 return itr
->second
.m_rewarded
;
13423 QuestStatus
Player::GetQuestStatus( uint32 quest_id
) const
13427 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13428 if( itr
!= mQuestStatus
.end() )
13429 return itr
->second
.m_status
;
13431 return QUEST_STATUS_NONE
;
13434 bool Player::CanShareQuest(uint32 quest_id
) const
13436 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13437 if( qInfo
&& qInfo
->HasFlag(QUEST_FLAGS_SHARABLE
) )
13439 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13440 if( itr
!= mQuestStatus
.end() )
13441 return itr
->second
.m_status
== QUEST_STATUS_NONE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
;
13446 void Player::SetQuestStatus( uint32 quest_id
, QuestStatus status
)
13448 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13451 if( status
== QUEST_STATUS_NONE
|| status
== QUEST_STATUS_INCOMPLETE
|| status
== QUEST_STATUS_COMPLETE
)
13453 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
13454 m_timedquests
.erase(qInfo
->GetQuestId());
13457 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
13459 q_status
.m_status
= status
;
13460 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13463 UpdateForQuestsGO();
13466 // not used in MaNGOS, but used in scripting code
13467 uint32
Player::GetReqKillOrCastCurrentCount(uint32 quest_id
, int32 entry
)
13469 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13473 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13474 if ( qInfo
->ReqCreatureOrGOId
[j
] == entry
)
13475 return mQuestStatus
[quest_id
].m_creatureOrGOcount
[j
];
13480 void Player::AdjustQuestReqItemCount( Quest
const* pQuest
, QuestStatusData
& questStatusData
)
13482 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13484 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
13486 uint32 reqitemcount
= pQuest
->ReqItemCount
[i
];
13487 if( reqitemcount
!= 0 )
13489 uint32 quest_id
= pQuest
->GetQuestId();
13490 uint32 curitemcount
= GetItemCount(pQuest
->ReqItemId
[i
],true);
13492 questStatusData
.m_itemcount
[i
] = std::min(curitemcount
, reqitemcount
);
13493 if (questStatusData
.uState
!= QUEST_NEW
) questStatusData
.uState
= QUEST_CHANGED
;
13499 uint16
Player::FindQuestSlot( uint32 quest_id
) const
13501 for ( uint16 i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13502 if ( GetQuestSlotQuestId(i
) == quest_id
)
13505 return MAX_QUEST_LOG_SIZE
;
13508 void Player::AreaExploredOrEventHappens( uint32 questId
)
13512 uint16 log_slot
= FindQuestSlot( questId
);
13513 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13515 QuestStatusData
& q_status
= mQuestStatus
[questId
];
13517 if(!q_status
.m_explored
)
13519 q_status
.m_explored
= true;
13520 if (q_status
.uState
!= QUEST_NEW
)
13521 q_status
.uState
= QUEST_CHANGED
;
13524 if( CanCompleteQuest( questId
) )
13525 CompleteQuest( questId
);
13529 //not used in mangosd, function for external script library
13530 void Player::GroupEventHappens( uint32 questId
, WorldObject
const* pEventObject
)
13532 if( Group
*pGroup
= GetGroup() )
13534 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
13536 Player
*pGroupGuy
= itr
->getSource();
13538 // for any leave or dead (with not released body) group member at appropriate distance
13539 if( pGroupGuy
&& pGroupGuy
->IsAtGroupRewardDistance(pEventObject
) && !pGroupGuy
->GetCorpse() )
13540 pGroupGuy
->AreaExploredOrEventHappens(questId
);
13544 AreaExploredOrEventHappens(questId
);
13547 void Player::ItemAddedQuestCheck( uint32 entry
, uint32 count
)
13549 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13551 uint32 questid
= GetQuestSlotQuestId(i
);
13552 if ( questid
== 0 )
13555 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13557 if ( q_status
.m_status
!= QUEST_STATUS_INCOMPLETE
)
13560 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13561 if( !qInfo
|| !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13564 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13566 uint32 reqitem
= qInfo
->ReqItemId
[j
];
13567 if ( reqitem
== entry
)
13569 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
13570 uint32 curitemcount
= q_status
.m_itemcount
[j
];
13571 if ( curitemcount
< reqitemcount
)
13573 uint32 additemcount
= ( curitemcount
+ count
<= reqitemcount
? count
: reqitemcount
- curitemcount
);
13574 q_status
.m_itemcount
[j
] += additemcount
;
13575 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13577 SendQuestUpdateAddItem( qInfo
, j
, additemcount
);
13579 if ( CanCompleteQuest( questid
) )
13580 CompleteQuest( questid
);
13585 UpdateForQuestsGO();
13586 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM
, entry
);
13589 void Player::ItemRemovedQuestCheck( uint32 entry
, uint32 count
)
13591 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13593 uint32 questid
= GetQuestSlotQuestId(i
);
13596 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13599 if( !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13602 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13604 uint32 reqitem
= qInfo
->ReqItemId
[j
];
13605 if ( reqitem
== entry
)
13607 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13609 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
13610 uint32 curitemcount
;
13611 if( q_status
.m_status
!= QUEST_STATUS_COMPLETE
)
13612 curitemcount
= q_status
.m_itemcount
[j
];
13614 curitemcount
= GetItemCount(entry
,true);
13615 if ( curitemcount
< reqitemcount
+ count
)
13617 uint32 remitemcount
= ( curitemcount
<= reqitemcount
? count
: count
+ reqitemcount
- curitemcount
);
13618 q_status
.m_itemcount
[j
] = curitemcount
- remitemcount
;
13619 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13621 IncompleteQuest( questid
);
13627 UpdateForQuestsGO();
13630 void Player::KilledMonster( uint32 entry
, uint64 guid
)
13632 uint32 addkillcount
= 1;
13633 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE
, entry
, addkillcount
);
13634 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13636 uint32 questid
= GetQuestSlotQuestId(i
);
13640 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13643 // just if !ingroup || !noraidgroup || raidgroup
13644 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13645 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
&& (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo
->GetType() == QUEST_TYPE_RAID
))
13647 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
13649 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13651 // skip GO activate objective or none
13652 if(qInfo
->ReqCreatureOrGOId
[j
] <=0)
13655 // skip Cast at creature objective
13656 if(qInfo
->ReqSpell
[j
] !=0 )
13659 uint32 reqkill
= qInfo
->ReqCreatureOrGOId
[j
];
13661 if ( reqkill
== entry
)
13663 uint32 reqkillcount
= qInfo
->ReqCreatureOrGOCount
[j
];
13664 uint32 curkillcount
= q_status
.m_creatureOrGOcount
[j
];
13665 if ( curkillcount
< reqkillcount
)
13667 q_status
.m_creatureOrGOcount
[j
] = curkillcount
+ addkillcount
;
13668 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13670 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curkillcount
, addkillcount
);
13672 if ( CanCompleteQuest( questid
) )
13673 CompleteQuest( questid
);
13675 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13684 void Player::CastedCreatureOrGO( uint32 entry
, uint64 guid
, uint32 spell_id
)
13686 bool isCreature
= IS_CREATURE_GUID(guid
);
13688 uint32 addCastCount
= 1;
13689 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13691 uint32 questid
= GetQuestSlotQuestId(i
);
13695 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13699 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13701 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13703 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
13705 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13707 // skip kill creature objective (0) or wrong spell casts
13708 if(qInfo
->ReqSpell
[j
] != spell_id
)
13711 uint32 reqTarget
= 0;
13715 // creature activate objectives
13716 if(qInfo
->ReqCreatureOrGOId
[j
] > 0)
13717 // checked at quest_template loading
13718 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
13722 // GO activate objective
13723 if(qInfo
->ReqCreatureOrGOId
[j
] < 0)
13724 // checked at quest_template loading
13725 reqTarget
= - qInfo
->ReqCreatureOrGOId
[j
];
13728 // other not this creature/GO related objectives
13729 if( reqTarget
!= entry
)
13732 uint32 reqCastCount
= qInfo
->ReqCreatureOrGOCount
[j
];
13733 uint32 curCastCount
= q_status
.m_creatureOrGOcount
[j
];
13734 if ( curCastCount
< reqCastCount
)
13736 q_status
.m_creatureOrGOcount
[j
] = curCastCount
+ addCastCount
;
13737 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13739 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curCastCount
, addCastCount
);
13742 if ( CanCompleteQuest( questid
) )
13743 CompleteQuest( questid
);
13745 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13753 void Player::TalkedToCreature( uint32 entry
, uint64 guid
)
13755 uint32 addTalkCount
= 1;
13756 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13758 uint32 questid
= GetQuestSlotQuestId(i
);
13762 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13766 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13768 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13770 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
13772 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13774 // skip spell casts and Gameobject objectives
13775 if(qInfo
->ReqSpell
[j
] > 0 || qInfo
->ReqCreatureOrGOId
[j
] < 0)
13778 uint32 reqTarget
= 0;
13780 if(qInfo
->ReqCreatureOrGOId
[j
] > 0) // creature activate objectives
13781 // checked at quest_template loading
13782 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
13786 if ( reqTarget
== entry
)
13788 uint32 reqTalkCount
= qInfo
->ReqCreatureOrGOCount
[j
];
13789 uint32 curTalkCount
= q_status
.m_creatureOrGOcount
[j
];
13790 if ( curTalkCount
< reqTalkCount
)
13792 q_status
.m_creatureOrGOcount
[j
] = curTalkCount
+ addTalkCount
;
13793 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13795 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curTalkCount
, addTalkCount
);
13797 if ( CanCompleteQuest( questid
) )
13798 CompleteQuest( questid
);
13800 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13809 void Player::MoneyChanged( uint32 count
)
13811 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13813 uint32 questid
= GetQuestSlotQuestId(i
);
13817 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13818 if( qInfo
&& qInfo
->GetRewOrReqMoney() < 0 )
13820 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13822 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13824 if(int32(count
) >= -qInfo
->GetRewOrReqMoney())
13826 if ( CanCompleteQuest( questid
) )
13827 CompleteQuest( questid
);
13830 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
13832 if(int32(count
) < -qInfo
->GetRewOrReqMoney())
13833 IncompleteQuest( questid
);
13839 bool Player::HasQuestForItem( uint32 itemid
) const
13841 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13843 uint32 questid
= GetQuestSlotQuestId(i
);
13844 if ( questid
== 0 )
13847 QuestStatusMap::const_iterator qs_itr
= mQuestStatus
.find(questid
);
13848 if(qs_itr
== mQuestStatus
.end())
13851 QuestStatusData
const& q_status
= qs_itr
->second
;
13853 if (q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13855 Quest
const* qinfo
= objmgr
.GetQuestTemplate(questid
);
13859 // hide quest if player is in raid-group and quest is no raid quest
13860 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
13863 // There should be no mixed ReqItem/ReqSource drop
13864 // This part for ReqItem drop
13865 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13867 if(itemid
== qinfo
->ReqItemId
[j
] && q_status
.m_itemcount
[j
] < qinfo
->ReqItemCount
[j
] )
13870 // This part - for ReqSource
13871 for (int j
= 0; j
< QUEST_SOURCE_ITEM_IDS_COUNT
; j
++)
13873 // examined item is a source item
13874 if (qinfo
->ReqSourceId
[j
] == itemid
)
13876 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(itemid
);
13879 if (pProto
->MaxCount
&& GetItemCount(itemid
,true) < pProto
->MaxCount
)
13882 // allows custom amount drop when not 0
13883 if (qinfo
->ReqSourceCount
[j
])
13885 if (GetItemCount(itemid
,true) < qinfo
->ReqSourceCount
[j
])
13887 } else if (GetItemCount(itemid
,true) < pProto
->Stackable
)
13896 void Player::SendQuestComplete( uint32 quest_id
)
13900 WorldPacket
data( SMSG_QUESTUPDATE_COMPLETE
, 4 );
13901 data
<< uint32(quest_id
);
13902 GetSession()->SendPacket( &data
);
13903 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id
);
13907 void Player::SendQuestReward( Quest
const *pQuest
, uint32 XP
, Object
* questGiver
)
13909 uint32 questid
= pQuest
->GetQuestId();
13910 sLog
.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid
);
13911 WorldPacket
data( SMSG_QUESTGIVER_QUEST_COMPLETE
, (4+4+4+4+4) );
13912 data
<< uint32(questid
);
13914 if ( getLevel() < sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
13916 data
<< uint32(XP
);
13917 data
<< uint32(pQuest
->GetRewOrReqMoney());
13922 data
<< uint32(pQuest
->GetRewOrReqMoney() + int32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getRate(RATE_DROP_MONEY
)));
13925 data
<< uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorableKills()));
13926 data
<< uint32(pQuest
->GetBonusTalents()); // bonus talents
13927 GetSession()->SendPacket( &data
);
13929 if (pQuest
->GetQuestCompleteScript() != 0)
13930 sWorld
.ScriptsStart(sQuestEndScripts
, pQuest
->GetQuestCompleteScript(), questGiver
, this);
13933 void Player::SendQuestFailed( uint32 quest_id
)
13937 WorldPacket
data( SMSG_QUESTGIVER_QUEST_FAILED
, 4+4 );
13939 data
<< uint32(0); // failed reason (4 for inventory is full)
13940 GetSession()->SendPacket( &data
);
13941 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13945 void Player::SendQuestTimerFailed( uint32 quest_id
)
13949 WorldPacket
data( SMSG_QUESTUPDATE_FAILEDTIMER
, 4 );
13951 GetSession()->SendPacket( &data
);
13952 sLog
.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13956 void Player::SendCanTakeQuestResponse( uint32 msg
)
13958 WorldPacket
data( SMSG_QUESTGIVER_QUEST_INVALID
, 4 );
13959 data
<< uint32(msg
);
13960 GetSession()->SendPacket( &data
);
13961 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13964 void Player::SendPushToPartyResponse( Player
*pPlayer
, uint32 msg
)
13968 WorldPacket
data( MSG_QUEST_PUSH_RESULT
, (8+1) );
13969 data
<< uint64(pPlayer
->GetGUID());
13970 data
<< uint8(msg
); // valid values: 0-8
13971 GetSession()->SendPacket( &data
);
13972 sLog
.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13976 void Player::SendQuestUpdateAddItem( Quest
const* pQuest
, uint32 item_idx
, uint32 count
)
13978 WorldPacket
data( SMSG_QUESTUPDATE_ADD_ITEM
, 0 );
13979 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13980 //data << pQuest->ReqItemId[item_idx];
13982 GetSession()->SendPacket( &data
);
13985 void Player::SendQuestUpdateAddCreatureOrGo( Quest
const* pQuest
, uint64 guid
, uint32 creatureOrGO_idx
, uint32 old_count
, uint32 add_count
)
13987 assert(old_count
+ add_count
< 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13989 int32 entry
= pQuest
->ReqCreatureOrGOId
[ creatureOrGO_idx
];
13991 // client expected gameobject template id in form (id|0x80000000)
13992 entry
= (-entry
) | 0x80000000;
13994 WorldPacket
data( SMSG_QUESTUPDATE_ADD_KILL
, (4*4+8) );
13995 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13996 data
<< uint32(pQuest
->GetQuestId());
13997 data
<< uint32(entry
);
13998 data
<< uint32(old_count
+ add_count
);
13999 data
<< uint32(pQuest
->ReqCreatureOrGOCount
[ creatureOrGO_idx
]);
14000 data
<< uint64(guid
);
14001 GetSession()->SendPacket(&data
);
14003 uint16 log_slot
= FindQuestSlot( pQuest
->GetQuestId() );
14004 if( log_slot
< MAX_QUEST_LOG_SIZE
)
14005 SetQuestSlotCounter(log_slot
,creatureOrGO_idx
,GetQuestSlotCounter(log_slot
,creatureOrGO_idx
)+add_count
);
14008 /*********************************************************/
14009 /*** LOAD SYSTEM ***/
14010 /*********************************************************/
14012 bool Player::MinimalLoadFromDB( QueryResult
*result
, uint32 guid
)
14014 bool delete_result
= true;
14017 // 0 1 2 3 4 5 6 7 8 9
14018 result
= CharacterDatabase
.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid
);
14019 if(!result
) return false;
14021 else delete_result
= false;
14023 Field
*fields
= result
->Fetch();
14025 if(!LoadValues( fields
[1].GetString()))
14027 sLog
.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid
));
14028 if(delete_result
) delete result
;
14032 // overwrite possible wrong/corrupted guid
14033 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
14035 m_name
= fields
[2].GetCppString();
14037 Relocate(fields
[3].GetFloat(),fields
[4].GetFloat(),fields
[5].GetFloat());
14038 SetMapId(fields
[6].GetUInt32());
14039 // the instance id is not needed at character enum
14041 m_Played_time
[0] = fields
[7].GetUInt32();
14042 m_Played_time
[1] = fields
[8].GetUInt32();
14044 m_atLoginFlags
= fields
[9].GetUInt32();
14046 // I don't see these used anywhere ..
14049 _LoadBoundInstances();*/
14051 if (delete_result
) delete result
;
14053 for (int i
= 0; i
< PLAYER_SLOTS_COUNT
; i
++)
14056 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
14057 m_deathState
= DEAD
;
14062 void Player::_LoadDeclinedNames(QueryResult
* result
)
14068 delete m_declinedname
;
14070 m_declinedname
= new DeclinedName
;
14071 Field
*fields
= result
->Fetch();
14072 for(int i
= 0; i
< MAX_DECLINED_NAME_CASES
; ++i
)
14073 m_declinedname
->name
[i
] = fields
[i
].GetCppString();
14078 void Player::_LoadArenaTeamInfo(QueryResult
*result
)
14080 // arenateamid, played_week, played_season, personal_rating
14081 memset((void*)&m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
], 0, sizeof(uint32
)*18);
14087 Field
*fields
= result
->Fetch();
14089 uint32 arenateamid
= fields
[0].GetUInt32();
14090 uint32 played_week
= fields
[1].GetUInt32();
14091 uint32 played_season
= fields
[2].GetUInt32();
14092 uint32 personal_rating
= fields
[3].GetUInt32();
14094 ArenaTeam
* aTeam
= objmgr
.GetArenaTeamById(arenateamid
);
14097 sLog
.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid
, played_week
, played_season
, personal_rating
);
14100 uint8 arenaSlot
= aTeam
->GetSlot();
14102 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6] = arenateamid
; // TeamID
14103 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 1] = ((aTeam
->GetCaptain() == GetGUID()) ? (uint32
)0 : (uint32
)1); // Captain 0, member 1
14104 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 2] = played_week
; // Played Week
14105 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 3] = played_season
; // Played Season
14106 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 4] = 0; // Unk
14107 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 5] = personal_rating
; // Personal Rating
14109 }while (result
->NextRow());
14113 bool Player::LoadPositionFromDB(uint32
& mapid
, float& x
,float& y
,float& z
,float& o
, bool& in_flight
, uint64 guid
)
14115 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid
));
14119 Field
*fields
= result
->Fetch();
14121 x
= fields
[0].GetFloat();
14122 y
= fields
[1].GetFloat();
14123 z
= fields
[2].GetFloat();
14124 o
= fields
[3].GetFloat();
14125 mapid
= fields
[4].GetUInt32();
14126 in_flight
= !fields
[5].GetCppString().empty();
14132 bool Player::LoadValuesArrayFromDB(Tokens
& data
, uint64 guid
)
14134 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid
));
14138 Field
*fields
= result
->Fetch();
14140 data
= StrSplit(fields
[0].GetCppString(), " ");
14147 uint32
Player::GetUInt32ValueFromArray(Tokens
const& data
, uint16 index
)
14149 if(index
>= data
.size())
14152 return (uint32
)atoi(data
[index
].c_str());
14155 float Player::GetFloatValueFromArray(Tokens
const& data
, uint16 index
)
14158 uint32 temp
= Player::GetUInt32ValueFromArray(data
,index
);
14159 memcpy(&result
, &temp
, sizeof(result
));
14164 uint32
Player::GetUInt32ValueFromDB(uint16 index
, uint64 guid
)
14167 if(!LoadValuesArrayFromDB(data
,guid
))
14170 return GetUInt32ValueFromArray(data
,index
);
14173 float Player::GetFloatValueFromDB(uint16 index
, uint64 guid
)
14176 uint32 temp
= Player::GetUInt32ValueFromDB(index
, guid
);
14177 memcpy(&result
, &temp
, sizeof(result
));
14182 bool Player::LoadFromDB( uint32 guid
, SqlQueryHolder
*holder
)
14184 //// 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
14185 //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);
14186 QueryResult
*result
= holder
->GetResult(PLAYER_LOGIN_QUERY_LOADFROM
);
14190 sLog
.outError("ERROR: Player (GUID: %u) not found in table `characters`, can't load. ",guid
);
14194 Field
*fields
= result
->Fetch();
14196 uint32 dbAccountId
= fields
[1].GetUInt32();
14198 // check if the character's account in the db and the logged in account match.
14199 // player should be able to load/delete character only with correct account!
14200 if( dbAccountId
!= GetSession()->GetAccountId() )
14202 sLog
.outError("ERROR: Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid
,GetSession()->GetAccountId(),dbAccountId
);
14207 Object::_Create( guid
, 0, HIGHGUID_PLAYER
);
14209 m_name
= fields
[3].GetCppString();
14211 // check name limitations
14212 if(!ObjectMgr::IsValidName(m_name
) || GetSession()->GetSecurity() == SEC_PLAYER
&& objmgr
.IsReservedName(m_name
))
14215 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME
),guid
);
14219 if(!LoadValues( fields
[2].GetString()))
14221 sLog
.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid
));
14226 // overwrite possible wrong/corrupted guid
14227 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
14229 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
14230 for(uint8 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
14232 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), 0 );
14233 SetVisibleItemSlot(slot
,NULL
);
14237 delete m_items
[slot
];
14238 m_items
[slot
] = NULL
;
14242 // update money limits
14243 if(GetMoney() > MAX_MONEY_AMOUNT
)
14244 SetMoney(MAX_MONEY_AMOUNT
);
14246 sLog
.outDebug("Load Basic value of player %s is: ", m_name
.c_str());
14249 m_race
= fields
[4].GetUInt8();
14250 //Need to call it to initialize m_team (m_team can be calculated from m_race)
14251 //Other way is to saves m_team into characters table.
14252 setFactionForRace(m_race
);
14255 m_class
= fields
[5].GetUInt8();
14257 // load home bind and check in same time class/race pair, it used later for restore broken positions
14258 if(!_LoadHomeBind(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND
)))
14261 InitPrimaryProffesions(); // to max set before any spell loaded
14263 // init saved position, and fix it later if problematic
14264 uint32 transGUID
= fields
[24].GetUInt32();
14265 Relocate(fields
[6].GetFloat(),fields
[7].GetFloat(),fields
[8].GetFloat(),fields
[10].GetFloat());
14266 SetMapId(fields
[9].GetUInt32());
14267 SetDifficulty(fields
[32].GetUInt32()); // may be changed in _LoadGroup
14269 _LoadGroup(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP
));
14271 _LoadArenaTeamInfo(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO
));
14273 uint32 arena_currency
= GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
) + fields
[33].GetUInt32();
14274 if (arena_currency
> sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
))
14275 arena_currency
= sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
);
14277 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, arena_currency
);
14279 // check arena teams integrity
14280 for(uint32 arena_slot
= 0; arena_slot
< MAX_ARENA_SLOT
; ++arena_slot
)
14282 uint32 arena_team_id
= GetArenaTeamId(arena_slot
);
14286 if(ArenaTeam
* at
= objmgr
.GetArenaTeamById(arena_team_id
))
14287 if(at
->HaveMember(GetGUID()))
14290 // arena team not exist or not member, cleanup fields
14291 for(int j
=0; j
< 6; ++j
)
14292 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arena_slot
* 6 + j
, 0);
14295 _LoadBoundInstances(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES
));
14297 if(!IsPositionValid())
14299 sLog
.outError("ERROR: 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());
14300 RelocateToHomebind();
14304 m_movementInfo
.t_x
= 0.0f
;
14305 m_movementInfo
.t_y
= 0.0f
;
14306 m_movementInfo
.t_z
= 0.0f
;
14307 m_movementInfo
.t_o
= 0.0f
;
14310 uint32 bgid
= fields
[34].GetUInt32();
14311 uint32 bgteam
= fields
[35].GetUInt32();
14313 if(bgid
) //saved in BattleGround
14315 SetBattleGroundEntryPoint(fields
[36].GetUInt32(),fields
[37].GetFloat(),fields
[38].GetFloat(),fields
[39].GetFloat(),fields
[40].GetFloat());
14317 // check entry point and fix to homebind if need
14318 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(m_bgEntryPoint
.mapid
);
14319 if(!mapEntry
|| mapEntry
->Instanceable() || !MapManager::IsValidMapCoord(m_bgEntryPoint
))
14320 SetBattleGroundEntryPoint(m_homebindMapId
,m_homebindX
,m_homebindY
,m_homebindZ
,0.0f
);
14322 BattleGround
*currentBg
= sBattleGroundMgr
.GetBattleGround(bgid
, BATTLEGROUND_TYPE_NONE
);
14324 if(currentBg
&& currentBg
->IsPlayerInBattleGround(GetGUID()))
14326 BattleGroundQueueTypeId bgQueueTypeId
= sBattleGroundMgr
.BGQueueTypeId(currentBg
->GetTypeID(), currentBg
->GetArenaType());
14327 uint32 queueSlot
= AddBattleGroundQueueId(bgQueueTypeId
);
14329 SetBattleGroundId(currentBg
->GetInstanceID(), currentBg
->GetTypeID());
14332 //join player to battleground group
14333 currentBg
->EventPlayerLoggedIn(this, GetGUID());
14334 currentBg
->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), bgteam
);
14336 SetInviteForBattleGroundQueueType(bgQueueTypeId
,currentBg
->GetInstanceID());
14340 Relocate(GetBattleGroundEntryPoint());
14341 //RemoveArenaAuras(true);
14346 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(GetMapId());
14347 // if server restart after player save in BG or area
14348 // player can have current coordinates in to BG/Arean map, fix this
14349 if(!mapEntry
|| mapEntry
->IsBattleGroundOrArena())
14351 // return to BG master
14352 SetMapId(fields
[36].GetUInt32());
14353 Relocate(fields
[37].GetFloat(),fields
[38].GetFloat(),fields
[39].GetFloat(),fields
[40].GetFloat());
14355 // check entry point and fix to homebind if need
14356 mapEntry
= sMapStore
.LookupEntry(GetMapId());
14357 if(!mapEntry
|| mapEntry
->IsBattleGroundOrArena() || !IsPositionValid())
14358 RelocateToHomebind();
14362 if (transGUID
!= 0)
14364 m_movementInfo
.t_x
= fields
[20].GetFloat();
14365 m_movementInfo
.t_y
= fields
[21].GetFloat();
14366 m_movementInfo
.t_z
= fields
[22].GetFloat();
14367 m_movementInfo
.t_o
= fields
[23].GetFloat();
14369 if( !MaNGOS::IsValidMapCoord(
14370 GetPositionX()+m_movementInfo
.t_x
,GetPositionY()+m_movementInfo
.t_y
,
14371 GetPositionZ()+m_movementInfo
.t_z
,GetOrientation()+m_movementInfo
.t_o
) ||
14372 // transport size limited
14373 m_movementInfo
.t_x
> 50 || m_movementInfo
.t_y
> 50 || m_movementInfo
.t_z
> 50 )
14375 sLog
.outError("ERROR: Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
14376 guid
,GetPositionX()+m_movementInfo
.t_x
,GetPositionY()+m_movementInfo
.t_y
,
14377 GetPositionZ()+m_movementInfo
.t_z
,GetOrientation()+m_movementInfo
.t_o
);
14379 RelocateToHomebind();
14381 m_movementInfo
.t_x
= 0.0f
;
14382 m_movementInfo
.t_y
= 0.0f
;
14383 m_movementInfo
.t_z
= 0.0f
;
14384 m_movementInfo
.t_o
= 0.0f
;
14390 if (transGUID
!= 0)
14392 for (MapManager::TransportSet::iterator iter
= MapManager::Instance().m_Transports
.begin(); iter
!= MapManager::Instance().m_Transports
.end(); ++iter
)
14394 if( (*iter
)->GetGUIDLow() == transGUID
)
14396 MapEntry
const* transMapEntry
= sMapStore
.LookupEntry((*iter
)->GetMapId());
14397 // client without expansion support
14398 if(GetSession()->Expansion() < transMapEntry
->Expansion())
14400 sLog
.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter
)->GetMapId());
14404 m_transport
= *iter
;
14405 m_transport
->AddPassenger(this);
14406 SetMapId(m_transport
->GetMapId());
14413 sLog
.outError("ERROR: Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
14416 RelocateToHomebind();
14418 m_movementInfo
.t_x
= 0.0f
;
14419 m_movementInfo
.t_y
= 0.0f
;
14420 m_movementInfo
.t_z
= 0.0f
;
14421 m_movementInfo
.t_o
= 0.0f
;
14426 else // not transport case
14428 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(GetMapId());
14429 // client without expansion support
14430 if(GetSession()->Expansion() < mapEntry
->Expansion())
14432 sLog
.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
14433 RelocateToHomebind();
14437 // NOW player must have valid map
14438 // load the player's map here if it's not already loaded
14439 Map
*map
= GetMap();
14441 // since the player may not be bound to the map yet, make sure subsequent
14442 // getmap calls won't create new maps
14443 SetInstanceId(map
->GetInstanceId());
14445 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14446 if(GetInstanceId() && !sInstanceSaveManager
.GetInstanceSave(GetInstanceId()))
14448 AreaTrigger
const* at
= objmgr
.GetMapEntranceTrigger(GetMapId());
14450 Relocate(at
->target_X
, at
->target_Y
, at
->target_Z
, at
->target_Orientation
);
14452 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());
14455 SaveRecallPosition();
14457 time_t now
= time(NULL
);
14458 time_t logoutTime
= time_t(fields
[16].GetUInt64());
14460 // since last logout (in seconds)
14461 uint64 time_diff
= uint64(now
- logoutTime
);
14463 // set value, including drunk invisibility detection
14464 // calculate sobering. after 15 minutes logged out, the player will be sober again
14466 if(time_diff
> 15*MINUTE
)
14469 soberFactor
= 1-time_diff
/(15.0f
*MINUTE
);
14470 uint16 newDrunkenValue
= uint16(soberFactor
*(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFE));
14471 SetDrunkValue(newDrunkenValue
);
14473 m_rest_bonus
= fields
[15].GetFloat();
14474 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14475 float bubble0
= 0.031;
14476 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14477 float bubble1
= 0.125;
14479 if((int32
)fields
[16].GetUInt32() > 0)
14481 float bubble
= fields
[17].GetUInt32() > 0
14482 ? bubble1
*sWorld
.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY
)
14483 : bubble0
*sWorld
.getRate(RATE_REST_OFFLINE_IN_WILDERNESS
);
14485 SetRestBonus(GetRestBonus()+ time_diff
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
14488 m_cinematic
= fields
[12].GetUInt32();
14489 m_Played_time
[0]= fields
[13].GetUInt32();
14490 m_Played_time
[1]= fields
[14].GetUInt32();
14492 m_resetTalentsCost
= fields
[18].GetUInt32();
14493 m_resetTalentsTime
= time_t(fields
[19].GetUInt64());
14495 // reserve some flags
14496 uint32 old_safe_flags
= GetUInt32Value(PLAYER_FLAGS
) & ( PLAYER_FLAGS_HIDE_CLOAK
| PLAYER_FLAGS_HIDE_HELM
);
14498 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
) )
14499 SetUInt32Value(PLAYER_FLAGS
, 0 | old_safe_flags
);
14501 m_taxi
.LoadTaxiMask( fields
[11].GetString() ); // must be before InitTaxiNodesForLevel
14503 uint32 extraflags
= fields
[25].GetUInt32();
14505 m_stableSlots
= fields
[26].GetUInt32();
14506 if(m_stableSlots
> 4)
14508 sLog
.outError("Player can have not more 4 stable slots, but have in DB %u",uint32(m_stableSlots
));
14512 m_atLoginFlags
= fields
[27].GetUInt32();
14515 // Update Honor kills data
14516 m_lastHonorUpdateTime
= logoutTime
;
14517 UpdateHonorFields();
14519 m_deathExpireTime
= (time_t)fields
[30].GetUInt64();
14520 if(m_deathExpireTime
> now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
)
14521 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
-1;
14523 std::string taxi_nodes
= fields
[31].GetCppString();
14527 // clear channel spell data (if saved at channel spell casting)
14528 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT
, 0);
14529 SetUInt32Value(UNIT_CHANNEL_SPELL
,0);
14531 // clear charm/summon related fields
14538 // reset some aura modifiers before aura apply
14539 SetFarSightGUID(0);
14540 SetUInt32Value(PLAYER_TRACK_CREATURES
, 0 );
14541 SetUInt32Value(PLAYER_TRACK_RESOURCES
, 0 );
14545 // make sure the unit is considered out of combat for proper loading
14548 // make sure the unit is considered not in duel for proper loading
14549 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
14550 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
14552 // remember loaded power/health values to restore after stats initialization and modifier applying
14553 uint32 savedHealth
= GetHealth();
14554 uint32 savedPower
[MAX_POWERS
];
14555 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
14556 savedPower
[i
] = GetPower(Powers(i
));
14558 // reset stats before loading any modifiers
14559 InitStatsForLevel();
14560 InitTaxiNodesForLevel();
14561 InitGlyphsForLevel();
14564 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14566 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14569 _LoadAuras(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS
), time_diff
);
14572 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14573 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
14574 m_deathState
= DEAD
;
14576 _LoadSpells(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS
));
14578 // after spell load, learn rewarded spell if need also
14579 _LoadQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS
));
14580 _LoadDailyQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS
));
14582 // after spell and quest load
14583 InitTalentForLevel();
14584 learnDefaultSpells();
14586 _LoadTutorials(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS
));
14588 // must be before inventory (some items required reputation check)
14589 _LoadReputation(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION
));
14591 _LoadInventory(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY
), time_diff
);
14593 // update items with duration and realtime
14594 UpdateItemDuration(time_diff
, true);
14596 _LoadActions(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS
));
14598 // unread mails and next delivery time, actual mails not loaded
14599 _LoadMailInit(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT
), holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE
));
14601 m_social
= sSocialMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST
), GetGUIDLow());
14603 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14604 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14605 if(uint32 curTitle
= GetUInt32Value(PLAYER_CHOSEN_TITLE
))
14607 if(!HasTitle(curTitle
))
14608 SetUInt32Value(PLAYER_CHOSEN_TITLE
,0);
14611 // Not finish taxi flight path
14612 if(!m_taxi
.LoadTaxiDestinationsFromString(taxi_nodes
,GetTeam()))
14614 // problems with taxi path loading
14615 TaxiNodesEntry
const* nodeEntry
= NULL
;
14616 if(uint32 node_id
= m_taxi
.GetTaxiSource())
14617 nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
14619 if(!nodeEntry
) // don't know taxi start node, to homebind
14621 sLog
.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14622 RelocateToHomebind();
14623 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14625 else // have start node, to it
14627 sLog
.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14628 SetMapId(nodeEntry
->map_id
);
14629 Relocate(nodeEntry
->x
, nodeEntry
->y
, nodeEntry
->z
,0.0f
);
14630 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14632 m_taxi
.ClearTaxiDestinations();
14634 else if(uint32 node_id
= m_taxi
.GetTaxiSource())
14636 // save source node as recall coord to prevent recall and fall from sky
14637 TaxiNodesEntry
const* nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
14638 assert(nodeEntry
); // checked in m_taxi.LoadTaxiDestinationsFromString
14639 m_recallMap
= nodeEntry
->map_id
;
14640 m_recallX
= nodeEntry
->x
;
14641 m_recallY
= nodeEntry
->y
;
14642 m_recallZ
= nodeEntry
->z
;
14644 // flight will started later
14647 // has to be called after last Relocate() in Player::LoadFromDB
14648 SetFallInformation(0, GetPositionZ());
14650 _LoadSpellCooldowns(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS
));
14652 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14653 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14655 RemoveAllAurasOnDeath();
14657 //apply all stat bonuses from items and auras
14658 SetCanModifyStats(true);
14661 // restore remembered power/health values (but not more max values)
14662 SetHealth(savedHealth
> GetMaxHealth() ? GetMaxHealth() : savedHealth
);
14663 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
14664 SetPower(Powers(i
),savedPower
[i
] > GetMaxPower(Powers(i
)) ? GetMaxPower(Powers(i
)) : savedPower
[i
]);
14666 sLog
.outDebug("The value of player %s after load item and aura is: ", m_name
.c_str());
14670 if(GetSession()->GetSecurity() > SEC_PLAYER
)
14672 switch(sWorld
.getConfig(CONFIG_GM_LOGIN_STATE
))
14675 case 0: break; // disable
14676 case 1: SetGameMaster(true); break; // enable
14677 case 2: // save state
14678 if(extraflags
& PLAYER_EXTRA_GM_ON
)
14679 SetGameMaster(true);
14683 switch(sWorld
.getConfig(CONFIG_GM_VISIBLE_STATE
))
14686 case 0: SetGMVisible(false); break; // invisible
14687 case 1: break; // visible
14688 case 2: // save state
14689 if(extraflags
& PLAYER_EXTRA_GM_INVISIBLE
)
14690 SetGMVisible(false);
14694 switch(sWorld
.getConfig(CONFIG_GM_ACCEPT_TICKETS
))
14697 case 0: break; // disable
14698 case 1: SetAcceptTicket(true); break; // enable
14699 case 2: // save state
14700 if(extraflags
& PLAYER_EXTRA_GM_ACCEPT_TICKETS
)
14701 SetAcceptTicket(true);
14705 switch(sWorld
.getConfig(CONFIG_GM_CHAT
))
14708 case 0: break; // disable
14709 case 1: SetGMChat(true); break; // enable
14710 case 2: // save state
14711 if(extraflags
& PLAYER_EXTRA_GM_CHAT
)
14716 switch(sWorld
.getConfig(CONFIG_GM_WISPERING_TO
))
14719 case 0: break; // disable
14720 case 1: SetAcceptWhispers(true); break; // enable
14721 case 2: // save state
14722 if(extraflags
& PLAYER_EXTRA_ACCEPT_WHISPERS
)
14723 SetAcceptWhispers(true);
14728 _LoadDeclinedNames(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES
));
14730 m_achievementMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS
), holder
->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS
));
14731 m_achievementMgr
.CheckAllAchievementCriteria();
14735 bool Player::isAllowedToLoot(Creature
* creature
)
14737 if(Player
* recipient
= creature
->GetLootRecipient())
14739 if (recipient
== this)
14741 if( Group
* otherGroup
= recipient
->GetGroup())
14743 Group
* thisGroup
= GetGroup();
14746 return thisGroup
== otherGroup
;
14751 // prevent other players from looting if the recipient got disconnected
14752 return !creature
->hasLootRecipient();
14755 void Player::_LoadActions(QueryResult
*result
)
14757 m_actionButtons
.clear();
14759 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14765 Field
*fields
= result
->Fetch();
14767 uint8 button
= fields
[0].GetUInt8();
14769 if(addActionButton(button
, fields
[1].GetUInt16(), fields
[2].GetUInt8(), fields
[3].GetUInt8()))
14770 m_actionButtons
[button
].uState
= ACTIONBUTTON_UNCHANGED
;
14773 sLog
.outError( " ...at loading, and will deleted in DB also");
14775 // Will deleted in DB at next save (it can create data until save but marked as deleted)
14776 m_actionButtons
[button
].uState
= ACTIONBUTTON_DELETED
;
14779 while( result
->NextRow() );
14785 void Player::_LoadAuras(QueryResult
*result
, uint32 timediff
)
14788 for (int i
= 0; i
< TOTAL_AURAS
; i
++)
14789 m_modAuras
[i
].clear();
14791 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14797 Field
*fields
= result
->Fetch();
14798 uint64 caster_guid
= fields
[0].GetUInt64();
14799 uint32 spellid
= fields
[1].GetUInt32();
14800 uint32 effindex
= fields
[2].GetUInt32();
14801 uint32 stackcount
= fields
[3].GetUInt32();
14802 int32 damage
= (int32
)fields
[4].GetUInt32();
14803 int32 maxduration
= (int32
)fields
[5].GetUInt32();
14804 int32 remaintime
= (int32
)fields
[6].GetUInt32();
14805 int32 remaincharges
= (int32
)fields
[7].GetUInt32();
14807 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellid
);
14810 sLog
.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid
,effindex
);
14816 sLog
.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid
,effindex
);
14820 // negative effects should continue counting down after logout
14821 if (remaintime
!= -1 && !IsPositiveEffect(spellid
, effindex
))
14823 if(remaintime
<= int32(timediff
))
14826 remaintime
-= timediff
;
14829 // prevent wrong values of remaincharges
14830 if(spellproto
->procCharges
)
14832 if(remaincharges
<= 0 || remaincharges
> spellproto
->procCharges
)
14833 remaincharges
= spellproto
->procCharges
;
14838 //do not load single target auras (unless they were cast by the player)
14839 if (caster_guid
!= GetGUID() && IsSingleTargetSpell(spellproto
))
14842 for(uint32 i
=0; i
<stackcount
; i
++)
14844 Aura
* aura
= CreateAura(spellproto
, effindex
, NULL
, this, NULL
);
14846 damage
= aura
->GetModifier()->m_amount
;
14847 aura
->SetLoadedState(caster_guid
,damage
,maxduration
,remaintime
,remaincharges
);
14849 sLog
.outDetail("Added aura spellid %u, effect %u", spellproto
->Id
, effindex
);
14852 while( result
->NextRow() );
14857 if(m_class
== CLASS_WARRIOR
)
14858 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
14861 void Player::_LoadGlyphAuras()
14863 for (uint8 i
= 0; i
<= MAX_GLYPH_SLOT_INDEX
; ++i
)
14865 if (uint32 glyph
= GetGlyph(i
))
14867 if (GlyphPropertiesEntry
const *gp
= sGlyphPropertiesStore
.LookupEntry(glyph
))
14869 if (GlyphSlotEntry
const *gs
= sGlyphSlotStore
.LookupEntry(GetGlyphSlot(i
)))
14871 if(gp
->TypeFlags
== gs
->TypeFlags
)
14873 CastSpell(this, gp
->SpellId
, true);
14877 sLog
.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name
.c_str(), gp
->TypeFlags
, gs
->TypeFlags
);
14880 sLog
.outError("Player %s has not existing glyph slot entry %u on index %u", m_name
.c_str(), GetGlyphSlot(i
), i
);
14883 sLog
.outError("Player %s has not existing glyph entry %u on index %u", m_name
.c_str(), glyph
, i
);
14885 // On any error remove glyph
14891 void Player::LoadCorpse()
14895 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14899 if(Corpse
*corpse
= GetCorpse())
14901 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, corpse
&& !sMapStore
.LookupEntry(corpse
->GetMapId())->Instanceable() );
14905 //Prevent Dead Player login without corpse
14906 ResurrectPlayer(0.5f
);
14911 void Player::_LoadInventory(QueryResult
*result
, uint32 timediff
)
14913 //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());
14914 std::map
<uint64
, Bag
*> bagMap
; // fast guid lookup for bags
14915 //NOTE: the "order by `bag`" is important because it makes sure
14916 //the bagMap is filled before items in the bags are loaded
14917 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14918 //expected to be equipped before offhand items (TODO: fixme)
14920 uint32 zone
= GetZoneId();
14924 std::list
<Item
*> problematicItems
;
14926 // prevent items from being added to the queue when stored
14927 m_itemUpdateQueueBlocked
= true;
14930 Field
*fields
= result
->Fetch();
14931 uint32 bag_guid
= fields
[1].GetUInt32();
14932 uint8 slot
= fields
[2].GetUInt8();
14933 uint32 item_guid
= fields
[3].GetUInt32();
14934 uint32 item_id
= fields
[4].GetUInt32();
14936 ItemPrototype
const * proto
= objmgr
.GetItemPrototype(item_id
);
14940 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14941 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid
);
14942 sLog
.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id
);
14946 Item
*item
= NewItemOrBag(proto
);
14948 if(!item
->LoadFromDB(item_guid
, GetGUID(), result
))
14950 sLog
.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id
);
14951 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14952 item
->FSetState(ITEM_REMOVED
);
14953 item
->SaveToDB(); // it also deletes item object !
14957 // not allow have in alive state item limited to another map/zone
14958 if(isAlive() && item
->IsLimitedToAnotherMapOrZone(GetMapId(),zone
) )
14960 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14961 item
->FSetState(ITEM_REMOVED
);
14962 item
->SaveToDB(); // it also deletes item object !
14966 // "Conjured items disappear if you are logged out for more than 15 minutes"
14967 if ((timediff
> 15*60) && (item
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_CONJURED
)))
14969 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14970 item
->FSetState(ITEM_REMOVED
);
14971 item
->SaveToDB(); // it also deletes item object !
14975 bool success
= true;
14979 // the item is not in a bag
14980 item
->SetContainer( NULL
);
14981 item
->SetSlot(slot
);
14983 if( IsInventoryPos( INVENTORY_SLOT_BAG_0
, slot
) )
14985 ItemPosCountVec dest
;
14986 if( CanStoreItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false ) == EQUIP_ERR_OK
)
14987 item
= StoreItem(dest
, item
, true);
14991 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0
, slot
) )
14994 if( CanEquipItem( slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
14995 QuickEquipItem(dest
, item
);
14999 else if( IsBankPos( INVENTORY_SLOT_BAG_0
, slot
) )
15001 ItemPosCountVec dest
;
15002 if( CanBankItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
15003 item
= BankItem(dest
, item
, true);
15010 // store bags that may contain items in them
15011 if(item
->IsBag() && IsBagPos(item
->GetPos()))
15012 bagMap
[item_guid
] = (Bag
*)item
;
15017 item
->SetSlot(NULL_SLOT
);
15018 // the item is in a bag, find the bag
15019 std::map
<uint64
, Bag
*>::iterator itr
= bagMap
.find(bag_guid
);
15020 if(itr
!= bagMap
.end())
15021 itr
->second
->StoreItem(slot
, item
, true );
15026 // item's state may have changed after stored
15028 item
->SetState(ITEM_UNCHANGED
, this);
15031 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
);
15032 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
15033 problematicItems
.push_back(item
);
15035 } while (result
->NextRow());
15038 m_itemUpdateQueueBlocked
= false;
15040 // send by mail problematic items
15041 while(!problematicItems
.empty())
15044 MailItemsInfo mi
; // item list preparing
15046 for(int i
= 0; !problematicItems
.empty() && i
< MAX_MAIL_ITEMS
; ++i
)
15048 Item
* item
= problematicItems
.front();
15049 problematicItems
.pop_front();
15051 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
15054 std::string subject
= GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM
);
15056 WorldSession::SendMailTo(this, MAIL_NORMAL
, MAIL_STATIONERY_GM
, GetGUIDLow(), GetGUIDLow(), subject
, 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
);
15060 _ApplyAllItemMods();
15063 // load mailed item which should receive current player
15064 void Player::_LoadMailedItems(Mail
*mail
)
15066 // data needs to be at first place for Item::LoadFromDB
15067 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
);
15073 Field
*fields
= result
->Fetch();
15074 uint32 item_guid_low
= fields
[1].GetUInt32();
15075 uint32 item_template
= fields
[2].GetUInt32();
15077 mail
->AddItem(item_guid_low
, item_template
);
15079 ItemPrototype
const *proto
= objmgr
.GetItemPrototype(item_template
);
15083 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
);
15084 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
15085 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low
);
15089 Item
*item
= NewItemOrBag(proto
);
15091 if(!item
->LoadFromDB(item_guid_low
, 0, result
))
15093 sLog
.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail
->messageID
, item_guid_low
);
15094 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
15095 item
->FSetState(ITEM_REMOVED
);
15096 item
->SaveToDB(); // it also deletes item object !
15101 } while (result
->NextRow());
15106 void Player::_LoadMailInit(QueryResult
*resultUnread
, QueryResult
*resultDelivery
)
15108 //set a count of unread mails
15109 //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);
15112 Field
*fieldMail
= resultUnread
->Fetch();
15113 unReadMails
= fieldMail
[0].GetUInt8();
15114 delete resultUnread
;
15117 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
15118 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
15119 if (resultDelivery
)
15121 Field
*fieldMail
= resultDelivery
->Fetch();
15122 m_nextMailDelivereTime
= (time_t)fieldMail
[0].GetUInt64();
15123 delete resultDelivery
;
15127 void Player::_LoadMail()
15130 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
15131 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());
15136 Field
*fields
= result
->Fetch();
15137 Mail
*m
= new Mail
;
15138 m
->messageID
= fields
[0].GetUInt32();
15139 m
->messageType
= fields
[1].GetUInt8();
15140 m
->sender
= fields
[2].GetUInt32();
15141 m
->receiver
= fields
[3].GetUInt32();
15142 m
->subject
= fields
[4].GetCppString();
15143 m
->itemTextId
= fields
[5].GetUInt32();
15144 bool has_items
= fields
[6].GetBool();
15145 m
->expire_time
= (time_t)fields
[7].GetUInt64();
15146 m
->deliver_time
= (time_t)fields
[8].GetUInt64();
15147 m
->money
= fields
[9].GetUInt32();
15148 m
->COD
= fields
[10].GetUInt32();
15149 m
->checked
= fields
[11].GetUInt32();
15150 m
->stationery
= fields
[12].GetUInt8();
15151 m
->mailTemplateId
= fields
[13].GetInt16();
15153 if(m
->mailTemplateId
&& !sMailTemplateStore
.LookupEntry(m
->mailTemplateId
))
15155 sLog
.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m
->messageID
, m
->mailTemplateId
);
15156 m
->mailTemplateId
= 0;
15159 m
->state
= MAIL_STATE_UNCHANGED
;
15162 _LoadMailedItems(m
);
15164 m_mail
.push_back(m
);
15165 } while( result
->NextRow() );
15168 m_mailsLoaded
= true;
15171 void Player::LoadPet()
15173 //fixme: the pet should still be loaded if the player is not in world
15174 // just not added to the map
15177 Pet
*pet
= new Pet
;
15178 if(!pet
->LoadPetFromDB(this,0,0,true))
15183 void Player::_LoadQuestStatus(QueryResult
*result
)
15185 mQuestStatus
.clear();
15189 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
15190 //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());
15196 Field
*fields
= result
->Fetch();
15198 uint32 quest_id
= fields
[0].GetUInt32();
15199 // used to be new, no delete?
15200 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
15204 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
15206 uint32 qstatus
= fields
[1].GetUInt32();
15207 if(qstatus
< MAX_QUEST_STATUS
)
15208 questStatusData
.m_status
= QuestStatus(qstatus
);
15211 questStatusData
.m_status
= QUEST_STATUS_NONE
;
15212 sLog
.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id
,qstatus
);
15215 questStatusData
.m_rewarded
= ( fields
[2].GetUInt8() > 0 );
15216 questStatusData
.m_explored
= ( fields
[3].GetUInt8() > 0 );
15218 time_t quest_time
= time_t(fields
[4].GetUInt64());
15220 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && !GetQuestRewardStatus(quest_id
) && questStatusData
.m_status
!= QUEST_STATUS_NONE
)
15222 AddTimedQuest( quest_id
);
15224 if (quest_time
<= sWorld
.GetGameTime())
15225 questStatusData
.m_timer
= 1;
15227 questStatusData
.m_timer
= (quest_time
- sWorld
.GetGameTime()) * IN_MILISECONDS
;
15232 questStatusData
.m_creatureOrGOcount
[0] = fields
[5].GetUInt32();
15233 questStatusData
.m_creatureOrGOcount
[1] = fields
[6].GetUInt32();
15234 questStatusData
.m_creatureOrGOcount
[2] = fields
[7].GetUInt32();
15235 questStatusData
.m_creatureOrGOcount
[3] = fields
[8].GetUInt32();
15236 questStatusData
.m_itemcount
[0] = fields
[9].GetUInt32();
15237 questStatusData
.m_itemcount
[1] = fields
[10].GetUInt32();
15238 questStatusData
.m_itemcount
[2] = fields
[11].GetUInt32();
15239 questStatusData
.m_itemcount
[3] = fields
[12].GetUInt32();
15241 questStatusData
.uState
= QUEST_UNCHANGED
;
15243 // add to quest log
15244 if( slot
< MAX_QUEST_LOG_SIZE
&&
15245 ( questStatusData
.m_status
==QUEST_STATUS_INCOMPLETE
||
15246 questStatusData
.m_status
==QUEST_STATUS_COMPLETE
&&
15247 (!questStatusData
.m_rewarded
|| pQuest
->IsDaily()) ) )
15249 SetQuestSlot(slot
,quest_id
,quest_time
);
15251 if(questStatusData
.m_status
== QUEST_STATUS_COMPLETE
)
15252 SetQuestSlotState(slot
,QUEST_STATE_COMPLETE
);
15254 for(uint8 idx
= 0; idx
< QUEST_OBJECTIVES_COUNT
; ++idx
)
15255 if(questStatusData
.m_creatureOrGOcount
[idx
])
15256 SetQuestSlotCounter(slot
,idx
,questStatusData
.m_creatureOrGOcount
[idx
]);
15261 if(questStatusData
.m_rewarded
)
15263 // learn rewarded spell if unknown
15264 learnQuestRewardedSpells(pQuest
);
15266 // set rewarded title if any
15267 if(pQuest
->GetCharTitleId())
15269 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
15270 SetTitle(titleEntry
);
15273 if(pQuest
->GetBonusTalents())
15274 m_questRewardTalentCount
+=pQuest
->GetBonusTalents();
15277 sLog
.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData
.m_status
, quest_id
, GetGUIDLow());
15280 while( result
->NextRow() );
15285 // clear quest log tail
15286 for ( uint16 i
= slot
; i
< MAX_QUEST_LOG_SIZE
; ++i
)
15290 void Player::_LoadDailyQuestStatus(QueryResult
*result
)
15292 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
15293 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
15295 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
15299 uint32 quest_daily_idx
= 0;
15303 if(quest_daily_idx
>= PLAYER_MAX_DAILY_QUESTS
) // max amount with exist data in query
15305 sLog
.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15309 Field
*fields
= result
->Fetch();
15311 uint32 quest_id
= fields
[0].GetUInt32();
15313 // save _any_ from daily quest times (it must be after last reset anyway)
15314 m_lastDailyQuestTime
= (time_t)fields
[1].GetUInt64();
15316 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
15320 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
15323 sLog
.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id
, GetGUIDLow());
15325 while( result
->NextRow() );
15330 m_DailyQuestChanged
= false;
15333 void Player::_LoadReputation(QueryResult
*result
)
15335 m_factions
.clear();
15337 // Set initial reputations (so everything is nifty before DB data load)
15338 SetInitialFactions();
15340 //QueryResult *result = CharacterDatabase.PQuery("SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'",GetGUIDLow());
15346 Field
*fields
= result
->Fetch();
15348 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(fields
[0].GetUInt32());
15349 if( factionEntry
&& (factionEntry
->reputationListID
>= 0))
15351 FactionState
* faction
= &m_factions
[factionEntry
->reputationListID
];
15353 // update standing to current
15354 faction
->Standing
= int32(fields
[1].GetUInt32());
15356 uint32 dbFactionFlags
= fields
[2].GetUInt32();
15358 if( dbFactionFlags
& FACTION_FLAG_VISIBLE
)
15359 SetFactionVisible(faction
); // have internal checks for forced invisibility
15361 if( dbFactionFlags
& FACTION_FLAG_INACTIVE
)
15362 SetFactionInactive(faction
,true); // have internal checks for visibility requirement
15364 if( dbFactionFlags
& FACTION_FLAG_AT_WAR
) // DB at war
15365 SetFactionAtWar(faction
,true); // have internal checks for FACTION_FLAG_PEACE_FORCED
15366 else // DB not at war
15368 // allow remove if visible (and then not FACTION_FLAG_INVISIBLE_FORCED or FACTION_FLAG_HIDDEN)
15369 if( faction
->Flags
& FACTION_FLAG_VISIBLE
)
15370 SetFactionAtWar(faction
,false); // have internal checks for FACTION_FLAG_PEACE_FORCED
15373 // set atWar for hostile
15374 if(GetReputationRank(factionEntry
) <= REP_HOSTILE
)
15375 SetFactionAtWar(faction
,true);
15377 // reset changed flag if values similar to saved in DB
15378 if(faction
->Flags
==dbFactionFlags
)
15379 faction
->Changed
= false;
15382 while( result
->NextRow() );
15388 void Player::_LoadSpells(QueryResult
*result
)
15390 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
15396 Field
*fields
= result
->Fetch();
15398 addSpell(fields
[0].GetUInt16(), fields
[1].GetBool(), false, false, fields
[2].GetBool());
15400 while( result
->NextRow() );
15406 void Player::_LoadTutorials(QueryResult
*result
)
15408 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
15414 Field
*fields
= result
->Fetch();
15416 for (int iI
=0; iI
<8; iI
++)
15417 m_Tutorials
[iI
] = fields
[iI
].GetUInt32();
15419 while( result
->NextRow() );
15424 m_TutorialsChanged
= false;
15427 void Player::_LoadGroup(QueryResult
*result
)
15429 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
15432 uint64 leaderGuid
= MAKE_NEW_GUID((*result
)[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
15434 Group
* group
= objmgr
.GetGroupByLeader(leaderGuid
);
15437 uint8 subgroup
= group
->GetMemberGroup(GetGUID());
15438 SetGroup(group
, subgroup
);
15439 if(getLevel() >= LEVELREQUIREMENT_HEROIC
)
15441 // the group leader may change the instance difficulty while the player is offline
15442 SetDifficulty(group
->GetDifficulty());
15448 void Player::_LoadBoundInstances(QueryResult
*result
)
15450 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15451 m_boundInstances
[i
].clear();
15453 Group
*group
= GetGroup();
15455 //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));
15460 Field
*fields
= result
->Fetch();
15461 bool perm
= fields
[1].GetBool();
15462 uint32 mapId
= fields
[2].GetUInt32();
15463 uint32 instanceId
= fields
[0].GetUInt32();
15464 uint8 difficulty
= fields
[3].GetUInt8();
15465 time_t resetTime
= (time_t)fields
[4].GetUInt64();
15466 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15467 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15468 // and in that case it is not used
15472 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
);
15473 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
15477 // since non permanent binds are always solo bind, they can always be reset
15478 InstanceSave
*save
= sInstanceSaveManager
.AddInstanceSave(mapId
, instanceId
, difficulty
, resetTime
, !perm
, true);
15479 if(save
) BindToInstance(save
, perm
, true);
15480 } while(result
->NextRow());
15485 InstancePlayerBind
* Player::GetBoundInstance(uint32 mapid
, uint8 difficulty
)
15487 // some instances only have one difficulty
15488 const MapEntry
* entry
= sMapStore
.LookupEntry(mapid
);
15489 if(!entry
|| !entry
->SupportsHeroicMode()) difficulty
= DIFFICULTY_NORMAL
;
15491 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
15492 if(itr
!= m_boundInstances
[difficulty
].end())
15493 return &itr
->second
;
15498 void Player::UnbindInstance(uint32 mapid
, uint8 difficulty
, bool unload
)
15500 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
15501 UnbindInstance(itr
, difficulty
, unload
);
15504 void Player::UnbindInstance(BoundInstancesMap::iterator
&itr
, uint8 difficulty
, bool unload
)
15506 if(itr
!= m_boundInstances
[difficulty
].end())
15508 if(!unload
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr
->second
.save
->GetInstanceId());
15509 itr
->second
.save
->RemovePlayer(this); // save can become invalid
15510 m_boundInstances
[difficulty
].erase(itr
++);
15514 InstancePlayerBind
* Player::BindToInstance(InstanceSave
*save
, bool permanent
, bool load
)
15518 InstancePlayerBind
& bind
= m_boundInstances
[save
->GetDifficulty()][save
->GetMapId()];
15521 // update the save when the group kills a boss
15522 if(permanent
!= bind
.perm
|| save
!= bind
.save
)
15523 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());
15526 if(!load
) CharacterDatabase
.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save
->GetInstanceId(), permanent
);
15528 if(bind
.save
!= save
)
15530 if(bind
.save
) bind
.save
->RemovePlayer(this);
15531 save
->AddPlayer(this);
15534 if(permanent
) save
->SetCanReset(false);
15537 bind
.perm
= permanent
;
15538 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());
15545 void Player::SendRaidInfo()
15547 uint32 counter
= 0;
15549 WorldPacket
data(SMSG_RAID_INSTANCE_INFO
, 4);
15551 size_t p_counter
= data
.wpos();
15552 data
<< uint32(counter
); // placeholder
15554 for(int i
= 0; i
< TOTAL_DIFFICULTIES
; ++i
)
15556 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15558 if(itr
->second
.perm
)
15560 InstanceSave
*save
= itr
->second
.save
;
15561 data
<< uint32(save
->GetMapId());
15562 data
<< uint32(save
->GetResetTime() - time(NULL
));
15563 data
<< uint32(save
->GetInstanceId());
15564 data
<< uint32(save
->GetDifficulty());
15569 data
.put
<uint32
>(p_counter
,counter
);
15570 GetSession()->SendPacket(&data
);
15574 - called on every successful teleportation to a map
15576 void Player::SendSavedInstances()
15578 bool hasBeenSaved
= false;
15581 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15583 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15585 if(itr
->second
.perm
) // only permanent binds are sent
15587 hasBeenSaved
= true;
15593 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15594 data
.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP
);
15595 data
<< uint32(hasBeenSaved
);
15596 GetSession()->SendPacket(&data
);
15601 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15603 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15605 if(itr
->second
.perm
)
15607 data
.Initialize(SMSG_UPDATE_LAST_INSTANCE
);
15608 data
<< uint32(itr
->second
.save
->GetMapId());
15609 GetSession()->SendPacket(&data
);
15615 /// convert the player's binds to the group
15616 void Player::ConvertInstancesToGroup(Player
*player
, Group
*group
, uint64 player_guid
)
15618 bool has_binds
= false;
15619 bool has_solo
= false;
15621 if(player
) { player_guid
= player
->GetGUID(); if(!group
) group
= player
->GetGroup(); }
15622 assert(player_guid
);
15624 // copy all binds to the group, when changing leader it's assumed the character
15625 // will not have any solo binds
15629 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15631 for (BoundInstancesMap::iterator itr
= player
->m_boundInstances
[i
].begin(); itr
!= player
->m_boundInstances
[i
].end();)
15634 if(group
) group
->BindToInstance(itr
->second
.save
, itr
->second
.perm
, true);
15635 // permanent binds are not removed
15636 if(!itr
->second
.perm
)
15638 player
->UnbindInstance(itr
, i
, true); // increments itr
15647 // if the player's not online we don't know what binds it has
15648 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
));
15649 // the following should not get executed when changing leaders
15650 if(!player
|| has_solo
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid
));
15653 bool Player::_LoadHomeBind(QueryResult
*result
)
15655 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(), getClass());
15658 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
15663 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15666 Field
*fields
= result
->Fetch();
15667 m_homebindMapId
= fields
[0].GetUInt32();
15668 m_homebindZoneId
= fields
[1].GetUInt16();
15669 m_homebindX
= fields
[2].GetFloat();
15670 m_homebindY
= fields
[3].GetFloat();
15671 m_homebindZ
= fields
[4].GetFloat();
15674 MapEntry
const* bindMapEntry
= sMapStore
.LookupEntry(m_homebindMapId
);
15676 // accept saved data only for valid position (and non instanceable), and accessable
15677 if( MapManager::IsValidMapCoord(m_homebindMapId
,m_homebindX
,m_homebindY
,m_homebindZ
) &&
15678 !bindMapEntry
->Instanceable() && GetSession()->Expansion() >= bindMapEntry
->Expansion())
15683 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15688 m_homebindMapId
= info
->mapId
;
15689 m_homebindZoneId
= info
->zoneId
;
15690 m_homebindX
= info
->positionX
;
15691 m_homebindY
= info
->positionY
;
15692 m_homebindZ
= info
->positionZ
;
15694 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
);
15697 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
15698 m_homebindMapId
, m_homebindZoneId
, m_homebindX
, m_homebindY
, m_homebindZ
);
15703 /*********************************************************/
15704 /*** SAVE SYSTEM ***/
15705 /*********************************************************/
15707 void Player::SaveToDB()
15709 // delay auto save at any saves (manual, in code, or autosave)
15710 m_nextSave
= sWorld
.getConfig(CONFIG_INTERVAL_SAVE
);
15712 // first save/honor gain after midnight will also update the player's honor fields
15713 UpdateHonorFields();
15715 int is_save_resting
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
) ? 1 : 0;
15716 //save, far from tavern/city
15717 //save, but in tavern/city
15718 sLog
.outDebug("The value of player %s at save: ", m_name
.c_str());
15721 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15722 uint32 tmp_bytes
= GetUInt32Value(UNIT_FIELD_BYTES_1
);
15723 uint32 tmp_bytes2
= GetUInt32Value(UNIT_FIELD_BYTES_2
);
15724 uint32 tmp_flags
= GetUInt32Value(UNIT_FIELD_FLAGS
);
15725 uint32 tmp_pflags
= GetUInt32Value(PLAYER_FLAGS
);
15726 uint32 tmp_displayid
= GetDisplayId();
15728 // Set player sit state to standing on save, also stealth and shifted form
15729 SetByteValue(UNIT_FIELD_BYTES_1
, 0, UNIT_STAND_STATE_STAND
);
15730 SetByteValue(UNIT_FIELD_BYTES_2
, 3, 0); // shapeshift
15731 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_STUNNED
);
15732 SetDisplayId(GetNativeDisplayId());
15734 bool inworld
= IsInWorld();
15736 CharacterDatabase
.BeginTransaction();
15738 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15740 std::string sql_name
= m_name
;
15741 CharacterDatabase
.escape_string(sql_name
);
15743 std::ostringstream ss
;
15744 ss
<< "INSERT INTO characters (guid,account,name,race,class,"
15745 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15746 "taximask, online, cinematic, "
15747 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15748 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15749 "death_expire_time, taxi_path, arena_pending_points, bgid, bgteam, bgmap, bgx, bgy, bgz, bgo) VALUES ("
15750 << GetGUIDLow() << ", "
15751 << GetSession()->GetAccountId() << ", '"
15752 << sql_name
<< "', "
15754 << m_class
<< ", ";
15756 if(!IsBeingTeleported())
15758 ss
<< GetMapId() << ", "
15759 << (uint32
)GetDifficulty() << ", "
15760 << finiteAlways(GetPositionX()) << ", "
15761 << finiteAlways(GetPositionY()) << ", "
15762 << finiteAlways(GetPositionZ()) << ", "
15763 << finiteAlways(GetOrientation()) << ", '";
15767 ss
<< GetTeleportDest().mapid
<< ", "
15768 << (uint32
)GetDifficulty() << ", "
15769 << finiteAlways(GetTeleportDest().x
) << ", "
15770 << finiteAlways(GetTeleportDest().y
) << ", "
15771 << finiteAlways(GetTeleportDest().z
) << ", "
15772 << finiteAlways(GetTeleportDest().o
) << ", '";
15776 for( i
= 0; i
< m_valuesCount
; i
++ )
15778 ss
<< GetUInt32Value(i
) << " ";
15783 ss
<< m_taxi
; // string with TaxiMaskSize numbers
15786 ss
<< (inworld
? 1 : 0);
15792 ss
<< m_Played_time
[0];
15794 ss
<< m_Played_time
[1];
15797 ss
<< finiteAlways(m_rest_bonus
);
15799 ss
<< (uint64
)time(NULL
);
15801 ss
<< is_save_resting
;
15803 ss
<< m_resetTalentsCost
;
15805 ss
<< (uint64
)m_resetTalentsTime
;
15808 ss
<< finiteAlways(m_movementInfo
.t_x
);
15810 ss
<< finiteAlways(m_movementInfo
.t_y
);
15812 ss
<< finiteAlways(m_movementInfo
.t_z
);
15814 ss
<< finiteAlways(m_movementInfo
.t_o
);
15817 ss
<< m_transport
->GetGUIDLow();
15822 ss
<< m_ExtraFlags
;
15825 ss
<< uint32(m_stableSlots
); // to prevent save uint8 as char
15828 ss
<< uint32(m_atLoginFlags
);
15834 ss
<< (uint64
)m_deathExpireTime
;
15837 ss
<< m_taxi
.SaveTaxiDestinationsToString();
15839 ss
<< GetBattleGroundId();
15843 ss
<< m_bgEntryPoint
.mapid
<< ", "
15844 << finiteAlways(m_bgEntryPoint
.x
) << ", "
15845 << finiteAlways(m_bgEntryPoint
.y
) << ", "
15846 << finiteAlways(m_bgEntryPoint
.z
) << ", "
15847 << finiteAlways(m_bgEntryPoint
.o
);
15850 CharacterDatabase
.Execute( ss
.str().c_str() );
15852 if(m_mailsUpdated
) //save mails only when needed
15856 _SaveQuestStatus();
15857 _SaveDailyQuestStatus();
15860 _SaveSpellCooldowns();
15865 CharacterDatabase
.CommitTransaction();
15867 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15868 SetDisplayId(tmp_displayid
);
15869 SetUInt32Value(UNIT_FIELD_BYTES_1
, tmp_bytes
);
15870 SetUInt32Value(UNIT_FIELD_BYTES_2
, tmp_bytes2
);
15871 SetUInt32Value(UNIT_FIELD_FLAGS
, tmp_flags
);
15872 SetUInt32Value(PLAYER_FLAGS
, tmp_pflags
);
15874 // save pet (hunter pet level and experience and all type pets health/mana).
15875 if(Pet
* pet
= GetPet())
15876 pet
->SavePetToDB(PET_SAVE_AS_CURRENT
);
15877 m_achievementMgr
.SaveToDB();
15880 // fast save function for item/money cheating preventing - save only inventory and money state
15881 void Player::SaveInventoryAndGoldToDB()
15884 //money is in data field
15885 SaveDataFieldToDB();
15888 void Player::_SaveActions()
15890 for(ActionButtonList::iterator itr
= m_actionButtons
.begin(); itr
!= m_actionButtons
.end(); )
15892 switch (itr
->second
.uState
)
15894 case ACTIONBUTTON_NEW
:
15895 CharacterDatabase
.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15896 GetGUIDLow(), (uint32
)itr
->first
, (uint32
)itr
->second
.action
, (uint32
)itr
->second
.type
, (uint32
)itr
->second
.misc
);
15897 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
15900 case ACTIONBUTTON_CHANGED
:
15901 CharacterDatabase
.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15902 (uint32
)itr
->second
.action
, (uint32
)itr
->second
.type
, (uint32
)itr
->second
.misc
, GetGUIDLow(), (uint32
)itr
->first
);
15903 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
15906 case ACTIONBUTTON_DELETED
:
15907 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32
)itr
->first
);
15908 m_actionButtons
.erase(itr
++);
15917 void Player::_SaveAuras()
15919 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15921 AuraMap
const& auras
= GetAuras();
15926 spellEffectPair lastEffectPair
= auras
.begin()->first
;
15927 uint32 stackCounter
= 1;
15929 for(AuraMap::const_iterator itr
= auras
.begin(); ; ++itr
)
15931 if(itr
== auras
.end() || lastEffectPair
!= itr
->first
)
15933 AuraMap::const_iterator itr2
= itr
;
15934 // save previous spellEffectPair to db
15937 SpellEntry
const *spellInfo
= itr2
->second
->GetSpellProto();
15939 //skip all auras from spells that are passive or need a shapeshift
15940 if (!(itr2
->second
->IsPassive() || itr2
->second
->IsRemovedOnShapeLost()))
15942 //do not save single target auras (unless they were cast by the player)
15943 if (!(itr2
->second
->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo
)))
15946 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15947 for (i
= 0; i
< 3; i
++)
15948 if (spellInfo
->EffectApplyAuraName
[i
] == SPELL_AURA_MOD_SHAPESHIFT
||
15949 spellInfo
->EffectApplyAuraName
[i
] == SPELL_AURA_MOD_STEALTH
)
15954 CharacterDatabase
.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15955 "VALUES ('%u', '" I64FMTD
"' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15956 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()));
15961 if(itr
== auras
.end())
15965 if (lastEffectPair
== itr
->first
)
15969 lastEffectPair
= itr
->first
;
15975 void Player::_SaveInventory()
15977 // force items in buyback slots to new state
15978 // and remove those that aren't already
15979 for (uint8 i
= BUYBACK_SLOT_START
; i
< BUYBACK_SLOT_END
; i
++)
15981 Item
*item
= m_items
[i
];
15982 if (!item
|| item
->GetState() == ITEM_NEW
) continue;
15983 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
15984 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item
->GetGUIDLow());
15985 m_items
[i
]->FSetState(ITEM_NEW
);
15988 // update enchantment durations
15989 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
15991 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
15995 if (m_itemUpdateQueue
.empty()) return;
15997 // do not save if the update queue is corrupt
15998 bool error
= false;
15999 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); i
++)
16001 Item
*item
= m_itemUpdateQueue
[i
];
16002 if(!item
|| item
->GetState() == ITEM_REMOVED
) continue;
16003 Item
*test
= GetItemByPos( item
->GetBagSlot(), item
->GetSlot());
16007 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());
16010 else if (test
!= item
)
16012 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());
16019 sLog
.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
16020 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED
);
16024 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); i
++)
16026 Item
*item
= m_itemUpdateQueue
[i
];
16027 if(!item
) continue;
16029 Bag
*container
= item
->GetContainer();
16030 uint32 bag_guid
= container
? container
->GetGUIDLow() : 0;
16032 switch(item
->GetState())
16035 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());
16038 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());
16041 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
16043 case ITEM_UNCHANGED
:
16047 item
->SaveToDB(); // item have unchanged inventory record and can be save standalone
16049 m_itemUpdateQueue
.clear();
16052 void Player::_SaveMail()
16054 if (!m_mailsLoaded
)
16057 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
16060 if (m
->state
== MAIL_STATE_CHANGED
)
16062 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'",
16063 m
->itemTextId
, m
->HasItems() ? 1 : 0, (uint64
)m
->expire_time
, (uint64
)m
->deliver_time
, m
->money
, m
->COD
, m
->checked
, m
->messageID
);
16064 if(m
->removedItems
.size())
16066 for(std::vector
<uint32
>::iterator itr2
= m
->removedItems
.begin(); itr2
!= m
->removedItems
.end(); ++itr2
)
16067 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2
);
16068 m
->removedItems
.clear();
16070 m
->state
= MAIL_STATE_UNCHANGED
;
16072 else if (m
->state
== MAIL_STATE_DELETED
)
16075 for(std::vector
<MailItemInfo
>::iterator itr2
= m
->items
.begin(); itr2
!= m
->items
.end(); ++itr2
)
16076 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2
->item_guid
);
16078 CharacterDatabase
.PExecute("DELETE FROM item_text WHERE id = '%u'", m
->itemTextId
);
16079 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", m
->messageID
);
16080 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m
->messageID
);
16084 //deallocate deleted mails...
16085 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); )
16087 if ((*itr
)->state
== MAIL_STATE_DELETED
)
16092 itr
= m_mail
.begin();
16098 m_mailsUpdated
= false;
16101 void Player::_SaveQuestStatus()
16103 // we don't need transactions here.
16104 for( QuestStatusMap::iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
16106 switch (i
->second
.uState
)
16109 CharacterDatabase
.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
16110 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD
"', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
16111 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]);
16113 case QUEST_CHANGED
:
16114 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' ",
16115 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
);
16117 case QUEST_UNCHANGED
:
16120 i
->second
.uState
= QUEST_UNCHANGED
;
16124 void Player::_SaveDailyQuestStatus()
16126 if(!m_DailyQuestChanged
)
16129 m_DailyQuestChanged
= false;
16131 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
16133 // we don't need transactions here.
16134 CharacterDatabase
.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
16135 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
16136 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
16137 CharacterDatabase
.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD
"')",
16138 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
),uint64(m_lastDailyQuestTime
));
16141 void Player::_SaveReputation()
16143 for(FactionStateList::iterator itr
= m_factions
.begin(); itr
!= m_factions
.end(); ++itr
)
16145 if (itr
->second
.Changed
)
16147 CharacterDatabase
.PExecute("DELETE FROM character_reputation WHERE guid = '%u' AND faction='%u'", GetGUIDLow(), itr
->second
.ID
);
16148 CharacterDatabase
.PExecute("INSERT INTO character_reputation (guid,faction,standing,flags) VALUES ('%u', '%u', '%i', '%u')", GetGUIDLow(), itr
->second
.ID
, itr
->second
.Standing
, itr
->second
.Flags
);
16149 itr
->second
.Changed
= false;
16154 void Player::_SaveSpells()
16156 for (PlayerSpellMap::iterator itr
= m_spells
.begin(), next
= m_spells
.begin(); itr
!= m_spells
.end();)
16158 if (itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->second
->state
== PLAYERSPELL_CHANGED
)
16159 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr
->first
);
16161 // add only changed/new not dependent spells
16162 if (!itr
->second
->dependent
&& (itr
->second
->state
== PLAYERSPELL_NEW
|| itr
->second
->state
== PLAYERSPELL_CHANGED
))
16163 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);
16165 if (itr
->second
->state
== PLAYERSPELL_REMOVED
)
16167 delete itr
->second
;
16168 m_spells
.erase(itr
++);
16172 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
16179 void Player::_SaveTutorials()
16181 if(!m_TutorialsChanged
)
16185 // it's better than rebuilding indexes multiple times
16186 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID
);
16189 Rows
= result
->Fetch()[0].GetUInt32();
16195 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'",
16196 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
);
16200 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]);
16203 m_TutorialsChanged
= false;
16206 void Player::outDebugValues() const
16208 if(!sLog
.IsOutDebug()) // optimize disabled debug output
16211 sLog
.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA
));
16212 sLog
.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY
), GetStat(STAT_STRENGTH
));
16213 sLog
.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT
), GetStat(STAT_SPIRIT
));
16214 sLog
.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA
), GetStat(STAT_SPIRIT
));
16215 sLog
.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE
));
16216 sLog
.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY
), GetResistance(SPELL_SCHOOL_FIRE
));
16217 sLog
.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE
), GetResistance(SPELL_SCHOOL_FROST
));
16218 sLog
.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW
), GetResistance(SPELL_SCHOOL_ARCANE
));
16219 sLog
.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE
), GetFloatValue(UNIT_FIELD_MAXDAMAGE
));
16220 sLog
.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
));
16221 sLog
.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
));
16222 sLog
.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK
), GetAttackTime(RANGED_ATTACK
));
16225 /*********************************************************/
16226 /*** FLOOD FILTER SYSTEM ***/
16227 /*********************************************************/
16229 void Player::UpdateSpeakTime()
16231 // ignore chat spam protection for GMs in any mode
16232 if(GetSession()->GetSecurity() > SEC_PLAYER
)
16235 time_t current
= time (NULL
);
16236 if(m_speakTime
> current
)
16238 uint32 max_count
= sWorld
.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT
);
16243 if(m_speakCount
>= max_count
)
16245 // prevent overwrite mute time, if message send just before mutes set, for example.
16246 time_t new_mute
= current
+ sWorld
.getConfig(CONFIG_CHATFLOOD_MUTE_TIME
);
16247 if(GetSession()->m_muteTime
< new_mute
)
16248 GetSession()->m_muteTime
= new_mute
;
16256 m_speakTime
= current
+ sWorld
.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY
);
16259 bool Player::CanSpeak() const
16261 return GetSession()->m_muteTime
<= time (NULL
);
16264 /*********************************************************/
16265 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
16266 /*********************************************************/
16268 void Player::SendAttackSwingNotInRange()
16270 WorldPacket
data(SMSG_ATTACKSWING_NOTINRANGE
, 0);
16271 GetSession()->SendPacket( &data
);
16274 void Player::SavePositionInDB(uint32 mapid
, float x
,float y
,float z
,float o
,uint32 zone
,uint64 guid
)
16276 std::ostringstream ss
;
16277 ss
<< "UPDATE characters SET position_x='"<<x
<<"',position_y='"<<y
16278 << "',position_z='"<<z
<<"',orientation='"<<o
<<"',map='"<<mapid
16279 << "',zone='"<<zone
<<"',trans_x='0',trans_y='0',trans_z='0',"
16280 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
16281 sLog
.outDebug(ss
.str().c_str());
16282 CharacterDatabase
.Execute(ss
.str().c_str());
16285 void Player::SaveDataFieldToDB()
16287 std::ostringstream ss
;
16288 ss
<<"UPDATE characters SET data='";
16290 for(uint16 i
= 0; i
< m_valuesCount
; i
++ )
16292 ss
<< GetUInt32Value(i
) << " ";
16294 ss
<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
16296 CharacterDatabase
.Execute(ss
.str().c_str());
16299 bool Player::SaveValuesArrayInDB(Tokens
const& tokens
, uint64 guid
)
16301 std::ostringstream ss2
;
16302 ss2
<<"UPDATE characters SET data='";
16304 for (Tokens::const_iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
, ++i
)
16306 ss2
<<tokens
[i
]<<" ";
16308 ss2
<<"' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
16310 return CharacterDatabase
.Execute(ss2
.str().c_str());
16313 void Player::SetUInt32ValueInArray(Tokens
& tokens
,uint16 index
, uint32 value
)
16316 snprintf(buf
,11,"%u",value
);
16318 if(index
>= tokens
.size())
16321 tokens
[index
] = buf
;
16324 void Player::SetUInt32ValueInDB(uint16 index
, uint32 value
, uint64 guid
)
16327 if(!LoadValuesArrayFromDB(tokens
,guid
))
16330 if(index
>= tokens
.size())
16334 snprintf(buf
,11,"%u",value
);
16335 tokens
[index
] = buf
;
16337 SaveValuesArrayInDB(tokens
,guid
);
16340 void Player::SetFloatValueInDB(uint16 index
, float value
, uint64 guid
)
16343 memcpy(&temp
, &value
, sizeof(value
));
16344 Player::SetUInt32ValueInDB(index
, temp
, guid
);
16347 void Player::Customize(uint64 guid
, uint8 gender
, uint8 skin
, uint8 face
, uint8 hairStyle
, uint8 hairColor
, uint8 facialHair
)
16350 if(!LoadValuesArrayFromDB(tokens
, guid
))
16353 uint32 unit_bytes0
= GetUInt32ValueFromArray(tokens
, UNIT_FIELD_BYTES_0
);
16354 uint8 race
= unit_bytes0
& 0xFF;
16355 uint8 class_
= (unit_bytes0
>> 8) & 0xFF;
16357 PlayerInfo
const* info
= objmgr
.GetPlayerInfo(race
, class_
);
16361 unit_bytes0
&= ~(0xFF << 16);
16362 unit_bytes0
|= (gender
<< 16);
16363 SetUInt32ValueInArray(tokens
, UNIT_FIELD_BYTES_0
, unit_bytes0
);
16365 SetUInt32ValueInArray(tokens
, UNIT_FIELD_DISPLAYID
, gender
? info
->displayId_f
: info
->displayId_m
);
16366 SetUInt32ValueInArray(tokens
, UNIT_FIELD_NATIVEDISPLAYID
, gender
? info
->displayId_f
: info
->displayId_m
);
16368 SetUInt32ValueInArray(tokens
, PLAYER_BYTES
, (skin
| (face
<< 8) | (hairStyle
<< 16) | (hairColor
<< 24)));
16370 uint32 player_bytes2
= GetUInt32ValueFromArray(tokens
, PLAYER_BYTES_2
);
16371 player_bytes2
&= ~0xFF;
16372 player_bytes2
|= facialHair
;
16373 SetUInt32ValueInArray(tokens
, PLAYER_BYTES_2
, player_bytes2
);
16375 uint32 player_bytes3
= GetUInt32ValueFromArray(tokens
, PLAYER_BYTES_3
);
16376 player_bytes3
&= ~0xFF;
16377 player_bytes3
|= gender
;
16378 SetUInt32ValueInArray(tokens
, PLAYER_BYTES_3
, player_bytes3
);
16380 SaveValuesArrayInDB(tokens
, guid
);
16383 void Player::SendAttackSwingNotStanding()
16385 WorldPacket
data(SMSG_ATTACKSWING_NOTSTANDING
, 0);
16386 GetSession()->SendPacket( &data
);
16389 void Player::SendAttackSwingDeadTarget()
16391 WorldPacket
data(SMSG_ATTACKSWING_DEADTARGET
, 0);
16392 GetSession()->SendPacket( &data
);
16395 void Player::SendAttackSwingCantAttack()
16397 WorldPacket
data(SMSG_ATTACKSWING_CANT_ATTACK
, 0);
16398 GetSession()->SendPacket( &data
);
16401 void Player::SendAttackSwingCancelAttack()
16403 WorldPacket
data(SMSG_CANCEL_COMBAT
, 0);
16404 GetSession()->SendPacket( &data
);
16407 void Player::SendAttackSwingBadFacingAttack()
16409 WorldPacket
data(SMSG_ATTACKSWING_BADFACING
, 0);
16410 GetSession()->SendPacket( &data
);
16413 void Player::SendAutoRepeatCancel()
16415 WorldPacket
data(SMSG_CANCEL_AUTO_REPEAT
, GetPackGUID().size());
16416 data
.append(GetPackGUID()); // may be it's target guid
16417 GetSession()->SendPacket( &data
);
16420 void Player::PlaySound(uint32 Sound
, bool OnlySelf
)
16422 WorldPacket
data(SMSG_PLAY_SOUND
, 4);
16425 GetSession()->SendPacket( &data
);
16427 SendMessageToSet( &data
, true );
16430 void Player::SendExplorationExperience(uint32 Area
, uint32 Experience
)
16432 WorldPacket
data( SMSG_EXPLORATION_EXPERIENCE
, 8 );
16434 data
<< Experience
;
16435 GetSession()->SendPacket(&data
);
16438 void Player::SendDungeonDifficulty(bool IsInGroup
)
16440 uint8 val
= 0x00000001;
16441 WorldPacket
data(MSG_SET_DUNGEON_DIFFICULTY
, 12);
16442 data
<< (uint32
)GetDifficulty();
16443 data
<< uint32(val
);
16444 data
<< uint32(IsInGroup
);
16445 GetSession()->SendPacket(&data
);
16448 void Player::SendResetFailedNotify(uint32 mapid
)
16450 WorldPacket
data(SMSG_RESET_FAILED_NOTIFY
, 4);
16451 data
<< uint32(mapid
);
16452 GetSession()->SendPacket(&data
);
16455 /// Reset all solo instances and optionally send a message on success for each
16456 void Player::ResetInstances(uint8 method
)
16458 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
16460 // we assume that when the difficulty changes, all instances that can be reset will be
16461 uint8 dif
= GetDifficulty();
16463 for (BoundInstancesMap::iterator itr
= m_boundInstances
[dif
].begin(); itr
!= m_boundInstances
[dif
].end();)
16465 InstanceSave
*p
= itr
->second
.save
;
16466 const MapEntry
*entry
= sMapStore
.LookupEntry(itr
->first
);
16467 if(!entry
|| !p
->CanReset())
16473 if(method
== INSTANCE_RESET_ALL
)
16475 // the "reset all instances" method can only reset normal maps
16476 if(dif
== DIFFICULTY_HEROIC
|| entry
->map_type
== MAP_RAID
)
16483 // if the map is loaded, reset it
16484 Map
*map
= MapManager::Instance().FindMap(p
->GetMapId(), p
->GetInstanceId());
16485 if(map
&& map
->IsDungeon())
16486 ((InstanceMap
*)map
)->Reset(method
);
16488 // since this is a solo instance there should not be any players inside
16489 if(method
== INSTANCE_RESET_ALL
|| method
== INSTANCE_RESET_CHANGE_DIFFICULTY
)
16490 SendResetInstanceSuccess(p
->GetMapId());
16493 m_boundInstances
[dif
].erase(itr
++);
16495 // the following should remove the instance save from the manager and delete it as well
16496 p
->RemovePlayer(this);
16500 void Player::SendResetInstanceSuccess(uint32 MapId
)
16502 WorldPacket
data(SMSG_INSTANCE_RESET
, 4);
16504 GetSession()->SendPacket(&data
);
16507 void Player::SendResetInstanceFailed(uint32 reason
, uint32 MapId
)
16509 // TODO: find what other fail reasons there are besides players in the instance
16510 WorldPacket
data(SMSG_INSTANCE_RESET_FAILED
, 4);
16513 GetSession()->SendPacket(&data
);
16516 /*********************************************************/
16517 /*** Update timers ***/
16518 /*********************************************************/
16520 ///checks the 15 afk reports per 5 minutes limit
16521 void Player::UpdateAfkReport(time_t currTime
)
16523 if(m_bgAfkReportedTimer
<= currTime
)
16525 m_bgAfkReportedCount
= 0;
16526 m_bgAfkReportedTimer
= currTime
+5*MINUTE
;
16530 void Player::UpdateContestedPvP(uint32 diff
)
16532 if(!m_contestedPvPTimer
||isInCombat())
16534 if(m_contestedPvPTimer
<= diff
)
16536 ResetContestedPvP();
16539 m_contestedPvPTimer
-= diff
;
16542 void Player::UpdatePvPFlag(time_t currTime
)
16546 if(pvpInfo
.endTimer
== 0 || currTime
< (pvpInfo
.endTimer
+ 300))
16552 void Player::UpdateDuelFlag(time_t currTime
)
16554 if(!duel
|| duel
->startTimer
== 0 ||currTime
< duel
->startTimer
+ 3)
16557 SetUInt32Value(PLAYER_DUEL_TEAM
, 1);
16558 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 2);
16560 duel
->startTimer
= 0;
16561 duel
->startTime
= currTime
;
16562 duel
->opponent
->duel
->startTimer
= 0;
16563 duel
->opponent
->duel
->startTime
= currTime
;
16566 void Player::RemovePet(Pet
* pet
, PetSaveMode mode
, bool returnreagent
)
16571 if(returnreagent
&& (pet
|| m_temporaryUnsummonedPetNumber
))
16573 //returning of reagents only for players, so best done here
16574 uint32 spellId
= pet
? pet
->GetUInt32Value(UNIT_CREATED_BY_SPELL
) : m_oldpetspell
;
16575 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellId
);
16579 for(uint32 i
= 0; i
< 7; ++i
)
16581 if(spellInfo
->Reagent
[i
] > 0)
16583 ItemPosCountVec dest
; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16584 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, spellInfo
->Reagent
[i
], spellInfo
->ReagentCount
[i
] );
16585 if( msg
== EQUIP_ERR_OK
)
16587 Item
* item
= StoreNewItem( dest
, spellInfo
->Reagent
[i
], true);
16589 SendNewItem(item
,spellInfo
->ReagentCount
[i
],true,false);
16594 m_temporaryUnsummonedPetNumber
= 0;
16597 if(!pet
|| pet
->GetOwnerGUID()!=GetGUID())
16600 // only if current pet in slot
16601 switch(pet
->getPetType())
16607 m_guardianPets
.erase(pet
->GetGUID());
16610 if(GetPetGUID() == pet
->GetGUID())
16619 switch(pet
->GetEntry())
16621 //warlock pets except imp are removed(?) when logging out
16626 mode
= PET_SAVE_NOT_IN_SLOT
;
16631 pet
->SavePetToDB(mode
);
16633 pet
->CleanupsBeforeDelete();
16634 pet
->AddObjectToRemoveList();
16635 pet
->m_removed
= true;
16637 if(pet
->isControlled())
16639 WorldPacket
data(SMSG_PET_SPELLS
, 8);
16642 GetSession()->SendPacket(&data
);
16645 SetGroupUpdateFlag(GROUP_UPDATE_PET
);
16649 void Player::RemoveMiniPet()
16651 if(Pet
* pet
= GetMiniPet())
16653 pet
->Remove(PET_SAVE_AS_DELETED
);
16658 Pet
* Player::GetMiniPet()
16662 return ObjectAccessor::GetPet(m_miniPet
);
16665 void Player::RemoveGuardians()
16667 while(!m_guardianPets
.empty())
16669 uint64 guid
= *m_guardianPets
.begin();
16670 if(Pet
* pet
= ObjectAccessor::GetPet(guid
))
16671 pet
->Remove(PET_SAVE_AS_DELETED
);
16673 m_guardianPets
.erase(guid
);
16677 bool Player::HasGuardianWithEntry(uint32 entry
)
16679 // pet guid middle part is entry (and creature also)
16680 // and in guardian list must be guardians with same entry _always_
16681 for(GuardianPetList::const_iterator itr
= m_guardianPets
.begin(); itr
!= m_guardianPets
.end(); ++itr
)
16682 if(GUID_ENPART(*itr
)==entry
)
16688 void Player::Uncharm()
16690 Unit
* charm
= GetCharm();
16694 charm
->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM
);
16695 charm
->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS
);
16698 void Player::BuildPlayerChat(WorldPacket
*data
, uint8 msgtype
, const std::string
& text
, uint32 language
) const
16700 *data
<< (uint8
)msgtype
;
16701 *data
<< (uint32
)language
;
16702 *data
<< (uint64
)GetGUID();
16703 *data
<< (uint32
)language
; //language 2.1.0 ?
16704 *data
<< (uint64
)GetGUID();
16705 *data
<< (uint32
)(text
.length()+1);
16707 *data
<< (uint8
)chatTag();
16710 void Player::Say(const std::string
& text
, const uint32 language
)
16712 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16713 BuildPlayerChat(&data
, CHAT_MSG_SAY
, text
, language
);
16714 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_SAY
),true);
16717 void Player::Yell(const std::string
& text
, const uint32 language
)
16719 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16720 BuildPlayerChat(&data
, CHAT_MSG_YELL
, text
, language
);
16721 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_YELL
),true);
16724 void Player::TextEmote(const std::string
& text
)
16726 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16727 BuildPlayerChat(&data
, CHAT_MSG_EMOTE
, text
, LANG_UNIVERSAL
);
16728 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE
),true, !sWorld
.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT
) );
16731 void Player::Whisper(const std::string
& text
, uint32 language
,uint64 receiver
)
16733 if (language
!= LANG_ADDON
) // if not addon data
16734 language
= LANG_UNIVERSAL
; // whispers should always be readable
16736 Player
*rPlayer
= objmgr
.GetPlayer(receiver
);
16738 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16739 if(!rPlayer
->isDND() || isGameMaster())
16741 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16742 BuildPlayerChat(&data
, CHAT_MSG_WHISPER
, text
, language
);
16743 rPlayer
->GetSession()->SendPacket(&data
);
16745 data
.Initialize(SMSG_MESSAGECHAT
, 200);
16746 rPlayer
->BuildPlayerChat(&data
, CHAT_MSG_REPLY
, text
, language
);
16747 GetSession()->SendPacket(&data
);
16751 // announce to player that player he is whispering to is dnd and cannot receive his message
16752 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND
, rPlayer
->GetName(), rPlayer
->dndMsg
.c_str());
16755 if(!isAcceptWhispers())
16757 SetAcceptWhispers(true);
16758 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON
);
16761 // announce to player that player he is whispering to is afk
16762 if(rPlayer
->isAFK())
16763 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK
, rPlayer
->GetName(), rPlayer
->afkMsg
.c_str());
16765 // if player whisper someone, auto turn of dnd to be able to receive an answer
16766 if(isDND() && !rPlayer
->isGameMaster())
16770 void Player::PetSpellInitialize()
16772 Pet
* pet
= GetPet();
16777 sLog
.outDebug("Pet Spells Groups");
16779 CharmInfo
*charmInfo
= pet
->GetCharmInfo();
16781 WorldPacket
data(SMSG_PET_SPELLS
, 8+4+4+4+10*4);
16782 data
<< uint64(pet
->GetGUID());
16783 data
<< uint32(pet
->GetCreatureInfo()->family
); // creature family (required for pet talents)
16785 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState()) << uint16(0);
16788 for(uint32 i
= 0; i
< 10; i
++)
16790 data
<< uint32(charmInfo
->GetActionBarEntry(i
)->Raw
);
16793 size_t spellsCountPos
= data
.wpos();
16797 data
<< uint8(addlist
); // placeholder
16799 if(pet
->isControlled() && ((pet
->getPetType() == HUNTER_PET
) || ((pet
->GetCreatureInfo()->type
== CREATURE_TYPE_DEMON
) && (getClass() == CLASS_WARLOCK
))))
16802 for (PetSpellMap::iterator itr
= pet
->m_spells
.begin(); itr
!= pet
->m_spells
.end(); ++itr
)
16804 if(itr
->second
->state
== PETSPELL_REMOVED
)
16807 data
<< uint16(itr
->first
);
16808 data
<< uint16(itr
->second
->active
); // pet spell active state isn't boolean
16813 data
.put
<uint8
>(spellsCountPos
, addlist
);
16815 uint8 cooldownsCount
= pet
->m_CreatureSpellCooldowns
.size() + pet
->m_CreatureCategoryCooldowns
.size();
16816 data
<< uint8(cooldownsCount
);
16818 time_t curTime
= time(NULL
);
16820 for(CreatureSpellCooldowns::const_iterator itr
= pet
->m_CreatureSpellCooldowns
.begin(); itr
!= pet
->m_CreatureSpellCooldowns
.end(); ++itr
)
16822 time_t cooldown
= 0;
16824 if(itr
->second
> curTime
)
16825 cooldown
= (itr
->second
- curTime
) * IN_MILISECONDS
;
16827 data
<< uint16(itr
->first
); // spellid
16828 data
<< uint16(0); // spell category?
16829 data
<< uint32(itr
->second
); // cooldown
16830 data
<< uint32(0); // category cooldown
16833 for(CreatureSpellCooldowns::const_iterator itr
= pet
->m_CreatureCategoryCooldowns
.begin(); itr
!= pet
->m_CreatureCategoryCooldowns
.end(); ++itr
)
16835 time_t cooldown
= 0;
16837 if(itr
->second
> curTime
)
16838 cooldown
= (itr
->second
- curTime
) * IN_MILISECONDS
;
16840 data
<< uint16(itr
->first
); // spellid
16841 data
<< uint16(0); // spell category?
16842 data
<< uint32(0); // cooldown
16843 data
<< uint32(itr
->second
); // category cooldown
16846 GetSession()->SendPacket(&data
);
16849 void Player::PossessSpellInitialize()
16851 Unit
* charm
= GetCharm();
16856 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
16860 sLog
.outError("Player::PossessSpellInitialize(): charm ("I64FMTD
") has no charminfo!", charm
->GetGUID());
16865 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);// first line + actionbar + spellcount + spells + last adds
16868 data
<< uint64(charm
->GetGUID());
16869 data
<< uint32(0x00000000);
16871 data
<< uint8(0) << uint8(0) << uint16(0);
16873 for(uint32 i
= 0; i
< 10; i
++) //40
16875 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
16878 data
<< uint8(addlist
); //1
16881 data
<< uint8(count
); // cooldowns count
16883 GetSession()->SendPacket(&data
);
16886 void Player::CharmSpellInitialize()
16888 Unit
* charm
= GetCharm();
16893 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
16896 sLog
.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD
") has no charminfo!", charm
->GetGUID());
16902 if(charm
->GetTypeId() != TYPEID_PLAYER
)
16904 CreatureInfo
const *cinfo
= ((Creature
*)charm
)->GetCreatureInfo();
16906 if(cinfo
&& cinfo
->type
== CREATURE_TYPE_DEMON
&& getClass() == CLASS_WARLOCK
)
16908 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
16910 if(charmInfo
->GetCharmSpell(i
)->spellId
)
16916 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);// first line + actionbar + spellcount + spells + last adds
16918 data
<< uint64(charm
->GetGUID());
16919 data
<< uint32(0x00000000);
16921 if(charm
->GetTypeId() != TYPEID_PLAYER
)
16922 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState());
16924 data
<< uint8(0) << uint8(0);
16927 for(uint32 i
= 0; i
< 10; i
++) //40
16929 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
16932 data
<< uint8(addlist
); //1
16936 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
16938 CharmSpellEntry
*cspell
= charmInfo
->GetCharmSpell(i
);
16939 if(cspell
->spellId
)
16941 data
<< uint16(cspell
->spellId
);
16942 data
<< uint16(cspell
->active
);
16948 data
<< uint8(count
); // cooldowns count
16950 GetSession()->SendPacket(&data
);
16953 bool Player::IsAffectedBySpellmod(SpellEntry
const *spellInfo
, SpellModifier
*mod
, Spell
const* spell
)
16955 if (!mod
|| !spellInfo
)
16958 if(mod
->charges
== -1 && mod
->lastAffected
) // marked as expired but locked until spell casting finish
16960 // prevent apply to any spell except spell that trigger expire
16963 if(mod
->lastAffected
!= spell
)
16966 else if(mod
->lastAffected
!= FindCurrentSpellBySpellId(spellInfo
->Id
))
16970 return spellmgr
.IsAffectedByMod(spellInfo
, mod
);
16973 void Player::AddSpellMod(SpellModifier
* mod
, bool apply
)
16975 uint16 Opcode
= (mod
->type
== SPELLMOD_FLAT
) ? SMSG_SET_FLAT_SPELL_MODIFIER
: SMSG_SET_PCT_SPELL_MODIFIER
;
16977 for(int eff
=0;eff
<96;++eff
)
16981 if (eff
<64) _mask
= uint64(1) << (eff
- 0);
16982 else _mask2
= uint64(1) << (eff
-64);
16983 if ( mod
->mask
& _mask
|| mod
->mask2
& _mask2
)
16986 for (SpellModList::iterator itr
= m_spellMods
[mod
->op
].begin(); itr
!= m_spellMods
[mod
->op
].end(); ++itr
)
16988 if ((*itr
)->type
== mod
->type
&& ((*itr
)->mask
& _mask
|| (*itr
)->mask2
& _mask2
))
16989 val
+= (*itr
)->value
;
16991 val
+= apply
? mod
->value
: -(mod
->value
);
16992 WorldPacket
data(Opcode
, (1+1+4));
16993 data
<< uint8(eff
);
16994 data
<< uint8(mod
->op
);
16995 data
<< int32(val
);
16996 SendDirectMessage(&data
);
17001 m_spellMods
[mod
->op
].push_back(mod
);
17004 if (mod
->charges
== -1)
17005 --m_SpellModRemoveCount
;
17006 m_spellMods
[mod
->op
].remove(mod
);
17011 void Player::RemoveSpellMods(Spell
const* spell
)
17013 if(!spell
|| (m_SpellModRemoveCount
== 0))
17016 for(int i
=0;i
<MAX_SPELLMOD
;++i
)
17018 for (SpellModList::iterator itr
= m_spellMods
[i
].begin(); itr
!= m_spellMods
[i
].end();)
17020 SpellModifier
*mod
= *itr
;
17023 if (mod
&& mod
->charges
== -1 && (mod
->lastAffected
== spell
|| mod
->lastAffected
==NULL
))
17025 RemoveAurasDueToSpell(mod
->spellId
);
17026 if (m_spellMods
[i
].empty())
17029 itr
= m_spellMods
[i
].begin();
17035 // send Proficiency
17036 void Player::SendProficiency(uint8 pr1
, uint32 pr2
)
17038 WorldPacket
data(SMSG_SET_PROFICIENCY
, 8);
17039 data
<< pr1
<< pr2
;
17040 GetSession()->SendPacket (&data
);
17043 void Player::RemovePetitionsAndSigns(uint64 guid
, uint32 type
)
17045 QueryResult
*result
= NULL
;
17047 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
17049 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
17052 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.
17053 { // and SendPetitionQueryOpcode reads data from the DB
17054 Field
*fields
= result
->Fetch();
17055 uint64 ownerguid
= MAKE_NEW_GUID(fields
[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
17056 uint64 petitionguid
= MAKE_NEW_GUID(fields
[1].GetUInt32(), 0, HIGHGUID_ITEM
);
17058 // send update if charter owner in game
17059 Player
* owner
= objmgr
.GetPlayer(ownerguid
);
17061 owner
->GetSession()->SendPetitionQueryOpcode(petitionguid
);
17063 } while ( result
->NextRow() );
17068 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
17070 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
17073 CharacterDatabase
.BeginTransaction();
17076 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid
));
17077 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid
));
17081 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
17082 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
17084 CharacterDatabase
.CommitTransaction();
17087 void Player::LeaveAllArenaTeams(uint64 guid
)
17089 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
));
17095 Field
*fields
= result
->Fetch();
17096 uint32 at_id
= fields
[0].GetUInt32();
17099 ArenaTeam
* at
= objmgr
.GetArenaTeamById(at_id
);
17101 at
->DelMember(guid
);
17103 } while (result
->NextRow());
17108 void Player::SetRestBonus (float rest_bonus_new
)
17110 // Prevent resting on max level
17111 if(getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
17112 rest_bonus_new
= 0;
17114 if(rest_bonus_new
< 0)
17115 rest_bonus_new
= 0;
17117 float rest_bonus_max
= (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)*1.5/2;
17119 if(rest_bonus_new
> rest_bonus_max
)
17120 m_rest_bonus
= rest_bonus_max
;
17122 m_rest_bonus
= rest_bonus_new
;
17124 // update data for client
17125 if(m_rest_bonus
>10)
17126 SetByteValue(PLAYER_BYTES_2
, 3, 0x01); // Set Reststate = Rested
17127 else if(m_rest_bonus
<=1)
17128 SetByteValue(PLAYER_BYTES_2
, 3, 0x02); // Set Reststate = Normal
17131 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE
, uint32(m_rest_bonus
));
17134 void Player::HandleStealthedUnitsDetection()
17136 std::list
<Unit
*> stealthedUnits
;
17138 CellPair
p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
17140 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
17141 cell
.SetNoCreate();
17143 MaNGOS::AnyStealthedCheck u_check
;
17144 MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
> searcher(this,stealthedUnits
, u_check
);
17146 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, WorldTypeMapContainer
> world_unit_searcher(searcher
);
17147 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, GridTypeMapContainer
> grid_unit_searcher(searcher
);
17149 CellLock
<GridReadGuard
> cell_lock(cell
, p
);
17150 cell_lock
->Visit(cell_lock
, world_unit_searcher
, *GetMap());
17151 cell_lock
->Visit(cell_lock
, grid_unit_searcher
, *GetMap());
17153 for (std::list
<Unit
*>::iterator i
= stealthedUnits
.begin(); i
!= stealthedUnits
.end();)
17157 i
= stealthedUnits
.erase(i
);
17161 if ((*i
)->isVisibleForOrDetect(this,true))
17164 (*i
)->SendUpdateToPlayer(this);
17165 m_clientGUIDs
.insert((*i
)->GetGUID());
17167 #ifdef MANGOS_DEBUG
17168 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17169 sLog
.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i
)->GetGUIDLow(),(*i
)->GetTypeId(),GetGUIDLow(),GetDistance(*i
));
17172 // target aura duration for caster show only if target exist at caster client
17173 // send data at target visibility change (adding to client)
17174 if((*i
)!=this && (*i
)->isType(TYPEMASK_UNIT
))
17175 SendAurasForTarget(*i
);
17177 i
= stealthedUnits
.erase(i
);
17185 bool Player::ActivateTaxiPathTo(std::vector
<uint32
> const& nodes
, uint32 mount_id
, Creature
* npc
)
17187 if(nodes
.size() < 2)
17190 // not let cheating with start flight mounted
17193 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17194 data
<< uint32(ERR_TAXIPLAYERALREADYMOUNTED
);
17195 GetSession()->SendPacket(&data
);
17199 if( m_ShapeShiftFormSpellId
&& m_form
!= FORM_BATTLESTANCE
&& m_form
!= FORM_BERSERKERSTANCE
&& m_form
!= FORM_DEFENSIVESTANCE
&& m_form
!= FORM_SHADOW
)
17201 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17202 data
<< uint32(ERR_TAXIPLAYERSHAPESHIFTED
);
17203 GetSession()->SendPacket(&data
);
17207 // 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
17208 if(GetSession()->isLogingOut() ||
17209 (!m_currentSpells
[CURRENT_GENERIC_SPELL
] ||
17210 m_currentSpells
[CURRENT_GENERIC_SPELL
]->m_spellInfo
->Effect
[0] != SPELL_EFFECT_SEND_TAXI
)&&
17211 IsNonMeleeSpellCasted(false) ||
17214 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17215 data
<< uint32(ERR_TAXIPLAYERBUSY
);
17216 GetSession()->SendPacket(&data
);
17220 if(HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_DISABLE_MOVE
))
17223 uint32 sourcenode
= nodes
[0];
17225 // starting node too far away (cheat?)
17226 TaxiNodesEntry
const* node
= sTaxiNodesStore
.LookupEntry(sourcenode
);
17227 if( !node
|| node
->map_id
!= GetMapId() ||
17228 (node
->x
- GetPositionX())*(node
->x
- GetPositionX())+
17229 (node
->y
- GetPositionY())*(node
->y
- GetPositionY())+
17230 (node
->z
- GetPositionZ())*(node
->z
- GetPositionZ()) >
17231 (2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
) )
17233 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17234 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
17235 GetSession()->SendPacket(&data
);
17239 // Prepare to flight start now
17241 // stop combat at start taxi flight if any
17244 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
17247 // clean not finished taxi path if any
17248 m_taxi
.ClearTaxiDestinations();
17250 // 0 element current node
17251 m_taxi
.AddTaxiDestination(sourcenode
);
17253 // fill destinations path tail
17254 uint32 sourcepath
= 0;
17255 uint32 totalcost
= 0;
17257 uint32 prevnode
= sourcenode
;
17258 uint32 lastnode
= 0;
17260 for(uint32 i
= 1; i
< nodes
.size(); ++i
)
17264 lastnode
= nodes
[i
];
17265 objmgr
.GetTaxiPath(prevnode
, lastnode
, path
, cost
);
17269 m_taxi
.ClearTaxiDestinations();
17275 if(prevnode
== sourcenode
)
17278 m_taxi
.AddTaxiDestination(lastnode
);
17280 prevnode
= lastnode
;
17283 if(!mount_id
) // if not provide then attempt use default.
17284 mount_id
= objmgr
.GetTaxiMount(sourcenode
, GetTeam());
17286 if (mount_id
== 0 || sourcepath
== 0)
17288 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17289 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
17290 GetSession()->SendPacket(&data
);
17291 m_taxi
.ClearTaxiDestinations();
17295 uint32 money
= GetMoney();
17299 totalcost
= (uint32
)ceil(totalcost
*GetReputationPriceDiscount(npc
));
17302 if(money
< totalcost
)
17304 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17305 data
<< uint32(ERR_TAXINOTENOUGHMONEY
);
17306 GetSession()->SendPacket(&data
);
17307 m_taxi
.ClearTaxiDestinations();
17311 //Checks and preparations done, DO FLIGHT
17312 ModifyMoney(-(int32
)totalcost
);
17313 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING
, totalcost
);
17315 // prevent stealth flight
17316 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH
);
17318 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17319 data
<< uint32(ERR_TAXIOK
);
17320 GetSession()->SendPacket(&data
);
17322 sLog
.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
17324 GetSession()->SendDoFlight(mount_id
, sourcepath
);
17329 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask
, uint32 unTimeMs
)
17331 // last check 2.0.10
17332 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+m_spells
.size()*8);
17334 data
<< uint8(0x0); // flags (0x1, 0x2)
17335 time_t curTime
= time(NULL
);
17336 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
17338 if (itr
->second
->state
== PLAYERSPELL_REMOVED
)
17340 uint32 unSpellId
= itr
->first
;
17341 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(unSpellId
);
17348 // Not send cooldown for this spells
17349 if (spellInfo
->Attributes
& SPELL_ATTR_DISABLED_WHILE_ACTIVE
)
17352 if((idSchoolMask
& GetSpellSchoolMask(spellInfo
)) && GetSpellCooldownDelay(unSpellId
) < unTimeMs
)
17355 data
<< unTimeMs
; // in m.secs
17356 AddSpellCooldown(unSpellId
, 0, curTime
+ unTimeMs
/IN_MILISECONDS
);
17359 GetSession()->SendPacket(&data
);
17362 void Player::InitDataForForm(bool reapplyMods
)
17364 SpellShapeshiftEntry
const* ssEntry
= sSpellShapeshiftStore
.LookupEntry(m_form
);
17365 if(ssEntry
&& ssEntry
->attackSpeed
)
17367 SetAttackTime(BASE_ATTACK
,ssEntry
->attackSpeed
);
17368 SetAttackTime(OFF_ATTACK
,ssEntry
->attackSpeed
);
17369 SetAttackTime(RANGED_ATTACK
, BASE_ATTACK_TIME
);
17372 SetRegularAttackTime();
17378 if(getPowerType()!=POWER_ENERGY
)
17379 setPowerType(POWER_ENERGY
);
17383 case FORM_DIREBEAR
:
17385 if(getPowerType()!=POWER_RAGE
)
17386 setPowerType(POWER_RAGE
);
17389 default: // 0, for example
17391 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(getClass());
17392 if(cEntry
&& cEntry
->powerType
< MAX_POWERS
&& uint32(getPowerType()) != cEntry
->powerType
)
17393 setPowerType(Powers(cEntry
->powerType
));
17398 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
17400 UpdateEquipSpellsAtFormChange();
17402 UpdateAttackPowerAndDamage();
17403 UpdateAttackPowerAndDamage(true);
17406 // Return true is the bought item has a max count to force refresh of window by caller
17407 bool Player::BuyItemFromVendor(uint64 vendorguid
, uint32 item
, uint8 count
, uint64 bagguid
, uint8 slot
)
17409 // cheating attempt
17410 if(count
< 1) count
= 1;
17415 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
17418 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, NULL
, item
, 0);
17422 Creature
*pCreature
= ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid
,UNIT_NPC_FLAG_VENDOR
);
17425 sLog
.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid
)) );
17426 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR
, NULL
, item
, 0);
17430 VendorItemData
const* vItems
= pCreature
->GetVendorItems();
17431 if(!vItems
|| vItems
->Empty())
17433 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
17437 size_t vendor_slot
= vItems
->FindItemSlot(item
);
17438 if(vendor_slot
>= vItems
->GetItemCount())
17440 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
17444 VendorItem
const* crItem
= vItems
->m_items
[vendor_slot
];
17446 // check current item amount if it limited
17447 if( crItem
->maxcount
!= 0 )
17449 if(pCreature
->GetVendorItemCurrentCount(crItem
) < pProto
->BuyCount
* count
)
17451 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD
, pCreature
, item
, 0);
17456 if( uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
17458 SendBuyError( BUY_ERR_REPUTATION_REQUIRE
, pCreature
, item
, 0);
17462 if(crItem
->ExtendedCost
)
17464 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
17467 sLog
.outError("Item %u have wrong ExtendedCost field value %u", pProto
->ItemId
, crItem
->ExtendedCost
);
17471 // honor points price
17472 if(GetHonorPoints() < (iece
->reqhonorpoints
* count
))
17474 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS
, NULL
, NULL
);
17478 // arena points price
17479 if(GetArenaPoints() < (iece
->reqarenapoints
* count
))
17481 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS
, NULL
, NULL
);
17486 for (uint8 i
= 0; i
< 5; ++i
)
17488 if(iece
->reqitem
[i
] && !HasItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
)))
17490 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS
, NULL
, NULL
);
17495 // check for personal arena rating requirement
17496 if( GetMaxPersonalArenaRatingRequirement() < iece
->reqpersonalarenarating
)
17498 // probably not the proper equip err
17499 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK
,NULL
,NULL
);
17504 uint32 price
= pProto
->BuyPrice
* count
;
17506 // reputation discount
17507 price
= uint32(floor(price
* GetReputationPriceDiscount(pCreature
)));
17509 if( GetMoney() < price
)
17511 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, pCreature
, item
, 0);
17515 uint8 bag
= 0; // init for case invalid bagGUID
17517 if (bagguid
!= NULL_BAG
&& slot
!= NULL_SLOT
)
17520 if( bagguid
== GetGUID() )
17522 bag
= INVENTORY_SLOT_BAG_0
;
17526 for (int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
;i
++)
17528 pBag
= (Bag
*)GetItemByPos(INVENTORY_SLOT_BAG_0
,i
);
17531 if( bagguid
== pBag
->GetGUID() )
17541 if( IsInventoryPos( bag
, slot
) || (bagguid
== NULL_BAG
&& slot
== NULL_SLOT
) )
17543 ItemPosCountVec dest
;
17544 uint8 msg
= CanStoreNewItem( bag
, slot
, dest
, item
, pProto
->BuyCount
* count
);
17545 if( msg
!= EQUIP_ERR_OK
)
17547 SendEquipError( msg
, NULL
, NULL
);
17551 ModifyMoney( -(int32
)price
);
17552 if(crItem
->ExtendedCost
) // case for new honor system
17554 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
17555 if(iece
->reqhonorpoints
)
17556 ModifyHonorPoints( - int32(iece
->reqhonorpoints
* count
));
17557 if(iece
->reqarenapoints
)
17558 ModifyArenaPoints( - int32(iece
->reqarenapoints
* count
));
17559 for (uint8 i
= 0; i
< 5; ++i
)
17561 if(iece
->reqitem
[i
])
17562 DestroyItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
), true);
17566 if(Item
*it
= StoreNewItem( dest
, item
, true ))
17568 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
17570 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
17571 data
<< pCreature
->GetGUID();
17572 data
<< (uint32
)(vendor_slot
+1); // numbered from 1 at client
17573 data
<< (uint32
)(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
17574 data
<< (uint32
)count
;
17575 GetSession()->SendPacket(&data
);
17577 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
17580 else if( IsEquipmentPos( bag
, slot
) )
17582 if(pProto
->BuyCount
* count
!= 1)
17584 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
, NULL
, NULL
);
17589 uint8 msg
= CanEquipNewItem( slot
, dest
, item
, false );
17590 if( msg
!= EQUIP_ERR_OK
)
17592 SendEquipError( msg
, NULL
, NULL
);
17596 ModifyMoney( -(int32
)price
);
17597 if(crItem
->ExtendedCost
) // case for new honor system
17599 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
17600 if(iece
->reqhonorpoints
)
17601 ModifyHonorPoints( - int32(iece
->reqhonorpoints
));
17602 if(iece
->reqarenapoints
)
17603 ModifyArenaPoints( - int32(iece
->reqarenapoints
));
17604 for (uint8 i
= 0; i
< 5; ++i
)
17606 if(iece
->reqitem
[i
])
17607 DestroyItemCount(iece
->reqitem
[i
], iece
->reqitemcount
[i
], true);
17611 if(Item
*it
= EquipNewItem( dest
, item
, true ))
17613 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
17615 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
17616 data
<< pCreature
->GetGUID();
17617 data
<< (uint32
)(vendor_slot
+1); // numbered from 1 at client
17618 data
<< (uint32
)(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
17619 data
<< (uint32
)count
;
17620 GetSession()->SendPacket(&data
);
17622 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
17624 AutoUnequipOffhandIfNeed();
17629 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
, NULL
, NULL
);
17633 return crItem
->maxcount
!=0;
17636 uint32
Player::GetMaxPersonalArenaRatingRequirement()
17638 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17639 // the personal rating of the arena team must match the required limit as well
17640 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17641 uint32 max_personal_rating
= 0;
17642 for(int i
= 0; i
< MAX_ARENA_SLOT
; ++i
)
17644 if(ArenaTeam
* at
= objmgr
.GetArenaTeamById(GetArenaTeamId(i
)))
17646 uint32 p_rating
= GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ (i
* 6) + 5);
17647 uint32 t_rating
= at
->GetRating();
17648 p_rating
= p_rating
<t_rating
? p_rating
: t_rating
;
17649 if(max_personal_rating
< p_rating
)
17650 max_personal_rating
= p_rating
;
17653 return max_personal_rating
;
17656 void Player::UpdateHomebindTime(uint32 time
)
17658 // GMs never get homebind timer online
17659 if (m_InstanceValid
|| isGameMaster())
17661 if(m_HomebindTimer
) // instance valid, but timer not reset
17664 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
17667 GetSession()->SendPacket(&data
);
17669 // instance is valid, reset homebind timer
17670 m_HomebindTimer
= 0;
17672 else if (m_HomebindTimer
> 0)
17674 if (time
>= m_HomebindTimer
)
17676 // teleport to homebind location
17677 TeleportTo(m_homebindMapId
, m_homebindX
, m_homebindY
, m_homebindZ
, GetOrientation());
17680 m_HomebindTimer
-= time
;
17684 // instance is invalid, start homebind timer
17685 m_HomebindTimer
= 60000;
17686 // send message to player
17687 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
17688 data
<< m_HomebindTimer
;
17690 GetSession()->SendPacket(&data
);
17691 sLog
.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17695 void Player::UpdatePvP(bool state
, bool ovrride
)
17697 if(!state
|| ovrride
)
17700 if(Pet
* pet
= GetPet())
17701 pet
->SetPvP(state
);
17702 if(Unit
* charmed
= GetCharm())
17703 charmed
->SetPvP(state
);
17705 pvpInfo
.endTimer
= 0;
17709 if(pvpInfo
.endTimer
!= 0)
17710 pvpInfo
.endTimer
= time(NULL
);
17715 if(Pet
* pet
= GetPet())
17716 pet
->SetPvP(state
);
17717 if(Unit
* charmed
= GetCharm())
17718 charmed
->SetPvP(state
);
17723 void Player::AddSpellAndCategoryCooldowns(SpellEntry
const* spellInfo
, uint32 itemId
, Spell
* spell
, bool infinityCooldown
)
17725 // init cooldown values
17730 // some special item spells without correct cooldown in SpellInfo
17731 // cooldown information stored in item prototype
17732 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
17736 if(ItemPrototype
const* proto
= ObjectMgr::GetItemPrototype(itemId
))
17738 for(int idx
= 0; idx
< 5; ++idx
)
17740 if(proto
->Spells
[idx
].SpellId
== spellInfo
->Id
)
17742 cat
= proto
->Spells
[idx
].SpellCategory
;
17743 rec
= proto
->Spells
[idx
].SpellCooldown
;
17744 catrec
= proto
->Spells
[idx
].SpellCategoryCooldown
;
17751 // if no cooldown found above then base at DBC data
17752 if(rec
< 0 && catrec
< 0)
17754 cat
= spellInfo
->Category
;
17755 rec
= spellInfo
->RecoveryTime
;
17756 catrec
= spellInfo
->CategoryRecoveryTime
;
17759 time_t curTime
= time(NULL
);
17764 // overwrite time for selected category
17765 if(infinityCooldown
)
17767 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
17768 // but not allow ignore until reset or re-login
17769 catrecTime
= catrec
> 0 ? curTime
+MONTH
: 0;
17770 recTime
= rec
> 0 ? curTime
+MONTH
: catrecTime
;
17774 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
17775 // prevent 0 cooldowns set by another way
17776 if (rec
<= 0 && catrec
<= 0 && (cat
== 76 || IsAutoRepeatRangedSpell(spellInfo
) && spellInfo
->Id
!= SPELL_ID_AUTOSHOT
))
17777 rec
= GetAttackTime(RANGED_ATTACK
);
17779 // Now we have cooldown data (if found any), time to apply mods
17781 ApplySpellMod(spellInfo
->Id
, SPELLMOD_COOLDOWN
, rec
, spell
);
17784 ApplySpellMod(spellInfo
->Id
, SPELLMOD_COOLDOWN
, catrec
, spell
);
17786 // replace negative cooldowns by 0
17787 if (rec
< 0) rec
= 0;
17788 if (catrec
< 0) catrec
= 0;
17790 // no cooldown after applying spell mods
17791 if( rec
== 0 && catrec
== 0)
17794 catrecTime
= catrec
? curTime
+catrec
/IN_MILISECONDS
: 0;
17795 recTime
= rec
? curTime
+rec
/IN_MILISECONDS
: catrecTime
;
17798 // self spell cooldown
17800 AddSpellCooldown(spellInfo
->Id
, itemId
, recTime
);
17803 if (cat
&& catrec
> 0)
17805 SpellCategoryStore::const_iterator i_scstore
= sSpellCategoryStore
.find(cat
);
17806 if(i_scstore
!= sSpellCategoryStore
.end())
17808 for(SpellCategorySet::const_iterator i_scset
= i_scstore
->second
.begin(); i_scset
!= i_scstore
->second
.end(); ++i_scset
)
17810 if(*i_scset
== spellInfo
->Id
) // skip main spell, already handled above
17813 AddSpellCooldown(*i_scset
, itemId
, catrecTime
);
17819 void Player::AddSpellCooldown(uint32 spellid
, uint32 itemid
, time_t end_time
)
17823 sc
.itemid
= itemid
;
17824 m_spellCooldowns
[spellid
] = sc
;
17827 void Player::SendCooldownEvent(SpellEntry
const *spellInfo
, uint32 itemId
, Spell
* spell
)
17829 // start cooldowns at server side, if any
17830 AddSpellAndCategoryCooldowns(spellInfo
,itemId
,spell
);
17832 // Send activate cooldown timer (possible 0) at client side
17833 WorldPacket
data(SMSG_COOLDOWN_EVENT
, (4+8));
17834 data
<< spellInfo
->Id
;
17836 SendDirectMessage(&data
);
17839 void Player::UpdatePotionCooldown(Spell
* spell
)
17841 // no potion used i combat or still in combat
17842 if(!m_lastPotionId
|| isInCombat())
17845 // Call not from spell cast, send cooldown event for item spells if no in combat
17848 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
17849 if(ItemPrototype
const* proto
= ObjectMgr::GetItemPrototype(m_lastPotionId
))
17850 for(int idx
= 0; idx
< 5; ++idx
)
17851 if(proto
->Spells
[idx
].SpellId
&& proto
->Spells
[idx
].SpellTrigger
== ITEM_SPELLTRIGGER_ON_USE
)
17852 if(SpellEntry
const* spellInfo
= sSpellStore
.LookupEntry(proto
->Spells
[idx
].SpellId
))
17853 SendCooldownEvent(spellInfo
,m_lastPotionId
);
17855 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
17857 SendCooldownEvent(spell
->m_spellInfo
,m_lastPotionId
,spell
);
17859 m_lastPotionId
= 0;
17862 //slot to be excluded while counting
17863 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition
, int8 slot
)
17865 if(!enchantmentcondition
)
17868 SpellItemEnchantmentConditionEntry
const *Condition
= sSpellItemEnchantmentConditionStore
.LookupEntry(enchantmentcondition
);
17873 uint8 curcount
[4] = {0, 0, 0, 0};
17875 //counting current equipped gem colors
17876 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
17880 Item
*pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
17881 if(pItem2
&& pItem2
->GetProto()->Socket
[0].Color
)
17883 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17885 uint32 enchant_id
= pItem2
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17889 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17893 uint32 gemid
= enchantEntry
->GemID
;
17897 ItemPrototype
const* gemProto
= sItemStorage
.LookupEntry
<ItemPrototype
>(gemid
);
17901 GemPropertiesEntry
const* gemProperty
= sGemPropertiesStore
.LookupEntry(gemProto
->GemProperties
);
17905 uint8 GemColor
= gemProperty
->color
;
17907 for(uint8 b
= 0, tmpcolormask
= 1; b
< 4; b
++, tmpcolormask
<<= 1)
17909 if(tmpcolormask
& GemColor
)
17916 bool activate
= true;
17918 for(int i
= 0; i
< 5; i
++)
17920 if(!Condition
->Color
[i
])
17923 uint32 _cur_gem
= curcount
[Condition
->Color
[i
] - 1];
17925 // if have <CompareColor> use them as count, else use <value> from Condition
17926 uint32 _cmp_gem
= Condition
->CompareColor
[i
] ? curcount
[Condition
->CompareColor
[i
] - 1]: Condition
->Value
[i
];
17928 switch(Condition
->Comparator
[i
])
17930 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17931 activate
&= (_cur_gem
< _cmp_gem
) ? true : false;
17933 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17934 activate
&= (_cur_gem
> _cmp_gem
) ? true : false;
17936 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17937 activate
&= (_cur_gem
>= _cmp_gem
) ? true : false;
17942 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");
17947 void Player::CorrectMetaGemEnchants(uint8 exceptslot
, bool apply
)
17949 //cycle all equipped items
17950 for(uint32 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
17952 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17953 if(slot
== exceptslot
)
17956 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
17958 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
)
17961 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17963 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17967 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17971 uint32 condition
= enchantEntry
->EnchantmentCondition
;
17974 //was enchant active with/without item?
17975 bool wasactive
= EnchantmentFitsRequirements(condition
, apply
? exceptslot
: -1);
17976 //should it now be?
17977 if(wasactive
^ EnchantmentFitsRequirements(condition
, apply
? -1 : exceptslot
))
17979 // ignore item gem conditions
17980 //if state changed, (dis)apply enchant
17981 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
),!wasactive
,true,true);
17988 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17989 void Player::ToggleMetaGemsActive(uint8 exceptslot
, bool apply
)
17991 //cycle all equipped items
17992 for(int slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
17994 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17995 if(slot
== exceptslot
)
17998 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
18000 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
) //if item has no sockets or no item is equipped go to next item
18003 //cycle all (gem)enchants
18004 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
18006 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
18007 if(!enchant_id
) //if no enchant go to next enchant(slot)
18010 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
18014 //only metagems to be (de)activated, so only enchants with condition
18015 uint32 condition
= enchantEntry
->EnchantmentCondition
;
18017 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
), apply
);
18022 void Player::LeaveBattleground(bool teleportToEntryPoint
)
18024 if(BattleGround
*bg
= GetBattleGround())
18026 bool need_debuf
= bg
->isBattleGround() && (bg
->GetStatus() == STATUS_IN_PROGRESS
) && sWorld
.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER
);
18028 bg
->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint
, true);
18030 // call after remove to be sure that player resurrected for correct cast
18032 CastSpell(this, 26013, true); // Deserter
18036 bool Player::CanJoinToBattleground() const
18038 // check Deserter debuff
18039 if(GetDummyAura(26013))
18045 bool Player::CanReportAfkDueToLimit()
18047 // a player can complain about 15 people per 5 minutes
18048 if(m_bgAfkReportedCount
>= 15)
18050 ++m_bgAfkReportedCount
;
18054 ///This player has been blamed to be inactive in a battleground
18055 void Player::ReportedAfkBy(Player
* reporter
)
18057 BattleGround
*bg
= GetBattleGround();
18058 if(!bg
|| bg
!= reporter
->GetBattleGround() || GetTeam() != reporter
->GetTeam())
18061 // check if player has 'Idle' or 'Inactive' debuff
18062 if(m_bgAfkReporter
.find(reporter
->GetGUIDLow())==m_bgAfkReporter
.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter
->CanReportAfkDueToLimit())
18064 m_bgAfkReporter
.insert(reporter
->GetGUIDLow());
18065 // 3 players have to complain to apply debuff
18066 if(m_bgAfkReporter
.size() >= 3)
18068 // cast 'Idle' spell
18069 CastSpell(this, 43680, true);
18070 m_bgAfkReporter
.clear();
18075 bool Player::IsVisibleInGridForPlayer( Player
* pl
) const
18077 // gamemaster in GM mode see all, including ghosts
18078 if(pl
->isGameMaster() && GetSession()->GetSecurity() <= pl
->GetSession()->GetSecurity())
18081 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
18082 if (InBattleGround())
18084 if (!(isAlive() || m_deathTimer
> 0) && !IsFriendlyTo(pl
) )
18089 // Live player see live player or dead player with not realized corpse
18090 if(pl
->isAlive() || pl
->m_deathTimer
> 0)
18092 return isAlive() || m_deathTimer
> 0;
18095 // Ghost see other friendly ghosts, that's for sure
18096 if(!(isAlive() || m_deathTimer
> 0) && IsFriendlyTo(pl
))
18099 // Dead player see live players near own corpse
18102 Corpse
*corpse
= pl
->GetCorpse();
18105 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
18106 if(corpse
->IsWithinDistInMap(this,(20+25)*sWorld
.getRate(RATE_CREATURE_AGGRO
)))
18111 // and not see any other
18115 bool Player::IsVisibleGloballyFor( Player
* u
) const
18120 // Always can see self
18124 // Visible units, always are visible for all players
18125 if (GetVisibility() == VISIBILITY_ON
)
18128 // GMs are visible for higher gms (or players are visible for gms)
18129 if (u
->GetSession()->GetSecurity() > SEC_PLAYER
)
18130 return GetSession()->GetSecurity() <= u
->GetSession()->GetSecurity();
18132 // non faction visibility non-breakable for non-GMs
18133 if (GetVisibility() == VISIBILITY_OFF
)
18136 // non-gm stealth/invisibility not hide from global player lists
18140 void Player::UpdateVisibilityOf(WorldObject
* target
)
18142 if(HaveAtClient(target
))
18144 if(!target
->isVisibleForInState(this,true))
18146 target
->DestroyForPlayer(this);
18147 m_clientGUIDs
.erase(target
->GetGUID());
18149 #ifdef MANGOS_DEBUG
18150 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
18151 sLog
.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
18157 if(target
->isVisibleForInState(this,false))
18159 target
->SendUpdateToPlayer(this);
18160 if(target
->GetTypeId()!=TYPEID_GAMEOBJECT
||!((GameObject
*)target
)->IsTransport())
18161 m_clientGUIDs
.insert(target
->GetGUID());
18163 #ifdef MANGOS_DEBUG
18164 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
18165 sLog
.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
18168 // target aura duration for caster show only if target exist at caster client
18169 // send data at target visibility change (adding to client)
18170 if(target
!=this && target
->isType(TYPEMASK_UNIT
))
18171 SendAurasForTarget((Unit
*)target
);
18173 if(target
->GetTypeId()==TYPEID_UNIT
&& ((Creature
*)target
)->isAlive())
18174 ((Creature
*)target
)->SendMonsterMoveWithSpeedToCurrentDestination(this);
18180 inline void UpdateVisibilityOf_helper(std::set
<uint64
>& s64
, T
* target
)
18182 s64
.insert(target
->GetGUID());
18186 inline void UpdateVisibilityOf_helper(std::set
<uint64
>& s64
, GameObject
* target
)
18188 if(!target
->IsTransport())
18189 s64
.insert(target
->GetGUID());
18193 void Player::UpdateVisibilityOf(T
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
)
18195 if(HaveAtClient(target
))
18197 if(!target
->isVisibleForInState(this,true))
18199 target
->BuildOutOfRangeUpdateBlock(&data
);
18200 m_clientGUIDs
.erase(target
->GetGUID());
18202 #ifdef MANGOS_DEBUG
18203 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
18204 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
));
18210 if(target
->isVisibleForInState(this,false))
18212 visibleNow
.insert(target
);
18213 target
->BuildUpdate(data_updates
);
18214 target
->BuildCreateUpdateBlockForPlayer(&data
, this);
18215 UpdateVisibilityOf_helper(m_clientGUIDs
,target
);
18217 #ifdef MANGOS_DEBUG
18218 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
18219 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
));
18225 template void Player::UpdateVisibilityOf(Player
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
18226 template void Player::UpdateVisibilityOf(Creature
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
18227 template void Player::UpdateVisibilityOf(Corpse
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
18228 template void Player::UpdateVisibilityOf(GameObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
18229 template void Player::UpdateVisibilityOf(DynamicObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
18231 void Player::InitPrimaryProffesions()
18233 SetFreePrimaryProffesions(sWorld
.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL
));
18236 void Player::SendComboPoints()
18238 Unit
*combotarget
= ObjectAccessor::GetUnit(*this, m_comboTarget
);
18241 WorldPacket
data(SMSG_UPDATE_COMBO_POINTS
, combotarget
->GetPackGUID().size()+1);
18242 data
.append(combotarget
->GetPackGUID());
18243 data
<< uint8(m_comboPoints
);
18244 GetSession()->SendPacket(&data
);
18248 void Player::AddComboPoints(Unit
* target
, int8 count
)
18253 // without combo points lost (duration checked in aura)
18254 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
18256 if(target
->GetGUID() == m_comboTarget
)
18258 m_comboPoints
+= count
;
18263 if(Unit
* target
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
18264 target
->RemoveComboPointHolder(GetGUIDLow());
18266 m_comboTarget
= target
->GetGUID();
18267 m_comboPoints
= count
;
18269 target
->AddComboPointHolder(GetGUIDLow());
18272 if (m_comboPoints
> 5) m_comboPoints
= 5;
18273 if (m_comboPoints
< 0) m_comboPoints
= 0;
18278 void Player::ClearComboPoints()
18283 // without combopoints lost (duration checked in aura)
18284 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
18290 if(Unit
* target
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
18291 target
->RemoveComboPointHolder(GetGUIDLow());
18296 void Player::SetGroup(Group
*group
, int8 subgroup
)
18302 // never use SetGroup without a subgroup unless you specify NULL for group
18303 assert(subgroup
>= 0);
18304 m_group
.link(group
, this);
18305 m_group
.setSubGroup((uint8
)subgroup
);
18309 void Player::SendInitialPacketsBeforeAddToMap()
18311 WorldPacket
data(SMSG_SET_REST_START_OBSOLETE
, 4);
18312 data
<< uint32(0); // unknown, may be rest state time or experience
18313 GetSession()->SendPacket(&data
);
18316 data
.Initialize(SMSG_BINDPOINTUPDATE
, 5*4);
18317 data
<< m_homebindX
<< m_homebindY
<< m_homebindZ
;
18318 data
<< (uint32
) m_homebindMapId
;
18319 data
<< (uint32
) m_homebindZoneId
;
18320 GetSession()->SendPacket(&data
);
18322 // SMSG_SET_PROFICIENCY
18323 // SMSG_UPDATE_AURA_DURATION
18326 data
.Initialize(SMSG_TUTORIAL_FLAGS
, 8*4);
18327 for (int i
= 0; i
< 8; ++i
)
18328 data
<< uint32( GetTutorialInt(i
) );
18329 GetSession()->SendPacket(&data
);
18331 SendInitialSpells();
18333 data
.Initialize(SMSG_SEND_UNLEARN_SPELLS
, 4);
18334 data
<< uint32(0); // count, for(count) uint32;
18335 GetSession()->SendPacket(&data
);
18337 SendInitialActionButtons();
18338 SendInitialReputations();
18339 m_achievementMgr
.SendAllAchievementData();
18342 uint32 newzone
, newarea
;
18343 GetZoneAndAreaId(newzone
,newarea
);
18344 UpdateZone(newzone
,newarea
); // also call SendInitWorldStates();
18346 // SMSG_SET_AURA_SINGLE
18348 data
.Initialize(SMSG_LOGIN_SETTIMESPEED
, 8);
18349 data
<< uint32(secsToTimeBitFields(sWorld
.GetGameTime()));
18350 data
<< (float)0.01666667f
; // game speed
18351 GetSession()->SendPacket( &data
);
18353 data
.Initialize(SMSG_TIME_SYNC_REQ
, 4); // new 2.0.x, enable movement
18354 data
<< uint32(0x00000000); // on blizz it increments periodically
18355 GetSession()->SendPacket(&data
);
18357 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
18358 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
) || isInFlight())
18359 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2
);
18364 void Player::SendInitialPacketsAfterAddToMap()
18366 WorldPacket
data(SMSG_TIME_SYNC_REQ
, 4); // new 2.0.x, enable movement
18367 data
<< uint32(0x00000000); // on blizz it increments periodically
18368 GetSession()->SendPacket(&data
);
18370 CastSpell(this, 836, true); // LOGINEFFECT
18372 // set some aura effects that send packet to player client after add player to map
18373 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
18374 // same auras state lost at far teleport, send it one more time in this case also
18375 static const AuraType auratypes
[] =
18377 SPELL_AURA_MOD_FEAR
, SPELL_AURA_TRANSFORM
, SPELL_AURA_WATER_WALK
,
18378 SPELL_AURA_FEATHER_FALL
, SPELL_AURA_HOVER
, SPELL_AURA_SAFE_FALL
,
18379 SPELL_AURA_FLY
, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
, SPELL_AURA_NONE
18381 for(AuraType
const* itr
= &auratypes
[0]; itr
&& itr
[0] != SPELL_AURA_NONE
; ++itr
)
18383 Unit::AuraList
const& auraList
= GetAurasByType(*itr
);
18384 if(!auraList
.empty())
18385 auraList
.front()->ApplyModifier(true,true);
18388 if(HasAuraType(SPELL_AURA_MOD_STUN
))
18389 SetMovement(MOVE_ROOT
);
18391 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
18392 if(HasAuraType(SPELL_AURA_MOD_ROOT
))
18394 WorldPacket
data(SMSG_FORCE_MOVE_ROOT
, 10);
18395 data
.append(GetPackGUID());
18397 SendMessageToSet(&data
,true);
18400 SendAurasForTarget(this);
18401 SendEnchantmentDurations(); // must be after add to map
18402 SendItemDurations(); // must be after add to map
18405 void Player::SendUpdateToOutOfRangeGroupMembers()
18407 if (m_groupUpdateMask
== GROUP_UPDATE_FLAG_NONE
)
18409 if(Group
* group
= GetGroup())
18410 group
->UpdatePlayerOutOfRange(this);
18412 m_groupUpdateMask
= GROUP_UPDATE_FLAG_NONE
;
18413 m_auraUpdateMask
= 0;
18414 if(Pet
*pet
= GetPet())
18415 pet
->ResetAuraUpdateMask();
18418 void Player::SendTransferAborted(uint32 mapid
, uint8 reason
, uint8 arg
)
18420 WorldPacket
data(SMSG_TRANSFER_ABORTED
, 4+2);
18421 data
<< uint32(mapid
);
18422 data
<< uint8(reason
); // transfer abort reason
18425 case TRANSFER_ABORT_INSUF_EXPAN_LVL
:
18426 case TRANSFER_ABORT_DIFFICULTY
:
18427 case TRANSFER_ABORT_UNIQUE_MESSAGE
:
18428 data
<< uint8(arg
);
18431 GetSession()->SendPacket(&data
);
18434 void Player::SendInstanceResetWarning(uint32 mapid
, uint32 time
)
18436 // type of warning, based on the time remaining until reset
18439 type
= RAID_INSTANCE_WELCOME
;
18440 else if(time
> 900 && time
<= 3600)
18441 type
= RAID_INSTANCE_WARNING_HOURS
;
18442 else if(time
> 300 && time
<= 900)
18443 type
= RAID_INSTANCE_WARNING_MIN
;
18445 type
= RAID_INSTANCE_WARNING_MIN_SOON
;
18446 WorldPacket
data(SMSG_RAID_INSTANCE_MESSAGE
, 4+4+4);
18447 data
<< uint32(type
);
18448 data
<< uint32(mapid
);
18449 data
<< uint32(time
);
18450 GetSession()->SendPacket(&data
);
18453 void Player::ApplyEquipCooldown( Item
* pItem
)
18455 for(int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
18457 _Spell
const& spellData
= pItem
->GetProto()->Spells
[i
];
18460 if( !spellData
.SpellId
)
18463 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
18464 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
)
18467 AddSpellCooldown(spellData
.SpellId
, pItem
->GetEntry(), time(NULL
) + 30);
18469 WorldPacket
data(SMSG_ITEM_COOLDOWN
, 12);
18470 data
<< pItem
->GetGUID();
18471 data
<< uint32(spellData
.SpellId
);
18472 GetSession()->SendPacket(&data
);
18476 void Player::resetSpells()
18478 // not need after this call
18479 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS
))
18481 m_atLoginFlags
= m_atLoginFlags
& ~AT_LOGIN_RESET_SPELLS
;
18482 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS
), GetGUIDLow());
18485 // make full copy of map (spells removed and marked as deleted at another spell remove
18486 // and we can't use original map for safe iterative with visit each spell at loop end
18487 PlayerSpellMap smap
= GetSpellMap();
18489 for(PlayerSpellMap::const_iterator iter
= smap
.begin();iter
!= smap
.end(); ++iter
)
18490 removeSpell(iter
->first
); // only iter->first can be accessed, object by iter->second can be deleted already
18492 learnDefaultSpells();
18493 learnQuestRewardedSpells();
18496 void Player::learnDefaultSpells()
18498 // learn default race/class spells
18499 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(),getClass());
18500 for (PlayerCreateInfoSpells::const_iterator itr
= info
->spell
.begin(); itr
!=info
->spell
.end(); ++itr
)
18502 uint32 tspell
= *itr
;
18503 sLog
.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell
);
18504 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
18505 addSpell(tspell
,true,true,true,false);
18506 else // but send in normal spell in game learn case
18507 learnSpell(tspell
,true);
18511 void Player::learnQuestRewardedSpells(Quest
const* quest
)
18513 uint32 spell_id
= quest
->GetRewSpellCast();
18515 // skip quests without rewarded spell
18519 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
18523 // check learned spells state
18524 bool found
= false;
18525 for(int i
=0; i
< 3; ++i
)
18527 if(spellInfo
->Effect
[i
] == SPELL_EFFECT_LEARN_SPELL
&& !HasSpell(spellInfo
->EffectTriggerSpell
[i
]))
18534 // skip quests with not teaching spell or already known spell
18538 // prevent learn non first rank unknown profession and second specialization for same profession)
18539 uint32 learned_0
= spellInfo
->EffectTriggerSpell
[0];
18540 if( spellmgr
.GetSpellRank(learned_0
) > 1 && !HasSpell(learned_0
) )
18542 // not have first rank learned (unlearned prof?)
18543 uint32 first_spell
= spellmgr
.GetFirstSpellInChain(learned_0
);
18544 if( !HasSpell(first_spell
) )
18547 SpellEntry
const *learnedInfo
= sSpellStore
.LookupEntry(learned_0
);
18552 if(learnedInfo
->Effect
[0]==SPELL_EFFECT_TRADE_SKILL
&& learnedInfo
->Effect
[1]==0)
18554 // search other specialization for same prof
18555 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
18557 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->first
==learned_0
)
18560 SpellEntry
const *itrInfo
= sSpellStore
.LookupEntry(itr
->first
);
18564 // compare only specializations
18565 if(itrInfo
->Effect
[0]!=SPELL_EFFECT_TRADE_SKILL
|| itrInfo
->Effect
[1]!=0)
18568 // compare same chain spells
18569 if(spellmgr
.GetFirstSpellInChain(itr
->first
) != first_spell
)
18572 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18573 if(!spellmgr
.IsHighRankOfSpell(learned_0
,itr
->first
))
18579 CastSpell( this, spell_id
, true);
18582 void Player::learnQuestRewardedSpells()
18584 // learn spells received from quest completing
18585 for(QuestStatusMap::const_iterator itr
= mQuestStatus
.begin(); itr
!= mQuestStatus
.end(); ++itr
)
18587 // skip no rewarded quests
18588 if(!itr
->second
.m_rewarded
)
18591 Quest
const* quest
= objmgr
.GetQuestTemplate(itr
->first
);
18595 learnQuestRewardedSpells(quest
);
18599 void Player::learnSkillRewardedSpells(uint32 skill_id
, uint32 skill_value
)
18601 uint32 raceMask
= getRaceMask();
18602 uint32 classMask
= getClassMask();
18603 for (uint32 j
=0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
18605 SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
);
18606 if (!pAbility
|| pAbility
->skillId
!=skill_id
|| pAbility
->learnOnGetSkill
!= ABILITY_LEARNED_ON_GET_PROFESSION_SKILL
)
18608 // Check race if set
18609 if (pAbility
->racemask
&& !(pAbility
->racemask
& raceMask
))
18611 // Check class if set
18612 if (pAbility
->classmask
&& !(pAbility
->classmask
& classMask
))
18615 if (sSpellStore
.LookupEntry(pAbility
->spellId
))
18617 // need unlearn spell
18618 if (skill_value
< pAbility
->req_skill_value
)
18619 removeSpell(pAbility
->spellId
);
18621 else if (!IsInWorld())
18622 addSpell(pAbility
->spellId
,true,true,true,false);
18624 learnSpell(pAbility
->spellId
,true);
18629 void Player::SendAurasForTarget(Unit
*target
)
18631 if(target
->GetVisibleAuras()->empty()) // speedup things
18634 WorldPacket
data(SMSG_AURA_UPDATE_ALL
);
18635 data
.append(target
->GetPackGUID());
18637 Unit::VisibleAuraMap
const *visibleAuras
= target
->GetVisibleAuras();
18638 for(Unit::VisibleAuraMap::const_iterator itr
= visibleAuras
->begin(); itr
!= visibleAuras
->end(); ++itr
)
18640 for(uint32 j
= 0; j
< 3; ++j
)
18642 if(Aura
*aura
= target
->GetAura(itr
->second
, j
))
18644 data
<< uint8(aura
->GetAuraSlot());
18645 data
<< uint32(aura
->GetId());
18649 uint8 auraFlags
= aura
->GetAuraFlags();
18651 data
<< uint8(auraFlags
);
18653 data
<< uint8(aura
->GetAuraLevel());
18655 data
<< uint8(aura
->GetAuraCharges());
18657 if(!(auraFlags
& AFLAG_NOT_CASTER
))
18659 data
<< uint8(0); // packed GUID of someone (caster?)
18662 if(auraFlags
& AFLAG_DURATION
) // include aura duration
18664 data
<< uint32(aura
->GetAuraMaxDuration());
18665 data
<< uint32(aura
->GetAuraDuration());
18673 GetSession()->SendPacket(&data
);
18676 void Player::SetDailyQuestStatus( uint32 quest_id
)
18678 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
18680 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
18682 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
18683 m_lastDailyQuestTime
= time(NULL
); // last daily quest time
18684 m_DailyQuestChanged
= true;
18690 void Player::ResetDailyQuestStatus()
18692 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
18693 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
18695 // DB data deleted in caller
18696 m_DailyQuestChanged
= false;
18697 m_lastDailyQuestTime
= 0;
18700 BattleGround
* Player::GetBattleGround() const
18702 if(GetBattleGroundId()==0)
18705 return sBattleGroundMgr
.GetBattleGround(GetBattleGroundId(), m_bgTypeID
);
18708 bool Player::InArena() const
18710 BattleGround
*bg
= GetBattleGround();
18711 if(!bg
|| !bg
->isArena())
18717 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId
) const
18719 // get a template bg instead of running one
18720 BattleGround
*bg
= sBattleGroundMgr
.GetBattleGroundTemplate(bgTypeId
);
18724 if(getLevel() < bg
->GetMinLevel() || getLevel() > bg
->GetMaxLevel())
18730 BGQueueIdBasedOnLevel
Player::GetBattleGroundQueueIdFromLevel(BattleGroundTypeId bgTypeId
) const
18732 //returned to hardcoded version of this function, because there is no way to code it dynamic
18733 uint32 level
= getLevel();
18734 if( bgTypeId
== BATTLEGROUND_AV
)
18737 uint32 queue_id
= (level
/ 10) - 1; // for ranges 0 - 19, 20 - 29, 30 - 39, 40 - 49, 50 - 59, 60 - 69, 70 -79, 80
18738 if( queue_id
>= MAX_BATTLEGROUND_QUEUES
)
18740 sLog
.outError("BattleGround: too high queue_id %u this shouldn't happen", queue_id
);
18741 return QUEUE_ID_MAX_LEVEL_80
;
18743 return BGQueueIdBasedOnLevel(queue_id
);
18746 float Player::GetReputationPriceDiscount( Creature
const* pCreature
) const
18748 FactionTemplateEntry
const* vendor_faction
= pCreature
->getFactionTemplateEntry();
18749 if(!vendor_faction
|| !vendor_faction
->faction
)
18752 ReputationRank rank
= GetReputationRank(vendor_faction
->faction
);
18753 if(rank
<= REP_NEUTRAL
)
18756 return 1.0f
- 0.05f
* (rank
- REP_NEUTRAL
);
18759 bool Player::IsSpellFitByClassAndRace( uint32 spell_id
) const
18761 uint32 racemask
= getRaceMask();
18762 uint32 classmask
= getClassMask();
18764 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
18765 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
18769 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
18771 // skip wrong race skills
18772 if( _spell_idx
->second
->racemask
&& (_spell_idx
->second
->racemask
& racemask
) == 0)
18775 // skip wrong class skills
18776 if( _spell_idx
->second
->classmask
&& (_spell_idx
->second
->classmask
& classmask
) == 0)
18785 bool Player::HasQuestForGO(int32 GOId
) const
18787 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
18789 uint32 questid
= GetQuestSlotQuestId(i
);
18790 if ( questid
== 0 )
18793 QuestStatusMap::const_iterator qs_itr
= mQuestStatus
.find(questid
);
18794 if(qs_itr
== mQuestStatus
.end())
18797 QuestStatusData
const& qs
= qs_itr
->second
;
18799 if (qs
.m_status
== QUEST_STATUS_INCOMPLETE
)
18801 Quest
const* qinfo
= objmgr
.GetQuestTemplate(questid
);
18805 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
18808 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
18810 if (qinfo
->ReqCreatureOrGOId
[j
]>=0) //skip non GO case
18813 if((-1)*GOId
== qinfo
->ReqCreatureOrGOId
[j
] && qs
.m_creatureOrGOcount
[j
] < qinfo
->ReqCreatureOrGOCount
[j
])
18821 void Player::UpdateForQuestsGO()
18823 if(m_clientGUIDs
.empty())
18827 WorldPacket packet
;
18828 for(ClientGUIDs::iterator itr
=m_clientGUIDs
.begin(); itr
!=m_clientGUIDs
.end(); ++itr
)
18830 if(IS_GAMEOBJECT_GUID(*itr
))
18832 GameObject
*obj
= HashMapHolder
<GameObject
>::Find(*itr
);
18834 obj
->BuildValuesUpdateBlockForPlayer(&udata
,this);
18837 udata
.BuildPacket(&packet
);
18838 GetSession()->SendPacket(&packet
);
18841 void Player::SummonIfPossible(bool agree
)
18845 m_summon_expire
= 0;
18849 // expire and auto declined
18850 if(m_summon_expire
< time(NULL
))
18853 // stop taxi flight at summon
18856 GetMotionMaster()->MovementExpired();
18857 m_taxi
.ClearTaxiDestinations();
18860 // drop flag at summon
18861 if(BattleGround
*bg
= GetBattleGround())
18862 bg
->EventPlayerDroppedFlag(this);
18864 m_summon_expire
= 0;
18866 TeleportTo(m_summon_mapid
, m_summon_x
, m_summon_y
, m_summon_z
,GetOrientation());
18869 void Player::RemoveItemDurations( Item
*item
)
18871 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); ++itr
)
18875 m_itemDuration
.erase(itr
);
18881 void Player::AddItemDurations( Item
*item
)
18883 if(item
->GetUInt32Value(ITEM_FIELD_DURATION
))
18885 m_itemDuration
.push_back(item
);
18886 item
->SendTimeUpdate(this);
18890 void Player::AutoUnequipOffhandIfNeed()
18892 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
18896 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
18897 if (CanTitanGrip() || (offItem
->GetProto()->InventoryType
!= INVTYPE_2HWEAPON
&& !IsTwoHandUsed()))
18900 ItemPosCountVec off_dest
;
18901 uint8 off_msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false );
18902 if( off_msg
== EQUIP_ERR_OK
)
18904 RemoveItem(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
, true);
18905 StoreItem( off_dest
, offItem
, true );
18910 mi
.AddItem(offItem
->GetGUIDLow(), offItem
->GetEntry(), offItem
);
18911 MoveItemFromInventory(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
, true);
18912 CharacterDatabase
.BeginTransaction();
18913 offItem
->DeleteFromInventoryDB(); // deletes item from character's inventory
18914 offItem
->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
18915 CharacterDatabase
.CommitTransaction();
18917 std::string subject
= GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM
);
18918 WorldSession::SendMailTo(this, MAIL_NORMAL
, MAIL_STATIONERY_GM
, GetGUIDLow(), GetGUIDLow(), subject
, 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
);
18922 bool Player::HasItemFitToSpellReqirements(SpellEntry
const* spellInfo
, Item
const* ignoreItem
)
18924 if(spellInfo
->EquippedItemClass
< 0)
18927 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18928 // for optimize check 2 used cases only
18929 switch(spellInfo
->EquippedItemClass
)
18931 case ITEM_CLASS_WEAPON
:
18933 for(int i
= EQUIPMENT_SLOT_MAINHAND
; i
< EQUIPMENT_SLOT_TABARD
; ++i
)
18934 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
18935 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18939 case ITEM_CLASS_ARMOR
:
18941 // tabard not have dependent spells
18942 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_MAINHAND
; ++i
)
18943 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
18944 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18947 // shields can be equipped to offhand slot
18948 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
))
18949 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18952 // ranged slot can have some armor subclasses
18953 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_RANGED
))
18954 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18960 sLog
.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo
->EquippedItemClass
);
18967 bool Player::CanNoReagentCast(SpellEntry
const* spellInfo
) const
18969 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18970 if (spellInfo
->AttributesEx5
& SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
&&
18971 HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PREPARATION
))
18974 // Check no reagent use mask
18975 uint64 noReagentMask_0_1
= GetUInt64Value(PLAYER_NO_REAGENT_COST_1
);
18976 uint32 noReagentMask_2
= GetUInt64Value(PLAYER_NO_REAGENT_COST_1
+2);
18977 if (spellInfo
->SpellFamilyFlags
& noReagentMask_0_1
||
18978 spellInfo
->SpellFamilyFlags2
& noReagentMask_2
)
18984 void Player::RemoveItemDependentAurasAndCasts( Item
* pItem
)
18986 AuraMap
& auras
= GetAuras();
18987 for(AuraMap::iterator itr
= auras
.begin(); itr
!= auras
.end(); )
18989 Aura
* aura
= itr
->second
;
18991 // skip passive (passive item dependent spells work in another way) and not self applied auras
18992 SpellEntry
const* spellInfo
= aura
->GetSpellProto();
18993 if(aura
->IsPassive() || aura
->GetCasterGUID()!=GetGUID())
18999 // skip if not item dependent or have alternative item
19000 if(HasItemFitToSpellReqirements(spellInfo
,pItem
))
19006 // no alt item, remove aura, restart check
19007 RemoveAurasDueToSpell(aura
->GetId());
19008 itr
= auras
.begin();
19011 // currently casted spells can be dependent from item
19012 for (uint32 i
= 0; i
< CURRENT_MAX_SPELL
; i
++)
19014 if( m_currentSpells
[i
] && m_currentSpells
[i
]->getState()!=SPELL_STATE_DELAYED
&&
19015 !HasItemFitToSpellReqirements(m_currentSpells
[i
]->m_spellInfo
,pItem
) )
19020 uint32
Player::GetResurrectionSpellId()
19022 // search priceless resurrection possibilities
19024 uint32 spell_id
= 0;
19025 AuraList
const& dummyAuras
= GetAurasByType(SPELL_AURA_DUMMY
);
19026 for(AuraList::const_iterator itr
= dummyAuras
.begin(); itr
!= dummyAuras
.end(); ++itr
)
19028 // Soulstone Resurrection // prio: 3 (max, non death persistent)
19029 if( prio
< 2 && (*itr
)->GetSpellProto()->SpellVisual
[0] == 99 && (*itr
)->GetSpellProto()->SpellIconID
== 92 )
19031 switch((*itr
)->GetId())
19033 case 20707: spell_id
= 3026; break; // rank 1
19034 case 20762: spell_id
= 20758; break; // rank 2
19035 case 20763: spell_id
= 20759; break; // rank 3
19036 case 20764: spell_id
= 20760; break; // rank 4
19037 case 20765: spell_id
= 20761; break; // rank 5
19038 case 27239: spell_id
= 27240; break; // rank 6
19039 case 47883: spell_id
= 47882; break; // rank 7
19041 sLog
.outError("Unhandled spell %%u: S.Resurrection",(*itr
)->GetId());
19047 // Twisting Nether // prio: 2 (max)
19048 else if((*itr
)->GetId()==23701 && roll_chance_i(10))
19055 // Reincarnation (passive spell) // prio: 1
19056 if(prio
< 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
19062 // Used in triggers for check "Only to targets that grant experience or honor" req
19063 bool Player::isHonorOrXPTarget(Unit
* pVictim
)
19065 uint32 v_level
= pVictim
->getLevel();
19066 uint32 k_grey
= MaNGOS::XP::GetGrayLevel(getLevel());
19068 // Victim level less gray level
19069 if(v_level
<=k_grey
)
19072 if(pVictim
->GetTypeId() == TYPEID_UNIT
)
19074 if (((Creature
*)pVictim
)->isTotem() ||
19075 ((Creature
*)pVictim
)->isPet() ||
19076 ((Creature
*)pVictim
)->GetCreatureInfo()->flags_extra
& CREATURE_FLAG_EXTRA_NO_XP_AT_KILL
)
19082 bool Player::RewardPlayerAndGroupAtKill(Unit
* pVictim
)
19084 bool PvP
= pVictim
->isCharmedOwnedByPlayerOrPlayer();
19086 // prepare data for near group iteration (PvP and !PvP cases)
19088 bool honored_kill
= false;
19090 if(Group
*pGroup
= GetGroup())
19093 uint32 sum_level
= 0;
19094 Player
* member_with_max_level
= NULL
;
19095 Player
* not_gray_member_with_max_level
= NULL
;
19097 pGroup
->GetDataForXPAtKill(pVictim
,count
,sum_level
,member_with_max_level
,not_gray_member_with_max_level
);
19099 if(member_with_max_level
)
19101 /// not get Xp in PvP or no not gray players in group
19102 xp
= (PvP
|| !not_gray_member_with_max_level
) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level
, pVictim
);
19104 /// skip in check PvP case (for speed, not used)
19105 bool is_raid
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsRaid() && pGroup
->isRaidGroup();
19106 bool is_dungeon
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsDungeon();
19107 float group_rate
= MaNGOS::XP::xp_in_group_rate(count
,is_raid
);
19109 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
19111 Player
* pGroupGuy
= itr
->getSource();
19115 if(!pGroupGuy
->IsAtGroupRewardDistance(pVictim
))
19116 continue; // member (alive or dead) or his corpse at req. distance
19118 // honor can be in PvP and !PvP (racial leader) cases (for alive)
19119 if(pGroupGuy
->isAlive() && pGroupGuy
->RewardHonor(pVictim
,count
) && pGroupGuy
==this)
19120 honored_kill
= true;
19122 // xp and reputation only in !PvP case
19125 float rate
= group_rate
* float(pGroupGuy
->getLevel()) / sum_level
;
19127 // if is in dungeon then all receive full reputation at kill
19128 // rewarded any alive/dead/near_corpse group member
19129 pGroupGuy
->RewardReputation(pVictim
,is_dungeon
? 1.0f
: rate
);
19131 // XP updated only for alive group member
19132 if(pGroupGuy
->isAlive() && not_gray_member_with_max_level
&&
19133 pGroupGuy
->getLevel() <= not_gray_member_with_max_level
->getLevel())
19135 uint32 itr_xp
= (member_with_max_level
== not_gray_member_with_max_level
) ? uint32(xp
*rate
) : uint32((xp
*rate
/2)+1);
19137 pGroupGuy
->GiveXP(itr_xp
, pVictim
);
19138 if(Pet
* pet
= pGroupGuy
->GetPet())
19139 pet
->GivePetXP(itr_xp
/2);
19142 // quest objectives updated only for alive group member or dead but with not released body
19143 if(pGroupGuy
->isAlive()|| !pGroupGuy
->GetCorpse())
19145 // normal creature (not pet/etc) can be only in !PvP case
19146 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
19147 pGroupGuy
->KilledMonster(pVictim
->GetEntry(), pVictim
->GetGUID());
19153 else // if (!pGroup)
19155 xp
= PvP
? 0 : MaNGOS::XP::Gain(this, pVictim
);
19157 // honor can be in PvP and !PvP (racial leader) cases
19158 if(RewardHonor(pVictim
,1))
19159 honored_kill
= true;
19161 // xp and reputation only in !PvP case
19164 RewardReputation(pVictim
,1);
19165 GiveXP(xp
, pVictim
);
19167 if(Pet
* pet
= GetPet())
19168 pet
->GivePetXP(xp
);
19170 // normal creature (not pet/etc) can be only in !PvP case
19171 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
19172 KilledMonster(pVictim
->GetEntry(),pVictim
->GetGUID());
19175 return xp
|| honored_kill
;
19178 bool Player::IsAtGroupRewardDistance(WorldObject
const* pRewardSource
) const
19180 if(pRewardSource
->GetDistance(this) <= sWorld
.getConfig(CONFIG_GROUP_XP_DISTANCE
))
19186 Corpse
* corpse
= GetCorpse();
19190 return pRewardSource
->GetDistance(corpse
) <= sWorld
.getConfig(CONFIG_GROUP_XP_DISTANCE
);
19193 uint32
Player::GetBaseWeaponSkillValue (WeaponAttackType attType
) const
19195 Item
* item
= GetWeaponForAttack(attType
,true);
19197 // unarmed only with base attack
19198 if(attType
!= BASE_ATTACK
&& !item
)
19201 // weapon skill or (unarmed for base attack)
19202 uint32 skill
= item
? item
->GetSkill() : SKILL_UNARMED
;
19203 return GetBaseSkillValue(skill
);
19206 void Player::ResurectUsingRequestData()
19208 /// Teleport before resurrecting, otherwise the player might get attacked from creatures near his corpse
19209 TeleportTo(m_resurrectMap
, m_resurrectX
, m_resurrectY
, m_resurrectZ
, GetOrientation());
19211 ResurrectPlayer(0.0f
,false);
19213 if(GetMaxHealth() > m_resurrectHealth
)
19214 SetHealth( m_resurrectHealth
);
19216 SetHealth( GetMaxHealth() );
19218 if(GetMaxPower(POWER_MANA
) > m_resurrectMana
)
19219 SetPower(POWER_MANA
, m_resurrectMana
);
19221 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
) );
19223 SetPower(POWER_RAGE
, 0 );
19225 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
) );
19227 SpawnCorpseBones();
19230 void Player::SetClientControl(Unit
* target
, uint8 allowMove
)
19232 WorldPacket
data(SMSG_CLIENT_CONTROL_UPDATE
, target
->GetPackGUID().size()+1);
19233 data
.append(target
->GetPackGUID());
19234 data
<< uint8(allowMove
);
19235 GetSession()->SendPacket(&data
);
19238 void Player::UpdateZoneDependentAuras( uint32 newZone
)
19240 // remove new continent flight forms
19241 if( !IsAllowUseFlyMountsHere() )
19243 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
);
19244 RemoveSpellsCausingAura(SPELL_AURA_FLY
);
19247 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
19248 SpellAreaForAreaMapBounds saBounds
= spellmgr
.GetSpellAreaForAreaMapBounds(newZone
);
19249 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
19250 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,newZone
,0))
19251 if( !HasAura(itr
->second
->spellId
,0) )
19252 CastSpell(this,itr
->second
->spellId
,true);
19255 void Player::UpdateAreaDependentAuras( uint32 newArea
)
19257 // remove auras from spells with area limitations
19258 for(AuraMap::iterator iter
= m_Auras
.begin(); iter
!= m_Auras
.end();)
19260 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
19261 if(spellmgr
.GetSpellAllowedInLocationError(iter
->second
->GetSpellProto(),GetMapId(),m_zoneUpdateId
,newArea
,this) != SPELL_CAST_OK
)
19267 // some auras applied at subzone enter
19268 SpellAreaForAreaMapBounds saBounds
= spellmgr
.GetSpellAreaForAreaMapBounds(newArea
);
19269 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
19270 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,m_zoneUpdateId
,newArea
))
19271 if( !HasAura(itr
->second
->spellId
,0) )
19272 CastSpell(this,itr
->second
->spellId
,true);
19275 uint32
Player::GetCorpseReclaimDelay(bool pvp
) const
19277 if( pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
19278 !pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
19280 return copseReclaimDelay
[0];
19283 time_t now
= time(NULL
);
19284 // 0..2 full period
19285 uint32 count
= (now
< m_deathExpireTime
) ? (m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
: 0;
19286 return copseReclaimDelay
[count
];
19289 void Player::UpdateCorpseReclaimDelay()
19291 bool pvp
= m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
;
19293 if( pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
19294 !pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
19297 time_t now
= time(NULL
);
19298 if(now
< m_deathExpireTime
)
19300 // full and partly periods 1..3
19301 uint32 count
= (m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
+1;
19302 if(count
< MAX_DEATH_COUNT
)
19303 m_deathExpireTime
= now
+(count
+1)*DEATH_EXPIRE_STEP
;
19305 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
;
19308 m_deathExpireTime
= now
+DEATH_EXPIRE_STEP
;
19311 void Player::SendCorpseReclaimDelay(bool load
)
19313 Corpse
* corpse
= GetCorpse();
19320 if(corpse
->GetGhostTime() > m_deathExpireTime
)
19323 bool pvp
= corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
;
19326 if( pvp
&& sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
19327 !pvp
&& sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
19329 count
= (m_deathExpireTime
-corpse
->GetGhostTime())/DEATH_EXPIRE_STEP
;
19330 if(count
>=MAX_DEATH_COUNT
)
19331 count
= MAX_DEATH_COUNT
-1;
19336 time_t expected_time
= corpse
->GetGhostTime()+copseReclaimDelay
[count
];
19338 time_t now
= time(NULL
);
19339 if(now
>= expected_time
)
19342 delay
= expected_time
-now
;
19345 delay
= GetCorpseReclaimDelay(corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
);
19347 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
19348 WorldPacket
data(SMSG_CORPSE_RECLAIM_DELAY
, 4);
19349 data
<< uint32(delay
*IN_MILISECONDS
);
19350 GetSession()->SendPacket( &data
);
19353 Player
* Player::GetNextRandomRaidMember(float radius
)
19355 Group
*pGroup
= GetGroup();
19359 std::vector
<Player
*> nearMembers
;
19360 nearMembers
.reserve(pGroup
->GetMembersCount());
19362 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
19364 Player
* Target
= itr
->getSource();
19366 // IsHostileTo check duel and controlled by enemy
19367 if( Target
&& Target
!= this && IsWithinDistInMap(Target
, radius
) &&
19368 !Target
->HasInvisibilityAura() && !IsHostileTo(Target
) )
19369 nearMembers
.push_back(Target
);
19372 if (nearMembers
.empty())
19375 uint32 randTarget
= urand(0,nearMembers
.size()-1);
19376 return nearMembers
[randTarget
];
19379 PartyResult
Player::CanUninviteFromGroup() const
19381 const Group
* grp
= GetGroup();
19383 return PARTY_RESULT_YOU_NOT_IN_GROUP
;
19385 if(!grp
->IsLeader(GetGUID()) && !grp
->IsAssistant(GetGUID()))
19386 return PARTY_RESULT_YOU_NOT_LEADER
;
19388 if(InBattleGround())
19389 return PARTY_RESULT_INVITE_RESTRICTED
;
19391 return PARTY_RESULT_OK
;
19394 void Player::SetBattleGroundRaid(Group
* group
, int8 subgroup
)
19396 //we must move references from m_group to m_originalGroup
19397 SetOriginalGroup(GetGroup(), GetSubGroup());
19400 m_group
.link(group
, this);
19401 m_group
.setSubGroup((uint8
)subgroup
);
19404 void Player::RemoveFromBattleGroundRaid()
19406 //remove existing reference
19408 if( Group
* group
= GetOriginalGroup() )
19410 m_group
.link(group
, this);
19411 m_group
.setSubGroup(GetOriginalSubGroup());
19413 SetOriginalGroup(NULL
);
19416 void Player::SetOriginalGroup(Group
*group
, int8 subgroup
)
19418 if( group
== NULL
)
19419 m_originalGroup
.unlink();
19422 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
19423 assert(subgroup
>= 0);
19424 m_originalGroup
.link(group
, this);
19425 m_originalGroup
.setSubGroup((uint8
)subgroup
);
19429 void Player::UpdateUnderwaterState( Map
* m
, float x
, float y
, float z
)
19431 LiquidData liquid_status
;
19432 ZLiquidStatus res
= m
->getLiquidStatus(x
, y
, z
, MAP_ALL_LIQUIDS
, &liquid_status
);
19435 m_MirrorTimerFlags
&= ~(UNDERWATER_INWATER
|UNDERWATER_INLAVA
|UNDERWATER_INSLIME
|UNDERWARER_INDARKWATER
);
19436 // Small hack for enable breath in WMO
19438 m_MirrorTimerFlags
|=UNDERWATER_INWATER
;
19442 // All liquids type - check under water position
19443 if (liquid_status
.type
&(MAP_LIQUID_TYPE_WATER
|MAP_LIQUID_TYPE_OCEAN
|MAP_LIQUID_TYPE_MAGMA
|MAP_LIQUID_TYPE_SLIME
))
19445 if ( res
& LIQUID_MAP_UNDER_WATER
)
19446 m_MirrorTimerFlags
|= UNDERWATER_INWATER
;
19448 m_MirrorTimerFlags
&= ~UNDERWATER_INWATER
;
19451 // Allow travel in dark water on taxi or transport
19452 if (liquid_status
.type
& MAP_LIQUID_TYPE_DARK_WATER
&& !isInFlight() && !(GetUnitMovementFlags()&MOVEMENTFLAG_ONTRANSPORT
))
19453 m_MirrorTimerFlags
|= UNDERWARER_INDARKWATER
;
19455 m_MirrorTimerFlags
&= ~UNDERWARER_INDARKWATER
;
19457 // in lava check, anywhere in lava level
19458 if (liquid_status
.type
&MAP_LIQUID_TYPE_MAGMA
)
19460 if (res
& (LIQUID_MAP_UNDER_WATER
|LIQUID_MAP_IN_WATER
|LIQUID_MAP_WATER_WALK
))
19461 m_MirrorTimerFlags
|= UNDERWATER_INLAVA
;
19463 m_MirrorTimerFlags
&= ~UNDERWATER_INLAVA
;
19465 // in slime check, anywhere in slime level
19466 if (liquid_status
.type
&MAP_LIQUID_TYPE_SLIME
)
19468 if (res
& (LIQUID_MAP_UNDER_WATER
|LIQUID_MAP_IN_WATER
|LIQUID_MAP_WATER_WALK
))
19469 m_MirrorTimerFlags
|= UNDERWATER_INSLIME
;
19471 m_MirrorTimerFlags
&= ~UNDERWATER_INSLIME
;
19475 void Player::SetCanParry( bool value
)
19477 if(m_canParry
==value
)
19480 m_canParry
= value
;
19481 UpdateParryPercentage();
19484 void Player::SetCanBlock( bool value
)
19486 if(m_canBlock
==value
)
19489 m_canBlock
= value
;
19490 UpdateBlockPercentage();
19493 bool ItemPosCount::isContainedIn(ItemPosCountVec
const& vec
) const
19495 for(ItemPosCountVec::const_iterator itr
= vec
.begin(); itr
!= vec
.end();++itr
)
19496 if(itr
->pos
== pos
)
19502 bool Player::CanUseBattleGroundObject()
19504 return ( //InBattleGround() && // in battleground - not need, check in other cases
19505 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
19506 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
19507 !HasStealthAura() && // not stealthed
19508 !HasInvisibilityAura() && // not invisible
19509 !HasAura(SPELL_RECENTLY_DROPPED_FLAG
, 0) && // can't pickup
19510 //TODO player cannot use object when he is invulnerable (immune) - (ice block, divine shield, divine protection, divine intervention ...)
19511 isAlive() // live player
19515 bool Player::CanCaptureTowerPoint()
19517 return ( !HasStealthAura() && // not stealthed
19518 !HasInvisibilityAura() && // not invisible
19519 isAlive() // live player
19523 uint32
Player::GetBarberShopCost(uint8 newhairstyle
, uint8 newhaircolor
, uint8 newfacialhair
)
19525 uint32 level
= getLevel();
19527 if(level
> GT_MAX_LEVEL
)
19528 level
= GT_MAX_LEVEL
; // max level in this dbc
19530 uint8 hairstyle
= GetByteValue(PLAYER_BYTES
, 2);
19531 uint8 haircolor
= GetByteValue(PLAYER_BYTES
, 3);
19532 uint8 facialhair
= GetByteValue(PLAYER_BYTES_2
, 0);
19534 if((hairstyle
== newhairstyle
) && (haircolor
== newhaircolor
) && (facialhair
== newfacialhair
))
19537 GtBarberShopCostBaseEntry
const *bsc
= sGtBarberShopCostBaseStore
.LookupEntry(level
- 1);
19539 if(!bsc
) // shouldn't happen
19544 if(hairstyle
!= newhairstyle
)
19545 cost
+= bsc
->cost
; // full price
19547 if((haircolor
!= newhaircolor
) && (hairstyle
== newhairstyle
))
19548 cost
+= bsc
->cost
* 0.5f
; // +1/2 of price
19550 if(facialhair
!= newfacialhair
)
19551 cost
+= bsc
->cost
* 0.75f
; // +3/4 of price
19553 return uint32(cost
);
19556 void Player::InitGlyphsForLevel()
19558 for(uint32 i
= 0; i
< sGlyphSlotStore
.GetNumRows(); ++i
)
19559 if(GlyphSlotEntry
const * gs
= sGlyphSlotStore
.LookupEntry(i
))
19561 SetGlyphSlot(gs
->Order
- 1, gs
->Id
);
19563 uint32 level
= getLevel();
19566 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19568 value
|= (0x01 | 0x02);
19578 SetUInt32Value(PLAYER_GLYPHS_ENABLED
, value
);
19581 void Player::EnterVehicle(Vehicle
*vehicle
)
19583 VehicleEntry
const *ve
= sVehicleStore
.LookupEntry(vehicle
->GetVehicleId());
19587 VehicleSeatEntry
const *veSeat
= sVehicleSeatStore
.LookupEntry(ve
->m_seatID
[0]);
19591 vehicle
->SetCharmerGUID(GetGUID());
19592 vehicle
->RemoveFlag(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_SPELLCLICK
);
19593 vehicle
->SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_UNK_24
);
19594 vehicle
->setFaction(getFaction());
19596 SetCharm(vehicle
); // charm
19597 SetFarSightGUID(vehicle
->GetGUID()); // set view
19599 SetClientControl(vehicle
, 1); // redirect controls to vehicle
19601 WorldPacket
data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA
, 0);
19602 GetSession()->SendPacket(&data
);
19604 data
.Initialize(MSG_MOVE_TELEPORT_ACK
, 30);
19605 data
.append(GetPackGUID());
19606 data
<< uint32(0); // counter?
19607 data
<< uint32(MOVEMENTFLAG_ONTRANSPORT
); // transport
19608 data
<< uint16(0); // special flags
19609 data
<< uint32(getMSTime()); // time
19610 data
<< vehicle
->GetPositionX(); // x
19611 data
<< vehicle
->GetPositionY(); // y
19612 data
<< vehicle
->GetPositionZ(); // z
19613 data
<< vehicle
->GetOrientation(); // o
19614 // transport part, TODO: load/calculate seat offsets
19615 data
<< uint64(vehicle
->GetGUID()); // transport guid
19616 data
<< float(veSeat
->m_attachmentOffsetX
); // transport offsetX
19617 data
<< float(veSeat
->m_attachmentOffsetY
); // transport offsetY
19618 data
<< float(veSeat
->m_attachmentOffsetZ
); // transport offsetZ
19619 data
<< float(0); // transport orientation
19620 data
<< uint32(getMSTime()); // transport time
19621 data
<< uint8(0); // seat
19622 // end of transport part
19623 data
<< uint32(0); // fall time
19624 GetSession()->SendPacket(&data
);
19626 data
.Initialize(SMSG_PET_SPELLS
, 8+4+4+4+4*10+1+1);
19627 data
<< uint64(vehicle
->GetGUID());
19628 data
<< uint32(0x00000000);
19629 data
<< uint32(0x00000000);
19630 data
<< uint32(0x00000101);
19632 for(uint32 i
= 0; i
< 10; ++i
)
19633 data
<< uint16(0) << uint8(0) << uint8(i
+8);
19637 GetSession()->SendPacket(&data
);
19640 void Player::ExitVehicle(Vehicle
*vehicle
)
19642 vehicle
->SetCharmerGUID(0);
19643 vehicle
->SetFlag(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_SPELLCLICK
);
19644 vehicle
->RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_UNK_24
);
19645 vehicle
->setFaction((GetTeam() == ALLIANCE
) ? vehicle
->GetCreatureInfo()->faction_A
: vehicle
->GetCreatureInfo()->faction_H
);
19648 SetFarSightGUID(0);
19650 SetClientControl(vehicle
, 0);
19652 WorldPacket
data(MSG_MOVE_TELEPORT_ACK
, 30);
19653 data
.append(GetPackGUID());
19654 data
<< uint32(0); // counter?
19655 data
<< uint32(MOVEMENTFLAG_FLY_UNK1
); // fly unk
19656 data
<< uint16(0x40); // special flags
19657 data
<< uint32(getMSTime()); // time
19658 data
<< vehicle
->GetPositionX(); // x
19659 data
<< vehicle
->GetPositionY(); // y
19660 data
<< vehicle
->GetPositionZ(); // z
19661 data
<< vehicle
->GetOrientation(); // o
19662 data
<< uint32(0); // fall time
19663 GetSession()->SendPacket(&data
);
19665 data
.Initialize(SMSG_PET_SPELLS
, 8+4);
19668 GetSession()->SendPacket(&data
);
19670 // only for flyable vehicles?
19671 CastSpell(this, 45472, true); // Parachute
19674 bool Player::HasTitle(uint32 bitIndex
)
19676 if (bitIndex
> 128)
19679 uint32 fieldIndexOffset
= bitIndex
/32;
19680 uint32 flag
= 1 << (bitIndex
%32);
19681 return HasFlag(PLAYER__FIELD_KNOWN_TITLES
+fieldIndexOffset
, flag
);
19684 void Player::SetTitle(CharTitlesEntry
const* title
)
19686 uint32 fieldIndexOffset
= title
->bit_index
/32;
19687 uint32 flag
= 1 << (title
->bit_index
%32);
19688 SetFlag(PLAYER__FIELD_KNOWN_TITLES
+fieldIndexOffset
, flag
);
19691 void Player::ConvertRune(uint8 index
, uint8 newType
)
19693 SetCurrentRune(index
, newType
);
19695 WorldPacket
data(SMSG_CONVERT_RUNE
, 2);
19696 data
<< uint8(index
);
19697 data
<< uint8(newType
);
19698 GetSession()->SendPacket(&data
);
19701 void Player::ResyncRunes(uint8 count
)
19703 WorldPacket
data(SMSG_RESYNC_RUNES
, count
* 2);
19704 for(uint32 i
= 0; i
< count
; ++i
)
19706 data
<< uint8(GetCurrentRune(i
)); // rune type
19707 data
<< uint8(255 - (GetRuneCooldown(i
) * 51)); // passed cooldown time (0-255)
19709 GetSession()->SendPacket(&data
);
19712 void Player::AddRunePower(uint8 index
)
19714 WorldPacket
data(SMSG_ADD_RUNE_POWER
, 4);
19715 data
<< uint32(1 << index
); // mask (0x00-0x3F probably)
19716 GetSession()->SendPacket(&data
);
19719 void Player::InitRunes()
19721 if(getClass() != CLASS_DEATH_KNIGHT
)
19724 m_runes
= new Runes
;
19726 m_runes
->runeState
= 0;
19728 for(uint32 i
= 0; i
< MAX_RUNES
; ++i
)
19730 SetBaseRune(i
, i
/ 2); // init base types
19731 SetCurrentRune(i
, i
/ 2); // init current types
19732 SetRuneCooldown(i
, 0); // reset cooldowns
19733 m_runes
->SetRuneState(i
);
19736 for(uint32 i
= 0; i
< NUM_RUNE_TYPES
; ++i
)
19737 SetFloatValue(PLAYER_RUNE_REGEN_1
+ i
, 0.1f
);
19740 void Player::AutoStoreLoot(uint8 bag
, uint8 slot
, uint32 loot_id
, LootStore
const& store
, bool broadcast
)
19743 loot
.FillLoot (loot_id
,store
,this,true);
19745 uint32 max_slot
= loot
.GetMaxSlotInLootFor(this);
19746 for(uint32 i
= 0; i
< max_slot
; ++i
)
19748 LootItem
* lootItem
= loot
.LootItemInSlot(i
,this);
19750 ItemPosCountVec dest
;
19751 uint8 msg
= CanStoreNewItem (bag
,slot
,dest
,lootItem
->itemid
,lootItem
->count
);
19752 if(msg
!= EQUIP_ERR_OK
&& slot
!= NULL_SLOT
)
19753 msg
= CanStoreNewItem( bag
, NULL_SLOT
,dest
,lootItem
->itemid
,lootItem
->count
);
19754 if( msg
!= EQUIP_ERR_OK
&& bag
!= NULL_BAG
)
19755 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
,dest
,lootItem
->itemid
,lootItem
->count
);
19756 if(msg
!= EQUIP_ERR_OK
)
19758 SendEquipError( msg
, NULL
, NULL
);
19762 Item
* pItem
= StoreNewItem (dest
,lootItem
->itemid
,true,lootItem
->randomPropertyId
);
19763 SendNewItem(pItem
, lootItem
->count
, false, false, broadcast
);
19767 uint32
Player::CalculateTalentsPoints() const
19769 uint32 base_talent
= getLevel() < 10 ? 0 : uint32((getLevel()-9)*sWorld
.getRate(RATE_TALENT
));
19771 if(getClass() != CLASS_DEATH_KNIGHT
)
19772 return base_talent
;
19774 uint32 talentPointsForLevel
=
19775 (getLevel() < 56 ? 0 : uint32((getLevel()-55)*sWorld
.getRate(RATE_TALENT
)))
19776 + m_questRewardTalentCount
;
19778 if(talentPointsForLevel
> base_talent
)
19779 talentPointsForLevel
= base_talent
;
19781 return talentPointsForLevel
;
19784 bool Player::IsAllowUseFlyMountsHere() const
19786 if (isGameMaster())
19789 uint32 v_map
= GetVirtualMapForMapAndZone(GetMapId(), GetZoneId());
19790 return v_map
== 530 || v_map
== 571 && HasSpell(54197);
19793 void Player::learnSpellHighRank(uint32 spellid
)
19795 learnSpell(spellid
,false);
19797 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
19798 for(SpellChainMapNext::const_iterator itr
= nextMap
.lower_bound(spellid
); itr
!= nextMap
.upper_bound(spellid
); ++itr
)
19799 learnSpellHighRank(itr
->second
);
19802 void Player::_LoadSkills()
19804 // Note: skill data itself loaded from `data` field. This is only cleanup part of load
19806 // reset skill modifiers and set correct unlearn flags
19807 for (uint32 i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
19809 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
19811 // set correct unlearn bit
19812 uint32 id
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
19815 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
19816 if(!pSkill
) continue;
19818 // enable unlearn button for primary professions only
19819 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
19820 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
19822 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
19824 uint32 vskill
= SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
19826 learnSkillRewardedSpells(id
, vskill
);
19829 // special settings
19830 if(getClass()==CLASS_DEATH_KNIGHT
)
19832 uint32 base_level
= std::min(getLevel(),sWorld
.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL
));
19835 uint32 base_skill
= (base_level
-1)*5; // 270 at starting level 55
19837 base_skill
= 1; // skill mast be known and then > 0 in any case
19839 if(GetPureSkillValue (SKILL_FIRST_AID
) < base_skill
)
19840 SetSkill(SKILL_FIRST_AID
,base_skill
, base_skill
);
19841 if(GetPureSkillValue (SKILL_AXES
) < base_skill
)
19842 SetSkill(SKILL_AXES
, base_skill
,base_skill
);
19843 if(GetPureSkillValue (SKILL_DEFENSE
) < base_skill
)
19844 SetSkill(SKILL_DEFENSE
, base_skill
,base_skill
);
19845 if(GetPureSkillValue (SKILL_POLEARMS
) < base_skill
)
19846 SetSkill(SKILL_POLEARMS
, base_skill
,base_skill
);
19847 if(GetPureSkillValue (SKILL_SWORDS
) < base_skill
)
19848 SetSkill(SKILL_SWORDS
, base_skill
,base_skill
);
19849 if(GetPureSkillValue (SKILL_2H_AXES
) < base_skill
)
19850 SetSkill(SKILL_2H_AXES
, base_skill
,base_skill
);
19851 if(GetPureSkillValue (SKILL_2H_SWORDS
) < base_skill
)
19852 SetSkill(SKILL_2H_SWORDS
, base_skill
,base_skill
);
19853 if(GetPureSkillValue (SKILL_UNARMED
) < base_skill
)
19854 SetSkill(SKILL_UNARMED
, base_skill
,base_skill
);
19858 uint32
Player::GetPhaseMaskForSpawn() const
19860 uint32 phase
= PHASEMASK_NORMAL
;
19861 if(!isGameMaster())
19862 phase
= GetPhaseMask();
19865 AuraList
const& phases
= GetAurasByType(SPELL_AURA_PHASE
);
19866 if(!phases
.empty())
19867 phase
= phases
.front()->GetMiscValue();
19870 // some aura phases include 1 normal map in addition to phase itself
19871 if(uint32 n_phase
= phase
& ~PHASEMASK_NORMAL
)
19874 return PHASEMASK_NORMAL
;
19877 uint8
Player::CanEquipUniqueItem(Item
* pItem
, uint8 eslot
, uint32 limit_count
) const
19879 ItemPrototype
const* pProto
= pItem
->GetProto();
19881 // proto based limitations
19882 if(uint8 res
= CanEquipUniqueItem(pProto
,eslot
,limit_count
))
19885 // check unique-equipped on gems
19886 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
19888 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
19891 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
19895 ItemPrototype
const* pGem
= objmgr
.GetItemPrototype(enchantEntry
->GemID
);
19899 // include for check equip another gems with same limit category for not equipped item (and then not counted)
19900 uint32 gem_limit_count
= !pItem
->IsEquipped() && pGem
->ItemLimitCategory
19901 ? pItem
->GetGemCountWithLimitCategory(pGem
->ItemLimitCategory
) : 1;
19903 if(uint8 res
= CanEquipUniqueItem(pGem
, eslot
,gem_limit_count
))
19907 return EQUIP_ERR_OK
;
19910 uint8
Player::CanEquipUniqueItem( ItemPrototype
const* itemProto
, uint8 except_slot
, uint32 limit_count
) const
19912 // check unique-equipped on item
19913 if (itemProto
->Flags
& ITEM_FLAGS_UNIQUE_EQUIPPED
)
19915 // there is an equip limit on this item
19916 if(HasItemOrGemWithIdEquipped(itemProto
->ItemId
,1,except_slot
))
19917 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
19920 // check unique-equipped limit
19921 if (itemProto
->ItemLimitCategory
)
19923 ItemLimitCategoryEntry
const* limitEntry
= sItemLimitCategoryStore
.LookupEntry(itemProto
->ItemLimitCategory
);
19925 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
19927 if(limit_count
> limitEntry
->maxCount
)
19928 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
; // attempt add too many limit category items (gems)
19930 // there is an equip limit on this item
19931 if(HasItemOrGemWithLimitCategoryEquipped(itemProto
->ItemLimitCategory
,limitEntry
->maxCount
-limit_count
+1,except_slot
))
19932 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
19935 return EQUIP_ERR_OK
;
19938 void Player::HandleFall(MovementInfo
const& movementInfo
)
19940 // calculate total z distance of the fall
19941 float z_diff
= m_lastFallZ
- movementInfo
.z
;
19942 sLog
.outDebug("zDiff = %f", z_diff
);
19944 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
19945 // 14.57 can be calculated by resolving damageperc formular below to 0
19946 if (z_diff
>= 14.57f
&& !isDead() && !isGameMaster() &&
19947 !HasAuraType(SPELL_AURA_HOVER
) && !HasAuraType(SPELL_AURA_FEATHER_FALL
) &&
19948 !HasAuraType(SPELL_AURA_FLY
) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL
) )
19950 //Safe fall, fall height reduction
19951 int32 safe_fall
= GetTotalAuraModifier(SPELL_AURA_SAFE_FALL
);
19953 float damageperc
= 0.018f
*(z_diff
-safe_fall
)-0.2426f
;
19957 uint32 damage
= (uint32
)(damageperc
* GetMaxHealth()*sWorld
.getRate(RATE_DAMAGE_FALL
));
19959 float height
= movementInfo
.z
;
19960 UpdateGroundPositionZ(movementInfo
.x
,movementInfo
.y
,height
);
19964 //Prevent fall damage from being more than the player maximum health
19965 if (damage
> GetMaxHealth())
19966 damage
= GetMaxHealth();
19969 if (GetDummyAura(43621))
19970 damage
= GetMaxHealth()/2;
19972 EnvironmentalDamage(GetGUID(), DAMAGE_FALL
, damage
);
19974 // recheck alive, might have died of EnvironmentalDamage
19976 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING
, uint32(z_diff
*100));
19979 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
19980 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
);
19985 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type
, uint32 miscvalue1
/*=0*/, uint32 miscvalue2
/*=0*/, Unit
*unit
/*=NULL*/, uint32 time
/*=0*/ )
19987 GetAchievementMgr().UpdateAchievementCriteria(type
, miscvalue1
,miscvalue2
,unit
,time
);