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 enum CharacterCustomizeFlags
117 CHAR_CUSTOMIZE_FLAG_NONE
= 0x00000000,
118 CHAR_CUSTOMIZE_FLAG_CUSTOMIZE
= 0x00000001, // name, gender, etc...
119 CHAR_CUSTOMIZE_FLAG_FACTION
= 0x00010000, // name, gender, faction, etc...
120 CHAR_CUSTOMIZE_FLAG_RACE
= 0x00100000 // name, gender, race, etc...
123 // corpse reclaim times
124 #define DEATH_EXPIRE_STEP (5*MINUTE)
125 #define MAX_DEATH_COUNT 3
127 static uint32 copseReclaimDelay
[MAX_DEATH_COUNT
] = { 30, 60, 120 };
129 //== PlayerTaxi ================================================
131 PlayerTaxi::PlayerTaxi()
134 memset(m_taximask
, 0, sizeof(m_taximask
));
137 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race
, uint32 chrClass
, uint32 level
)
139 // class specific initial known nodes
142 case CLASS_DEATH_KNIGHT
:
144 for(int i
= 0; i
< TaxiMaskSize
; ++i
)
145 m_taximask
[i
] |= sOldContinentsNodesMask
[i
];
150 // race specific initial known nodes: capital and taxi hub masks
153 case RACE_HUMAN
: SetTaximaskNode(2); break; // Human
154 case RACE_ORC
: SetTaximaskNode(23); break; // Orc
155 case RACE_DWARF
: SetTaximaskNode(6); break; // Dwarf
156 case RACE_NIGHTELF
: SetTaximaskNode(26);
157 SetTaximaskNode(27); break; // Night Elf
158 case RACE_UNDEAD_PLAYER
: SetTaximaskNode(11); break;// Undead
159 case RACE_TAUREN
: SetTaximaskNode(22); break; // Tauren
160 case RACE_GNOME
: SetTaximaskNode(6); break; // Gnome
161 case RACE_TROLL
: SetTaximaskNode(23); break; // Troll
162 case RACE_BLOODELF
: SetTaximaskNode(82); break; // Blood Elf
163 case RACE_DRAENEI
: SetTaximaskNode(94); break; // Draenei
166 // new continent starting masks (It will be accessible only at new map)
167 switch(Player::TeamForRace(race
))
169 case ALLIANCE
: SetTaximaskNode(100); break;
170 case HORDE
: SetTaximaskNode(99); break;
172 // level dependent taxi hubs
174 SetTaximaskNode(213); //Shattered Sun Staging Area
177 void PlayerTaxi::LoadTaxiMask(const char* data
)
179 Tokens tokens
= StrSplit(data
, " ");
182 Tokens::iterator iter
;
183 for (iter
= tokens
.begin(), index
= 0;
184 (index
< TaxiMaskSize
) && (iter
!= tokens
.end()); ++iter
, ++index
)
186 // load and set bits only for existed taxi nodes
187 m_taximask
[index
] = sTaxiNodesMask
[index
] & uint32(atol((*iter
).c_str()));
191 void PlayerTaxi::AppendTaximaskTo( ByteBuffer
& data
, bool all
)
195 for (uint8 i
=0; i
<TaxiMaskSize
; ++i
)
196 data
<< uint32(sTaxiNodesMask
[i
]); // all existed nodes
200 for (uint8 i
=0; i
<TaxiMaskSize
; ++i
)
201 data
<< uint32(m_taximask
[i
]); // known nodes
205 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string
& values
, uint32 team
)
207 ClearTaxiDestinations();
209 Tokens tokens
= StrSplit(values
," ");
211 for(Tokens::iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
)
213 uint32 node
= uint32(atol(iter
->c_str()));
214 AddTaxiDestination(node
);
217 if(m_TaxiDestinations
.empty())
221 if(m_TaxiDestinations
.size() < 2)
224 for(size_t i
= 1; i
< m_TaxiDestinations
.size(); ++i
)
228 objmgr
.GetTaxiPath(m_TaxiDestinations
[i
-1],m_TaxiDestinations
[i
],path
,cost
);
233 // can't load taxi path without mount set (quest taxi path?)
234 if(!objmgr
.GetTaxiMountDisplayId(GetTaxiSource(),team
,true))
240 std::string
PlayerTaxi::SaveTaxiDestinationsToString()
242 if(m_TaxiDestinations
.empty())
245 std::ostringstream ss
;
247 for(size_t i
=0; i
< m_TaxiDestinations
.size(); ++i
)
248 ss
<< m_TaxiDestinations
[i
] << " ";
253 uint32
PlayerTaxi::GetCurrentTaxiPath() const
255 if(m_TaxiDestinations
.size() < 2)
261 objmgr
.GetTaxiPath(m_TaxiDestinations
[0],m_TaxiDestinations
[1],path
,cost
);
266 std::ostringstream
& operator<< (std::ostringstream
& ss
, PlayerTaxi
const& taxi
)
269 for(int i
= 0; i
< TaxiMaskSize
; ++i
)
270 ss
<< taxi
.m_taximask
[i
] << " ";
275 //== Player ====================================================
277 UpdateMask
Player::updateVisualBits
;
279 Player::Player (WorldSession
*session
): Unit(), m_achievementMgr(this), m_reputationMgr(this)
286 m_objectType
|= TYPEMASK_PLAYER
;
287 m_objectTypeId
= TYPEID_PLAYER
;
289 m_valuesCount
= PLAYER_END
;
296 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER
)
297 SetAcceptTicket(true);
299 // players always accept
300 if(GetSession()->GetSecurity() == SEC_PLAYER
)
301 SetAcceptWhispers(true);
309 m_usedTalentCount
= 0;
310 m_questRewardTalentCount
= 0;
313 m_weaponChangeTimer
= 0;
316 m_zoneUpdateTimer
= 0;
320 m_nextSave
= sWorld
.getConfig(CONFIG_INTERVAL_SAVE
);
322 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
323 // this must help in case next save after mass player load after server startup
324 m_nextSave
= urand(m_nextSave
/2,m_nextSave
*3/2);
326 clearResurrectRequestData();
328 m_SpellModRemoveCount
= 0;
330 memset(m_items
, 0, sizeof(Item
*)*PLAYER_SLOTS_COUNT
);
334 // group is initialized in the reference constructor
335 SetGroupInvite(NULL
);
336 m_groupUpdateMask
= 0;
337 m_auraUpdateMask
= 0;
341 m_GuildIdInvited
= 0;
342 m_ArenaTeamIdInvited
= 0;
344 m_atLoginFlags
= AT_LOGIN_NONE
;
346 mSemaphoreTeleport_Near
= false;
347 mSemaphoreTeleport_Far
= false;
349 m_DelayedOperations
= 0;
350 m_bCanDelayTeleport
= false;
351 m_bHasDelayedTeleport
= false;
352 m_teleport_options
= 0;
359 PlayerTalkClass
= new PlayerMenu( GetSession() );
360 m_currentBuybackSlot
= BUYBACK_SLOT_START
;
362 m_DailyQuestChanged
= false;
363 m_lastDailyQuestTime
= 0;
365 for (int i
=0; i
<MAX_TIMERS
; ++i
)
366 m_MirrorTimer
[i
] = DISABLED_MIRROR_TIMER
;
368 m_MirrorTimerFlags
= UNDERWATER_NONE
;
369 m_MirrorTimerFlagsLast
= UNDERWATER_NONE
;
375 m_deathExpireTime
= 0;
379 m_DetectInvTimer
= 1*IN_MILISECONDS
;
381 for (int j
=0; j
< PLAYER_MAX_BATTLEGROUND_QUEUES
; ++j
)
383 m_bgBattleGroundQueueID
[j
].bgQueueTypeId
= BATTLEGROUND_QUEUE_NONE
;
384 m_bgBattleGroundQueueID
[j
].invitedToInstance
= 0;
387 m_logintime
= time(NULL
);
388 m_Last_tick
= m_logintime
;
389 m_WeaponProficiency
= 0;
390 m_ArmorProficiency
= 0;
393 m_canDualWield
= false;
394 m_canTitanGrip
= false;
397 m_temporaryUnsummonedPetNumber
= 0;
398 //cache for UNIT_CREATED_BY_SPELL to allow
399 //returning reagents for temporarily removed pets
400 //when dying/logging out
403 ////////////////////Rest System/////////////////////
410 rest_type
=REST_TYPE_NO
;
411 ////////////////////Rest System/////////////////////
413 m_mailsLoaded
= false;
414 m_mailsUpdated
= false;
416 m_nextMailDelivereTime
= 0;
418 m_resetTalentsCost
= 0;
419 m_resetTalentsTime
= 0;
420 m_itemUpdateQueueBlocked
= false;
422 for (int i
= 0; i
< MAX_MOVE_TYPE
; ++i
)
423 m_forced_speed_changes
[i
] = 0;
427 /////////////////// Instance System /////////////////////
430 m_InstanceValid
= true;
431 m_dungeonDifficulty
= DUNGEON_DIFFICULTY_NORMAL
;
432 m_raidDifficulty
= RAID_DIFFICULTY_10MAN_NORMAL
;
439 for (int i
= 0; i
< BASEMOD_END
; ++i
)
441 m_auraBaseMod
[i
][FLAT_MOD
] = 0.0f
;
442 m_auraBaseMod
[i
][PCT_MOD
] = 1.0f
;
445 for (int i
= 0; i
< MAX_COMBAT_RATING
; ++i
)
446 m_baseRatingValue
[i
] = 0;
448 m_baseSpellPower
= 0;
451 m_armorPenetrationPct
= 0.0f
;
454 m_lastHonorUpdateTime
= time(NULL
);
466 m_contestedPvPTimer
= 0;
468 m_declinedname
= NULL
;
477 CleanupsBeforeDelete();
479 // it must be unloaded already in PlayerLogout and accessed only for loggined player
482 // Note: buy back item already deleted from DB when player was saved
483 for(int i
= 0; i
< PLAYER_SLOTS_COUNT
; ++i
)
490 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
493 //all mailed items should be deleted, also all mail should be deallocated
494 for (PlayerMails::const_iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
497 for (ItemMap::const_iterator iter
= mMitems
.begin(); iter
!= mMitems
.end(); ++iter
)
498 delete iter
->second
; //if item is duplicated... then server may crash ... but that item should be deallocated
500 delete PlayerTalkClass
;
504 m_transport
->RemovePassenger(this);
507 for(size_t x
= 0; x
< ItemSetEff
.size(); x
++)
509 delete ItemSetEff
[x
];
511 // clean up player-instance binds, may unload some instance saves
512 for(uint8 i
= 0; i
< MAX_DIFFICULTY
; ++i
)
513 for(BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
514 itr
->second
.save
->RemovePlayer(this);
516 delete m_declinedname
;
520 void Player::CleanupsBeforeDelete()
522 if(m_uint32Values
) // only for fully created Object
525 DuelComplete(DUEL_INTERUPTED
);
527 Unit::CleanupsBeforeDelete();
530 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
)
532 //FIXME: outfitId not used in player creating
534 Object::_Create(guidlow
, 0, HIGHGUID_PLAYER
);
538 PlayerInfo
const* info
= objmgr
.GetPlayerInfo(race
, class_
);
541 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
545 for (int i
= 0; i
< PLAYER_SLOTS_COUNT
; ++i
)
548 SetLocationMapId(info
->mapId
);
549 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
);
551 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(class_
);
554 sLog
.outError("Class %u not found in DBC (Wrong DBC files?)",class_
);
558 SetMap(MapManager::Instance().CreateMap(info
->mapId
, this));
560 uint8 powertype
= cEntry
->powerType
;
562 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, DEFAULT_WORLD_OBJECT_SIZE
);
563 SetFloatValue(UNIT_FIELD_COMBATREACH
, 1.5f
);
565 setFactionForRace(race
);
567 uint32 RaceClassGender
= ( race
) | ( class_
<< 8 ) | ( gender
<< 16 );
569 SetUInt32Value(UNIT_FIELD_BYTES_0
, ( RaceClassGender
| ( powertype
<< 24 ) ) );
571 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_PVP
);
572 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
);
573 SetFlag(UNIT_FIELD_FLAGS_2
, UNIT_FLAG2_REGENERATE_POWER
);
574 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
); // fix cast time showed in spell tooltip on client
575 SetFloatValue(UNIT_FIELD_HOVERHEIGHT
, 1.0f
); // default for players in 3.0.3
577 // -1 is default value
578 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX
, uint32(-1));
580 SetUInt32Value(PLAYER_BYTES
, (skin
| (face
<< 8) | (hairStyle
<< 16) | (hairColor
<< 24)));
581 SetUInt32Value(PLAYER_BYTES_2
, (facialHair
| (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
582 SetByteValue(PLAYER_BYTES_3
, 0, gender
);
584 SetUInt32Value( PLAYER_GUILDID
, 0 );
585 SetUInt32Value( PLAYER_GUILDRANK
, 0 );
586 SetUInt32Value( PLAYER_GUILD_TIMESTAMP
, 0 );
588 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES
, 0 ); // 0=disabled
589 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1
, 0 ); // 0=disabled
590 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES2
, 0 ); // 0=disabled
591 SetUInt32Value( PLAYER_CHOSEN_TITLE
, 0 );
592 SetUInt32Value( PLAYER_FIELD_KILLS
, 0 );
593 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 0 );
594 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION
, 0 );
595 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0 );
597 // set starting level
598 uint32 start_level
= getClass() != CLASS_DEATH_KNIGHT
599 ? sWorld
.getConfig(CONFIG_START_PLAYER_LEVEL
)
600 : sWorld
.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL
);
602 if (GetSession()->GetSecurity() >= SEC_MODERATOR
)
604 uint32 gm_level
= sWorld
.getConfig(CONFIG_START_GM_LEVEL
);
605 if(gm_level
> start_level
)
606 start_level
= gm_level
;
609 SetUInt32Value(UNIT_FIELD_LEVEL
, start_level
);
613 SetUInt32Value (PLAYER_FIELD_COINAGE
, sWorld
.getConfig(CONFIG_START_PLAYER_MONEY
));
614 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_START_HONOR_POINTS
));
615 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_START_ARENA_POINTS
));
618 m_Last_tick
= time(NULL
);
619 m_Played_time
[PLAYED_TIME_TOTAL
] = 0;
620 m_Played_time
[PLAYED_TIME_LEVEL
] = 0;
622 // base stats and related field values
624 InitTaxiNodesForLevel();
625 InitGlyphsForLevel();
626 InitTalentForLevel();
627 InitPrimaryProfessions(); // to max set before any spell added
629 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
630 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
631 SetHealth(GetMaxHealth());
632 if (getPowerType()==POWER_MANA
)
634 UpdateMaxPower(POWER_MANA
); // Update max Mana (for add bonus from intellect)
635 SetPower(POWER_MANA
,GetMaxPower(POWER_MANA
));
638 if(getPowerType() == POWER_RUNIC_POWER
)
640 SetPower(POWER_RUNE
, 8);
641 SetMaxPower(POWER_RUNE
, 8);
642 SetPower(POWER_RUNIC_POWER
, 0);
643 SetMaxPower(POWER_RUNIC_POWER
, 1000);
647 learnDefaultSpells();
649 // original action bar
650 for (PlayerCreateInfoActions::const_iterator action_itr
= info
->action
.begin(); action_itr
!= info
->action
.end(); ++action_itr
)
651 addActionButton(action_itr
->button
,action_itr
->action
,action_itr
->type
);
654 CharStartOutfitEntry
const* oEntry
= NULL
;
655 for (uint32 i
= 1; i
< sCharStartOutfitStore
.GetNumRows(); ++i
)
657 if(CharStartOutfitEntry
const* entry
= sCharStartOutfitStore
.LookupEntry(i
))
659 if(entry
->RaceClassGender
== RaceClassGender
)
669 for(int j
= 0; j
< MAX_OUTFIT_ITEMS
; ++j
)
671 if(oEntry
->ItemId
[j
] <= 0)
674 uint32 item_id
= oEntry
->ItemId
[j
];
676 // Hack for not existed item id in dbc 3.0.3
680 ItemPrototype
const* iProto
= objmgr
.GetItemPrototype(item_id
);
683 sLog
.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id
,getRace(),getClass());
687 // BuyCount by default
688 uint32 count
= iProto
->BuyCount
;
690 // special amount for foor/drink
691 if(iProto
->Class
==ITEM_CLASS_CONSUMABLE
&& iProto
->SubClass
==ITEM_SUBCLASS_FOOD
)
693 switch(iProto
->Spells
[0].SpellCategory
)
696 count
= getClass()==CLASS_DEATH_KNIGHT
? 10 : 4;
702 if(iProto
->Stackable
< count
)
703 count
= iProto
->Stackable
;
706 StoreNewItemInBestSlots(item_id
, count
);
710 for (PlayerCreateInfoItems::const_iterator item_id_itr
= info
->item
.begin(); item_id_itr
!=info
->item
.end(); ++item_id_itr
++)
711 StoreNewItemInBestSlots(item_id_itr
->item_id
, item_id_itr
->item_amount
);
713 // bags and main-hand weapon must equipped at this moment
714 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
715 // or ammo not equipped in special bag
716 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
718 if(Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
721 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
722 uint8 msg
= CanEquipItem( NULL_SLOT
, eDest
, pItem
, false );
723 if( msg
== EQUIP_ERR_OK
)
725 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
726 EquipItem( eDest
, pItem
, true);
728 // move other items to more appropriate slots (ammo not equipped in special bag)
731 ItemPosCountVec sDest
;
732 msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, sDest
, pItem
, false );
733 if( msg
== EQUIP_ERR_OK
)
735 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
736 pItem
= StoreItem( sDest
, pItem
, true);
739 // if this is ammo then use it
740 msg
= CanUseAmmo( pItem
->GetEntry() );
741 if( msg
== EQUIP_ERR_OK
)
742 SetAmmo( pItem
->GetEntry() );
746 // all item positions resolved
751 bool Player::StoreNewItemInBestSlots(uint32 titem_id
, uint32 titem_amount
)
753 sLog
.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id
, titem_amount
);
755 // attempt equip by one
756 while(titem_amount
> 0)
759 uint8 msg
= CanEquipNewItem( NULL_SLOT
, eDest
, titem_id
, false );
760 if( msg
!= EQUIP_ERR_OK
)
763 EquipNewItem( eDest
, titem_id
, true);
764 AutoUnequipOffhandIfNeed();
768 if(titem_amount
== 0)
769 return true; // equipped
772 ItemPosCountVec sDest
;
773 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
774 uint8 msg
= CanStoreNewItem( INVENTORY_SLOT_BAG_0
, NULL_SLOT
, sDest
, titem_id
, titem_amount
);
775 if( msg
== EQUIP_ERR_OK
)
777 StoreNewItem( sDest
, titem_id
, true, Item::GenerateItemRandomPropertyId(titem_id
) );
778 return true; // stored
781 // item can't be added
782 sLog
.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id
,getRace(),getClass(),msg
);
786 void Player::SendMirrorTimer(MirrorTimerType Type
, uint32 MaxValue
, uint32 CurrentValue
, int32 Regen
)
788 if (int(MaxValue
) == DISABLED_MIRROR_TIMER
)
790 if (int(CurrentValue
) != DISABLED_MIRROR_TIMER
)
791 StopMirrorTimer(Type
);
794 WorldPacket
data(SMSG_START_MIRROR_TIMER
, (21));
795 data
<< (uint32
)Type
;
796 data
<< CurrentValue
;
800 data
<< (uint32
)0; // spell id
801 GetSession()->SendPacket( &data
);
804 void Player::StopMirrorTimer(MirrorTimerType Type
)
806 m_MirrorTimer
[Type
] = DISABLED_MIRROR_TIMER
;
807 WorldPacket
data(SMSG_STOP_MIRROR_TIMER
, 4);
808 data
<< (uint32
)Type
;
809 GetSession()->SendPacket( &data
);
812 uint32
Player::EnvironmentalDamage(EnviromentalDamage type
, uint32 damage
)
814 if(!isAlive() || isGameMaster())
817 // Absorb, resist some environmental damage type
820 if (type
== DAMAGE_LAVA
)
821 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE
, DIRECT_DAMAGE
, damage
, &absorb
, &resist
);
822 else if (type
== DAMAGE_SLIME
)
823 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE
, DIRECT_DAMAGE
, damage
, &absorb
, &resist
);
825 damage
-=absorb
+resist
;
827 DealDamageMods(this,damage
,&absorb
);
829 WorldPacket
data(SMSG_ENVIRONMENTALDAMAGELOG
, (21));
830 data
<< uint64(GetGUID());
831 data
<< uint8(type
!=DAMAGE_FALL_TO_VOID
? type
: DAMAGE_FALL
);
832 data
<< uint32(damage
);
833 data
<< uint32(absorb
);
834 data
<< uint32(resist
);
835 SendMessageToSet(&data
, true);
837 uint32 final_damage
= DealDamage(this, damage
, NULL
, SELF_DAMAGE
, SPELL_SCHOOL_MASK_NORMAL
, NULL
, false);
841 if(type
==DAMAGE_FALL
) // DealDamage not apply item durability loss at self damage
843 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
844 DurabilityLossAll(0.10f
,false);
845 // durability lost message
846 WorldPacket
data2(SMSG_DURABILITY_DAMAGE_DEATH
, 0);
847 GetSession()->SendPacket(&data2
);
850 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM
, 1, type
);
856 int32
Player::getMaxTimer(MirrorTimerType timer
)
861 return MINUTE
*IN_MILISECONDS
;
864 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING
) || GetSession()->GetSecurity() >= sWorld
.getConfig(CONFIG_DISABLE_BREATHING
))
865 return DISABLED_MIRROR_TIMER
;
866 int32 UnderWaterTime
= 3*MINUTE
*IN_MILISECONDS
;
867 AuraList
const& mModWaterBreathing
= GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING
);
868 for(AuraList::const_iterator i
= mModWaterBreathing
.begin(); i
!= mModWaterBreathing
.end(); ++i
)
869 UnderWaterTime
= uint32(UnderWaterTime
* (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
);
870 return UnderWaterTime
;
875 return DISABLED_MIRROR_TIMER
;
876 return 1*IN_MILISECONDS
;
884 void Player::UpdateMirrorTimers()
886 // Desync flags for update on next HandleDrowning
887 if (m_MirrorTimerFlags
)
888 m_MirrorTimerFlagsLast
= ~m_MirrorTimerFlags
;
891 void Player::HandleDrowning(uint32 time_diff
)
893 if (!m_MirrorTimerFlags
)
897 if (m_MirrorTimerFlags
& UNDERWATER_INWATER
)
899 // Breath timer not activated - activate it
900 if (m_MirrorTimer
[BREATH_TIMER
] == DISABLED_MIRROR_TIMER
)
902 m_MirrorTimer
[BREATH_TIMER
] = getMaxTimer(BREATH_TIMER
);
903 SendMirrorTimer(BREATH_TIMER
, m_MirrorTimer
[BREATH_TIMER
], m_MirrorTimer
[BREATH_TIMER
], -1);
905 else // If activated - do tick
907 m_MirrorTimer
[BREATH_TIMER
]-=time_diff
;
908 // Timer limit - need deal damage
909 if (m_MirrorTimer
[BREATH_TIMER
] < 0)
911 m_MirrorTimer
[BREATH_TIMER
]+= 1*IN_MILISECONDS
;
912 // Calculate and deal damage
913 // TODO: Check this formula
914 uint32 damage
= GetMaxHealth() / 5 + urand(0, getLevel()-1);
915 EnvironmentalDamage(DAMAGE_DROWNING
, damage
);
917 else if (!(m_MirrorTimerFlagsLast
& UNDERWATER_INWATER
)) // Update time in client if need
918 SendMirrorTimer(BREATH_TIMER
, getMaxTimer(BREATH_TIMER
), m_MirrorTimer
[BREATH_TIMER
], -1);
921 else if (m_MirrorTimer
[BREATH_TIMER
] != DISABLED_MIRROR_TIMER
) // Regen timer
923 int32 UnderWaterTime
= getMaxTimer(BREATH_TIMER
);
925 m_MirrorTimer
[BREATH_TIMER
]+=10*time_diff
;
926 if (m_MirrorTimer
[BREATH_TIMER
] >= UnderWaterTime
|| !isAlive())
927 StopMirrorTimer(BREATH_TIMER
);
928 else if (m_MirrorTimerFlagsLast
& UNDERWATER_INWATER
)
929 SendMirrorTimer(BREATH_TIMER
, UnderWaterTime
, m_MirrorTimer
[BREATH_TIMER
], 10);
933 if (m_MirrorTimerFlags
& UNDERWARER_INDARKWATER
)
935 // Fatigue timer not activated - activate it
936 if (m_MirrorTimer
[FATIGUE_TIMER
] == DISABLED_MIRROR_TIMER
)
938 m_MirrorTimer
[FATIGUE_TIMER
] = getMaxTimer(FATIGUE_TIMER
);
939 SendMirrorTimer(FATIGUE_TIMER
, m_MirrorTimer
[FATIGUE_TIMER
], m_MirrorTimer
[FATIGUE_TIMER
], -1);
943 m_MirrorTimer
[FATIGUE_TIMER
]-=time_diff
;
944 // Timer limit - need deal damage or teleport ghost to graveyard
945 if (m_MirrorTimer
[FATIGUE_TIMER
] < 0)
947 m_MirrorTimer
[FATIGUE_TIMER
]+= 1*IN_MILISECONDS
;
948 if (isAlive()) // Calculate and deal damage
950 uint32 damage
= GetMaxHealth() / 5 + urand(0, getLevel()-1);
951 EnvironmentalDamage(DAMAGE_EXHAUSTED
, damage
);
953 else if (HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
)) // Teleport ghost to graveyard
956 else if (!(m_MirrorTimerFlagsLast
& UNDERWARER_INDARKWATER
))
957 SendMirrorTimer(FATIGUE_TIMER
, getMaxTimer(FATIGUE_TIMER
), m_MirrorTimer
[FATIGUE_TIMER
], -1);
960 else if (m_MirrorTimer
[FATIGUE_TIMER
] != DISABLED_MIRROR_TIMER
) // Regen timer
962 int32 DarkWaterTime
= getMaxTimer(FATIGUE_TIMER
);
963 m_MirrorTimer
[FATIGUE_TIMER
]+=10*time_diff
;
964 if (m_MirrorTimer
[FATIGUE_TIMER
] >= DarkWaterTime
|| !isAlive())
965 StopMirrorTimer(FATIGUE_TIMER
);
966 else if (m_MirrorTimerFlagsLast
& UNDERWARER_INDARKWATER
)
967 SendMirrorTimer(FATIGUE_TIMER
, DarkWaterTime
, m_MirrorTimer
[FATIGUE_TIMER
], 10);
970 if (m_MirrorTimerFlags
& (UNDERWATER_INLAVA
|UNDERWATER_INSLIME
))
972 // Breath timer not activated - activate it
973 if (m_MirrorTimer
[FIRE_TIMER
] == DISABLED_MIRROR_TIMER
)
974 m_MirrorTimer
[FIRE_TIMER
] = getMaxTimer(FIRE_TIMER
);
977 m_MirrorTimer
[FIRE_TIMER
]-=time_diff
;
978 if (m_MirrorTimer
[FIRE_TIMER
] < 0)
980 m_MirrorTimer
[FIRE_TIMER
]+= 1*IN_MILISECONDS
;
981 // Calculate and deal damage
982 // TODO: Check this formula
983 uint32 damage
= urand(600, 700);
984 if (m_MirrorTimerFlags
&UNDERWATER_INLAVA
)
985 EnvironmentalDamage(DAMAGE_LAVA
, damage
);
987 EnvironmentalDamage(DAMAGE_SLIME
, damage
);
992 m_MirrorTimer
[FIRE_TIMER
] = DISABLED_MIRROR_TIMER
;
994 // Recheck timers flag
995 m_MirrorTimerFlags
&=~UNDERWATER_EXIST_TIMERS
;
996 for (int i
= 0; i
< MAX_TIMERS
; ++i
)
997 if (m_MirrorTimer
[i
]!=DISABLED_MIRROR_TIMER
)
999 m_MirrorTimerFlags
|=UNDERWATER_EXIST_TIMERS
;
1002 m_MirrorTimerFlagsLast
= m_MirrorTimerFlags
;
1005 ///The player sobers by 256 every 10 seconds
1006 void Player::HandleSobering()
1010 uint32 drunk
= (m_drunk
<= 256) ? 0 : (m_drunk
- 256);
1011 SetDrunkValue(drunk
);
1014 DrunkenState
Player::GetDrunkenstateByValue(uint16 value
)
1017 return DRUNKEN_SMASHED
;
1019 return DRUNKEN_DRUNK
;
1021 return DRUNKEN_TIPSY
;
1022 return DRUNKEN_SOBER
;
1025 void Player::SetDrunkValue(uint16 newDrunkenValue
, uint32 itemId
)
1027 uint32 oldDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
1029 m_drunk
= newDrunkenValue
;
1030 SetUInt32Value(PLAYER_BYTES_3
,(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFF0001) | (m_drunk
& 0xFFFE));
1032 uint32 newDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
1034 // special drunk invisibility detection
1035 if(newDrunkenState
>= DRUNKEN_DRUNK
)
1036 m_detectInvisibilityMask
|= (1<<6);
1038 m_detectInvisibilityMask
&= ~(1<<6);
1040 if(newDrunkenState
== oldDrunkenState
)
1043 WorldPacket
data(SMSG_CROSSED_INEBRIATION_THRESHOLD
, (8+4+4));
1044 data
<< uint64(GetGUID());
1045 data
<< uint32(newDrunkenState
);
1046 data
<< uint32(itemId
);
1048 SendMessageToSet(&data
, true);
1051 void Player::Update( uint32 p_time
)
1057 if(m_nextMailDelivereTime
&& m_nextMailDelivereTime
<= time(NULL
))
1062 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1063 m_nextMailDelivereTime
= 0;
1066 //used to implement delayed far teleports
1067 SetCanDelayTeleport(true);
1068 Unit::Update( p_time
);
1069 SetCanDelayTeleport(false);
1071 // update player only attacks
1072 if(uint32 ranged_att
= getAttackTimer(RANGED_ATTACK
))
1074 setAttackTimer(RANGED_ATTACK
, (p_time
>= ranged_att
? 0 : ranged_att
- p_time
) );
1077 if(uint32 off_att
= getAttackTimer(OFF_ATTACK
))
1079 setAttackTimer(OFF_ATTACK
, (p_time
>= off_att
? 0 : off_att
- p_time
) );
1082 time_t now
= time (NULL
);
1086 UpdateContestedPvP(p_time
);
1088 UpdateDuelFlag(now
);
1090 CheckDuelDistance(now
);
1092 UpdateAfkReport(now
);
1094 // Update items that have just a limited lifetime
1095 if (now
>m_Last_tick
)
1096 UpdateItemDuration(uint32(now
- m_Last_tick
));
1098 if (!m_timedquests
.empty())
1100 std::set
<uint32
>::iterator iter
= m_timedquests
.begin();
1101 while (iter
!= m_timedquests
.end())
1103 QuestStatusData
& q_status
= mQuestStatus
[*iter
];
1104 if( q_status
.m_timer
<= p_time
)
1106 uint32 quest_id
= *iter
;
1107 ++iter
; // current iter will be removed in FailQuest
1108 FailQuest(quest_id
);
1112 q_status
.m_timer
-= p_time
;
1113 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
1119 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING
))
1121 Unit
*pVictim
= getVictim();
1122 if (pVictim
&& !IsNonMeleeSpellCasted(false))
1124 // default combat reach 10
1125 // TODO add weapon,skill check
1127 float pldistance
= ATTACK_DISTANCE
;
1129 if (isAttackReady(BASE_ATTACK
))
1131 if(!IsWithinDistInMap(pVictim
, pldistance
))
1133 setAttackTimer(BASE_ATTACK
,100);
1134 if(m_swingErrorMsg
!= 1) // send single time (client auto repeat)
1136 SendAttackSwingNotInRange();
1137 m_swingErrorMsg
= 1;
1140 //120 degrees of radiant range
1141 else if( !HasInArc( 2*M_PI
/3, pVictim
))
1143 setAttackTimer(BASE_ATTACK
,100);
1144 if(m_swingErrorMsg
!= 2) // send single time (client auto repeat)
1146 SendAttackSwingBadFacingAttack();
1147 m_swingErrorMsg
= 2;
1152 m_swingErrorMsg
= 0; // reset swing error state
1154 // prevent base and off attack in same time, delay attack at 0.2 sec
1155 if(haveOffhandWeapon())
1157 uint32 off_att
= getAttackTimer(OFF_ATTACK
);
1158 if(off_att
< ATTACK_DISPLAY_DELAY
)
1159 setAttackTimer(OFF_ATTACK
,ATTACK_DISPLAY_DELAY
);
1161 AttackerStateUpdate(pVictim
, BASE_ATTACK
);
1162 resetAttackTimer(BASE_ATTACK
);
1166 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK
))
1168 if(!IsWithinDistInMap(pVictim
, pldistance
))
1170 setAttackTimer(OFF_ATTACK
,100);
1172 else if( !HasInArc( 2*M_PI
/3, pVictim
))
1174 setAttackTimer(OFF_ATTACK
,100);
1178 // prevent base and off attack in same time, delay attack at 0.2 sec
1179 uint32 base_att
= getAttackTimer(BASE_ATTACK
);
1180 if(base_att
< ATTACK_DISPLAY_DELAY
)
1181 setAttackTimer(BASE_ATTACK
,ATTACK_DISPLAY_DELAY
);
1183 AttackerStateUpdate(pVictim
, OFF_ATTACK
);
1184 resetAttackTimer(OFF_ATTACK
);
1188 Unit
*owner
= pVictim
->GetOwner();
1189 Unit
*u
= owner
? owner
: pVictim
;
1190 if(u
->IsPvP() && (!duel
|| duel
->opponent
!= u
))
1193 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT
);
1198 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
))
1200 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1202 int time_inn
= time(NULL
)-GetTimeInnEnter();
1203 if (time_inn
>= 10) //freeze update
1205 float bubble
= 0.125*sWorld
.getRate(RATE_REST_INGAME
);
1206 //speed collect rest bonus (section/in hour)
1207 SetRestBonus( GetRestBonus()+ time_inn
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
1208 UpdateInnerTime(time(NULL
));
1215 if(p_time
>= m_regenTimer
)
1218 m_regenTimer
-= p_time
;
1221 if (m_weaponChangeTimer
> 0)
1223 if(p_time
>= m_weaponChangeTimer
)
1224 m_weaponChangeTimer
= 0;
1226 m_weaponChangeTimer
-= p_time
;
1229 if (m_zoneUpdateTimer
> 0)
1231 if(p_time
>= m_zoneUpdateTimer
)
1233 uint32 newzone
, newarea
;
1234 GetZoneAndAreaId(newzone
,newarea
);
1236 if( m_zoneUpdateId
!= newzone
)
1237 UpdateZone(newzone
,newarea
); // also update area
1240 // use area updates as well
1241 // needed for free far all arenas for example
1242 if( m_areaUpdateId
!= newarea
)
1243 UpdateArea(newarea
);
1245 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
1249 m_zoneUpdateTimer
-= p_time
;
1254 // if no longer casting, set regen power as soon as it is up.
1255 if (!IsUnderLastManaUseEffect())
1256 SetFlag(UNIT_FIELD_FLAGS_2
, UNIT_FLAG2_REGENERATE_POWER
);
1262 if (m_deathState
== JUST_DIED
)
1269 if(p_time
>= m_nextSave
)
1271 // m_nextSave reseted in SaveToDB call
1273 sLog
.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1277 m_nextSave
-= p_time
;
1281 //Handle Water/drowning
1282 HandleDrowning(p_time
);
1284 //Handle detect stealth players
1285 if (m_DetectInvTimer
> 0)
1287 if (p_time
>= m_DetectInvTimer
)
1289 HandleStealthedUnitsDetection();
1290 m_DetectInvTimer
= 3000;
1293 m_DetectInvTimer
-= p_time
;
1297 if (now
> m_Last_tick
)
1299 uint32 elapsed
= uint32(now
- m_Last_tick
);
1300 m_Played_time
[PLAYED_TIME_TOTAL
] += elapsed
; // Total played time
1301 m_Played_time
[PLAYED_TIME_LEVEL
] += elapsed
; // Level played time
1307 m_drunkTimer
+= p_time
;
1309 if (m_drunkTimer
> 10*IN_MILISECONDS
)
1313 // not auto-free ghost from body in instances
1314 if(m_deathTimer
> 0 && !GetBaseMap()->Instanceable())
1316 if(p_time
>= m_deathTimer
)
1323 m_deathTimer
-= p_time
;
1326 UpdateEnchantTime(p_time
);
1327 UpdateHomebindTime(p_time
);
1330 SendUpdateToOutOfRangeGroupMembers();
1332 Pet
* pet
= GetPet();
1333 if(pet
&& !IsWithinDistInMap(pet
, OWNER_MAX_DISTANCE
) && (GetCharmGUID() && (pet
->GetGUID() != GetCharmGUID())))
1335 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
, true);
1338 //we should execute delayed teleports only for alive(!) players
1339 //because we don't want player's ghost teleported from graveyard
1340 if(IsHasDelayedTeleport() && isAlive())
1341 TeleportTo(m_teleport_dest
, m_teleport_options
);
1344 void Player::setDeathState(DeathState s
)
1346 uint32 ressSpellId
= 0;
1348 bool cur
= isAlive();
1350 if(s
== JUST_DIED
&& cur
)
1352 // drunken state is cleared on death
1354 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1357 clearResurrectRequestData();
1359 // remove form before other mods to prevent incorrect stats calculation
1360 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId
);
1362 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1363 RemovePet(NULL
, PET_SAVE_NOT_IN_SLOT
, true);
1365 // remove uncontrolled pets
1368 // save value before aura remove in Unit::setDeathState
1369 ressSpellId
= GetUInt32Value(PLAYER_SELF_RES_SPELL
);
1373 ressSpellId
= GetResurrectionSpellId();
1374 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP
, 1);
1375 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH
, 1);
1376 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON
, 1);
1378 Unit::setDeathState(s
);
1380 // restore resurrection spell id for player after aura remove
1381 if(s
== JUST_DIED
&& cur
&& ressSpellId
)
1382 SetUInt32Value(PLAYER_SELF_RES_SPELL
, ressSpellId
);
1384 if(isAlive() && !cur
)
1386 //clear aura case after resurrection by another way (spells will be applied before next death)
1387 SetUInt32Value(PLAYER_SELF_RES_SPELL
, 0);
1389 // restore default warrior stance
1390 if(getClass()== CLASS_WARRIOR
)
1391 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
1395 bool Player::BuildEnumData( QueryResult
* result
, WorldPacket
* p_data
)
1398 // "SELECT characters.guid, characters.name, characters.race, characters.class, characters.gender, characters.playerBytes, characters.playerBytes2, characters.level, "
1399 // 8 9 10 11 12 13 14
1400 // "characters.zone, characters.map, characters.position_x, characters.position_y, characters.position_z, guild_member.guildid, characters.playerFlags, "
1401 // 15 16 17 18 19 20
1402 // "characters.at_login, character_pet.entry, character_pet.modelid, character_pet.level, characters.data, character_declinedname.genitive "
1404 Field
*fields
= result
->Fetch();
1406 uint32 guid
= fields
[0].GetUInt32();
1407 uint8 pRace
= fields
[2].GetUInt8();
1408 uint8 pClass
= fields
[3].GetUInt8();
1410 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(pRace
, pClass
);
1413 sLog
.outError("Player %u has incorrect race/class pair. Don't build enum.", guid
);
1417 *p_data
<< uint64(MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
1418 *p_data
<< fields
[1].GetString(); // name
1419 *p_data
<< uint8(pRace
); // race
1420 *p_data
<< uint8(pClass
); // class
1421 *p_data
<< uint8(fields
[4].GetUInt8()); // gender
1423 uint32 playerBytes
= fields
[5].GetUInt32();
1424 *p_data
<< uint8(playerBytes
); // skin
1425 *p_data
<< uint8(playerBytes
>> 8); // face
1426 *p_data
<< uint8(playerBytes
>> 16); // hair style
1427 *p_data
<< uint8(playerBytes
>> 24); // hair color
1429 uint32 playerBytes2
= fields
[6].GetUInt32();
1430 *p_data
<< uint8(playerBytes2
& 0xFF); // facial hair
1432 *p_data
<< uint8(fields
[7].GetUInt8()); // level
1433 *p_data
<< uint32(fields
[8].GetUInt32()); // zone
1434 *p_data
<< uint32(fields
[9].GetUInt32()); // map
1436 *p_data
<< fields
[10].GetFloat(); // x
1437 *p_data
<< fields
[11].GetFloat(); // y
1438 *p_data
<< fields
[12].GetFloat(); // z
1440 *p_data
<< uint32(fields
[13].GetUInt32()); // guild id
1442 uint32 char_flags
= 0;
1443 uint32 playerFlags
= fields
[14].GetUInt32();
1444 uint32 atLoginFlags
= fields
[15].GetUInt32();
1445 if(playerFlags
& PLAYER_FLAGS_HIDE_HELM
)
1446 char_flags
|= CHARACTER_FLAG_HIDE_HELM
;
1447 if(playerFlags
& PLAYER_FLAGS_HIDE_CLOAK
)
1448 char_flags
|= CHARACTER_FLAG_HIDE_CLOAK
;
1449 if(playerFlags
& PLAYER_FLAGS_GHOST
)
1450 char_flags
|= CHARACTER_FLAG_GHOST
;
1451 if(atLoginFlags
& AT_LOGIN_RENAME
)
1452 char_flags
|= CHARACTER_FLAG_RENAME
;
1453 if(sWorld
.getConfig(CONFIG_DECLINED_NAMES_USED
))
1455 if(!fields
[20].GetCppString().empty())
1456 char_flags
|= CHARACTER_FLAG_DECLINED
;
1459 char_flags
|= CHARACTER_FLAG_DECLINED
;
1461 *p_data
<< uint32(char_flags
); // character flags
1462 // character customize flags
1463 *p_data
<< uint32(atLoginFlags
& AT_LOGIN_CUSTOMIZE
? CHAR_CUSTOMIZE_FLAG_CUSTOMIZE
: CHAR_CUSTOMIZE_FLAG_NONE
);
1464 *p_data
<< uint8(1); // unknown
1468 uint32 petDisplayId
= 0;
1469 uint32 petLevel
= 0;
1470 uint32 petFamily
= 0;
1472 // show pet at selection character in character list only for non-ghost character
1473 if (result
&& !(playerFlags
& PLAYER_FLAGS_GHOST
) && (pClass
== CLASS_WARLOCK
|| pClass
== CLASS_HUNTER
|| pClass
== CLASS_DEATH_KNIGHT
))
1475 uint32 entry
= fields
[16].GetUInt32();
1476 CreatureInfo
const* cInfo
= sCreatureStorage
.LookupEntry
<CreatureInfo
>(entry
);
1479 petDisplayId
= fields
[17].GetUInt32();
1480 petLevel
= fields
[18].GetUInt32();
1481 petFamily
= cInfo
->family
;
1485 *p_data
<< uint32(petDisplayId
);
1486 *p_data
<< uint32(petLevel
);
1487 *p_data
<< uint32(petFamily
);
1490 // TODO: do not access data field here
1491 Tokens data
= StrSplit(fields
[19].GetCppString(), " ");
1493 for (uint8 slot
= 0; slot
< EQUIPMENT_SLOT_END
; slot
++)
1495 uint32 visualbase
= PLAYER_VISIBLE_ITEM_1_ENTRYID
+ (slot
* 2);
1496 uint32 item_id
= GetUInt32ValueFromArray(data
, visualbase
);
1497 const ItemPrototype
* proto
= objmgr
.GetItemPrototype(item_id
);
1500 *p_data
<< uint32(0);
1501 *p_data
<< uint8(0);
1502 *p_data
<< uint32(0);
1506 SpellItemEnchantmentEntry
const *enchant
= NULL
;
1508 uint32 enchants
= GetUInt32ValueFromArray(data
, visualbase
+ 1);
1509 for(uint8 enchantSlot
= PERM_ENCHANTMENT_SLOT
; enchantSlot
<= TEMP_ENCHANTMENT_SLOT
; ++enchantSlot
)
1511 // values stored in 2 uint16
1512 uint32 enchantId
= 0x0000FFFF & (enchants
>> enchantSlot
*16);
1516 if ((enchant
= sSpellItemEnchantmentStore
.LookupEntry(enchantId
)))
1520 *p_data
<< uint32(proto
->DisplayInfoID
);
1521 *p_data
<< uint8(proto
->InventoryType
);
1522 *p_data
<< uint32(enchant
? enchant
->aura_id
: 0);
1524 *p_data
<< uint32(0); // first bag display id
1525 *p_data
<< uint8(0); // first bag inventory type
1526 *p_data
<< uint32(0); // enchant?
1531 bool Player::ToggleAFK()
1533 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1535 bool state
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1537 // afk player not allowed in battleground
1538 if(state
&& InBattleGround())
1539 LeaveBattleground();
1544 bool Player::ToggleDND()
1546 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1548 return HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1551 uint8
Player::chatTag() const
1568 bool Player::TeleportTo(uint32 mapid
, float x
, float y
, float z
, float orientation
, uint32 options
)
1570 if(!MapManager::IsValidMapCoord(mapid
, x
, y
, z
, orientation
))
1572 sLog
.outError("TeleportTo: invalid map %d or absent instance template.", mapid
);
1576 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1577 Pet
* pet
= GetPet();
1579 MapEntry
const* mEntry
= sMapStore
.LookupEntry(mapid
);
1581 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1582 // don't let gm level > 1 either
1583 if(!InBattleGround() && mEntry
->IsBattleGroundOrArena())
1586 // client without expansion support
1587 if(GetSession()->Expansion() < mEntry
->Expansion())
1589 sLog
.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid
);
1592 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1594 SendTransferAborted(mapid
, TRANSFER_ABORT_INSUF_EXPAN_LVL
, mEntry
->Expansion());
1596 return false; // normal client can't teleport to this map...
1600 sLog
.outDebug("Player %s is being teleported to map %u", GetName(), mapid
);
1603 // if we were on a transport, leave
1604 if (!(options
& TELE_TO_NOT_LEAVE_TRANSPORT
) && m_transport
)
1606 m_transport
->RemovePassenger(this);
1608 m_movementInfo
.t_x
= 0.0f
;
1609 m_movementInfo
.t_y
= 0.0f
;
1610 m_movementInfo
.t_z
= 0.0f
;
1611 m_movementInfo
.t_o
= 0.0f
;
1612 m_movementInfo
.t_seat
= -1;
1613 m_movementInfo
.t_time
= 0;
1616 // The player was ported to another map and looses the duel immediately.
1617 // We have to perform this check before the teleport, otherwise the
1618 // ObjectAccessor won't find the flag.
1619 if (duel
&& GetMapId()!=mapid
)
1621 GameObject
* obj
= GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER
));
1623 DuelComplete(DUEL_FLED
);
1626 // reset movement flags at teleport, because player will continue move with these flags after teleport
1627 m_movementInfo
.SetMovementFlags(MOVEMENTFLAG_NONE
);
1629 if ((GetMapId() == mapid
) && (!m_transport
))
1631 //lets reset far teleport flag if it wasn't reset during chained teleports
1632 SetSemaphoreTeleportFar(false);
1633 //setup delayed teleport flag
1634 SetDelayedTeleportFlag(IsCanDelayTeleport());
1635 //if teleport spell is casted in Unit::Update() func
1636 //then we need to delay it until update process will be finished
1637 if(IsHasDelayedTeleport())
1639 SetSemaphoreTeleportNear(true);
1640 //lets save teleport destination for player
1641 m_teleport_dest
= WorldLocation(mapid
, x
, y
, z
, orientation
);
1642 m_teleport_options
= options
;
1646 if (!(options
& TELE_TO_NOT_UNSUMMON_PET
))
1648 //same map, only remove pet if out of range for new position
1649 if(pet
&& !pet
->IsWithinDist3d(x
,y
,z
, OWNER_MAX_DISTANCE
))
1650 UnsummonPetTemporaryIfAny();
1653 if(!(options
& TELE_TO_NOT_LEAVE_COMBAT
))
1656 // this will be used instead of the current location in SaveToDB
1657 m_teleport_dest
= WorldLocation(mapid
, x
, y
, z
, orientation
);
1658 SetFallInformation(0, z
);
1660 // code for finish transfer called in WorldSession::HandleMovementOpcodes()
1661 // at client packet MSG_MOVE_TELEPORT_ACK
1662 SetSemaphoreTeleportNear(true);
1663 // near teleport, triggering send MSG_MOVE_TELEPORT_ACK from client at landing
1664 if(!GetSession()->PlayerLogout())
1667 BuildTeleportAckMsg(&data
, x
, y
, z
, orientation
);
1668 GetSession()->SendPacket(&data
);
1673 // far teleport to another map
1674 Map
* oldmap
= IsInWorld() ? GetMap() : NULL
;
1675 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1677 // Check enter rights before map getting to avoid creating instance copy for player
1678 // this check not dependent from map instance copy and same for all instance copies of selected map
1679 if (!MapManager::Instance().CanPlayerEnter(mapid
, this))
1682 // If the map is not created, assume it is possible to enter it.
1683 // It will be created in the WorldPortAck.
1684 Map
*map
= MapManager::Instance().FindMap(mapid
);
1685 if (!map
|| map
->CanEnter(this))
1687 //lets reset near teleport flag if it wasn't reset during chained teleports
1688 SetSemaphoreTeleportNear(false);
1689 //setup delayed teleport flag
1690 SetDelayedTeleportFlag(IsCanDelayTeleport());
1691 //if teleport spell is casted in Unit::Update() func
1692 //then we need to delay it until update process will be finished
1693 if(IsHasDelayedTeleport())
1695 SetSemaphoreTeleportFar(true);
1696 //lets save teleport destination for player
1697 m_teleport_dest
= WorldLocation(mapid
, x
, y
, z
, orientation
);
1698 m_teleport_options
= options
;
1706 ResetContestedPvP();
1708 // remove player from battleground on far teleport (when changing maps)
1709 if(BattleGround
const* bg
= GetBattleGround())
1711 // Note: at battleground join battleground id set before teleport
1712 // and we already will found "current" battleground
1713 // just need check that this is targeted map or leave
1714 if(bg
->GetMapId() != mapid
)
1715 LeaveBattleground(false); // don't teleport to entry point
1718 // remove pet on map change
1720 UnsummonPetTemporaryIfAny();
1722 // remove all dyn objects
1723 RemoveAllDynObjects();
1725 // stop spellcasting
1726 // not attempt interrupt teleportation spell at caster teleport
1727 if(!(options
& TELE_TO_SPELL
))
1728 if(IsNonMeleeSpellCasted(true))
1729 InterruptNonMeleeSpells(true);
1731 //remove auras before removing from map...
1732 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP
| AURA_INTERRUPT_FLAG_MOVE
| AURA_INTERRUPT_FLAG_TURNING
);
1734 if(!GetSession()->PlayerLogout())
1736 // send transfer packets
1737 WorldPacket
data(SMSG_TRANSFER_PENDING
, (4+4+4));
1738 data
<< uint32(mapid
);
1741 data
<< m_transport
->GetEntry() << GetMapId();
1743 GetSession()->SendPacket(&data
);
1745 data
.Initialize(SMSG_NEW_WORLD
, (20));
1748 data
<< (uint32
)mapid
<< m_movementInfo
.t_x
<< m_movementInfo
.t_y
<< m_movementInfo
.t_z
<< m_movementInfo
.t_o
;
1752 data
<< (uint32
)mapid
<< (float)x
<< (float)y
<< (float)z
<< (float)orientation
;
1754 GetSession()->SendPacket( &data
);
1755 SendSavedInstances();
1757 // remove from old map now
1758 if(oldmap
) oldmap
->Remove(this, false);
1761 // new final coordinates
1765 float final_o
= orientation
;
1769 final_x
+= m_movementInfo
.t_x
;
1770 final_y
+= m_movementInfo
.t_y
;
1771 final_z
+= m_movementInfo
.t_z
;
1772 final_o
+= m_movementInfo
.t_o
;
1775 m_teleport_dest
= WorldLocation(mapid
, final_x
, final_y
, final_z
, final_o
);
1776 SetFallInformation(0, final_z
);
1777 // if the player is saved before worldportack (at logout for example)
1778 // this will be used instead of the current location in SaveToDB
1780 // move packet sent by client always after far teleport
1781 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1782 SetSemaphoreTeleportFar(true);
1790 bool Player::TeleportToBGEntryPoint()
1792 ScheduleDelayedOperation(DELAYED_BG_MOUNT_RESTORE
);
1793 ScheduleDelayedOperation(DELAYED_BG_TAXI_RESTORE
);
1794 return TeleportTo(m_bgData
.joinPos
);
1797 void Player::ProcessDelayedOperations()
1799 if(m_DelayedOperations
== 0)
1802 if(m_DelayedOperations
& DELAYED_RESURRECT_PLAYER
)
1804 ResurrectPlayer(0.0f
, false);
1806 if(GetMaxHealth() > m_resurrectHealth
)
1807 SetHealth( m_resurrectHealth
);
1809 SetHealth( GetMaxHealth() );
1811 if(GetMaxPower(POWER_MANA
) > m_resurrectMana
)
1812 SetPower(POWER_MANA
, m_resurrectMana
);
1814 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
) );
1816 SetPower(POWER_RAGE
, 0 );
1817 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
) );
1822 if(m_DelayedOperations
& DELAYED_SAVE_PLAYER
)
1827 if(m_DelayedOperations
& DELAYED_SPELL_CAST_DESERTER
)
1829 CastSpell(this, 26013, true); // Deserter
1832 if (m_DelayedOperations
& DELAYED_BG_MOUNT_RESTORE
)
1834 if (m_bgData
.mountSpell
)
1836 CastSpell(this, m_bgData
.mountSpell
, true);
1837 m_bgData
.mountSpell
= 0;
1841 if (m_DelayedOperations
& DELAYED_BG_TAXI_RESTORE
)
1843 if (m_bgData
.HasTaxiPath())
1845 m_taxi
.AddTaxiDestination(m_bgData
.taxiPath
[0]);
1846 m_taxi
.AddTaxiDestination(m_bgData
.taxiPath
[1]);
1847 m_bgData
.ClearTaxiPath();
1849 ContinueTaxiFlight();
1853 //we have executed ALL delayed ops, so clear the flag
1854 m_DelayedOperations
= 0;
1857 void Player::AddToWorld()
1859 ///- Do not add/remove the player from the object storage
1860 ///- It will crash when updating the ObjectAccessor
1861 ///- The player should only be added when logging in
1864 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; ++i
)
1867 m_items
[i
]->AddToWorld();
1871 void Player::RemoveFromWorld()
1876 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1878 UnsummonAllTotems();
1882 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; ++i
)
1885 m_items
[i
]->RemoveFromWorld();
1888 ///- Do not add/remove the player from the object storage
1889 ///- It will crash when updating the ObjectAccessor
1890 ///- The player should only be removed when logging out
1891 Unit::RemoveFromWorld();
1894 void Player::RewardRage( uint32 damage
, uint32 weaponSpeedHitFactor
, bool attacker
)
1898 float rageconversion
= ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1902 addRage
= ((damage
/rageconversion
*7.5 + weaponSpeedHitFactor
)/2);
1904 // talent who gave more rage on attack
1905 addRage
*= 1.0f
+ GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT
) / 100.0f
;
1909 addRage
= damage
/rageconversion
*2.5;
1911 // Berserker Rage effect
1912 if(HasAura(18499,0))
1916 addRage
*= sWorld
.getRate(RATE_POWER_RAGE_INCOME
);
1918 ModifyPower(POWER_RAGE
, uint32(addRage
*10));
1921 void Player::RegenerateAll(uint32 diff
)
1923 // Not in combat or they have regeneration
1924 if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) ||
1925 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
) || IsPolymorphed() )
1927 RegenerateHealth(diff
);
1928 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN
))
1930 Regenerate(POWER_RAGE
, diff
);
1931 if(getClass() == CLASS_DEATH_KNIGHT
)
1932 Regenerate(POWER_RUNIC_POWER
, diff
);
1936 Regenerate(POWER_ENERGY
, diff
);
1938 Regenerate(POWER_MANA
, diff
);
1940 if (getClass() == CLASS_DEATH_KNIGHT
)
1941 Regenerate(POWER_RUNE
, diff
);
1943 m_regenTimer
= REGEN_TIME_FULL
;
1946 // diff contains the time in milliseconds since last regen.
1947 void Player::Regenerate(Powers power
, uint32 diff
)
1949 uint32 curValue
= GetPower(power
);
1950 uint32 maxValue
= GetMaxPower(power
);
1952 float addvalue
= 0.0f
;
1958 bool recentCast
= IsUnderLastManaUseEffect();
1959 float ManaIncreaseRate
= sWorld
.getRate(RATE_POWER_MANA
);
1962 // Mangos Updates Mana in intervals of 2s, which is correct
1963 addvalue
= GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER
) * ManaIncreaseRate
* 2.00f
;
1967 addvalue
= GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER
) * ManaIncreaseRate
* 2.00f
;
1970 case POWER_RAGE
: // Regenerate rage
1972 float RageDecreaseRate
= sWorld
.getRate(RATE_POWER_RAGE_LOSS
);
1973 addvalue
= 20 * RageDecreaseRate
; // 2 rage by tick (= 2 seconds => 1 rage/sec)
1975 case POWER_ENERGY
: // Regenerate energy (rogue)
1978 case POWER_RUNIC_POWER
:
1980 float RunicPowerDecreaseRate
= sWorld
.getRate(RATE_POWER_RUNICPOWER_LOSS
);
1981 addvalue
= 30 * RunicPowerDecreaseRate
; // 3 RunicPower by tick
1985 if (getClass() != CLASS_DEATH_KNIGHT
)
1988 for(uint32 i
= 0; i
< MAX_RUNES
; ++i
)
1990 if(uint16 cd
= GetRuneCooldown(i
)) // if we have cooldown, reduce it...
1991 SetRuneCooldown(i
, (cd
< diff
) ? 0 : cd
- diff
);
1995 case POWER_HAPPINESS
:
2000 // Mana regen calculated in Player::UpdateManaRegen()
2001 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
2002 if(power
!= POWER_MANA
)
2004 AuraList
const& ModPowerRegenPCTAuras
= GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT
);
2005 for(AuraList::const_iterator i
= ModPowerRegenPCTAuras
.begin(); i
!= ModPowerRegenPCTAuras
.end(); ++i
)
2006 if ((*i
)->GetModifier()->m_miscvalue
== power
)
2007 addvalue
*= ((*i
)->GetModifier()->m_amount
+ 100) / 100.0f
;
2010 // addvalue computed on a 2sec basis. => update to diff time
2011 addvalue
*= float(diff
) / REGEN_TIME_FULL
;
2013 if (power
!= POWER_RAGE
&& power
!= POWER_RUNIC_POWER
)
2015 curValue
+= uint32(addvalue
);
2016 if (curValue
> maxValue
)
2017 curValue
= maxValue
;
2021 if(curValue
<= uint32(addvalue
))
2024 curValue
-= uint32(addvalue
);
2026 SetPower(power
, curValue
);
2029 void Player::RegenerateHealth(uint32 diff
)
2031 uint32 curValue
= GetHealth();
2032 uint32 maxValue
= GetMaxHealth();
2034 if (curValue
>= maxValue
) return;
2036 float HealthIncreaseRate
= sWorld
.getRate(RATE_HEALTH
);
2038 float addvalue
= 0.0f
;
2041 if ( IsPolymorphed() )
2042 addvalue
= GetMaxHealth()/3;
2043 // normal regen case (maybe partly in combat case)
2044 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) )
2046 addvalue
= OCTRegenHPPerSpirit()* HealthIncreaseRate
;
2049 AuraList
const& mModHealthRegenPct
= GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT
);
2050 for(AuraList::const_iterator i
= mModHealthRegenPct
.begin(); i
!= mModHealthRegenPct
.end(); ++i
)
2051 addvalue
*= (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
;
2053 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
))
2054 addvalue
*= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) / 100.0f
;
2060 // always regeneration bonus (including combat)
2061 addvalue
+= GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
);
2066 addvalue
*= (float)diff
/ REGEN_TIME_FULL
;
2068 ModifyHealth(int32(addvalue
));
2071 bool Player::CanInteractWithNPCs(bool alive
) const
2073 if(alive
&& !isAlive())
2082 Player::GetNPCIfCanInteractWith(uint64 guid
, uint32 npcflagmask
)
2091 // exist (we need look pets also for some interaction (quest/etc)
2092 Creature
*unit
= ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid
);
2097 if(!CanInteractWithNPCs(!unit
->isSpiritService()))
2100 // appropriate npc type
2101 if(npcflagmask
&& !unit
->HasFlag( UNIT_NPC_FLAGS
, npcflagmask
))
2104 // alive or spirit healer
2105 if(!unit
->isAlive() && (!unit
->isSpiritService() || isAlive() ))
2108 // not allow interaction under control, but allow with own pets
2109 if(unit
->GetCharmerGUID())
2113 if( unit
->IsHostileTo(this))
2117 if(FactionTemplateEntry
const* factionTemplate
= sFactionTemplateStore
.LookupEntry(unit
->getFaction()))
2118 if(factionTemplate
->faction
)
2119 if(FactionEntry
const* faction
= sFactionStore
.LookupEntry(factionTemplate
->faction
))
2120 if(faction
->reputationListID
>= 0 && GetReputationMgr().GetRank(faction
) <= REP_UNFRIENDLY
)
2124 if(!unit
->IsWithinDistInMap(this,INTERACTION_DISTANCE
))
2130 GameObject
* Player::GetGameObjectIfCanInteractWith(uint64 guid
, GameobjectTypes type
) const
2132 if(GameObject
*go
= GetMap()->GetGameObject(guid
))
2134 if(go
->GetGoType() == type
)
2139 // TODO: find out how the client calculates the maximal usage distance to spellless working
2140 // gameobjects like guildbanks and mailboxes - 10.0 is a just an abitrary choosen number
2141 case GAMEOBJECT_TYPE_GUILD_BANK
:
2142 case GAMEOBJECT_TYPE_MAILBOX
:
2145 case GAMEOBJECT_TYPE_FISHINGHOLE
:
2146 maxdist
= 20.0f
+CONTACT_DISTANCE
; // max spell range
2149 maxdist
= INTERACTION_DISTANCE
;
2153 if (go
->IsWithinDistInMap(this, maxdist
))
2156 sLog
.outError("IsGameObjectOfTypeInRange: GameObject '%s' [GUID: %u] is too far away from player %s [GUID: %u] to be used by him (distance=%f, maximal 10 is allowed)", go
->GetGOInfo()->name
,
2157 go
->GetGUIDLow(), GetName(), GetGUIDLow(), go
->GetDistance(this));
2163 bool Player::IsUnderWater() const
2165 return IsInWater() &&
2166 GetPositionZ() < (GetBaseMap()->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2169 void Player::SetInWater(bool apply
)
2171 if(m_isInWater
==apply
)
2174 //define player in water by opcodes
2175 //move player's guid into HateOfflineList of those mobs
2176 //which can't swim and move guid back into ThreatList when
2178 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2179 m_isInWater
= apply
;
2181 // remove auras that need water/land
2182 RemoveAurasWithInterruptFlags(apply
? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER
: AURA_INTERRUPT_FLAG_NOT_UNDERWATER
);
2184 getHostilRefManager().updateThreatTables();
2187 void Player::SetGameMaster(bool on
)
2191 m_ExtraFlags
|= PLAYER_EXTRA_GM_ON
;
2193 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
2195 if (Pet
* pet
= GetPet())
2197 pet
->setFaction(35);
2198 pet
->getHostilRefManager().setOnlineOfflineState(false);
2201 for (int8 i
= 0; i
< MAX_TOTEM
; ++i
)
2203 if(Creature
*totem
= GetMap()->GetCreature(m_TotemSlot
[i
]))
2204 totem
->setFaction(35);
2206 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
2207 ResetContestedPvP();
2209 getHostilRefManager().setOnlineOfflineState(false);
2210 CombatStopWithPets();
2212 SetPhaseMask(PHASEMASK_ANYWHERE
,false); // see and visible in all phases
2217 AuraList
const& phases
= GetAurasByType(SPELL_AURA_PHASE
);
2218 SetPhaseMask(!phases
.empty() ? phases
.front()->GetMiscValue() : PHASEMASK_NORMAL
,false);
2220 m_ExtraFlags
&= ~ PLAYER_EXTRA_GM_ON
;
2221 setFactionForRace(getRace());
2222 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
2224 if (Pet
* pet
= GetPet())
2226 pet
->setFaction(getFaction());
2227 pet
->getHostilRefManager().setOnlineOfflineState(true);
2230 for (int8 i
= 0; i
< MAX_TOTEM
; ++i
)
2232 if(Creature
*totem
= GetMap()->GetCreature(m_TotemSlot
[i
]))
2233 totem
->setFaction(getFaction());
2235 // restore FFA PvP Server state
2236 if(sWorld
.IsFFAPvPRealm())
2237 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
2239 // restore FFA PvP area state, remove not allowed for GM mounts
2240 UpdateArea(m_areaUpdateId
);
2242 getHostilRefManager().setOnlineOfflineState(true);
2245 UpdateVisibilityForPlayer();
2248 void Player::SetGMVisible(bool on
)
2252 m_ExtraFlags
&= ~PLAYER_EXTRA_GM_INVISIBLE
; //remove flag
2254 // Reapply stealth/invisibility if active or show if not any
2255 if(HasAuraType(SPELL_AURA_MOD_STEALTH
))
2256 SetVisibility(VISIBILITY_GROUP_STEALTH
);
2257 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY
))
2258 SetVisibility(VISIBILITY_GROUP_INVISIBILITY
);
2260 SetVisibility(VISIBILITY_ON
);
2264 m_ExtraFlags
|= PLAYER_EXTRA_GM_INVISIBLE
; //add flag
2266 SetAcceptWhispers(false);
2267 SetGameMaster(true);
2269 SetVisibility(VISIBILITY_OFF
);
2273 bool Player::IsGroupVisibleFor(Player
* p
) const
2275 switch(sWorld
.getConfig(CONFIG_GROUP_VISIBILITY
))
2277 default: return IsInSameGroupWith(p
);
2278 case 1: return IsInSameRaidWith(p
);
2279 case 2: return GetTeam()==p
->GetTeam();
2283 bool Player::IsInSameGroupWith(Player
const* p
) const
2285 return (p
==this || (GetGroup() != NULL
&&
2286 GetGroup()->SameSubGroup((Player
*)this, (Player
*)p
)));
2289 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2290 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2291 void Player::UninviteFromGroup()
2293 Group
* group
= GetGroupInvite();
2297 group
->RemoveInvite(this);
2299 if(group
->GetMembersCount() <= 1) // group has just 1 member => disband
2301 if(group
->IsCreated())
2303 group
->Disband(true);
2304 objmgr
.RemoveGroup(group
);
2307 group
->RemoveAllInvites();
2313 void Player::RemoveFromGroup(Group
* group
, uint64 guid
)
2317 if (group
->RemoveMember(guid
, 0) <= 1)
2319 // group->Disband(); already disbanded in RemoveMember
2320 objmgr
.RemoveGroup(group
);
2322 // removemember sets the player's group pointer to NULL
2327 void Player::SendLogXPGain(uint32 GivenXP
, Unit
* victim
, uint32 RestXP
)
2329 WorldPacket
data(SMSG_LOG_XPGAIN
, 21);
2330 data
<< uint64(victim
? victim
->GetGUID() : 0); // guid
2331 data
<< uint32(GivenXP
+RestXP
); // given experience
2332 data
<< uint8(victim
? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2335 data
<< uint32(GivenXP
); // experience without rested bonus
2336 data
<< float(1); // 1 - none 0 - 100% group bonus output
2338 data
<< uint8(0); // new 2.4.0
2339 GetSession()->SendPacket(&data
);
2342 void Player::GiveXP(uint32 xp
, Unit
* victim
)
2350 uint32 level
= getLevel();
2352 // XP to money conversion processed in Player::RewardQuest
2353 if(level
>= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
2356 // handle SPELL_AURA_MOD_XP_PCT auras
2357 Unit::AuraList
const& ModXPPctAuras
= GetAurasByType(SPELL_AURA_MOD_XP_PCT
);
2358 for(Unit::AuraList::const_iterator i
= ModXPPctAuras
.begin();i
!= ModXPPctAuras
.end(); ++i
)
2359 xp
= uint32(xp
*(1.0f
+ (*i
)->GetModifier()->m_amount
/ 100.0f
));
2361 // XP resting bonus for kill
2362 uint32 rested_bonus_xp
= victim
? GetXPRestBonus(xp
) : 0;
2364 SendLogXPGain(xp
,victim
,rested_bonus_xp
);
2366 uint32 curXP
= GetUInt32Value(PLAYER_XP
);
2367 uint32 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2368 uint32 newXP
= curXP
+ xp
+ rested_bonus_xp
;
2370 while( newXP
>= nextLvlXP
&& level
< sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
2374 if ( level
< sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
2375 GiveLevel(level
+ 1);
2378 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2381 SetUInt32Value(PLAYER_XP
, newXP
);
2384 // Update player to next level
2385 // Current player experience not update (must be update by caller)
2386 void Player::GiveLevel(uint32 level
)
2388 if ( level
== getLevel() )
2391 PlayerLevelInfo info
;
2392 objmgr
.GetPlayerLevelInfo(getRace(),getClass(),level
,&info
);
2394 PlayerClassLevelInfo classInfo
;
2395 objmgr
.GetPlayerClassLevelInfo(getClass(),level
,&classInfo
);
2397 // send levelup info to client
2398 WorldPacket
data(SMSG_LEVELUP_INFO
, (4+4+MAX_POWERS
*4+MAX_STATS
*4));
2399 data
<< uint32(level
);
2400 data
<< uint32(int32(classInfo
.basehealth
) - int32(GetCreateHealth()));
2401 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2402 data
<< uint32(int32(classInfo
.basemana
) - int32(GetCreateMana()));
2410 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
) // Stats loop (0-4)
2411 data
<< uint32(int32(info
.stats
[i
]) - GetCreateStat(Stats(i
)));
2413 GetSession()->SendPacket(&data
);
2415 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, objmgr
.GetXPForLevel(level
));
2417 //update level, max level of skills
2418 m_Played_time
[PLAYED_TIME_LEVEL
] = 0; // Level Played Time reset
2420 _ApplyAllLevelScaleItemMods(false);
2424 UpdateSkillsForLevel ();
2426 // save base values (bonuses already included in stored stats
2427 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2428 SetCreateStat(Stats(i
), info
.stats
[i
]);
2430 SetCreateHealth(classInfo
.basehealth
);
2431 SetCreateMana(classInfo
.basemana
);
2433 InitTalentForLevel();
2434 InitTaxiNodesForLevel();
2435 InitGlyphsForLevel();
2439 // set current level health and mana/energy to maximum after applying all mods.
2440 SetHealth(GetMaxHealth());
2441 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2442 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2443 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2444 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2445 SetPower(POWER_FOCUS
, 0);
2446 SetPower(POWER_HAPPINESS
, 0);
2448 _ApplyAllLevelScaleItemMods(true);
2450 // update level to hunter/summon pet
2451 if (Pet
* pet
= GetPet())
2452 pet
->SynchronizeLevelWithOwner();
2454 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL
);
2457 void Player::InitTalentForLevel()
2459 uint32 level
= getLevel();
2460 // talents base at level diff ( talents = level - 9 but some can be used already)
2463 // Remove all talent points
2464 if(m_usedTalentCount
> 0) // Free any used talents
2467 SetFreeTalentPoints(0);
2472 uint32 talentPointsForLevel
= CalculateTalentsPoints();
2474 // if used more that have then reset
2475 if(m_usedTalentCount
> talentPointsForLevel
)
2477 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR
)
2480 SetFreeTalentPoints(0);
2482 // else update amount of free points
2484 SetFreeTalentPoints(talentPointsForLevel
-m_usedTalentCount
);
2487 if(!GetSession()->PlayerLoading())
2488 SendTalentsInfoData(false); // update at client
2491 void Player::InitStatsForLevel(bool reapplyMods
)
2493 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2494 _RemoveAllStatBonuses();
2496 PlayerClassLevelInfo classInfo
;
2497 objmgr
.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo
);
2499 PlayerLevelInfo info
;
2500 objmgr
.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info
);
2502 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL
, sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) );
2503 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, objmgr
.GetXPForLevel(getLevel()));
2505 UpdateSkillsForLevel ();
2507 // set default cast time multiplier
2508 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
);
2510 // reset size before reapply auras
2511 SetFloatValue(OBJECT_FIELD_SCALE_X
,1.0f
);
2513 // save base values (bonuses already included in stored stats
2514 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2515 SetCreateStat(Stats(i
), info
.stats
[i
]);
2517 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2518 SetStat(Stats(i
), info
.stats
[i
]);
2520 SetCreateHealth(classInfo
.basehealth
);
2523 SetCreateMana(classInfo
.basemana
);
2525 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2529 //reset rating fields values
2530 for(uint16 index
= PLAYER_FIELD_COMBAT_RATING_1
; index
< PLAYER_FIELD_COMBAT_RATING_1
+ MAX_COMBAT_RATING
; ++index
)
2531 SetUInt32Value(index
, 0);
2533 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS
,0);
2534 for (int i
= 0; i
< 7; ++i
)
2536 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG
+i
, 0);
2537 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS
+i
, 0);
2538 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT
+i
, 1.00f
);
2541 //reset attack power, damage and attack speed fields
2542 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
, 2000.0f
);
2543 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
+ 1, 2000.0f
); // offhand attack time
2544 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME
, 2000.0f
);
2546 SetFloatValue(UNIT_FIELD_MINDAMAGE
, 0.0f
);
2547 SetFloatValue(UNIT_FIELD_MAXDAMAGE
, 0.0f
);
2548 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
, 0.0f
);
2549 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
, 0.0f
);
2550 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
, 0.0f
);
2551 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
, 0.0f
);
2553 SetInt32Value(UNIT_FIELD_ATTACK_POWER
, 0 );
2554 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS
, 0 );
2555 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER
,0.0f
);
2556 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER
, 0 );
2557 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS
,0 );
2558 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER
,0.0f
);
2560 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2561 SetFloatValue(PLAYER_CRIT_PERCENTAGE
,0.0f
);
2562 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE
,0.0f
);
2563 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE
,0.0f
);
2565 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2566 for (uint8 i
= 0; i
< 7; ++i
)
2567 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1
+i
, 0.0f
);
2569 SetFloatValue(PLAYER_PARRY_PERCENTAGE
, 0.0f
);
2570 SetFloatValue(PLAYER_BLOCK_PERCENTAGE
, 0.0f
);
2571 SetUInt32Value(PLAYER_SHIELD_BLOCK
, 0);
2574 SetFloatValue(PLAYER_DODGE_PERCENTAGE
, 0.0f
);
2576 // set armor (resistance 0) to original value (create_agility*2)
2577 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2578 SetResistanceBuffMods(SpellSchools(0), true, 0.0f
);
2579 SetResistanceBuffMods(SpellSchools(0), false, 0.0f
);
2580 // set other resistance to original value (0)
2581 for (int i
= 1; i
< MAX_SPELL_SCHOOL
; ++i
)
2583 SetResistance(SpellSchools(i
), 0);
2584 SetResistanceBuffMods(SpellSchools(i
), true, 0.0f
);
2585 SetResistanceBuffMods(SpellSchools(i
), false, 0.0f
);
2588 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE
,0);
2589 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE
,0);
2590 for(int i
= 0; i
< MAX_SPELL_SCHOOL
; ++i
)
2592 SetUInt32Value(UNIT_FIELD_POWER_COST_MODIFIER
+i
,0);
2593 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER
+i
,0.0f
);
2595 // Reset no reagent cost field
2596 for(int i
= 0; i
< 3; ++i
)
2597 SetUInt32Value(PLAYER_NO_REAGENT_COST_1
+ i
, 0);
2598 // Init data for form but skip reapply item mods for form
2599 InitDataForForm(reapplyMods
);
2602 for (int i
= POWER_MANA
; i
< MAX_POWERS
; ++i
)
2603 SetMaxPower(Powers(i
), uint32(GetCreatePowers(Powers(i
))));
2605 SetMaxHealth(classInfo
.basehealth
); // stamina bonus will applied later
2607 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2608 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID
, 0);
2610 // cleanup unit flags (will be re-applied if need at aura load).
2611 RemoveFlag( UNIT_FIELD_FLAGS
,
2612 UNIT_FLAG_NON_ATTACKABLE
| UNIT_FLAG_DISABLE_MOVE
| UNIT_FLAG_NOT_ATTACKABLE_1
|
2613 UNIT_FLAG_PET_IN_COMBAT
| UNIT_FLAG_SILENCED
| UNIT_FLAG_PACIFIED
|
2614 UNIT_FLAG_STUNNED
| UNIT_FLAG_IN_COMBAT
| UNIT_FLAG_DISARMED
|
2615 UNIT_FLAG_CONFUSED
| UNIT_FLAG_FLEEING
| UNIT_FLAG_NOT_SELECTABLE
|
2616 UNIT_FLAG_SKINNABLE
| UNIT_FLAG_MOUNT
| UNIT_FLAG_TAXI_FLIGHT
);
2617 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
); // must be set
2619 SetFlag(UNIT_FIELD_FLAGS_2
,UNIT_FLAG2_REGENERATE_POWER
);// must be set
2621 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2622 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
| PLAYER_FLAGS_DND
| PLAYER_FLAGS_GM
| PLAYER_FLAGS_GHOST
);
2624 RemoveStandFlags(UNIT_STAND_FLAGS_ALL
); // one form stealth modified bytes
2625 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
| UNIT_BYTE2_FLAG_SANCTUARY
);
2627 // restore if need some important flags
2628 SetUInt32Value(PLAYER_FIELD_BYTES2
, 0 ); // flags empty by default
2630 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2631 _ApplyAllStatBonuses();
2633 // set current level health and mana/energy to maximum after applying all mods.
2634 SetHealth(GetMaxHealth());
2635 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2636 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2637 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2638 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2639 SetPower(POWER_FOCUS
, 0);
2640 SetPower(POWER_HAPPINESS
, 0);
2641 SetPower(POWER_RUNIC_POWER
, 0);
2643 // update level to hunter/summon pet
2644 if (Pet
* pet
= GetPet())
2645 pet
->SynchronizeLevelWithOwner();
2648 void Player::SendInitialSpells()
2650 time_t curTime
= time(NULL
);
2651 time_t infTime
= curTime
+ infinityCooldownDelayCheck
;
2653 uint16 spellCount
= 0;
2655 WorldPacket
data(SMSG_INITIAL_SPELLS
, (1+2+4*m_spells
.size()+2+m_spellCooldowns
.size()*(2+2+2+4+4)));
2658 size_t countPos
= data
.wpos();
2659 data
<< uint16(spellCount
); // spell count placeholder
2661 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2663 if(itr
->second
->state
== PLAYERSPELL_REMOVED
)
2666 if(!itr
->second
->active
|| itr
->second
->disabled
)
2669 data
<< uint32(itr
->first
);
2670 data
<< uint16(0); // it's not slot id
2675 data
.put
<uint16
>(countPos
,spellCount
); // write real count value
2677 uint16 spellCooldowns
= m_spellCooldowns
.size();
2678 data
<< uint16(spellCooldowns
);
2679 for(SpellCooldowns::const_iterator itr
=m_spellCooldowns
.begin(); itr
!=m_spellCooldowns
.end(); ++itr
)
2681 SpellEntry
const *sEntry
= sSpellStore
.LookupEntry(itr
->first
);
2685 data
<< uint32(itr
->first
);
2687 data
<< uint16(itr
->second
.itemid
); // cast item id
2688 data
<< uint16(sEntry
->Category
); // spell category
2690 // send infinity cooldown in special format
2691 if(itr
->second
.end
>= infTime
)
2693 data
<< uint32(1); // cooldown
2694 data
<< uint32(0x80000000); // category cooldown
2698 time_t cooldown
= itr
->second
.end
> curTime
? (itr
->second
.end
-curTime
)*IN_MILISECONDS
: 0;
2700 if(sEntry
->Category
) // may be wrong, but anyway better than nothing...
2702 data
<< uint32(0); // cooldown
2703 data
<< uint32(cooldown
); // category cooldown
2707 data
<< uint32(cooldown
); // cooldown
2708 data
<< uint32(0); // category cooldown
2712 GetSession()->SendPacket(&data
);
2714 sLog
.outDetail( "CHARACTER: Sent Initial Spells" );
2717 void Player::RemoveMail(uint32 id
)
2719 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
2721 if ((*itr
)->messageID
== id
)
2723 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2730 void Player::SendMailResult(uint32 mailId
, MailResponseType mailAction
, MailResponseResult mailError
, uint32 equipError
, uint32 item_guid
, uint32 item_count
)
2732 WorldPacket
data(SMSG_SEND_MAIL_RESULT
, (4+4+4+(mailError
== MAIL_ERR_EQUIP_ERROR
?4:(mailAction
== MAIL_ITEM_TAKEN
?4+4:0))));
2733 data
<< (uint32
) mailId
;
2734 data
<< (uint32
) mailAction
;
2735 data
<< (uint32
) mailError
;
2736 if ( mailError
== MAIL_ERR_EQUIP_ERROR
)
2737 data
<< (uint32
) equipError
;
2738 else if( mailAction
== MAIL_ITEM_TAKEN
)
2740 data
<< (uint32
) item_guid
; // item guid low?
2741 data
<< (uint32
) item_count
; // item count?
2743 GetSession()->SendPacket(&data
);
2746 void Player::SendNewMail()
2748 // deliver undelivered mail
2749 WorldPacket
data(SMSG_RECEIVED_MAIL
, 4);
2751 GetSession()->SendPacket(&data
);
2754 void Player::UpdateNextMailTimeAndUnreads()
2756 // calculate next delivery time (min. from non-delivered mails
2757 // and recalculate unReadMail
2758 time_t cTime
= time(NULL
);
2759 m_nextMailDelivereTime
= 0;
2761 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
2763 if((*itr
)->deliver_time
> cTime
)
2765 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> (*itr
)->deliver_time
)
2766 m_nextMailDelivereTime
= (*itr
)->deliver_time
;
2768 else if(((*itr
)->checked
& MAIL_CHECK_MASK_READ
) == 0)
2773 void Player::AddNewMailDeliverTime(time_t deliver_time
)
2775 if(deliver_time
<= time(NULL
)) // ready now
2780 else // not ready and no have ready mails
2782 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> deliver_time
)
2783 m_nextMailDelivereTime
= deliver_time
;
2787 bool Player::addSpell(uint32 spell_id
, bool active
, bool learning
, bool dependent
, bool disabled
)
2789 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
2792 // do character spell book cleanup (all characters)
2793 if(!IsInWorld() && !learning
) // spell load case
2795 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id
);
2796 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2799 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id
);
2804 if(!SpellMgr::IsSpellValid(spellInfo
,this,false))
2806 // do character spell book cleanup (all characters)
2807 if(!IsInWorld() && !learning
) // spell load case
2809 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id
);
2810 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2813 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id
);
2818 PlayerSpellState state
= learning
? PLAYERSPELL_NEW
: PLAYERSPELL_UNCHANGED
;
2820 bool dependent_set
= false;
2821 bool disabled_case
= false;
2822 bool superceded_old
= false;
2824 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2825 if (itr
!= m_spells
.end())
2827 uint32 next_active_spell_id
= 0;
2828 // fix activate state for non-stackable low rank (and find next spell for !active case)
2829 if(!SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
2831 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
2832 for(SpellChainMapNext::const_iterator next_itr
= nextMap
.lower_bound(spell_id
); next_itr
!= nextMap
.upper_bound(spell_id
); ++next_itr
)
2834 if(HasSpell(next_itr
->second
))
2836 // high rank already known so this must !active
2838 next_active_spell_id
= next_itr
->second
;
2844 // not do anything if already known in expected state
2845 if(itr
->second
->state
!= PLAYERSPELL_REMOVED
&& itr
->second
->active
== active
&&
2846 itr
->second
->dependent
== dependent
&& itr
->second
->disabled
== disabled
)
2848 if(!IsInWorld() && !learning
) // explicitly load from DB and then exist in it already and set correctly
2849 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2854 // dependent spell known as not dependent, overwrite state
2855 if (itr
->second
->state
!= PLAYERSPELL_REMOVED
&& !itr
->second
->dependent
&& dependent
)
2857 itr
->second
->dependent
= dependent
;
2858 if (itr
->second
->state
!= PLAYERSPELL_NEW
)
2859 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2860 dependent_set
= true;
2863 // update active state for known spell
2864 if(itr
->second
->active
!= active
&& itr
->second
->state
!= PLAYERSPELL_REMOVED
&& !itr
->second
->disabled
)
2866 itr
->second
->active
= active
;
2868 if(!IsInWorld() && !learning
&& !dependent_set
) // explicitly load from DB and then exist in it already and set correctly
2869 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2870 else if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2871 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2875 if (IsPassiveSpell(spell_id
) && IsNeedCastPassiveSpellAtLearn(spellInfo
))
2876 CastSpell (this,spell_id
,true);
2878 else if(IsInWorld())
2880 if(next_active_spell_id
)
2882 // update spell ranks in spellbook and action bar
2883 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, 4 + 4);
2884 data
<< uint32(spell_id
);
2885 data
<< uint32(next_active_spell_id
);
2886 GetSession()->SendPacket( &data
);
2890 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
2891 data
<< uint32(spell_id
);
2892 GetSession()->SendPacket(&data
);
2896 return active
; // learn (show in spell book if active now)
2899 if(itr
->second
->disabled
!= disabled
&& itr
->second
->state
!= PLAYERSPELL_REMOVED
)
2901 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2902 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2903 itr
->second
->disabled
= disabled
;
2908 disabled_case
= true;
2910 else switch(itr
->second
->state
)
2912 case PLAYERSPELL_UNCHANGED
: // known saved spell
2914 case PLAYERSPELL_REMOVED
: // re-learning removed not saved spell
2917 m_spells
.erase(itr
);
2918 state
= PLAYERSPELL_CHANGED
;
2919 break; // need re-add
2921 default: // known not saved yet spell (new or modified)
2923 // can be in case spell loading but learned at some previous spell loading
2924 if(!IsInWorld() && !learning
&& !dependent_set
)
2925 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2932 if(!disabled_case
) // skip new spell adding if spell already known (disabled spells case)
2934 // talent: unlearn all other talent ranks (high and low)
2935 if(TalentSpellPos
const* talentPos
= GetTalentSpellPos(spell_id
))
2937 if(TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry( talentPos
->talent_id
))
2939 for(int i
=0; i
< MAX_TALENT_RANK
; ++i
)
2941 // skip learning spell and no rank spell case
2942 uint32 rankSpellId
= talentInfo
->RankID
[i
];
2943 if(!rankSpellId
|| rankSpellId
==spell_id
)
2946 removeSpell(rankSpellId
,false,false);
2950 // non talent spell: learn low ranks (recursive call)
2951 else if(uint32 prev_spell
= spellmgr
.GetPrevSpellInChain(spell_id
))
2953 if(!IsInWorld() || disabled
) // at spells loading, no output, but allow save
2954 addSpell(prev_spell
,active
,true,true,disabled
);
2955 else // at normal learning
2956 learnSpell(prev_spell
,true);
2959 PlayerSpell
*newspell
= new PlayerSpell
;
2960 newspell
->state
= state
;
2961 newspell
->active
= active
;
2962 newspell
->dependent
= dependent
;
2963 newspell
->disabled
= disabled
;
2965 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2966 if(newspell
->active
&& !newspell
->disabled
&& !SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
2968 for( PlayerSpellMap::iterator itr2
= m_spells
.begin(); itr2
!= m_spells
.end(); ++itr2
)
2970 if(itr2
->second
->state
== PLAYERSPELL_REMOVED
) continue;
2971 SpellEntry
const *i_spellInfo
= sSpellStore
.LookupEntry(itr2
->first
);
2972 if(!i_spellInfo
) continue;
2974 if( spellmgr
.IsRankSpellDueToSpell(spellInfo
,itr2
->first
) )
2976 if(itr2
->second
->active
)
2978 if(spellmgr
.IsHighRankOfSpell(spell_id
,itr2
->first
))
2980 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2982 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, 4 + 4);
2983 data
<< uint32(itr2
->first
);
2984 data
<< uint32(spell_id
);
2985 GetSession()->SendPacket( &data
);
2988 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2989 itr2
->second
->active
= false;
2990 if(itr2
->second
->state
!= PLAYERSPELL_NEW
)
2991 itr2
->second
->state
= PLAYERSPELL_CHANGED
;
2992 superceded_old
= true; // new spell replace old in action bars and spell book.
2994 else if(spellmgr
.IsHighRankOfSpell(itr2
->first
,spell_id
))
2996 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2998 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, 4 + 4);
2999 data
<< uint32(spell_id
);
3000 data
<< uint32(itr2
->first
);
3001 GetSession()->SendPacket( &data
);
3004 // mark new spell as disable (not learned yet for client and will not learned)
3005 newspell
->active
= false;
3006 if(newspell
->state
!= PLAYERSPELL_NEW
)
3007 newspell
->state
= PLAYERSPELL_CHANGED
;
3014 m_spells
[spell_id
] = newspell
;
3016 // return false if spell disabled
3017 if (newspell
->disabled
)
3021 uint32 talentCost
= GetTalentSpellCost(spell_id
);
3023 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
3024 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
3025 if (talentCost
> 0 && IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_LEARN_SPELL
))
3027 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
3028 CastSpell(this, spell_id
, true);
3030 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
3031 else if (IsPassiveSpell(spell_id
))
3033 if (IsNeedCastPassiveSpellAtLearn(spellInfo
))
3034 CastSpell(this, spell_id
, true);
3036 else if (IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_SKILL_STEP
))
3038 CastSpell(this, spell_id
, true);
3042 // update used talent points count
3043 m_usedTalentCount
+= talentCost
;
3045 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
3046 if (uint32 freeProfs
= GetFreePrimaryProfessionPoints())
3048 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
3049 SetFreePrimaryProfessions(freeProfs
-1);
3052 // add dependent skills
3053 uint16 maxskill
= GetMaxSkillValueForLevel();
3055 SpellLearnSkillNode
const* spellLearnSkill
= spellmgr
.GetSpellLearnSkill(spell_id
);
3057 SkillLineAbilityMapBounds skill_bounds
= spellmgr
.GetSkillLineAbilityMapBounds(spell_id
);
3059 if (spellLearnSkill
)
3061 uint32 skill_value
= GetPureSkillValue(spellLearnSkill
->skill
);
3062 uint32 skill_max_value
= GetPureMaxSkillValue(spellLearnSkill
->skill
);
3064 if (skill_value
< spellLearnSkill
->value
)
3065 skill_value
= spellLearnSkill
->value
;
3067 uint32 new_skill_max_value
= spellLearnSkill
->maxvalue
== 0 ? maxskill
: spellLearnSkill
->maxvalue
;
3069 if (skill_max_value
< new_skill_max_value
)
3070 skill_max_value
= new_skill_max_value
;
3072 SetSkill(spellLearnSkill
->skill
,skill_value
,skill_max_value
);
3076 // not ranked skills
3077 for(SkillLineAbilityMap::const_iterator _spell_idx
= skill_bounds
.first
; _spell_idx
!= skill_bounds
.second
; ++_spell_idx
)
3079 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
3083 if (HasSkill(pSkill
->id
))
3086 if (_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
3087 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3088 ((pSkill
->id
==SKILL_LOCKPICKING
|| pSkill
->id
==SKILL_RUNEFORGING
) && _spell_idx
->second
->max_value
==0))
3090 switch(GetSkillRangeType(pSkill
,_spell_idx
->second
->racemask
!=0))
3092 case SKILL_RANGE_LANGUAGE
:
3093 SetSkill(pSkill
->id
, 300, 300 );
3095 case SKILL_RANGE_LEVEL
:
3096 SetSkill(pSkill
->id
, 1, GetMaxSkillValueForLevel() );
3098 case SKILL_RANGE_MONO
:
3099 SetSkill(pSkill
->id
, 1, 1 );
3108 // learn dependent spells
3109 SpellLearnSpellMapBounds spell_bounds
= spellmgr
.GetSpellLearnSpellMapBounds(spell_id
);
3111 for(SpellLearnSpellMap::const_iterator itr2
= spell_bounds
.first
; itr2
!= spell_bounds
.second
; ++itr2
)
3113 if (!itr2
->second
.autoLearned
)
3115 if (!IsInWorld() || !itr2
->second
.active
) // at spells loading, no output, but allow save
3116 addSpell(itr2
->second
.spell
,itr2
->second
.active
,true,true,false);
3117 else // at normal learning
3118 learnSpell(itr2
->second
.spell
,true);
3122 if (!GetSession()->PlayerLoading())
3124 // not ranked skills
3125 for(SkillLineAbilityMap::const_iterator _spell_idx
= skill_bounds
.first
; _spell_idx
!= skill_bounds
.second
; ++_spell_idx
)
3127 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE
,_spell_idx
->second
->skillId
);
3128 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS
,_spell_idx
->second
->skillId
);
3131 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL
,spell_id
);
3134 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
3135 return active
&& !disabled
&& !superceded_old
;
3138 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry
const* spellInfo
) const
3140 // note: form passives activated with shapeshift spells be implemented by HandleShapeshiftBoosts instead of spell_learn_spell
3141 // talent dependent passives activated at form apply have proper stance data
3142 bool need_cast
= (!spellInfo
->Stances
|| (m_form
!= 0 && (spellInfo
->Stances
& (1<<(m_form
-1)))));
3144 //Check CasterAuraStates
3145 return need_cast
&& (!spellInfo
->CasterAuraState
|| HasAuraState(AuraState(spellInfo
->CasterAuraState
)));
3148 void Player::learnSpell(uint32 spell_id
, bool dependent
)
3150 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
3152 bool disabled
= (itr
!= m_spells
.end()) ? itr
->second
->disabled
: false;
3153 bool active
= disabled
? itr
->second
->active
: true;
3155 bool learning
= addSpell(spell_id
,active
,true,dependent
,false);
3157 // learn all disabled higher ranks (recursive)
3160 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
3161 for(SpellChainMapNext::const_iterator i
= nextMap
.lower_bound(spell_id
); i
!= nextMap
.upper_bound(spell_id
); ++i
)
3163 PlayerSpellMap::iterator iter
= m_spells
.find(i
->second
);
3164 if (iter
!= m_spells
.end() && iter
->second
->disabled
)
3165 learnSpell(i
->second
,false);
3169 // prevent duplicated entires in spell book, also not send if not in world (loading)
3170 if(!learning
|| !IsInWorld ())
3173 WorldPacket
data(SMSG_LEARNED_SPELL
, 4);
3174 data
<< uint32(spell_id
);
3175 GetSession()->SendPacket(&data
);
3178 void Player::removeSpell(uint32 spell_id
, bool disabled
, bool learn_low_rank
)
3180 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
3181 if (itr
== m_spells
.end())
3184 if (itr
->second
->state
== PLAYERSPELL_REMOVED
|| (disabled
&& itr
->second
->disabled
))
3187 // unlearn non talent higher ranks (recursive)
3188 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
3189 for(SpellChainMapNext::const_iterator itr2
= nextMap
.lower_bound(spell_id
); itr2
!= nextMap
.upper_bound(spell_id
); ++itr2
)
3190 if(HasSpell(itr2
->second
) && !GetTalentSpellPos(itr2
->second
))
3191 removeSpell(itr2
->second
,disabled
,false);
3193 // re-search, it can be corrupted in prev loop
3194 itr
= m_spells
.find(spell_id
);
3195 if (itr
== m_spells
.end())
3196 return; // already unleared
3198 bool cur_active
= itr
->second
->active
;
3199 bool cur_dependent
= itr
->second
->dependent
;
3203 itr
->second
->disabled
= disabled
;
3204 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
3205 itr
->second
->state
= PLAYERSPELL_CHANGED
;
3209 if(itr
->second
->state
== PLAYERSPELL_NEW
)
3212 m_spells
.erase(itr
);
3215 itr
->second
->state
= PLAYERSPELL_REMOVED
;
3218 RemoveAurasDueToSpell(spell_id
);
3221 for(int i
= 0; i
< 3; ++i
)
3222 if(PetAura
const* petSpell
= spellmgr
.GetPetAura(spell_id
, i
))
3223 RemovePetAura(petSpell
);
3225 // free talent points
3226 uint32 talentCosts
= GetTalentSpellCost(spell_id
);
3229 if(talentCosts
< m_usedTalentCount
)
3230 m_usedTalentCount
-= talentCosts
;
3232 m_usedTalentCount
= 0;
3235 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3236 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
3238 uint32 freeProfs
= GetFreePrimaryProfessionPoints()+1;
3239 if(freeProfs
<= sWorld
.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL
))
3240 SetFreePrimaryProfessions(freeProfs
);
3243 // remove dependent skill
3244 SpellLearnSkillNode
const* spellLearnSkill
= spellmgr
.GetSpellLearnSkill(spell_id
);
3247 uint32 prev_spell
= spellmgr
.GetPrevSpellInChain(spell_id
);
3248 if(!prev_spell
) // first rank, remove skill
3249 SetSkill(spellLearnSkill
->skill
,0,0);
3252 // search prev. skill setting by spell ranks chain
3253 SpellLearnSkillNode
const* prevSkill
= spellmgr
.GetSpellLearnSkill(prev_spell
);
3254 while(!prevSkill
&& prev_spell
)
3256 prev_spell
= spellmgr
.GetPrevSpellInChain(prev_spell
);
3257 prevSkill
= spellmgr
.GetSpellLearnSkill(spellmgr
.GetFirstSpellInChain(prev_spell
));
3260 if (!prevSkill
) // not found prev skill setting, remove skill
3261 SetSkill(spellLearnSkill
->skill
,0,0);
3262 else // set to prev. skill setting values
3264 uint32 skill_value
= GetPureSkillValue(prevSkill
->skill
);
3265 uint32 skill_max_value
= GetPureMaxSkillValue(prevSkill
->skill
);
3267 if (skill_value
> prevSkill
->value
)
3268 skill_value
= prevSkill
->value
;
3270 uint32 new_skill_max_value
= prevSkill
->maxvalue
== 0 ? GetMaxSkillValueForLevel() : prevSkill
->maxvalue
;
3272 if (skill_max_value
> new_skill_max_value
)
3273 skill_max_value
= new_skill_max_value
;
3275 SetSkill(prevSkill
->skill
,skill_value
,skill_max_value
);
3282 // not ranked skills
3283 SkillLineAbilityMapBounds bounds
= spellmgr
.GetSkillLineAbilityMapBounds(spell_id
);
3285 for(SkillLineAbilityMap::const_iterator _spell_idx
= bounds
.first
; _spell_idx
!= bounds
.second
; ++_spell_idx
)
3287 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
3291 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
&&
3292 pSkill
->categoryId
!= SKILL_CATEGORY_CLASS
||// not unlearn class skills (spellbook/talent pages)
3293 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3294 ((pSkill
->id
==SKILL_LOCKPICKING
|| pSkill
->id
==SKILL_RUNEFORGING
) && _spell_idx
->second
->max_value
==0))
3296 // not reset skills for professions and racial abilities
3297 if ((pSkill
->categoryId
==SKILL_CATEGORY_SECONDARY
|| pSkill
->categoryId
==SKILL_CATEGORY_PROFESSION
) &&
3298 (IsProfessionSkill(pSkill
->id
) || _spell_idx
->second
->racemask
!=0))
3301 SetSkill(pSkill
->id
, 0, 0 );
3306 // remove dependent spells
3307 SpellLearnSpellMapBounds spell_bounds
= spellmgr
.GetSpellLearnSpellMapBounds(spell_id
);
3309 for(SpellLearnSpellMap::const_iterator itr2
= spell_bounds
.first
; itr2
!= spell_bounds
.second
; ++itr2
)
3310 removeSpell(itr2
->second
.spell
, disabled
);
3312 // activate lesser rank in spellbook/action bar, and cast it if need
3313 bool prev_activate
= false;
3315 if (uint32 prev_id
= spellmgr
.GetPrevSpellInChain (spell_id
))
3317 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
3319 // if talent then lesser rank also talent and need learn
3323 learnSpell (prev_id
,false);
3325 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3326 else if (cur_active
&& !SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
3328 // need manually update dependence state (learn spell ignore like attempts)
3329 PlayerSpellMap::iterator prev_itr
= m_spells
.find(prev_id
);
3330 if (prev_itr
!= m_spells
.end())
3332 if (prev_itr
->second
->dependent
!= cur_dependent
)
3334 prev_itr
->second
->dependent
= cur_dependent
;
3335 if (prev_itr
->second
->state
!= PLAYERSPELL_NEW
)
3336 prev_itr
->second
->state
= PLAYERSPELL_CHANGED
;
3339 // now re-learn if need re-activate
3340 if (cur_active
&& !prev_itr
->second
->active
&& learn_low_rank
)
3342 if (addSpell(prev_id
,true,false,prev_itr
->second
->dependent
,prev_itr
->second
->disabled
))
3344 // downgrade spell ranks in spellbook and action bar
3345 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, 4 + 4);
3346 data
<< uint32(spell_id
);
3347 data
<< uint32(prev_id
);
3348 GetSession()->SendPacket( &data
);
3349 prev_activate
= true;
3356 // remove from spell book if not replaced by lesser rank
3359 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
3360 data
<< uint32(spell_id
);
3361 GetSession()->SendPacket(&data
);
3365 void Player::RemoveSpellCooldown( uint32 spell_id
, bool update
/* = false */ )
3367 m_spellCooldowns
.erase(spell_id
);
3370 SendClearCooldown(spell_id
, this);
3373 void Player::RemoveSpellCategoryCooldown(uint32 cat
, bool update
/* = false */)
3375 SpellCategoryStore::const_iterator ct
= sSpellCategoryStore
.find(cat
);
3376 if (ct
== sSpellCategoryStore
.end())
3379 const SpellCategorySet
& ct_set
= ct
->second
;
3380 for (SpellCooldowns::const_iterator i
= m_spellCooldowns
.begin(); i
!= m_spellCooldowns
.end();)
3382 if (ct_set
.find(i
->first
) != ct_set
.end())
3383 RemoveSpellCooldown((i
++)->first
, update
);
3389 void Player::RemoveArenaSpellCooldowns()
3391 // remove cooldowns on spells that has < 15 min CD
3392 SpellCooldowns::iterator itr
, next
;
3393 // iterate spell cooldowns
3394 for(itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); itr
= next
)
3398 SpellEntry
const * entry
= sSpellStore
.LookupEntry(itr
->first
);
3399 // check if spellentry is present and if the cooldown is less than 15 mins
3401 entry
->RecoveryTime
<= 15 * MINUTE
* IN_MILISECONDS
&&
3402 entry
->CategoryRecoveryTime
<= 15 * MINUTE
* IN_MILISECONDS
)
3405 RemoveSpellCooldown(itr
->first
, true);
3410 void Player::RemoveAllSpellCooldown()
3412 if(!m_spellCooldowns
.empty())
3414 for(SpellCooldowns::const_iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); ++itr
)
3415 SendClearCooldown(itr
->first
, this);
3417 m_spellCooldowns
.clear();
3421 void Player::_LoadSpellCooldowns(QueryResult
*result
)
3423 // some cooldowns can be already set at aura loading...
3425 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3429 time_t curTime
= time(NULL
);
3433 Field
*fields
= result
->Fetch();
3435 uint32 spell_id
= fields
[0].GetUInt32();
3436 uint32 item_id
= fields
[1].GetUInt32();
3437 time_t db_time
= (time_t)fields
[2].GetUInt64();
3439 if(!sSpellStore
.LookupEntry(spell_id
))
3441 sLog
.outError("Player %u has unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id
);
3445 // skip outdated cooldown
3446 if(db_time
<= curTime
)
3449 AddSpellCooldown(spell_id
, item_id
, db_time
);
3451 sLog
.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id
, item_id
, uint32(db_time
-curTime
));
3453 while( result
->NextRow() );
3459 void Player::_SaveSpellCooldowns()
3461 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3463 time_t curTime
= time(NULL
);
3464 time_t infTime
= curTime
+ infinityCooldownDelayCheck
;
3466 // remove outdated and save active
3467 for(SpellCooldowns::iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end();)
3469 if(itr
->second
.end
<= curTime
)
3470 m_spellCooldowns
.erase(itr
++);
3471 else if(itr
->second
.end
<= infTime
) // not save locked cooldowns, it will be reset or set at reload
3473 CharacterDatabase
.PExecute("INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ('%u', '%u', '%u', '" UI64FMTD
"')", GetGUIDLow(), itr
->first
, itr
->second
.itemid
, uint64(itr
->second
.end
));
3481 uint32
Player::resetTalentsCost() const
3483 // The first time reset costs 1 gold
3484 if(m_resetTalentsCost
< 1*GOLD
)
3487 else if(m_resetTalentsCost
< 5*GOLD
)
3489 // After that it increases in increments of 5 gold
3490 else if(m_resetTalentsCost
< 10*GOLD
)
3494 uint32 months
= (sWorld
.GetGameTime() - m_resetTalentsTime
)/MONTH
;
3497 // This cost will be reduced by a rate of 5 gold per month
3498 int32 new_cost
= int32(m_resetTalentsCost
) - 5*GOLD
*months
;
3499 // to a minimum of 10 gold.
3500 return (new_cost
< 10*GOLD
? 10*GOLD
: new_cost
);
3504 // After that it increases in increments of 5 gold
3505 int32 new_cost
= m_resetTalentsCost
+ 5*GOLD
;
3506 // until it hits a cap of 50 gold.
3507 if(new_cost
> 50*GOLD
)
3514 bool Player::resetTalents(bool no_cost
)
3516 // not need after this call
3517 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS
))
3518 RemoveAtLoginFlag(AT_LOGIN_RESET_TALENTS
,true);
3520 uint32 talentPointsForLevel
= CalculateTalentsPoints();
3522 if (m_usedTalentCount
== 0)
3524 SetFreeTalentPoints(talentPointsForLevel
);
3532 cost
= resetTalentsCost();
3534 if (GetMoney() < cost
)
3536 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, 0, 0, 0);
3541 for (unsigned int i
= 0; i
< sTalentStore
.GetNumRows(); ++i
)
3543 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry(i
);
3545 if (!talentInfo
) continue;
3547 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentInfo
->TalentTab
);
3552 // unlearn only talents for character class
3553 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3554 // to prevent unexpected lost normal learned spell skip another class talents
3555 if( (getClassMask() & talentTabInfo
->ClassMask
) == 0 )
3558 for (int j
= 0; j
< MAX_TALENT_RANK
; ++j
)
3560 for(PlayerSpellMap::iterator itr
= GetSpellMap().begin(); itr
!= GetSpellMap().end();)
3562 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->second
->disabled
)
3568 // remove learned spells (all ranks)
3569 uint32 itrFirstId
= spellmgr
.GetFirstSpellInChain(itr
->first
);
3571 // unlearn if first rank is talent or learned by talent
3572 if (itrFirstId
== talentInfo
->RankID
[j
])
3574 removeSpell(itr
->first
,!IsPassiveSpell(itr
->first
),false);
3575 itr
= GetSpellMap().begin();
3578 else if (spellmgr
.IsSpellLearnToSpell(talentInfo
->RankID
[j
],itrFirstId
))
3580 removeSpell(itr
->first
,!IsPassiveSpell(itr
->first
));
3581 itr
= GetSpellMap().begin();
3590 SetFreeTalentPoints(talentPointsForLevel
);
3594 ModifyMoney(-(int32
)cost
);
3595 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS
, cost
);
3596 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS
, 1);
3598 m_resetTalentsCost
= cost
;
3599 m_resetTalentsTime
= time(NULL
);
3602 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3603 RemovePet(NULL
,PET_SAVE_NOT_IN_SLOT
, true);
3604 /* when prev line will dropped use next line
3605 if(Pet* pet = GetPet())
3607 if(pet->getPetType()==HUNTER_PET && !pet->GetCreatureInfo()->isTameable(CanTameExoticPets()))
3608 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3615 m_canTitanGrip
= false;
3616 if(sWorld
.getConfig(CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET
))
3617 AutoUnequipOffhandIfNeed();
3623 Mail
* Player::GetMail(uint32 id
)
3625 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
3627 if ((*itr
)->messageID
== id
)
3635 void Player::_SetCreateBits(UpdateMask
*updateMask
, Player
*target
) const
3639 Object::_SetCreateBits(updateMask
, target
);
3643 for(uint16 index
= 0; index
< m_valuesCount
; index
++)
3645 if(GetUInt32Value(index
) != 0 && updateVisualBits
.GetBit(index
))
3646 updateMask
->SetBit(index
);
3651 void Player::_SetUpdateBits(UpdateMask
*updateMask
, Player
*target
) const
3655 Object::_SetUpdateBits(updateMask
, target
);
3659 Object::_SetUpdateBits(updateMask
, target
);
3660 *updateMask
&= updateVisualBits
;
3664 void Player::InitVisibleBits()
3666 updateVisualBits
.SetCount(PLAYER_END
);
3668 updateVisualBits
.SetBit(OBJECT_FIELD_GUID
);
3669 updateVisualBits
.SetBit(OBJECT_FIELD_TYPE
);
3670 updateVisualBits
.SetBit(OBJECT_FIELD_ENTRY
);
3671 updateVisualBits
.SetBit(OBJECT_FIELD_SCALE_X
);
3672 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 0);
3673 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 1);
3674 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 0);
3675 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 1);
3676 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 0);
3677 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 1);
3678 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 0);
3679 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 1);
3680 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 0);
3681 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 1);
3682 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_0
);
3683 updateVisualBits
.SetBit(UNIT_FIELD_HEALTH
);
3684 updateVisualBits
.SetBit(UNIT_FIELD_POWER1
);
3685 updateVisualBits
.SetBit(UNIT_FIELD_POWER2
);
3686 updateVisualBits
.SetBit(UNIT_FIELD_POWER3
);
3687 updateVisualBits
.SetBit(UNIT_FIELD_POWER4
);
3688 updateVisualBits
.SetBit(UNIT_FIELD_POWER5
);
3689 updateVisualBits
.SetBit(UNIT_FIELD_POWER6
);
3690 updateVisualBits
.SetBit(UNIT_FIELD_POWER7
);
3691 updateVisualBits
.SetBit(UNIT_FIELD_MAXHEALTH
);
3692 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER1
);
3693 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER2
);
3694 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER3
);
3695 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER4
);
3696 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER5
);
3697 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER6
);
3698 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER7
);
3699 updateVisualBits
.SetBit(UNIT_FIELD_LEVEL
);
3700 updateVisualBits
.SetBit(UNIT_FIELD_FACTIONTEMPLATE
);
3701 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 0);
3702 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 1);
3703 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 2);
3704 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS
);
3705 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS_2
);
3706 updateVisualBits
.SetBit(UNIT_FIELD_AURASTATE
);
3707 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 0);
3708 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 1);
3709 updateVisualBits
.SetBit(UNIT_FIELD_BOUNDINGRADIUS
);
3710 updateVisualBits
.SetBit(UNIT_FIELD_COMBATREACH
);
3711 updateVisualBits
.SetBit(UNIT_FIELD_DISPLAYID
);
3712 updateVisualBits
.SetBit(UNIT_FIELD_NATIVEDISPLAYID
);
3713 updateVisualBits
.SetBit(UNIT_FIELD_MOUNTDISPLAYID
);
3714 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_1
);
3715 updateVisualBits
.SetBit(UNIT_FIELD_PETNUMBER
);
3716 updateVisualBits
.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP
);
3717 updateVisualBits
.SetBit(UNIT_DYNAMIC_FLAGS
);
3718 updateVisualBits
.SetBit(UNIT_CHANNEL_SPELL
);
3719 updateVisualBits
.SetBit(UNIT_MOD_CAST_SPEED
);
3720 updateVisualBits
.SetBit(UNIT_FIELD_BASE_MANA
);
3721 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_2
);
3722 updateVisualBits
.SetBit(UNIT_FIELD_HOVERHEIGHT
);
3724 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 0);
3725 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 1);
3726 updateVisualBits
.SetBit(PLAYER_FLAGS
);
3727 updateVisualBits
.SetBit(PLAYER_GUILDID
);
3728 updateVisualBits
.SetBit(PLAYER_GUILDRANK
);
3729 updateVisualBits
.SetBit(PLAYER_BYTES
);
3730 updateVisualBits
.SetBit(PLAYER_BYTES_2
);
3731 updateVisualBits
.SetBit(PLAYER_BYTES_3
);
3732 updateVisualBits
.SetBit(PLAYER_DUEL_TEAM
);
3733 updateVisualBits
.SetBit(PLAYER_GUILD_TIMESTAMP
);
3735 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3736 for(uint16 i
= PLAYER_QUEST_LOG_1_1
; i
< PLAYER_QUEST_LOG_25_2
; i
+= 4)
3737 updateVisualBits
.SetBit(i
);
3739 // Players visible items are not inventory stuff
3740 for(uint16 i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
3742 uint32 offset
= i
* 2;
3745 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_ENTRYID
+ offset
);
3747 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT
+ offset
);
3750 updateVisualBits
.SetBit(PLAYER_CHOSEN_TITLE
);
3753 void Player::BuildCreateUpdateBlockForPlayer( UpdateData
*data
, Player
*target
) const
3755 for(int i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
3757 if(m_items
[i
] == NULL
)
3760 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3765 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
3767 if(m_items
[i
] == NULL
)
3770 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3772 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
3774 if(m_items
[i
] == NULL
)
3777 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3781 Unit::BuildCreateUpdateBlockForPlayer( data
, target
);
3784 void Player::DestroyForPlayer( Player
*target
, bool anim
) const
3786 Unit::DestroyForPlayer( target
, anim
);
3788 for(int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
3790 if(m_items
[i
] == NULL
)
3793 m_items
[i
]->DestroyForPlayer( target
);
3798 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
3800 if(m_items
[i
] == NULL
)
3803 m_items
[i
]->DestroyForPlayer( target
);
3805 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
3807 if(m_items
[i
] == NULL
)
3810 m_items
[i
]->DestroyForPlayer( target
);
3815 bool Player::HasSpell(uint32 spell
) const
3817 PlayerSpellMap::const_iterator itr
= m_spells
.find(spell
);
3818 return (itr
!= m_spells
.end() && itr
->second
->state
!= PLAYERSPELL_REMOVED
&&
3819 !itr
->second
->disabled
);
3822 bool Player::HasActiveSpell(uint32 spell
) const
3824 PlayerSpellMap::const_iterator itr
= m_spells
.find(spell
);
3825 return (itr
!= m_spells
.end() && itr
->second
->state
!= PLAYERSPELL_REMOVED
&&
3826 itr
->second
->active
&& !itr
->second
->disabled
);
3829 TrainerSpellState
Player::GetTrainerSpellState(TrainerSpell
const* trainer_spell
) const
3832 return TRAINER_SPELL_RED
;
3834 if (!trainer_spell
->learnedSpell
)
3835 return TRAINER_SPELL_RED
;
3838 if(HasSpell(trainer_spell
->learnedSpell
))
3839 return TRAINER_SPELL_GRAY
;
3841 // check race/class requirement
3842 if(!IsSpellFitByClassAndRace(trainer_spell
->learnedSpell
))
3843 return TRAINER_SPELL_RED
;
3845 // check level requirement
3846 if(getLevel() < trainer_spell
->reqLevel
)
3847 return TRAINER_SPELL_RED
;
3849 if(SpellChainNode
const* spell_chain
= spellmgr
.GetSpellChainNode(trainer_spell
->learnedSpell
))
3851 // check prev.rank requirement
3852 if(spell_chain
->prev
&& !HasSpell(spell_chain
->prev
))
3853 return TRAINER_SPELL_RED
;
3855 // check additional spell requirement
3856 if(spell_chain
->req
&& !HasSpell(spell_chain
->req
))
3857 return TRAINER_SPELL_RED
;
3860 // check skill requirement
3861 if(trainer_spell
->reqSkill
&& GetBaseSkillValue(trainer_spell
->reqSkill
) < trainer_spell
->reqSkillValue
)
3862 return TRAINER_SPELL_RED
;
3864 // exist, already checked at loading
3865 SpellEntry
const* spell
= sSpellStore
.LookupEntry(trainer_spell
->learnedSpell
);
3867 // secondary prof. or not prof. spell
3868 uint32 skill
= spell
->EffectMiscValue
[1];
3870 if(spell
->Effect
[1] != SPELL_EFFECT_SKILL
|| !IsPrimaryProfessionSkill(skill
))
3871 return TRAINER_SPELL_GREEN
;
3873 // check primary prof. limit
3874 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell
->Id
) && GetFreePrimaryProfessionPoints() == 0)
3875 return TRAINER_SPELL_GREEN_DISABLED
;
3877 return TRAINER_SPELL_GREEN
;
3880 void Player::DeleteFromDB(uint64 playerguid
, uint32 accountId
, bool updateRealmChars
)
3882 uint32 guid
= GUID_LOPART(playerguid
);
3884 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3885 // bones will be deleted by corpse/bones deleting thread shortly
3886 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid
);
3888 // remove from guild
3889 uint32 guildId
= GetGuildIdFromDB(playerguid
);
3892 Guild
* guild
= objmgr
.GetGuildById(guildId
);
3894 guild
->DelMember(guid
);
3897 // remove from arena teams
3898 LeaveAllArenaTeams(playerguid
);
3900 // the player was uninvited already on logout so just remove from group
3901 QueryResult
*resultGroup
= CharacterDatabase
.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid
);
3904 uint64 leaderGuid
= MAKE_NEW_GUID((*resultGroup
)[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
3906 Group
* group
= objmgr
.GetGroupByLeader(leaderGuid
);
3909 RemoveFromGroup(group
, playerguid
);
3913 // remove signs from petitions (also remove petitions if owner);
3914 RemovePetitionsAndSigns(playerguid
, 10);
3916 // return back all mails with COD and Item 0 1 2 3 4 5 6
3917 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
);
3922 Field
*fields
= resultMail
->Fetch();
3924 uint32 mail_id
= fields
[0].GetUInt32();
3925 uint16 mailTemplateId
= fields
[1].GetUInt16();
3926 uint32 sender
= fields
[2].GetUInt32();
3927 std::string subject
= fields
[3].GetCppString();
3928 uint32 itemTextId
= fields
[4].GetUInt32();
3929 uint32 money
= fields
[5].GetUInt32();
3930 bool has_items
= fields
[6].GetBool();
3932 //we can return mail now
3933 //so firstly delete the old one
3934 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id
);
3939 // data needs to be at first place for Item::LoadFromDB
3940 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
);
3945 Field
*fields2
= resultItems
->Fetch();
3947 uint32 item_guidlow
= fields2
[1].GetUInt32();
3948 uint32 item_template
= fields2
[2].GetUInt32();
3950 ItemPrototype
const* itemProto
= objmgr
.GetItemPrototype(item_template
);
3953 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow
);
3957 Item
*pItem
= NewItemOrBag(itemProto
);
3958 if(!pItem
->LoadFromDB(item_guidlow
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
),resultItems
))
3960 pItem
->FSetState(ITEM_REMOVED
);
3961 pItem
->SaveToDB(); // it also deletes item object !
3965 mi
.AddItem(item_guidlow
, item_template
, pItem
);
3967 while (resultItems
->NextRow());
3973 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id
);
3975 uint32 pl_account
= objmgr
.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
3977 WorldSession::SendReturnToSender(MAIL_NORMAL
, pl_account
, guid
, sender
, subject
, itemTextId
, &mi
, money
, mailTemplateId
);
3979 while (resultMail
->NextRow());
3984 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3985 // Get guids of character's pets, will deleted in transaction
3986 QueryResult
*resultPets
= CharacterDatabase
.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid
);
3988 // NOW we can finally clear other DB data related to character
3989 CharacterDatabase
.BeginTransaction();
3994 Field
*fields3
= resultPets
->Fetch();
3995 uint32 petguidlow
= fields3
[0].GetUInt32();
3996 Pet::DeleteFromDB(petguidlow
);
3997 } while (resultPets
->NextRow());
4001 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",guid
);
4002 CharacterDatabase
.PExecute("DELETE FROM character_account_data WHERE guid = '%u'",guid
);
4003 CharacterDatabase
.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid
);
4004 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid
);
4005 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid
);
4006 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid
);
4007 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid
);
4008 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid
);
4009 CharacterDatabase
.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid
);
4010 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid
);
4011 CharacterDatabase
.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid
);
4012 CharacterDatabase
.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid
);
4013 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid
);
4014 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid
);
4015 CharacterDatabase
.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid
);
4016 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid
);
4017 CharacterDatabase
.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid
,guid
);
4018 CharacterDatabase
.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid
);
4019 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid
);
4020 CharacterDatabase
.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid
);
4021 CharacterDatabase
.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid
);
4022 CharacterDatabase
.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid
);
4023 CharacterDatabase
.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid
);
4024 CharacterDatabase
.PExecute("DELETE FROM character_equipmentsets WHERE guid = '%u'",guid
);
4025 CharacterDatabase
.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid1 = '%u'",guid
);
4026 CharacterDatabase
.PExecute("DELETE FROM guild_eventlog WHERE PlayerGuid2 = '%u'",guid
);
4027 CharacterDatabase
.PExecute("DELETE FROM guild_bank_eventlog WHERE PlayerGuid = '%u'",guid
);
4028 CharacterDatabase
.CommitTransaction();
4030 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
4031 if(updateRealmChars
) sWorld
.UpdateRealmCharCount(accountId
);
4034 void Player::SetMovement(PlayerMovementType pType
)
4039 case MOVE_ROOT
: data
.Initialize(SMSG_FORCE_MOVE_ROOT
, GetPackGUID().size()+4); break;
4040 case MOVE_UNROOT
: data
.Initialize(SMSG_FORCE_MOVE_UNROOT
, GetPackGUID().size()+4); break;
4041 case MOVE_WATER_WALK
: data
.Initialize(SMSG_MOVE_WATER_WALK
, GetPackGUID().size()+4); break;
4042 case MOVE_LAND_WALK
: data
.Initialize(SMSG_MOVE_LAND_WALK
, GetPackGUID().size()+4); break;
4044 sLog
.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType
);
4047 data
.append(GetPackGUID());
4049 GetSession()->SendPacket( &data
);
4053 - a resurrectable corpse must not be loaded for the player (only bones)
4054 - the player must be in world
4056 void Player::BuildPlayerRepop()
4058 WorldPacket
data(SMSG_PRE_RESURRECT
, GetPackGUID().size());
4059 data
.append(GetPackGUID());
4060 GetSession()->SendPacket(&data
);
4062 if(getRace() == RACE_NIGHTELF
)
4063 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)
4064 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
4066 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
4067 // there must be SMSG.STOP_MIRROR_TIMER
4068 // there we must send 888 opcode
4070 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
4073 sLog
.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
4077 // create a corpse and place it at the player's location
4079 Corpse
*corpse
= GetCorpse();
4082 sLog
.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
4085 GetMap()->Add(corpse
);
4087 // convert player body to ghost
4090 SetMovement(MOVE_WATER_WALK
);
4091 if(!GetSession()->isLogingOut())
4092 SetMovement(MOVE_UNROOT
);
4094 // BG - remove insignia related
4095 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_SKINNABLE
);
4097 SendCorpseReclaimDelay();
4099 // to prevent cheating
4100 corpse
->ResetGhostTime();
4102 StopMirrorTimers(); //disable timers(bars)
4104 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, (float)1.0); //see radius of death player?
4106 // set and clear other
4107 SetByteValue(UNIT_FIELD_BYTES_1
, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND
);
4110 void Player::SendDelayResponse(const uint32 ml_seconds
)
4112 //FIXME: is this delay time arg really need? 50msec by default in code
4113 WorldPacket
data( SMSG_QUERY_TIME_RESPONSE
, 4+4 );
4114 data
<< (uint32
)time(NULL
);
4116 GetSession()->SendPacket( &data
);
4119 void Player::ResurrectPlayer(float restore_percent
, bool applySickness
)
4121 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // remove spirit healer position
4126 GetSession()->SendPacket(&data
);
4128 // speed change, land walk
4130 // remove death flag + set aura
4131 SetByteValue(UNIT_FIELD_BYTES_1
, 3, 0x00);
4132 if(getRace() == RACE_NIGHTELF
)
4133 RemoveAurasDueToSpell(20584); // speed bonuses
4134 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
4136 setDeathState(ALIVE
);
4138 SetMovement(MOVE_LAND_WALK
);
4139 SetMovement(MOVE_UNROOT
);
4143 // set health/powers (0- will be set in caller)
4144 if(restore_percent
>0.0f
)
4146 SetHealth(uint32(GetMaxHealth()*restore_percent
));
4147 SetPower(POWER_MANA
, uint32(GetMaxPower(POWER_MANA
)*restore_percent
));
4148 SetPower(POWER_RAGE
, 0);
4149 SetPower(POWER_ENERGY
, uint32(GetMaxPower(POWER_ENERGY
)*restore_percent
));
4152 // trigger update zone for alive state zone updates
4153 uint32 newzone
, newarea
;
4154 GetZoneAndAreaId(newzone
,newarea
);
4155 UpdateZone(newzone
,newarea
);
4157 // update visibility
4158 UpdateVisibilityForPlayer();
4163 //Characters from level 1-10 are not affected by resurrection sickness.
4164 //Characters from level 11-19 will suffer from one minute of sickness
4165 //for each level they are above 10.
4166 //Characters level 20 and up suffer from ten minutes of sickness.
4167 int32 startLevel
= sWorld
.getConfig(CONFIG_DEATH_SICKNESS_LEVEL
);
4169 if(int32(getLevel()) >= startLevel
)
4171 // set resurrection sickness
4172 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,true);
4174 // not full duration
4175 if(int32(getLevel()) < startLevel
+9)
4177 int32 delta
= (int32(getLevel()) - startLevel
+ 1)*MINUTE
;
4179 for(int i
=0; i
< 3; ++i
)
4181 if(Aura
* Aur
= GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,i
))
4183 Aur
->SetAuraDuration(delta
*IN_MILISECONDS
);
4184 Aur
->SendAuraUpdate(false);
4191 void Player::KillPlayer()
4193 SetMovement(MOVE_ROOT
);
4195 StopMirrorTimers(); //disable timers(bars)
4197 setDeathState(CORPSE
);
4198 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
4200 SetFlag(UNIT_DYNAMIC_FLAGS
, 0x00);
4201 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, !sMapStore
.LookupEntry(GetMapId())->Instanceable());
4203 // 6 minutes until repop at graveyard
4204 m_deathTimer
= 6*MINUTE
*IN_MILISECONDS
;
4206 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4208 // don't create corpse at this moment, player might be falling
4210 // update visibility
4211 UpdateObjectVisibility();
4214 void Player::CreateCorpse()
4216 // prevent existence 2 corpse for player
4219 uint32 _uf
, _pb
, _pb2
, _cfb1
, _cfb2
;
4221 Corpse
*corpse
= new Corpse( (m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
) ? CORPSE_RESURRECTABLE_PVP
: CORPSE_RESURRECTABLE_PVE
);
4224 if(!corpse
->Create(objmgr
.GenerateLowGuid(HIGHGUID_CORPSE
), this))
4230 _uf
= GetUInt32Value(UNIT_FIELD_BYTES_0
);
4231 _pb
= GetUInt32Value(PLAYER_BYTES
);
4232 _pb2
= GetUInt32Value(PLAYER_BYTES_2
);
4234 uint8 race
= (uint8
)(_uf
);
4235 uint8 skin
= (uint8
)(_pb
);
4236 uint8 face
= (uint8
)(_pb
>> 8);
4237 uint8 hairstyle
= (uint8
)(_pb
>> 16);
4238 uint8 haircolor
= (uint8
)(_pb
>> 24);
4239 uint8 facialhair
= (uint8
)(_pb2
);
4241 _cfb1
= ((0x00) | (race
<< 8) | (getGender() << 16) | (skin
<< 24));
4242 _cfb2
= ((face
) | (hairstyle
<< 8) | (haircolor
<< 16) | (facialhair
<< 24));
4244 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_1
, _cfb1
);
4245 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_2
, _cfb2
);
4247 uint32 flags
= CORPSE_FLAG_UNK2
;
4248 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
4249 flags
|= CORPSE_FLAG_HIDE_HELM
;
4250 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
4251 flags
|= CORPSE_FLAG_HIDE_CLOAK
;
4252 if(InBattleGround() && !InArena())
4253 flags
|= CORPSE_FLAG_LOOTABLE
; // to be able to remove insignia
4254 corpse
->SetUInt32Value( CORPSE_FIELD_FLAGS
, flags
);
4256 corpse
->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID
, GetNativeDisplayId() );
4258 corpse
->SetUInt32Value( CORPSE_FIELD_GUILD
, GetGuildId() );
4261 uint32 iIventoryType
;
4263 for (int i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
4267 iDisplayID
= m_items
[i
]->GetProto()->DisplayInfoID
;
4268 iIventoryType
= m_items
[i
]->GetProto()->InventoryType
;
4270 _cfi
= iDisplayID
| (iIventoryType
<< 24);
4271 corpse
->SetUInt32Value(CORPSE_FIELD_ITEM
+ i
, _cfi
);
4275 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4276 const MapEntry
*entry
= sMapStore
.LookupEntry(corpse
->GetMapId());
4278 if(entry
->map_type
!= MAP_BATTLEGROUND
)
4281 // register for player, but not show
4282 ObjectAccessor::Instance().AddCorpse(corpse
);
4285 void Player::SpawnCorpseBones()
4287 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4288 SaveToDB(); // prevent loading as ghost without corpse
4291 Corpse
* Player::GetCorpse() const
4293 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4296 void Player::DurabilityLossAll(double percent
, bool inventory
)
4298 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
4299 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4300 DurabilityLoss(pItem
,percent
);
4304 // bags not have durability
4305 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4307 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
4308 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4309 DurabilityLoss(pItem
,percent
);
4311 // keys not have durability
4312 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4314 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
4315 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4316 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
4317 if(Item
* pItem
= GetItemByPos( i
, j
))
4318 DurabilityLoss(pItem
,percent
);
4322 void Player::DurabilityLoss(Item
* item
, double percent
)
4327 uint32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4332 uint32 pDurabilityLoss
= uint32(pMaxDurability
*percent
);
4334 if(pDurabilityLoss
< 1 )
4335 pDurabilityLoss
= 1;
4337 DurabilityPointsLoss(item
,pDurabilityLoss
);
4340 void Player::DurabilityPointsLossAll(int32 points
, bool inventory
)
4342 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
4343 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4344 DurabilityPointsLoss(pItem
,points
);
4348 // bags not have durability
4349 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
4351 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
4352 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4353 DurabilityPointsLoss(pItem
,points
);
4355 // keys not have durability
4356 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
4358 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
4359 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4360 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
4361 if(Item
* pItem
= GetItemByPos( i
, j
))
4362 DurabilityPointsLoss(pItem
,points
);
4366 void Player::DurabilityPointsLoss(Item
* item
, int32 points
)
4368 int32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4369 int32 pOldDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4370 int32 pNewDurability
= pOldDurability
- points
;
4372 if (pNewDurability
< 0)
4374 else if (pNewDurability
> pMaxDurability
)
4375 pNewDurability
= pMaxDurability
;
4377 if (pOldDurability
!= pNewDurability
)
4379 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4380 if ( pNewDurability
== 0 && pOldDurability
> 0 && item
->IsEquipped())
4381 _ApplyItemMods(item
,item
->GetSlot(), false);
4383 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, pNewDurability
);
4385 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4386 if ( pNewDurability
> 0 && pOldDurability
== 0 && item
->IsEquipped())
4387 _ApplyItemMods(item
,item
->GetSlot(), true);
4389 item
->SetState(ITEM_CHANGED
, this);
4393 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot
)
4395 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
))
4396 DurabilityPointsLoss(pItem
,1);
4399 uint32
Player::DurabilityRepairAll(bool cost
, float discountMod
, bool guildBank
)
4401 uint32 TotalCost
= 0;
4402 // equipped, backpack, bags itself
4403 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
4404 TotalCost
+= DurabilityRepair(( (INVENTORY_SLOT_BAG_0
<< 8) | i
),cost
,discountMod
, guildBank
);
4406 // bank, buyback and keys not repaired
4408 // items in inventory bags
4409 for(int j
= INVENTORY_SLOT_BAG_START
; j
< INVENTORY_SLOT_BAG_END
; ++j
)
4410 for(int i
= 0; i
< MAX_BAG_SIZE
; ++i
)
4411 TotalCost
+= DurabilityRepair(( (j
<< 8) | i
),cost
,discountMod
, guildBank
);
4415 uint32
Player::DurabilityRepair(uint16 pos
, bool cost
, float discountMod
, bool guildBank
)
4417 Item
* item
= GetItemByPos(pos
);
4419 uint32 TotalCost
= 0;
4423 uint32 maxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4427 uint32 curDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4431 uint32 LostDurability
= maxDurability
- curDurability
;
4432 if(LostDurability
>0)
4434 ItemPrototype
const *ditemProto
= item
->GetProto();
4436 DurabilityCostsEntry
const *dcost
= sDurabilityCostsStore
.LookupEntry(ditemProto
->ItemLevel
);
4439 sLog
.outError("RepairDurability: Wrong item lvl %u", ditemProto
->ItemLevel
);
4443 uint32 dQualitymodEntryId
= (ditemProto
->Quality
+1)*2;
4444 DurabilityQualityEntry
const *dQualitymodEntry
= sDurabilityQualityStore
.LookupEntry(dQualitymodEntryId
);
4445 if(!dQualitymodEntry
)
4447 sLog
.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId
);
4451 uint32 dmultiplier
= dcost
->multiplier
[ItemSubClassToDurabilityMultiplierId(ditemProto
->Class
,ditemProto
->SubClass
)];
4452 uint32 costs
= uint32(LostDurability
*dmultiplier
*double(dQualitymodEntry
->quality_mod
));
4454 costs
= uint32(costs
* discountMod
);
4456 if (costs
==0) //fix for ITEM_QUALITY_ARTIFACT
4461 if (GetGuildId()==0)
4463 DEBUG_LOG("You are not member of a guild");
4467 Guild
*pGuild
= objmgr
.GetGuildById(GetGuildId());
4471 if (!pGuild
->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR
))
4473 DEBUG_LOG("You do not have rights to withdraw for repairs");
4477 if (pGuild
->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs
)
4479 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4483 if (pGuild
->GetGuildBankMoney() < costs
)
4485 DEBUG_LOG("There is not enough money in bank");
4489 pGuild
->MemberMoneyWithdraw(costs
, GetGUIDLow());
4492 else if (GetMoney() < costs
)
4494 DEBUG_LOG("You do not have enough money");
4498 ModifyMoney( -int32(costs
) );
4502 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, maxDurability
);
4503 item
->SetState(ITEM_CHANGED
, this);
4505 // reapply mods for total broken and repaired item if equipped
4506 if(IsEquipmentPos(pos
) && !curDurability
)
4507 _ApplyItemMods(item
,pos
& 255, true);
4511 void Player::RepopAtGraveyard()
4513 // note: this can be called also when the player is alive
4514 // for example from WorldSession::HandleMovementOpcodes
4516 AreaTableEntry
const *zone
= GetAreaEntryByAreaID(GetAreaId());
4518 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4519 if ((!isAlive() && zone
&& zone
->flags
& AREA_FLAG_NEED_FLY
) || GetTransport())
4521 ResurrectPlayer(0.5f
);
4525 WorldSafeLocsEntry
const *ClosestGrave
= NULL
;
4527 // Special handle for battleground maps
4528 if( BattleGround
*bg
= GetBattleGround() )
4529 ClosestGrave
= bg
->GetClosestGraveYard(this);
4531 ClosestGrave
= objmgr
.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4533 // stop countdown until repop
4536 // if no grave found, stay at the current location
4537 // and don't show spirit healer location
4540 TeleportTo(ClosestGrave
->map_id
, ClosestGrave
->x
, ClosestGrave
->y
, ClosestGrave
->z
, GetOrientation());
4541 if(isDead()) // not send if alive, because it used in TeleportTo()
4543 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // show spirit healer position on minimap
4544 data
<< ClosestGrave
->map_id
;
4545 data
<< ClosestGrave
->x
;
4546 data
<< ClosestGrave
->y
;
4547 data
<< ClosestGrave
->z
;
4548 GetSession()->SendPacket(&data
);
4553 void Player::JoinedChannel(Channel
*c
)
4555 m_channels
.push_back(c
);
4558 void Player::LeftChannel(Channel
*c
)
4560 m_channels
.remove(c
);
4563 void Player::CleanupChannels()
4565 while(!m_channels
.empty())
4567 Channel
* ch
= *m_channels
.begin();
4568 m_channels
.erase(m_channels
.begin()); // remove from player's channel list
4569 ch
->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4570 if (ChannelMgr
* cMgr
= channelMgr(GetTeam()))
4571 cMgr
->LeftChannel(ch
->GetName()); // deleted channel if empty
4574 sLog
.outDebug("Player: channels cleaned up!");
4577 void Player::UpdateLocalChannels(uint32 newZone
)
4579 if(m_channels
.empty())
4582 AreaTableEntry
const* current_zone
= GetAreaEntryByAreaID(newZone
);
4586 ChannelMgr
* cMgr
= channelMgr(GetTeam());
4590 std::string current_zone_name
= current_zone
->area_name
[GetSession()->GetSessionDbcLocale()];
4592 for(JoinedChannelsList::iterator i
= m_channels
.begin(), next
; i
!= m_channels
.end(); i
= next
)
4596 // skip non built-in channels
4597 if(!(*i
)->IsConstant())
4600 ChatChannelsEntry
const* ch
= GetChannelEntryFor((*i
)->GetChannelId());
4604 if((ch
->flags
& 4) == 4) // global channel without zone name in pattern
4608 char new_channel_name_buf
[100];
4609 snprintf(new_channel_name_buf
,100,ch
->pattern
[m_session
->GetSessionDbcLocale()],current_zone_name
.c_str());
4610 Channel
* new_channel
= cMgr
->GetJoinChannel(new_channel_name_buf
,ch
->ChannelID
);
4612 if((*i
)!=new_channel
)
4614 new_channel
->Join(GetGUID(),""); // will output Changed Channel: N. Name
4616 // leave old channel
4617 (*i
)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4618 std::string name
= (*i
)->GetName(); // store name, (*i)erase in LeftChannel
4619 LeftChannel(*i
); // remove from player's channel list
4620 cMgr
->LeftChannel(name
); // delete if empty
4623 sLog
.outDebug("Player: channels cleaned up!");
4626 void Player::LeaveLFGChannel()
4628 for(JoinedChannelsList::iterator i
= m_channels
.begin(); i
!= m_channels
.end(); ++i
)
4632 (*i
)->Leave(GetGUID());
4638 void Player::UpdateDefense()
4640 uint32 defense_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_DEFENSE
);
4642 if(UpdateSkill(SKILL_DEFENSE
,defense_skill_gain
))
4644 // update dependent from defense skill part
4645 UpdateDefenseBonusesMod();
4649 void Player::HandleBaseModValue(BaseModGroup modGroup
, BaseModType modType
, float amount
, bool apply
)
4651 if(modGroup
>= BASEMOD_END
|| modType
>= MOD_END
)
4653 sLog
.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4662 m_auraBaseMod
[modGroup
][modType
] += apply
? amount
: -amount
;
4665 if(amount
<= -100.0f
)
4668 val
= (100.0f
+ amount
) / 100.0f
;
4669 m_auraBaseMod
[modGroup
][modType
] *= apply
? val
: (1.0f
/val
);
4673 if(!CanModifyStats())
4678 case CRIT_PERCENTAGE
: UpdateCritPercentage(BASE_ATTACK
); break;
4679 case RANGED_CRIT_PERCENTAGE
: UpdateCritPercentage(RANGED_ATTACK
); break;
4680 case OFFHAND_CRIT_PERCENTAGE
: UpdateCritPercentage(OFF_ATTACK
); break;
4681 case SHIELD_BLOCK_VALUE
: UpdateShieldBlockValue(); break;
4686 float Player::GetBaseModValue(BaseModGroup modGroup
, BaseModType modType
) const
4688 if(modGroup
>= BASEMOD_END
|| modType
> MOD_END
)
4690 sLog
.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4694 if(modType
== PCT_MOD
&& m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4697 return m_auraBaseMod
[modGroup
][modType
];
4700 float Player::GetTotalBaseModValue(BaseModGroup modGroup
) const
4702 if(modGroup
>= BASEMOD_END
)
4704 sLog
.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4708 if(m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4711 return m_auraBaseMod
[modGroup
][FLAT_MOD
] * m_auraBaseMod
[modGroup
][PCT_MOD
];
4714 uint32
Player::GetShieldBlockValue() const
4716 float value
= (m_auraBaseMod
[SHIELD_BLOCK_VALUE
][FLAT_MOD
] + GetStat(STAT_STRENGTH
) * 0.5f
- 10)*m_auraBaseMod
[SHIELD_BLOCK_VALUE
][PCT_MOD
];
4718 value
= (value
< 0) ? 0 : value
;
4720 return uint32(value
);
4723 float Player::GetMeleeCritFromAgility()
4725 uint32 level
= getLevel();
4726 uint32 pclass
= getClass();
4728 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4730 GtChanceToMeleeCritBaseEntry
const *critBase
= sGtChanceToMeleeCritBaseStore
.LookupEntry(pclass
-1);
4731 GtChanceToMeleeCritEntry
const *critRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4732 if (critBase
==NULL
|| critRatio
==NULL
)
4735 float crit
=critBase
->base
+ GetStat(STAT_AGILITY
)*critRatio
->ratio
;
4739 float Player::GetDodgeFromAgility()
4741 // Table for base dodge values
4742 float dodge_base
[MAX_CLASSES
] = {
4744 0.00652f
, // Paladin
4751 0.02011f
, // Warlock
4755 // Crit/agility to dodge/agility coefficient multipliers
4756 float crit_to_dodge
[MAX_CLASSES
] = {
4770 uint32 level
= getLevel();
4771 uint32 pclass
= getClass();
4773 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4775 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4776 GtChanceToMeleeCritEntry
const *dodgeRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4777 if (dodgeRatio
==NULL
|| pclass
> MAX_CLASSES
)
4780 float dodge
=dodge_base
[pclass
-1] + GetStat(STAT_AGILITY
) * dodgeRatio
->ratio
* crit_to_dodge
[pclass
-1];
4781 return dodge
*100.0f
;
4784 float Player::GetSpellCritFromIntellect()
4786 uint32 level
= getLevel();
4787 uint32 pclass
= getClass();
4789 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4791 GtChanceToSpellCritBaseEntry
const *critBase
= sGtChanceToSpellCritBaseStore
.LookupEntry(pclass
-1);
4792 GtChanceToSpellCritEntry
const *critRatio
= sGtChanceToSpellCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4793 if (critBase
==NULL
|| critRatio
==NULL
)
4796 float crit
=critBase
->base
+ GetStat(STAT_INTELLECT
)*critRatio
->ratio
;
4800 float Player::GetRatingCoefficient(CombatRating cr
) const
4802 uint32 level
= getLevel();
4804 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4806 GtCombatRatingsEntry
const *Rating
= sGtCombatRatingsStore
.LookupEntry(cr
*GT_MAX_LEVEL
+level
-1);
4808 return 1.0f
; // By default use minimum coefficient (not must be called)
4810 return Rating
->ratio
;
4813 float Player::GetRatingBonusValue(CombatRating cr
) const
4815 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
)) / GetRatingCoefficient(cr
);
4818 uint32
Player::GetMeleeCritDamageReduction(uint32 damage
) const
4820 float melee
= GetRatingBonusValue(CR_CRIT_TAKEN_MELEE
)*2.2f
;
4821 if (melee
>33.0f
) melee
= 33.0f
;
4822 return uint32 (melee
* damage
/100.0f
);
4825 uint32
Player::GetRangedCritDamageReduction(uint32 damage
) const
4827 float ranged
= GetRatingBonusValue(CR_CRIT_TAKEN_RANGED
)*2.2f
;
4828 if (ranged
>33.0f
) ranged
=33.0f
;
4829 return uint32 (ranged
* damage
/100.0f
);
4832 uint32
Player::GetSpellCritDamageReduction(uint32 damage
) const
4834 float spell
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
)*2.2f
;
4835 // In wow script resilience limited to 33%
4838 return uint32 (spell
* damage
/ 100.0f
);
4841 uint32
Player::GetDotDamageReduction(uint32 damage
) const
4843 float spellDot
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
);
4844 // Dot resilience not limited (limit it by 100%)
4845 if (spellDot
> 100.0f
)
4847 return uint32 (spellDot
* damage
/ 100.0f
);
4850 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType
) const
4855 return GetUInt32Value(PLAYER_EXPERTISE
) / 4.0f
;
4857 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE
) / 4.0f
;
4864 float Player::OCTRegenHPPerSpirit()
4866 uint32 level
= getLevel();
4867 uint32 pclass
= getClass();
4869 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4871 GtOCTRegenHPEntry
const *baseRatio
= sGtOCTRegenHPStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4872 GtRegenHPPerSptEntry
const *moreRatio
= sGtRegenHPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4873 if (baseRatio
==NULL
|| moreRatio
==NULL
)
4876 // Formula from PaperDollFrame script
4877 float spirit
= GetStat(STAT_SPIRIT
);
4878 float baseSpirit
= spirit
;
4879 if (baseSpirit
>50) baseSpirit
= 50;
4880 float moreSpirit
= spirit
- baseSpirit
;
4881 float regen
= baseSpirit
* baseRatio
->ratio
+ moreSpirit
* moreRatio
->ratio
;
4885 float Player::OCTRegenMPPerSpirit()
4887 uint32 level
= getLevel();
4888 uint32 pclass
= getClass();
4890 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4892 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4893 GtRegenMPPerSptEntry
const *moreRatio
= sGtRegenMPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4894 if (moreRatio
==NULL
)
4897 // Formula get from PaperDollFrame script
4898 float spirit
= GetStat(STAT_SPIRIT
);
4899 float regen
= spirit
* moreRatio
->ratio
;
4903 void Player::ApplyRatingMod(CombatRating cr
, int32 value
, bool apply
)
4905 m_baseRatingValue
[cr
]+=(apply
? value
: -value
);
4907 int32 amount
= uint32(m_baseRatingValue
[cr
]);
4908 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4909 // stat used stored in miscValueB for this aura
4910 AuraList
const& modRatingFromStat
= GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT
);
4911 for(AuraList::const_iterator i
= modRatingFromStat
.begin();i
!= modRatingFromStat
.end(); ++i
)
4912 if ((*i
)->GetMiscValue() & (1<<cr
))
4913 amount
+= int32(GetStat(Stats((*i
)->GetMiscBValue())) * (*i
)->GetModifier()->m_amount
/ 100.0f
);
4916 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
, uint32(amount
));
4918 float RatingCoeffecient
= GetRatingCoefficient(cr
);
4919 float RatingChange
= 0.0f
;
4921 bool affectStats
= CanModifyStats();
4925 case CR_WEAPON_SKILL
: // Implemented in Unit::RollMeleeOutcomeAgainst
4926 case CR_DEFENSE_SKILL
:
4927 UpdateDefenseBonusesMod();
4930 UpdateDodgePercentage();
4933 UpdateParryPercentage();
4936 UpdateBlockPercentage();
4939 UpdateMeleeHitChances();
4942 UpdateRangedHitChances();
4945 UpdateSpellHitChances();
4950 UpdateCritPercentage(BASE_ATTACK
);
4951 UpdateCritPercentage(OFF_ATTACK
);
4954 case CR_CRIT_RANGED
:
4956 UpdateCritPercentage(RANGED_ATTACK
);
4960 UpdateAllSpellCritChances();
4962 case CR_HIT_TAKEN_MELEE
: // Implemented in Unit::MeleeMissChanceCalc
4963 case CR_HIT_TAKEN_RANGED
:
4965 case CR_HIT_TAKEN_SPELL
: // Implemented in Unit::MagicSpellHitResult
4967 case CR_CRIT_TAKEN_MELEE
: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4968 case CR_CRIT_TAKEN_RANGED
:
4970 case CR_CRIT_TAKEN_SPELL
: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4972 case CR_HASTE_MELEE
:
4973 RatingChange
= value
/ RatingCoeffecient
;
4974 ApplyAttackTimePercentMod(BASE_ATTACK
,RatingChange
,apply
);
4975 ApplyAttackTimePercentMod(OFF_ATTACK
,RatingChange
,apply
);
4977 case CR_HASTE_RANGED
:
4978 RatingChange
= value
/ RatingCoeffecient
;
4979 ApplyAttackTimePercentMod(RANGED_ATTACK
, RatingChange
, apply
);
4981 case CR_HASTE_SPELL
:
4982 RatingChange
= value
/ RatingCoeffecient
;
4983 ApplyCastTimePercentMod(RatingChange
,apply
);
4985 case CR_WEAPON_SKILL_MAINHAND
: // Implemented in Unit::RollMeleeOutcomeAgainst
4986 case CR_WEAPON_SKILL_OFFHAND
:
4987 case CR_WEAPON_SKILL_RANGED
:
4992 UpdateExpertise(BASE_ATTACK
);
4993 UpdateExpertise(OFF_ATTACK
);
4996 case CR_ARMOR_PENETRATION
:
4998 UpdateArmorPenetration();
5003 void Player::SetRegularAttackTime()
5005 for(int i
= 0; i
< MAX_ATTACK
; ++i
)
5007 Item
*tmpitem
= GetWeaponForAttack(WeaponAttackType(i
));
5008 if(tmpitem
&& !tmpitem
->IsBroken())
5010 ItemPrototype
const *proto
= tmpitem
->GetProto();
5012 SetAttackTime(WeaponAttackType(i
), proto
->Delay
);
5014 SetAttackTime(WeaponAttackType(i
), BASE_ATTACK_TIME
);
5019 //skill+step, checking for max value
5020 bool Player::UpdateSkill(uint32 skill_id
, uint32 step
)
5026 for (; i
< PLAYER_MAX_SKILLS
; ++i
)
5027 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill_id
)
5030 if(i
>=PLAYER_MAX_SKILLS
)
5033 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
5034 uint32 value
= SKILL_VALUE(data
);
5035 uint32 max
= SKILL_MAX(data
);
5037 if ((!max
) || (!value
) || (value
>= max
))
5040 if (value
*512 < max
*urand(0,512))
5042 uint32 new_value
= value
+step
;
5046 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,max
));
5047 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,skill_id
);
5054 inline int SkillGainChance(uint32 SkillValue
, uint32 GrayLevel
, uint32 GreenLevel
, uint32 YellowLevel
)
5056 if ( SkillValue
>= GrayLevel
)
5057 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREY
)*10;
5058 if ( SkillValue
>= GreenLevel
)
5059 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREEN
)*10;
5060 if ( SkillValue
>= YellowLevel
)
5061 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_YELLOW
)*10;
5062 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_ORANGE
)*10;
5065 bool Player::UpdateCraftSkill(uint32 spellid
)
5067 sLog
.outDebug("UpdateCraftSkill spellid %d", spellid
);
5069 SkillLineAbilityMapBounds bounds
= spellmgr
.GetSkillLineAbilityMapBounds(spellid
);
5071 for(SkillLineAbilityMap::const_iterator _spell_idx
= bounds
.first
; _spell_idx
!= bounds
.second
; ++_spell_idx
)
5073 if (_spell_idx
->second
->skillId
)
5075 uint32 SkillValue
= GetPureSkillValue(_spell_idx
->second
->skillId
);
5077 // Alchemy Discoveries here
5078 SpellEntry
const* spellEntry
= sSpellStore
.LookupEntry(spellid
);
5079 if (spellEntry
&& spellEntry
->Mechanic
==MECHANIC_DISCOVERY
)
5081 if (uint32 discoveredSpell
= GetSkillDiscoverySpell(_spell_idx
->second
->skillId
, spellid
, this))
5082 learnSpell(discoveredSpell
,false);
5085 uint32 craft_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_CRAFTING
);
5087 return UpdateSkillPro(_spell_idx
->second
->skillId
, SkillGainChance(SkillValue
,
5088 _spell_idx
->second
->max_value
,
5089 (_spell_idx
->second
->max_value
+ _spell_idx
->second
->min_value
)/2,
5090 _spell_idx
->second
->min_value
),
5097 bool Player::UpdateGatherSkill(uint32 SkillId
, uint32 SkillValue
, uint32 RedLevel
, uint32 Multiplicator
)
5099 sLog
.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId
, SkillValue
, RedLevel
);
5101 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
5103 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
5106 case SKILL_HERBALISM
:
5107 case SKILL_LOCKPICKING
:
5108 case SKILL_JEWELCRAFTING
:
5109 case SKILL_INSCRIPTION
:
5110 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
5111 case SKILL_SKINNING
:
5112 if( sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)==0)
5113 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
5115 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)), gathering_skill_gain
);
5117 if (sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)==0)
5118 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
5120 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)),gathering_skill_gain
);
5125 bool Player::UpdateFishingSkill()
5127 sLog
.outDebug("UpdateFishingSkill");
5129 uint32 SkillValue
= GetPureSkillValue(SKILL_FISHING
);
5131 int32 chance
= SkillValue
< 75 ? 100 : 2500/(SkillValue
-50);
5133 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
5135 return UpdateSkillPro(SKILL_FISHING
,chance
*10,gathering_skill_gain
);
5138 // levels sync. with spell requirement for skill levels to learn
5139 // bonus abilities in sSkillLineAbilityStore
5140 // Used only to avoid scan DBC at each skill grow
5141 static uint32 bonusSkillLevels
[] = {75,150,225,300,375,450};
5143 bool Player::UpdateSkillPro(uint16 SkillId
, int32 Chance
, uint32 step
)
5145 sLog
.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId
, Chance
/10.0);
5149 if(Chance
<= 0) // speedup in 0 chance case
5151 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
5156 for (; i
< PLAYER_MAX_SKILLS
; ++i
)
5157 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i
))) == SkillId
) break;
5158 if ( i
>= PLAYER_MAX_SKILLS
)
5161 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
5162 uint16 SkillValue
= SKILL_VALUE(data
);
5163 uint16 MaxValue
= SKILL_MAX(data
);
5165 if ( !MaxValue
|| !SkillValue
|| SkillValue
>= MaxValue
)
5168 int32 Roll
= irand(1,1000);
5170 if ( Roll
<= Chance
)
5172 uint32 new_value
= SkillValue
+step
;
5173 if(new_value
> MaxValue
)
5174 new_value
= MaxValue
;
5176 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,MaxValue
));
5177 for(uint32
* bsl
= &bonusSkillLevels
[0]; *bsl
; ++bsl
)
5179 if((SkillValue
< *bsl
&& new_value
>= *bsl
))
5181 learnSkillRewardedSpells( SkillId
, new_value
);
5185 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,SkillId
);
5186 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance
/10.0);
5190 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
5194 void Player::UpdateWeaponSkill (WeaponAttackType attType
)
5196 // no skill gain in pvp
5197 Unit
*pVictim
= getVictim();
5198 if(pVictim
&& pVictim
->GetTypeId() == TYPEID_PLAYER
)
5202 return; // always maximized SKILL_FERAL_COMBAT in fact
5204 if(m_form
== FORM_TREE
)
5205 return; // use weapon but not skill up
5207 uint32 weapon_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_WEAPON
);
5213 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
5216 UpdateSkill(SKILL_UNARMED
,weapon_skill_gain
);
5217 else if(tmpitem
->GetProto()->SubClass
!= ITEM_SUBCLASS_WEAPON_FISHING_POLE
)
5218 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
5224 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
5226 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
5230 UpdateAllCritPercentages();
5233 void Player::UpdateCombatSkills(Unit
*pVictim
, WeaponAttackType attType
, bool defence
)
5235 uint32 plevel
= getLevel(); // if defense than pVictim == attacker
5236 uint32 greylevel
= MaNGOS::XP::GetGrayLevel(plevel
);
5237 uint32 moblevel
= pVictim
->getLevelForTarget(this);
5238 if(moblevel
< greylevel
)
5241 if (moblevel
> plevel
+ 5)
5242 moblevel
= plevel
+ 5;
5244 uint32 lvldif
= moblevel
- greylevel
;
5248 uint32 skilldif
= 5 * plevel
- (defence
? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType
));
5252 float chance
= float(3 * lvldif
* skilldif
) / plevel
;
5255 if(getClass() == CLASS_WARRIOR
|| getClass() == CLASS_ROGUE
)
5256 chance
*= 0.1f
* GetStat(STAT_INTELLECT
);
5259 chance
= chance
< 1.0f
? 1.0f
: chance
; //minimum chance to increase skill is 1%
5261 if(roll_chance_f(chance
))
5266 UpdateWeaponSkill(attType
);
5272 void Player::ModifySkillBonus(uint32 skillid
,int32 val
, bool talent
)
5274 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5275 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skillid
)
5277 uint32 bonus_val
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5278 int16 temp_bonus
= SKILL_TEMP_BONUS(bonus_val
);
5279 int16 perm_bonus
= SKILL_PERM_BONUS(bonus_val
);
5281 if(talent
) // permanent bonus stored in high part
5282 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
,perm_bonus
+val
));
5283 else // temporary/item bonus stored in low part
5284 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
+val
,perm_bonus
));
5289 void Player::UpdateSkillsForLevel()
5291 uint16 maxconfskill
= sWorld
.GetConfigMaxSkillValue();
5292 uint32 maxSkill
= GetMaxSkillValueForLevel();
5294 bool alwaysMaxSkill
= sWorld
.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL
);
5296 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5297 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5299 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
5301 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(pskill
);
5305 if(GetSkillRangeType(pSkill
,false) != SKILL_RANGE_LEVEL
)
5308 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
5309 uint32 max
= SKILL_MAX(data
);
5310 uint32 val
= SKILL_VALUE(data
);
5312 /// update only level dependent max skill values
5315 /// miximize skill always
5317 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(maxSkill
,maxSkill
));
5318 /// update max skill value if current max skill not maximized
5319 else if(max
!= maxconfskill
)
5320 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(val
,maxSkill
));
5325 void Player::UpdateSkillsToMaxSkillsForLevel()
5327 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5328 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5330 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
5331 if( IsProfessionOrRidingSkill(pskill
))
5333 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
5335 uint32 max
= SKILL_MAX(data
);
5338 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(max
,max
));
5340 if(pskill
== SKILL_DEFENSE
)
5341 UpdateDefenseBonusesMod();
5345 // This functions sets a skill line value (and adds if doesn't exist yet)
5346 // To "remove" a skill line, set it's values to zero
5347 void Player::SetSkill(uint32 id
, uint16 currVal
, uint16 maxVal
)
5353 for (; i
< PLAYER_MAX_SKILLS
; ++i
)
5354 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == id
) break;
5356 if(i
<PLAYER_MAX_SKILLS
) //has skill
5360 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
5361 learnSkillRewardedSpells(id
, currVal
);
5362 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,id
);
5363 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL
,id
);
5367 // clear skill fields
5368 SetUInt32Value(PLAYER_SKILL_INDEX(i
),0);
5369 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),0);
5370 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
5372 // remove all spells that related to this skill
5373 for (uint32 j
=0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
5374 if(SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
))
5375 if (pAbility
->skillId
==id
)
5376 removeSpell(spellmgr
.GetFirstSpellInChain(pAbility
->spellId
));
5379 else if(currVal
) //add
5381 for (i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5382 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5384 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
5387 sLog
.outError("Skill not found in SkillLineStore: skill #%u", id
);
5390 // enable unlearn button for primary professions only
5391 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
5392 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
5394 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
5395 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
5396 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,id
);
5397 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL
,id
);
5399 // apply skill bonuses
5400 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
5402 // temporary bonuses
5403 AuraList
const& mModSkill
= GetAurasByType(SPELL_AURA_MOD_SKILL
);
5404 for(AuraList::const_iterator j
= mModSkill
.begin(); j
!= mModSkill
.end(); ++j
)
5405 if ((*j
)->GetModifier()->m_miscvalue
== int32(id
))
5406 (*j
)->ApplyModifier(true);
5408 // permanent bonuses
5409 AuraList
const& mModSkillTalent
= GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT
);
5410 for(AuraList::const_iterator j
= mModSkillTalent
.begin(); j
!= mModSkillTalent
.end(); ++j
)
5411 if ((*j
)->GetModifier()->m_miscvalue
== int32(id
))
5412 (*j
)->ApplyModifier(true);
5414 // Learn all spells for skill
5415 learnSkillRewardedSpells(id
, currVal
);
5421 bool Player::HasSkill(uint32 skill
) const
5423 if(!skill
)return false;
5424 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5426 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5434 uint16
Player::GetSkillValue(uint32 skill
) const
5439 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5441 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5443 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5445 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5446 result
+= SKILL_TEMP_BONUS(bonus
);
5447 result
+= SKILL_PERM_BONUS(bonus
);
5448 return result
< 0 ? 0 : result
;
5454 uint16
Player::GetMaxSkillValue(uint32 skill
) const
5457 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5459 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5461 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5463 int32 result
= int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5464 result
+= SKILL_TEMP_BONUS(bonus
);
5465 result
+= SKILL_PERM_BONUS(bonus
);
5466 return result
< 0 ? 0 : result
;
5472 uint16
Player::GetPureMaxSkillValue(uint32 skill
) const
5475 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5477 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5479 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5485 uint16
Player::GetBaseSkillValue(uint32 skill
) const
5488 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5490 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5492 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5493 result
+= SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5494 return result
< 0 ? 0 : result
;
5500 uint16
Player::GetPureSkillValue(uint32 skill
) const
5503 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; ++i
)
5505 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5507 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5513 int16
Player::GetSkillPermBonusValue(uint32 skill
) const
5518 for (int i
= 0; i
< PLAYER_MAX_SKILLS
; ++i
)
5520 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5522 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5529 int16
Player::GetSkillTempBonusValue(uint32 skill
) const
5534 for (int i
= 0; i
< PLAYER_MAX_SKILLS
; ++i
)
5536 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5538 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5545 void Player::SendInitialActionButtons() const
5547 sLog
.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5549 WorldPacket
data(SMSG_ACTION_BUTTONS
, 1+(MAX_ACTION_BUTTONS
*4));
5550 data
<< uint8(0); // can be 0, 1, 2 (talent spec)
5551 for(int button
= 0; button
< MAX_ACTION_BUTTONS
; ++button
)
5553 ActionButtonList::const_iterator itr
= m_actionButtons
.find(button
);
5554 if(itr
!= m_actionButtons
.end() && itr
->second
.uState
!= ACTIONBUTTON_DELETED
)
5555 data
<< uint32(itr
->second
.packedData
);
5560 GetSession()->SendPacket( &data
);
5561 sLog
.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5564 ActionButton
* Player::addActionButton(uint8 button
, uint32 action
, uint8 type
)
5566 if(button
>= MAX_ACTION_BUTTONS
)
5568 sLog
.outError( "Action %u not added into button %u for player %s: button must be < 144", action
, button
, GetName() );
5572 if(action
>= MAX_ACTION_BUTTON_ACTION_VALUE
)
5574 sLog
.outError( "Action %u not added into button %u for player %s: action must be < %u", action
, button
, GetName(), MAX_ACTION_BUTTON_ACTION_VALUE
);
5580 case ACTION_BUTTON_SPELL
:
5581 if(!sSpellStore
.LookupEntry(action
))
5583 sLog
.outError( "Action %u not added into button %u for player %s: spell not exist", action
, button
, GetName() );
5587 if(!HasSpell(action
))
5589 sLog
.outError( "Action %u not added into button %u for player %s: player don't known this spell", action
, button
, GetName() );
5593 case ACTION_BUTTON_ITEM
:
5594 if(!objmgr
.GetItemPrototype(action
))
5596 sLog
.outError( "Action %u not added into button %u for player %s: item not exist", action
, button
, GetName() );
5601 break; // pther cases not checked at this moment
5605 // it create new button (NEW state) if need or return existed
5606 ActionButton
& ab
= m_actionButtons
[button
];
5608 // set data and update to CHANGED if not NEW
5609 ab
.SetActionAndType(action
,ActionButtonType(type
));
5611 sLog
.outDetail( "Player '%u' Added Action '%u' (type %u) to Button '%u'", GetGUIDLow(), action
, uint32(type
), button
);
5615 void Player::removeActionButton(uint8 button
)
5617 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5618 if (buttonItr
==m_actionButtons
.end())
5621 if(buttonItr
->second
.uState
==ACTIONBUTTON_NEW
)
5622 m_actionButtons
.erase(buttonItr
); // new and not saved
5624 buttonItr
->second
.uState
= ACTIONBUTTON_DELETED
; // saved, will deleted at next save
5626 sLog
.outDetail( "Action Button '%u' Removed from Player '%u'", button
, GetGUIDLow() );
5629 bool Player::SetPosition(float x
, float y
, float z
, float orientation
, bool teleport
)
5631 // prevent crash when a bad coord is sent by the client
5632 if(!MaNGOS::IsValidMapCoord(x
,y
,z
,orientation
))
5634 sLog
.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x
,y
,z
,orientation
,teleport
,GetGUIDLow());
5640 const float old_x
= GetPositionX();
5641 const float old_y
= GetPositionY();
5642 const float old_z
= GetPositionZ();
5643 const float old_r
= GetOrientation();
5645 if( teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
|| old_r
!= orientation
)
5647 if (teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
)
5648 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE
| AURA_INTERRUPT_FLAG_TURNING
);
5650 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING
);
5652 // move and update visible state if need
5653 m
->PlayerRelocation(this, x
, y
, z
, orientation
);
5655 // reread after Map::Relocation
5662 if(GetGroup() && (old_x
!= x
|| old_y
!= y
))
5663 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION
);
5666 // code block for underwater state update
5667 UpdateUnderwaterState(m
, x
, y
, z
);
5669 CheckExploreSystem();
5674 void Player::SaveRecallPosition()
5676 m_recallMap
= GetMapId();
5677 m_recallX
= GetPositionX();
5678 m_recallY
= GetPositionY();
5679 m_recallZ
= GetPositionZ();
5680 m_recallO
= GetOrientation();
5683 void Player::SendMessageToSet(WorldPacket
*data
, bool self
)
5685 Map
* _map
= IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
5688 _map
->MessageBroadcast(this, data
, self
);
5692 //if player is not in world and map in not created/already destroyed
5693 //no need to create one, just send packet for itself!
5695 GetSession()->SendPacket(data
);
5698 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
)
5700 Map
* _map
= IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
5703 _map
->MessageDistBroadcast(this, data
, dist
, self
);
5708 GetSession()->SendPacket(data
);
5711 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
, bool own_team_only
)
5713 Map
* _map
= IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
5716 _map
->MessageDistBroadcast(this, data
, dist
, self
, own_team_only
);
5721 GetSession()->SendPacket(data
);
5724 void Player::SendDirectMessage(WorldPacket
*data
)
5726 GetSession()->SendPacket(data
);
5729 void Player::SendCinematicStart(uint32 CinematicSequenceId
)
5731 WorldPacket
data(SMSG_TRIGGER_CINEMATIC
, 4);
5732 data
<< uint32(CinematicSequenceId
);
5733 SendDirectMessage(&data
);
5736 void Player::SendMovieStart(uint32 MovieId
)
5738 WorldPacket
data(SMSG_TRIGGER_MOVIE
, 4);
5739 data
<< uint32(MovieId
);
5740 SendDirectMessage(&data
);
5743 void Player::CheckExploreSystem()
5751 uint16 areaFlag
= GetBaseMap()->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5752 if(areaFlag
==0xffff)
5754 int offset
= areaFlag
/ 32;
5758 sLog
.outError("Wrong area flag %u in map data for (X: %f Y: %f) point to field PLAYER_EXPLORED_ZONES_1 + %u ( %u must be < 128 ).",areaFlag
,GetPositionX(),GetPositionY(),offset
,offset
);
5762 uint32 val
= (uint32
)(1 << (areaFlag
% 32));
5763 uint32 currFields
= GetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
);
5765 if( !(currFields
& val
) )
5767 SetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
, (uint32
)(currFields
| val
));
5769 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA
);
5771 AreaTableEntry
const *p
= GetAreaEntryByAreaFlagAndMap(areaFlag
,GetMapId());
5774 sLog
.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5776 else if(p
->area_level
> 0)
5778 uint32 area
= p
->ID
;
5779 if (getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
5781 SendExplorationExperience(area
,0);
5785 int32 diff
= int32(getLevel()) - p
->area_level
;
5789 XP
= uint32(objmgr
.GetBaseXP(getLevel()+5)*sWorld
.getRate(RATE_XP_EXPLORE
));
5793 int32 exploration_percent
= (100-((diff
-5)*5));
5794 if (exploration_percent
> 100)
5795 exploration_percent
= 100;
5796 else if (exploration_percent
< 0)
5797 exploration_percent
= 0;
5799 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*exploration_percent
/100*sWorld
.getRate(RATE_XP_EXPLORE
));
5803 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*sWorld
.getRate(RATE_XP_EXPLORE
));
5807 SendExplorationExperience(area
,XP
);
5809 sLog
.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area
);
5814 uint32
Player::TeamForRace(uint8 race
)
5816 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5819 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5823 switch(rEntry
->TeamID
)
5825 case 7: return ALLIANCE
;
5826 case 1: return HORDE
;
5829 sLog
.outError("Race %u have wrong teamid %u in DBC: wrong DBC files?",uint32(race
),rEntry
->TeamID
);
5833 uint32
Player::getFactionForRace(uint8 race
)
5835 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5838 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5842 return rEntry
->FactionID
;
5845 void Player::setFactionForRace(uint8 race
)
5847 m_team
= TeamForRace(race
);
5848 setFaction( getFactionForRace(race
) );
5851 ReputationRank
Player::GetReputationRank(uint32 faction
) const
5853 FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(faction
);
5854 return GetReputationMgr().GetRank(factionEntry
);
5857 //Calculate total reputation percent player gain with quest/creature level
5858 int32
Player::CalculateReputationGain(uint32 creatureOrQuestLevel
, int32 rep
, int32 faction
, bool for_quest
)
5860 float percent
= 100.0f
;
5862 float rate
= for_quest
? sWorld
.getRate(RATE_REPUTATION_LOWLEVEL_QUEST
) : sWorld
.getRate(RATE_REPUTATION_LOWLEVEL_KILL
);
5864 if (rate
!= 1.0f
&& creatureOrQuestLevel
<= MaNGOS::XP::GetGrayLevel(getLevel()))
5867 float repMod
= GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN
);
5870 repMod
+= GetTotalAuraModifierByMiscValue(SPELL_AURA_MOD_FACTION_REPUTATION_GAIN
, faction
);
5872 percent
+= rep
> 0 ? repMod
: -repMod
;
5874 if (percent
<= 0.0f
)
5877 return int32(sWorld
.getRate(RATE_REPUTATION_GAIN
)*rep
*percent
/100.0f
);
5880 //Calculates how many reputation points player gains in victim's enemy factions
5881 void Player::RewardReputation(Unit
*pVictim
, float rate
)
5883 if(!pVictim
|| pVictim
->GetTypeId() == TYPEID_PLAYER
)
5886 ReputationOnKillEntry
const* Rep
= objmgr
.GetReputationOnKilEntry(((Creature
*)pVictim
)->GetCreatureInfo()->Entry
);
5891 if(Rep
->repfaction1
&& (!Rep
->team_dependent
|| GetTeam()==ALLIANCE
))
5893 int32 donerep1
= CalculateReputationGain(pVictim
->getLevel(), Rep
->repvalue1
, Rep
->repfaction1
, false);
5894 donerep1
= int32(donerep1
*rate
);
5895 FactionEntry
const *factionEntry1
= sFactionStore
.LookupEntry(Rep
->repfaction1
);
5896 uint32 current_reputation_rank1
= GetReputationMgr().GetRank(factionEntry1
);
5897 if (factionEntry1
&& current_reputation_rank1
<= Rep
->reputation_max_cap1
)
5898 GetReputationMgr().ModifyReputation(factionEntry1
, donerep1
);
5900 // Wiki: Team factions value divided by 2
5901 if (factionEntry1
&& Rep
->is_teamaward1
)
5903 FactionEntry
const *team1_factionEntry
= sFactionStore
.LookupEntry(factionEntry1
->team
);
5904 if(team1_factionEntry
)
5905 GetReputationMgr().ModifyReputation(team1_factionEntry
, donerep1
/ 2);
5909 if(Rep
->repfaction2
&& (!Rep
->team_dependent
|| GetTeam()==HORDE
))
5911 int32 donerep2
= CalculateReputationGain(pVictim
->getLevel(), Rep
->repvalue2
, Rep
->repfaction2
, false);
5912 donerep2
= int32(donerep2
*rate
);
5913 FactionEntry
const *factionEntry2
= sFactionStore
.LookupEntry(Rep
->repfaction2
);
5914 uint32 current_reputation_rank2
= GetReputationMgr().GetRank(factionEntry2
);
5915 if (factionEntry2
&& current_reputation_rank2
<= Rep
->reputation_max_cap2
)
5916 GetReputationMgr().ModifyReputation(factionEntry2
, donerep2
);
5918 // Wiki: Team factions value divided by 2
5919 if (factionEntry2
&& Rep
->is_teamaward2
)
5921 FactionEntry
const *team2_factionEntry
= sFactionStore
.LookupEntry(factionEntry2
->team
);
5922 if(team2_factionEntry
)
5923 GetReputationMgr().ModifyReputation(team2_factionEntry
, donerep2
/ 2);
5928 //Calculate how many reputation points player gain with the quest
5929 void Player::RewardReputation(Quest
const *pQuest
)
5931 // quest reputation reward/loss
5932 for(int i
= 0; i
< QUEST_REPUTATIONS_COUNT
; ++i
)
5934 if(pQuest
->RewRepFaction
[i
] && pQuest
->RewRepValue
[i
] )
5936 int32 rep
= CalculateReputationGain(GetQuestLevel(pQuest
), pQuest
->RewRepValue
[i
], pQuest
->RewRepFaction
[i
], true);
5937 FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(pQuest
->RewRepFaction
[i
]);
5939 GetReputationMgr().ModifyReputation(factionEntry
, rep
);
5943 // TODO: implement reputation spillover
5946 void Player::UpdateArenaFields(void)
5948 /* arena calcs go here */
5951 void Player::UpdateHonorFields()
5953 /// called when rewarding honor and at each save
5954 uint64 now
= time(NULL
);
5955 uint64 today
= uint64(time(NULL
) / DAY
) * DAY
;
5957 if(m_lastHonorUpdateTime
< today
)
5959 uint64 yesterday
= today
- DAY
;
5961 uint16 kills_today
= PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS
));
5963 // update yesterday's contribution
5964 if(m_lastHonorUpdateTime
>= yesterday
)
5966 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
));
5968 // this is the first update today, reset today's contribution
5969 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, 0);
5970 SetUInt32Value(PLAYER_FIELD_KILLS
, MAKE_PAIR32(0,kills_today
));
5974 // no honor/kills yesterday or today, reset
5975 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0);
5976 SetUInt32Value(PLAYER_FIELD_KILLS
, 0);
5980 m_lastHonorUpdateTime
= now
;
5983 ///Calculate the amount of honor gained based on the victim
5984 ///and the size of the group for which the honor is divided
5985 ///An exact honor value can also be given (overriding the calcs)
5986 bool Player::RewardHonor(Unit
*uVictim
, uint32 groupsize
, float honor
)
5988 // do not reward honor in arenas, but enable onkill spellproc
5991 if(!uVictim
|| uVictim
== this || uVictim
->GetTypeId() != TYPEID_PLAYER
)
5994 if( GetBGTeam() == ((Player
*)uVictim
)->GetBGTeam() )
6000 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
6001 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE
))
6004 uint64 victim_guid
= 0;
6005 uint32 victim_rank
= 0;
6007 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
6008 UpdateHonorFields();
6012 if(!uVictim
|| uVictim
== this || uVictim
->HasAuraType(SPELL_AURA_NO_PVP_CREDIT
))
6015 victim_guid
= uVictim
->GetGUID();
6017 if( uVictim
->GetTypeId() == TYPEID_PLAYER
)
6019 Player
*pVictim
= (Player
*)uVictim
;
6021 if( GetTeam() == pVictim
->GetTeam() && !sWorld
.IsFFAPvPRealm() )
6024 float f
= 1; //need for total kills (?? need more info)
6026 uint32 k_level
= getLevel();
6027 uint32 v_level
= pVictim
->getLevel();
6030 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6032 // [1..14] Alliance honor titles and player name
6033 // [15..28] Horde honor titles and player name
6034 // [29..38] Other title and player name
6036 uint32 victim_title
= pVictim
->GetUInt32Value(PLAYER_CHOSEN_TITLE
);
6037 // Get Killer titles, CharTitlesEntry::bit_index
6039 // title[1..14] -> rank[5..18]
6040 // title[15..28] -> rank[5..18]
6041 // title[other] -> 0
6042 if (victim_title
== 0)
6043 victim_guid
= 0; // Don't show HK: <rank> message, only log.
6044 else if (victim_title
< 15)
6045 victim_rank
= victim_title
+ 4;
6046 else if (victim_title
< 29)
6047 victim_rank
= victim_title
- 14 + 4;
6049 victim_guid
= 0; // Don't show HK: <rank> message, only log.
6052 k_grey
= MaNGOS::XP::GetGrayLevel(k_level
);
6057 float diff_level
= (k_level
== k_grey
) ? 1 : ((float(v_level
) - float(k_grey
)) / (float(k_level
) - float(k_grey
)));
6059 int32 v_rank
=1; //need more info
6061 honor
= ((f
* diff_level
* (190 + v_rank
*10))/6);
6062 honor
*= ((float)k_level
) / 70.0f
; //factor of dependence on levels of the killer
6064 // count the number of playerkills in one day
6065 ApplyModUInt32Value(PLAYER_FIELD_KILLS
, 1, true);
6066 // and those in a lifetime
6067 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 1, true);
6068 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL
);
6069 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS
, pVictim
->getClass());
6070 UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_HK_RACE
, pVictim
->getRace());
6074 Creature
*cVictim
= (Creature
*)uVictim
;
6076 if (!cVictim
->isRacialLeader())
6079 honor
= 100; // ??? need more info
6080 victim_rank
= 19; // HK: Leader
6084 if (uVictim
!= NULL
)
6086 honor
*= sWorld
.getRate(RATE_HONOR
);
6091 honor
*= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6094 // honor - for show honor points in log
6095 // victim_guid - for show victim name in log
6096 // victim_rank [1..4] HK: <dishonored rank>
6097 // victim_rank [5..19] HK: <alliance\horde rank>
6098 // victim_rank [0,20+] HK: <>
6099 WorldPacket
data(SMSG_PVP_CREDIT
,4+8+4);
6100 data
<< (uint32
) honor
;
6101 data
<< (uint64
) victim_guid
;
6102 data
<< (uint32
) victim_rank
;
6104 GetSession()->SendPacket(&data
);
6107 ModifyHonorPoints(int32(honor
));
6109 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, uint32(honor
), true);
6113 void Player::ModifyHonorPoints( int32 value
)
6117 if (GetHonorPoints() > sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
))
6118 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) + value
);
6120 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() > uint32(-value
) ? GetHonorPoints() + value
: 0);
6123 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() < sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) - value
? GetHonorPoints() + value
: sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
));
6126 void Player::ModifyArenaPoints( int32 value
)
6130 if (GetArenaPoints() > sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
))
6131 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) + value
);
6133 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() > uint32(-value
) ? GetArenaPoints() + value
: 0);
6136 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() < sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) - value
? GetArenaPoints() + value
: sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
));
6139 uint32
Player::GetGuildIdFromDB(uint64 guid
)
6141 QueryResult
* result
= CharacterDatabase
.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid
));
6145 uint32 id
= result
->Fetch()[0].GetUInt32();
6150 uint32
Player::GetRankFromDB(uint64 guid
)
6152 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid
) );
6155 uint32 v
= result
->Fetch()[0].GetUInt32();
6163 uint32
Player::GetArenaTeamIdFromDB(uint64 guid
, uint8 type
)
6165 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
);
6169 uint32 id
= (*result
)[0].GetUInt32();
6174 uint32
Player::GetZoneIdFromDB(uint64 guid
)
6176 uint32 guidLow
= GUID_LOPART(guid
);
6177 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow
);
6180 Field
* fields
= result
->Fetch();
6181 uint32 zone
= fields
[0].GetUInt32();
6186 // stored zone is zero, use generic and slow zone detection
6187 result
= CharacterDatabase
.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow
);
6190 fields
= result
->Fetch();
6191 uint32 map
= fields
[0].GetUInt32();
6192 float posx
= fields
[1].GetFloat();
6193 float posy
= fields
[2].GetFloat();
6194 float posz
= fields
[3].GetFloat();
6197 zone
= MapManager::Instance().GetZoneId(map
,posx
,posy
,posz
);
6200 CharacterDatabase
.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone
, guidLow
);
6206 uint32
Player::GetLevelFromDB(uint64 guid
)
6208 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT level FROM characters WHERE guid='%u'", GUID_LOPART(guid
) );
6212 Field
* fields
= result
->Fetch();
6213 uint32 level
= fields
[0].GetUInt32();
6219 void Player::UpdateArea(uint32 newArea
)
6221 // FFA_PVP flags are area and not zone id dependent
6222 // so apply them accordingly
6223 m_areaUpdateId
= newArea
;
6225 AreaTableEntry
const* area
= GetAreaEntryByAreaID(newArea
);
6227 if(area
&& (area
->flags
& AREA_FLAG_ARENA
))
6230 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6234 // remove ffa flag only if not ffapvp realm
6235 // removal in sanctuaries and capitals is handled in zone update
6236 if(HasByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
) && !sWorld
.IsFFAPvPRealm())
6237 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6240 UpdateAreaDependentAuras(newArea
);
6243 void Player::UpdateZone(uint32 newZone
, uint32 newArea
)
6245 AreaTableEntry
const* zone
= GetAreaEntryByAreaID(newZone
);
6249 if(m_zoneUpdateId
!= newZone
)
6251 SendInitWorldStates(newZone
, newArea
); // only if really enters to new zone, not just area change, works strange...
6253 if (sWorld
.getConfig(CONFIG_WEATHER
))
6255 if(Weather
*wth
= sWorld
.FindWeather(zone
->ID
))
6256 wth
->SendWeatherUpdateToPlayer(this);
6257 else if(!sWorld
.AddWeather(zone
->ID
))
6259 // send fine weather packet to remove old zone's weather
6260 Weather::SendFineWeatherUpdateToPlayer(this);
6265 m_zoneUpdateId
= newZone
;
6266 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
6268 // zone changed, so area changed as well, update it
6269 UpdateArea(newArea
);
6271 // in PvP, any not controlled zone (except zone->team == 6, default case)
6272 // in PvE, only opposition team capital
6276 pvpInfo
.inHostileArea
= GetTeam() != ALLIANCE
&& (sWorld
.IsPvPRealm() || zone
->flags
& AREA_FLAG_CAPITAL
);
6278 case AREATEAM_HORDE
:
6279 pvpInfo
.inHostileArea
= GetTeam() != HORDE
&& (sWorld
.IsPvPRealm() || zone
->flags
& AREA_FLAG_CAPITAL
);
6282 // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6283 pvpInfo
.inHostileArea
= sWorld
.IsPvPRealm() || InBattleGround();
6285 default: // 6 in fact
6286 pvpInfo
.inHostileArea
= false;
6290 if(pvpInfo
.inHostileArea
) // in hostile area
6292 if(!IsPvP() || pvpInfo
.endTimer
!= 0)
6293 UpdatePvP(true, true);
6295 else // in friendly area
6297 if(IsPvP() && !HasFlag(PLAYER_FLAGS
,PLAYER_FLAGS_IN_PVP
) && pvpInfo
.endTimer
== 0)
6298 pvpInfo
.endTimer
= time(0); // start toggle-off
6301 if(zone
->flags
& AREA_FLAG_SANCTUARY
) // in sanctuary
6303 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_SANCTUARY
);
6304 if(sWorld
.IsFFAPvPRealm())
6305 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6309 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_SANCTUARY
);
6312 if(zone
->flags
& AREA_FLAG_CAPITAL
) // in capital city
6314 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6315 SetRestType(REST_TYPE_IN_CITY
);
6316 InnEnter(time(0),GetMapId(),0,0,0);
6318 if(sWorld
.IsFFAPvPRealm())
6319 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6321 else // anywhere else
6323 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6325 if(GetRestType()==REST_TYPE_IN_TAVERN
) // has been in tavern. Is still in?
6327 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6329 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6330 SetRestType(REST_TYPE_NO
);
6332 if(sWorld
.IsFFAPvPRealm())
6333 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6336 else // not in tavern (leave city then)
6338 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6339 SetRestType(REST_TYPE_NO
);
6341 // Set player to FFA PVP when not in rested environment.
6342 if(sWorld
.IsFFAPvPRealm())
6343 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6348 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6349 // if player resurrected at teleport this will be applied in resurrect code
6351 DestroyZoneLimitedItem( true, newZone
);
6353 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6354 AutoUnequipOffhandIfNeed();
6356 // recent client version not send leave/join channel packets for built-in local channels
6357 UpdateLocalChannels( newZone
);
6361 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE
);
6363 UpdateZoneDependentAuras(newZone
);
6366 //If players are too far way of duel flag... then player loose the duel
6367 void Player::CheckDuelDistance(time_t currTime
)
6372 uint64 duelFlagGUID
= GetUInt64Value(PLAYER_DUEL_ARBITER
);
6373 GameObject
* obj
= GetMap()->GetGameObject(duelFlagGUID
);
6377 if(duel
->outOfBound
== 0)
6379 if(!IsWithinDistInMap(obj
, 50))
6381 duel
->outOfBound
= currTime
;
6383 WorldPacket
data(SMSG_DUEL_OUTOFBOUNDS
, 0);
6384 GetSession()->SendPacket(&data
);
6389 if(IsWithinDistInMap(obj
, 40))
6391 duel
->outOfBound
= 0;
6393 WorldPacket
data(SMSG_DUEL_INBOUNDS
, 0);
6394 GetSession()->SendPacket(&data
);
6396 else if(currTime
>= (duel
->outOfBound
+10))
6398 DuelComplete(DUEL_FLED
);
6403 void Player::DuelComplete(DuelCompleteType type
)
6405 // duel not requested
6409 WorldPacket
data(SMSG_DUEL_COMPLETE
, (1));
6410 data
<< (uint8
)((type
!= DUEL_INTERUPTED
) ? 1 : 0);
6411 GetSession()->SendPacket(&data
);
6412 duel
->opponent
->GetSession()->SendPacket(&data
);
6414 if(type
!= DUEL_INTERUPTED
)
6416 data
.Initialize(SMSG_DUEL_WINNER
, (1+20)); // we guess size
6417 data
<< (uint8
)((type
==DUEL_WON
) ? 0 : 1); // 0 = just won; 1 = fled
6418 data
<< duel
->opponent
->GetName();
6420 SendMessageToSet(&data
,true);
6423 if (type
== DUEL_WON
)
6425 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL
, 1);
6427 duel
->opponent
->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL
, 1);
6430 //Remove Duel Flag object
6431 GameObject
* obj
= GetMap()->GetGameObject(GetUInt64Value(PLAYER_DUEL_ARBITER
));
6433 duel
->initiator
->RemoveGameObject(obj
,true);
6436 std::vector
<uint32
> auras2remove
;
6437 AuraMap
const& vAuras
= duel
->opponent
->GetAuras();
6438 for (AuraMap::const_iterator i
= vAuras
.begin(); i
!= vAuras
.end(); ++i
)
6440 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6441 auras2remove
.push_back(i
->second
->GetId());
6444 for(size_t i
=0; i
<auras2remove
.size(); ++i
)
6445 duel
->opponent
->RemoveAurasDueToSpell(auras2remove
[i
]);
6447 auras2remove
.clear();
6448 AuraMap
const& auras
= GetAuras();
6449 for (AuraMap::const_iterator i
= auras
.begin(); i
!= auras
.end(); ++i
)
6451 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == duel
->opponent
->GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6452 auras2remove
.push_back(i
->second
->GetId());
6454 for(size_t i
=0; i
<auras2remove
.size(); ++i
)
6455 RemoveAurasDueToSpell(auras2remove
[i
]);
6457 // cleanup combo points
6458 if(GetComboTarget()==duel
->opponent
->GetGUID())
6460 else if(GetComboTarget()==duel
->opponent
->GetPetGUID())
6463 if(duel
->opponent
->GetComboTarget()==GetGUID())
6464 duel
->opponent
->ClearComboPoints();
6465 else if(duel
->opponent
->GetComboTarget()==GetPetGUID())
6466 duel
->opponent
->ClearComboPoints();
6469 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6470 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6471 duel
->opponent
->SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6472 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6474 delete duel
->opponent
->duel
;
6475 duel
->opponent
->duel
= NULL
;
6480 //---------------------------------------------------------//
6482 void Player::_ApplyItemMods(Item
*item
, uint8 slot
,bool apply
)
6484 if(slot
>= INVENTORY_SLOT_BAG_END
|| !item
)
6487 // not apply/remove mods for broken item
6488 if(item
->IsBroken())
6491 ItemPrototype
const *proto
= item
->GetProto();
6496 sLog
.outDetail("applying mods for item %u ",item
->GetGUIDLow());
6498 uint32 attacktype
= Player::GetAttackBySlot(slot
);
6499 if(attacktype
< MAX_ATTACK
)
6500 _ApplyWeaponDependentAuraMods(item
,WeaponAttackType(attacktype
),apply
);
6502 _ApplyItemBonuses(proto
,slot
,apply
);
6504 if( slot
==EQUIPMENT_SLOT_RANGED
)
6505 _ApplyAmmoBonuses();
6507 ApplyItemEquipSpell(item
,apply
);
6508 ApplyEnchantment(item
, apply
);
6510 if(proto
->Socket
[0].Color
) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6511 CorrectMetaGemEnchants(slot
, apply
);
6513 sLog
.outDebug("_ApplyItemMods complete.");
6516 void Player::_ApplyItemBonuses(ItemPrototype
const *proto
, uint8 slot
, bool apply
, bool only_level_scale
/*= false*/)
6518 if (slot
>= INVENTORY_SLOT_BAG_END
|| !proto
)
6521 ScalingStatDistributionEntry
const *ssd
= proto
->ScalingStatDistribution
? sScalingStatDistributionStore
.LookupEntry(proto
->ScalingStatDistribution
) : NULL
;
6522 if (only_level_scale
&& !ssd
)
6525 // req. check at equip, but allow use for extended range if range limit max level, set proper level
6526 uint32 ssd_level
= getLevel();
6527 if (ssd
&& ssd_level
> ssd
->MaxLevel
)
6528 ssd_level
= ssd
->MaxLevel
;
6530 ScalingStatValuesEntry
const *ssv
= proto
->ScalingStatValue
? sScalingStatValuesStore
.LookupEntry(ssd_level
) : NULL
;
6531 if (only_level_scale
&& !ssv
)
6534 for (int i
= 0; i
< MAX_ITEM_PROTO_STATS
; ++i
)
6536 uint32 statType
= 0;
6538 // If set ScalingStatDistribution need get stats and values from it
6541 if (ssd
->StatMod
[i
] < 0)
6543 statType
= ssd
->StatMod
[i
];
6544 val
= (ssv
->getssdMultiplier(proto
->ScalingStatValue
) * ssd
->Modifier
[i
]) / 10000;
6548 if (i
>= proto
->StatsCount
)
6550 statType
= proto
->ItemStat
[i
].ItemStatType
;
6551 val
= proto
->ItemStat
[i
].ItemStatValue
;
6560 HandleStatModifier(UNIT_MOD_MANA
, BASE_VALUE
, float(val
), apply
);
6562 case ITEM_MOD_HEALTH
: // modify HP
6563 HandleStatModifier(UNIT_MOD_HEALTH
, BASE_VALUE
, float(val
), apply
);
6565 case ITEM_MOD_AGILITY
: // modify agility
6566 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, BASE_VALUE
, float(val
), apply
);
6567 ApplyStatBuffMod(STAT_AGILITY
, float(val
), apply
);
6569 case ITEM_MOD_STRENGTH
: //modify strength
6570 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, BASE_VALUE
, float(val
), apply
);
6571 ApplyStatBuffMod(STAT_STRENGTH
, float(val
), apply
);
6573 case ITEM_MOD_INTELLECT
: //modify intellect
6574 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, BASE_VALUE
, float(val
), apply
);
6575 ApplyStatBuffMod(STAT_INTELLECT
, float(val
), apply
);
6577 case ITEM_MOD_SPIRIT
: //modify spirit
6578 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, BASE_VALUE
, float(val
), apply
);
6579 ApplyStatBuffMod(STAT_SPIRIT
, float(val
), apply
);
6581 case ITEM_MOD_STAMINA
: //modify stamina
6582 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, BASE_VALUE
, float(val
), apply
);
6583 ApplyStatBuffMod(STAT_STAMINA
, float(val
), apply
);
6585 case ITEM_MOD_DEFENSE_SKILL_RATING
:
6586 ApplyRatingMod(CR_DEFENSE_SKILL
, int32(val
), apply
);
6588 case ITEM_MOD_DODGE_RATING
:
6589 ApplyRatingMod(CR_DODGE
, int32(val
), apply
);
6591 case ITEM_MOD_PARRY_RATING
:
6592 ApplyRatingMod(CR_PARRY
, int32(val
), apply
);
6594 case ITEM_MOD_BLOCK_RATING
:
6595 ApplyRatingMod(CR_BLOCK
, int32(val
), apply
);
6597 case ITEM_MOD_HIT_MELEE_RATING
:
6598 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6600 case ITEM_MOD_HIT_RANGED_RATING
:
6601 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6603 case ITEM_MOD_HIT_SPELL_RATING
:
6604 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6606 case ITEM_MOD_CRIT_MELEE_RATING
:
6607 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6609 case ITEM_MOD_CRIT_RANGED_RATING
:
6610 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6612 case ITEM_MOD_CRIT_SPELL_RATING
:
6613 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6615 case ITEM_MOD_HIT_TAKEN_MELEE_RATING
:
6616 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6618 case ITEM_MOD_HIT_TAKEN_RANGED_RATING
:
6619 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6621 case ITEM_MOD_HIT_TAKEN_SPELL_RATING
:
6622 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6624 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING
:
6625 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6627 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING
:
6628 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6630 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING
:
6631 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6633 case ITEM_MOD_HASTE_MELEE_RATING
:
6634 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6636 case ITEM_MOD_HASTE_RANGED_RATING
:
6637 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6639 case ITEM_MOD_HASTE_SPELL_RATING
:
6640 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6642 case ITEM_MOD_HIT_RATING
:
6643 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6644 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6645 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6647 case ITEM_MOD_CRIT_RATING
:
6648 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6649 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6650 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6652 case ITEM_MOD_HIT_TAKEN_RATING
:
6653 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6654 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6655 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6657 case ITEM_MOD_CRIT_TAKEN_RATING
:
6658 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6659 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6660 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6662 case ITEM_MOD_RESILIENCE_RATING
:
6663 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6664 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6665 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6667 case ITEM_MOD_HASTE_RATING
:
6668 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6669 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6670 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6672 case ITEM_MOD_EXPERTISE_RATING
:
6673 ApplyRatingMod(CR_EXPERTISE
, int32(val
), apply
);
6675 case ITEM_MOD_ATTACK_POWER
:
6676 HandleStatModifier(UNIT_MOD_ATTACK_POWER
, TOTAL_VALUE
, float(val
), apply
);
6677 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(val
), apply
);
6679 case ITEM_MOD_RANGED_ATTACK_POWER
:
6680 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(val
), apply
);
6682 case ITEM_MOD_FERAL_ATTACK_POWER
:
6683 ApplyFeralAPBonus(int32(val
), apply
);
6685 case ITEM_MOD_MANA_REGENERATION
:
6686 ApplyManaRegenBonus(int32(val
), apply
);
6688 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
6689 ApplyRatingMod(CR_ARMOR_PENETRATION
, int32(val
), apply
);
6691 case ITEM_MOD_SPELL_POWER
:
6692 ApplySpellPowerBonus(int32(val
), apply
);
6694 // depricated item mods
6695 case ITEM_MOD_SPELL_HEALING_DONE
:
6696 case ITEM_MOD_SPELL_DAMAGE_DONE
:
6701 // Apply Spell Power from ScalingStatValue if set
6704 if (int32 spellbonus
= ssv
->getSpellBonus(proto
->ScalingStatValue
))
6705 ApplySpellPowerBonus(spellbonus
, apply
);
6708 // If set ScalingStatValue armor get it or use item armor
6709 uint32 armor
= proto
->Armor
;
6712 if (uint32 ssvarmor
= ssv
->getArmorMod(proto
->ScalingStatValue
))
6715 // Add armor bonus from ArmorDamageModifier if > 0
6716 if (proto
->ArmorDamageModifier
> 0)
6717 armor
+= uint32(proto
->ArmorDamageModifier
);
6720 HandleStatModifier(UNIT_MOD_ARMOR
, BASE_VALUE
, float(armor
), apply
);
6723 HandleBaseModValue(SHIELD_BLOCK_VALUE
, FLAT_MOD
, float(proto
->Block
), apply
);
6726 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY
, BASE_VALUE
, float(proto
->HolyRes
), apply
);
6729 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE
, BASE_VALUE
, float(proto
->FireRes
), apply
);
6731 if (proto
->NatureRes
)
6732 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE
, BASE_VALUE
, float(proto
->NatureRes
), apply
);
6734 if (proto
->FrostRes
)
6735 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST
, BASE_VALUE
, float(proto
->FrostRes
), apply
);
6737 if (proto
->ShadowRes
)
6738 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW
, BASE_VALUE
, float(proto
->ShadowRes
), apply
);
6740 if (proto
->ArcaneRes
)
6741 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE
, BASE_VALUE
, float(proto
->ArcaneRes
), apply
);
6743 WeaponAttackType attType
= BASE_ATTACK
;
6744 float damage
= 0.0f
;
6746 if( slot
== EQUIPMENT_SLOT_RANGED
&& (
6747 proto
->InventoryType
== INVTYPE_RANGED
|| proto
->InventoryType
== INVTYPE_THROWN
||
6748 proto
->InventoryType
== INVTYPE_RANGEDRIGHT
))
6750 attType
= RANGED_ATTACK
;
6752 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6754 attType
= OFF_ATTACK
;
6757 float minDamage
= proto
->Damage
[0].DamageMin
;
6758 float maxDamage
= proto
->Damage
[0].DamageMax
;
6760 // If set dpsMod in ScalingStatValue use it for min (70% from average), max (130% from average) damage
6763 if ((extraDPS
= ssv
->getDPSMod(proto
->ScalingStatValue
)))
6765 float average
= extraDPS
* proto
->Delay
/ 1000.0f
;
6766 minDamage
= 0.7f
* average
;
6767 maxDamage
= 1.3f
* average
;
6772 damage
= apply
? minDamage
: BASE_MINDAMAGE
;
6773 SetBaseWeaponDamage(attType
, MINDAMAGE
, damage
);
6774 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6779 damage
= apply
? maxDamage
: BASE_MAXDAMAGE
;
6780 SetBaseWeaponDamage(attType
, MAXDAMAGE
, damage
);
6783 // Apply feral bonus from ScalingStatValue if set
6786 if (int32 feral_bonus
= ssv
->getFeralBonus(proto
->ScalingStatValue
))
6787 ApplyFeralAPBonus(feral_bonus
, apply
);
6789 // Druids get feral AP bonus from weapon dps (lso use DPS from ScalingStatValue)
6790 if(getClass() == CLASS_DRUID
)
6792 int32 feral_bonus
= proto
->getFeralBonus(extraDPS
);
6793 if (feral_bonus
> 0)
6794 ApplyFeralAPBonus(feral_bonus
, apply
);
6797 if(!IsUseEquipedWeapon(slot
==EQUIPMENT_SLOT_MAINHAND
))
6802 if(slot
== EQUIPMENT_SLOT_RANGED
)
6803 SetAttackTime(RANGED_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6804 else if(slot
==EQUIPMENT_SLOT_MAINHAND
)
6805 SetAttackTime(BASE_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6806 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6807 SetAttackTime(OFF_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6810 if(CanModifyStats() && (damage
|| proto
->Delay
))
6811 UpdateDamagePhysical(attType
);
6814 void Player::_ApplyWeaponDependentAuraMods(Item
*item
,WeaponAttackType attackType
,bool apply
)
6816 AuraList
const& auraCritList
= GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT
);
6817 for(AuraList::const_iterator itr
= auraCritList
.begin(); itr
!=auraCritList
.end();++itr
)
6818 _ApplyWeaponDependentAuraCritMod(item
,attackType
,*itr
,apply
);
6820 AuraList
const& auraDamageFlatList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE
);
6821 for(AuraList::const_iterator itr
= auraDamageFlatList
.begin(); itr
!=auraDamageFlatList
.end();++itr
)
6822 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6824 AuraList
const& auraDamagePCTList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
);
6825 for(AuraList::const_iterator itr
= auraDamagePCTList
.begin(); itr
!=auraDamagePCTList
.end();++itr
)
6826 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6829 void Player::_ApplyWeaponDependentAuraCritMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6831 // generic not weapon specific case processes in aura code
6832 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6835 BaseModGroup mod
= BASEMOD_END
;
6838 case BASE_ATTACK
: mod
= CRIT_PERCENTAGE
; break;
6839 case OFF_ATTACK
: mod
= OFFHAND_CRIT_PERCENTAGE
;break;
6840 case RANGED_ATTACK
: mod
= RANGED_CRIT_PERCENTAGE
; break;
6844 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6846 HandleBaseModValue(mod
, FLAT_MOD
, float (aura
->GetModifier()->m_amount
), apply
);
6850 void Player::_ApplyWeaponDependentAuraDamageMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6852 // ignore spell mods for not wands
6853 Modifier
const* modifier
= aura
->GetModifier();
6854 if((modifier
->m_miscvalue
& SPELL_SCHOOL_MASK_NORMAL
)==0 && (getClassMask() & CLASSMASK_WAND_USERS
)==0)
6857 // generic not weapon specific case processes in aura code
6858 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6861 UnitMods unitMod
= UNIT_MOD_END
;
6864 case BASE_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_MAINHAND
; break;
6865 case OFF_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_OFFHAND
; break;
6866 case RANGED_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_RANGED
; break;
6870 UnitModifierType unitModType
= TOTAL_VALUE
;
6871 switch(modifier
->m_auraname
)
6873 case SPELL_AURA_MOD_DAMAGE_DONE
: unitModType
= TOTAL_VALUE
; break;
6874 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
: unitModType
= TOTAL_PCT
; break;
6878 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6880 HandleStatModifier(unitMod
, unitModType
, float(modifier
->m_amount
),apply
);
6884 void Player::ApplyItemEquipSpell(Item
*item
, bool apply
, bool form_change
)
6889 ItemPrototype
const *proto
= item
->GetProto();
6893 for (int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
6895 _Spell
const& spellData
= proto
->Spells
[i
];
6898 if(!spellData
.SpellId
)
6901 // wrong triggering type
6902 if(apply
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_EQUIP
)
6905 // check if it is valid spell
6906 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellData
.SpellId
);
6910 ApplyEquipSpell(spellproto
,item
,apply
,form_change
);
6914 void Player::ApplyEquipSpell(SpellEntry
const* spellInfo
, Item
* item
, bool apply
, bool form_change
)
6918 // Cannot be used in this stance/form
6919 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
) != SPELL_CAST_OK
)
6922 if(form_change
) // check aura active state from other form
6925 for (int k
=0; k
< 3; ++k
)
6927 spellEffectPair spair
= spellEffectPair(spellInfo
->Id
, k
);
6928 for (AuraMap::const_iterator iter
= m_Auras
.lower_bound(spair
); iter
!= m_Auras
.upper_bound(spair
); ++iter
)
6930 if(!item
|| iter
->second
->GetCastItemGUID() == item
->GetGUID())
6940 if(found
) // and skip re-cast already active aura at form change
6944 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item
? "item" : "itemset"), spellInfo
->Id
);
6946 CastSpell(this,spellInfo
,true,item
);
6950 if(form_change
) // check aura compatibility
6952 // Cannot be used in this stance/form
6953 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
)==SPELL_CAST_OK
)
6954 return; // and remove only not compatible at form change
6958 RemoveAurasDueToItemSpell(item
,spellInfo
->Id
); // un-apply all spells , not only at-equipped
6960 RemoveAurasDueToSpell(spellInfo
->Id
); // un-apply spell (item set case)
6964 void Player::UpdateEquipSpellsAtFormChange()
6966 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
6968 if(m_items
[i
] && !m_items
[i
]->IsBroken())
6970 ApplyItemEquipSpell(m_items
[i
],false,true); // remove spells that not fit to form
6971 ApplyItemEquipSpell(m_items
[i
],true,true); // add spells that fit form but not active
6975 // item set bonuses not dependent from item broken state
6976 for(size_t setindex
= 0; setindex
< ItemSetEff
.size(); ++setindex
)
6978 ItemSetEffect
* eff
= ItemSetEff
[setindex
];
6982 for(uint32 y
=0;y
<8; ++y
)
6984 SpellEntry
const* spellInfo
= eff
->spells
[y
];
6988 ApplyEquipSpell(spellInfo
,NULL
,false,true); // remove spells that not fit to form
6989 ApplyEquipSpell(spellInfo
,NULL
,true,true); // add spells that fit form but not active
6994 void Player::CastItemCombatSpell(Unit
* Target
, WeaponAttackType attType
)
6996 Item
*item
= GetWeaponForAttack(attType
, false);
6997 if(!item
|| item
->IsBroken())
7000 ItemPrototype
const *proto
= item
->GetProto();
7004 if (!Target
|| Target
== this )
7007 for (int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
7009 _Spell
const& spellData
= proto
->Spells
[i
];
7012 if(!spellData
.SpellId
)
7015 // wrong triggering type
7016 if(spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_CHANCE_ON_HIT
)
7019 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
7022 sLog
.outError("WORLD: unknown Item spellid %i", spellData
.SpellId
);
7026 // not allow proc extra attack spell at extra attack
7027 if( m_extraAttacks
&& IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_ADD_EXTRA_ATTACKS
) )
7030 float chance
= spellInfo
->procChance
;
7032 if(spellData
.SpellPPMRate
)
7034 uint32 WeaponSpeed
= proto
->Delay
;
7035 chance
= GetPPMProcChance(WeaponSpeed
, spellData
.SpellPPMRate
);
7037 else if(chance
> 100.0f
)
7039 chance
= GetWeaponProcChance();
7042 if (roll_chance_f(chance
))
7043 CastSpell(Target
, spellInfo
->Id
, true, item
);
7046 // item combat enchantments
7047 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
7049 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
7050 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
7051 if(!pEnchant
) continue;
7052 for (int s
=0;s
<3;s
++)
7054 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
)
7057 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
7060 sLog
.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
7064 // Use first rank to access spell item enchant procs
7065 float ppmRate
= spellmgr
.GetItemEnchantProcChance(spellInfo
->Id
);
7067 float chance
= ppmRate
7068 ? GetPPMProcChance(proto
->Delay
, ppmRate
)
7069 : pEnchant
->amount
[s
] != 0 ? float(pEnchant
->amount
[s
]) : GetWeaponProcChance();
7072 ApplySpellMod(spellInfo
->Id
,SPELLMOD_CHANCE_OF_SUCCESS
,chance
);
7073 ApplySpellMod(spellInfo
->Id
,SPELLMOD_FREQUENCY_OF_SUCCESS
,chance
);
7075 if (roll_chance_f(chance
))
7077 if(IsPositiveSpell(pEnchant
->spellid
[s
]))
7078 CastSpell(this, pEnchant
->spellid
[s
], true, item
);
7080 CastSpell(Target
, pEnchant
->spellid
[s
], true, item
);
7086 void Player::CastItemUseSpell(Item
*item
,SpellCastTargets
const& targets
,uint8 cast_count
, uint32 glyphIndex
)
7088 ItemPrototype
const* proto
= item
->GetProto();
7089 // special learning case
7090 if(proto
->Spells
[0].SpellId
==SPELL_ID_GENERIC_LEARN
|| proto
->Spells
[0].SpellId
==SPELL_ID_GENERIC_LEARN_PET
)
7092 uint32 learn_spell_id
= proto
->Spells
[0].SpellId
;
7093 uint32 learning_spell_id
= proto
->Spells
[1].SpellId
;
7095 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(learn_spell_id
);
7098 sLog
.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto
->ItemId
, learn_spell_id
);
7099 SendEquipError(EQUIP_ERR_NONE
,item
,NULL
);
7103 Spell
*spell
= new Spell(this, spellInfo
, false);
7104 spell
->m_CastItem
= item
;
7105 spell
->m_cast_count
= cast_count
; //set count of casts
7106 spell
->m_currentBasePoints
[0] = learning_spell_id
;
7107 spell
->prepare(&targets
);
7111 // use triggered flag only for items with many spell casts and for not first cast
7114 // item spells casted at use
7115 for(int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
7117 _Spell
const& spellData
= proto
->Spells
[i
];
7120 if(!spellData
.SpellId
)
7123 // wrong triggering type
7124 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_NO_DELAY_USE
)
7127 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
7130 sLog
.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto
->ItemId
, spellData
.SpellId
);
7134 Spell
*spell
= new Spell(this, spellInfo
, (count
> 0));
7135 spell
->m_CastItem
= item
;
7136 spell
->m_cast_count
= cast_count
; // set count of casts
7137 spell
->m_glyphIndex
= glyphIndex
; // glyph index
7138 spell
->prepare(&targets
);
7143 // Item enchantments spells casted at use
7144 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
7146 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
7147 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
7148 if(!pEnchant
) continue;
7149 for (int s
=0;s
<3;s
++)
7151 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL
)
7154 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
7157 sLog
.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
7161 Spell
*spell
= new Spell(this, spellInfo
, (count
> 0));
7162 spell
->m_CastItem
= item
;
7163 spell
->m_cast_count
= cast_count
; // set count of casts
7164 spell
->m_glyphIndex
= glyphIndex
; // glyph index
7165 spell
->prepare(&targets
);
7172 void Player::_RemoveAllItemMods()
7174 sLog
.outDebug("_RemoveAllItemMods start.");
7176 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
7180 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7184 // item set bonuses not dependent from item broken state
7186 RemoveItemsSetItem(this,proto
);
7188 if(m_items
[i
]->IsBroken())
7191 ApplyItemEquipSpell(m_items
[i
],false);
7192 ApplyEnchantment(m_items
[i
], false);
7196 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
7200 if(m_items
[i
]->IsBroken())
7202 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7206 uint32 attacktype
= Player::GetAttackBySlot(i
);
7207 if(attacktype
< MAX_ATTACK
)
7208 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),false);
7210 _ApplyItemBonuses(proto
,i
, false);
7212 if( i
== EQUIPMENT_SLOT_RANGED
)
7213 _ApplyAmmoBonuses();
7217 sLog
.outDebug("_RemoveAllItemMods complete.");
7220 void Player::_ApplyAllItemMods()
7222 sLog
.outDebug("_ApplyAllItemMods start.");
7224 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
7228 if(m_items
[i
]->IsBroken())
7231 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7235 uint32 attacktype
= Player::GetAttackBySlot(i
);
7236 if(attacktype
< MAX_ATTACK
)
7237 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),true);
7239 _ApplyItemBonuses(proto
,i
, true);
7241 if( i
== EQUIPMENT_SLOT_RANGED
)
7242 _ApplyAmmoBonuses();
7246 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
7250 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7254 // item set bonuses not dependent from item broken state
7256 AddItemsSetItem(this,m_items
[i
]);
7258 if(m_items
[i
]->IsBroken())
7261 ApplyItemEquipSpell(m_items
[i
],true);
7262 ApplyEnchantment(m_items
[i
], true);
7266 sLog
.outDebug("_ApplyAllItemMods complete.");
7269 void Player::_ApplyAllLevelScaleItemMods(bool apply
)
7271 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; ++i
)
7275 if(m_items
[i
]->IsBroken())
7278 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7282 _ApplyItemBonuses(proto
,i
, apply
, true);
7287 void Player::_ApplyAmmoBonuses()
7290 uint32 ammo_id
= GetUInt32Value(PLAYER_AMMO_ID
);
7294 float currentAmmoDPS
;
7296 ItemPrototype
const *ammo_proto
= objmgr
.GetItemPrototype( ammo_id
);
7297 if( !ammo_proto
|| ammo_proto
->Class
!=ITEM_CLASS_PROJECTILE
|| !CheckAmmoCompatibility(ammo_proto
))
7298 currentAmmoDPS
= 0.0f
;
7300 currentAmmoDPS
= ammo_proto
->Damage
[0].DamageMin
;
7302 if(currentAmmoDPS
== GetAmmoDPS())
7305 m_ammoDPS
= currentAmmoDPS
;
7307 if(CanModifyStats())
7308 UpdateDamagePhysical(RANGED_ATTACK
);
7311 bool Player::CheckAmmoCompatibility(const ItemPrototype
*ammo_proto
) const
7316 // check ranged weapon
7317 Item
*weapon
= GetWeaponForAttack( RANGED_ATTACK
);
7318 if(!weapon
|| weapon
->IsBroken() )
7321 ItemPrototype
const* weapon_proto
= weapon
->GetProto();
7322 if(!weapon_proto
|| weapon_proto
->Class
!=ITEM_CLASS_WEAPON
)
7325 // check ammo ws. weapon compatibility
7326 switch(weapon_proto
->SubClass
)
7328 case ITEM_SUBCLASS_WEAPON_BOW
:
7329 case ITEM_SUBCLASS_WEAPON_CROSSBOW
:
7330 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_ARROW
)
7333 case ITEM_SUBCLASS_WEAPON_GUN
:
7334 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_BULLET
)
7344 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7345 Called by remove insignia spell effect */
7346 void Player::RemovedInsignia(Player
* looterPlr
)
7348 if (!GetBattleGroundId())
7351 // If not released spirit, do it !
7352 if(m_deathTimer
> 0)
7359 Corpse
*corpse
= GetCorpse();
7363 // We have to convert player corpse to bones, not to be able to resurrect there
7364 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7365 Corpse
*bones
= ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7369 // Now we must make bones lootable, and send player loot
7370 bones
->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS
, CORPSE_DYNFLAG_LOOTABLE
);
7372 // We store the level of our player in the gold field
7373 // We retrieve this information at Player::SendLoot()
7374 bones
->loot
.gold
= getLevel();
7375 bones
->lootRecipient
= looterPlr
;
7376 looterPlr
->SendLoot(bones
->GetGUID(), LOOT_INSIGNIA
);
7379 void Player::SendLootRelease( uint64 guid
)
7381 WorldPacket
data( SMSG_LOOT_RELEASE_RESPONSE
, (8+1) );
7382 data
<< uint64(guid
) << uint8(1);
7383 SendDirectMessage( &data
);
7386 void Player::SendLoot(uint64 guid
, LootType loot_type
)
7388 if (uint64 lguid
= GetLootGUID())
7389 m_session
->DoLootRelease(lguid
);
7392 PermissionTypes permission
= ALL_PERMISSION
;
7394 sLog
.outDebug("Player::SendLoot");
7395 if (IS_GAMEOBJECT_GUID(guid
))
7397 sLog
.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7398 GameObject
*go
= GetMap()->GetGameObject(guid
);
7400 // not check distance for GO in case owned GO (fishing bobber case, for example)
7401 // And permit out of range GO with no owner in case fishing hole
7402 if (!go
|| (loot_type
!= LOOT_FISHINGHOLE
&& (loot_type
!= LOOT_FISHING
|| go
->GetOwnerGUID() != GetGUID()) && !go
->IsWithinDistInMap(this,INTERACTION_DISTANCE
)))
7404 SendLootRelease(guid
);
7410 if (go
->getLootState() == GO_READY
)
7412 uint32 lootid
= go
->GetGOInfo()->GetLootId();
7416 sLog
.outDebug(" if(lootid)");
7418 loot
->FillLoot(lootid
, LootTemplates_Gameobject
, this, false);
7421 if (loot_type
== LOOT_FISHING
)
7422 go
->getFishLoot(loot
,this);
7424 go
->SetLootState(GO_ACTIVATED
);
7427 else if (IS_ITEM_GUID(guid
))
7429 Item
*item
= GetItemByGuid( guid
);
7433 SendLootRelease(guid
);
7439 if (!item
->m_lootGenerated
)
7441 item
->m_lootGenerated
= true;
7446 case LOOT_DISENCHANTING
:
7447 loot
->FillLoot(item
->GetProto()->DisenchantID
, LootTemplates_Disenchant
, this,true);
7449 case LOOT_PROSPECTING
:
7450 loot
->FillLoot(item
->GetEntry(), LootTemplates_Prospecting
, this,true);
7453 loot
->FillLoot(item
->GetEntry(), LootTemplates_Milling
, this,true);
7456 loot
->FillLoot(item
->GetEntry(), LootTemplates_Item
, this,true);
7457 loot
->generateMoneyLoot(item
->GetProto()->MinMoneyLoot
,item
->GetProto()->MaxMoneyLoot
);
7462 else if (IS_CORPSE_GUID(guid
)) // remove insignia
7464 Corpse
*bones
= ObjectAccessor::GetCorpse(*this, guid
);
7466 if (!bones
|| !((loot_type
== LOOT_CORPSE
) || (loot_type
== LOOT_INSIGNIA
)) || (bones
->GetType() != CORPSE_BONES
) )
7468 SendLootRelease(guid
);
7472 loot
= &bones
->loot
;
7474 if (!bones
->lootForBody
)
7476 bones
->lootForBody
= true;
7477 uint32 pLevel
= bones
->loot
.gold
;
7478 bones
->loot
.clear();
7479 // It may need a better formula
7480 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7481 bones
->loot
.gold
= (uint32
)( urand(50, 150) * 0.016f
* pow( ((float)pLevel
)/5.76f
, 2.5f
) * sWorld
.getRate(RATE_DROP_MONEY
) );
7484 if (bones
->lootRecipient
!= this)
7485 permission
= NONE_PERMISSION
;
7489 Creature
*creature
= GetMap()->GetCreature(guid
);
7491 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7492 if (!creature
|| creature
->isAlive()!=(loot_type
== LOOT_PICKPOCKETING
) || !creature
->IsWithinDistInMap(this,INTERACTION_DISTANCE
))
7494 SendLootRelease(guid
);
7498 if (loot_type
== LOOT_PICKPOCKETING
&& IsFriendlyTo(creature
))
7500 SendLootRelease(guid
);
7504 loot
= &creature
->loot
;
7506 if (loot_type
== LOOT_PICKPOCKETING
)
7508 if (!creature
->lootForPickPocketed
)
7510 creature
->lootForPickPocketed
= true;
7513 if (uint32 lootid
= creature
->GetCreatureInfo()->pickpocketLootId
)
7514 loot
->FillLoot(lootid
, LootTemplates_Pickpocketing
, this, false);
7516 // Generate extra money for pick pocket loot
7517 const uint32 a
= urand(0, creature
->getLevel()/2);
7518 const uint32 b
= urand(0, getLevel()/2);
7519 loot
->gold
= uint32(10 * (a
+ b
) * sWorld
.getRate(RATE_DROP_MONEY
));
7524 // the player whose group may loot the corpse
7525 Player
*recipient
= creature
->GetLootRecipient();
7528 creature
->SetLootRecipient(this);
7532 if (creature
->lootForPickPocketed
)
7534 creature
->lootForPickPocketed
= false;
7538 if (!creature
->lootForBody
)
7540 creature
->lootForBody
= true;
7543 if (uint32 lootid
= creature
->GetCreatureInfo()->lootid
)
7544 loot
->FillLoot(lootid
, LootTemplates_Creature
, recipient
, false);
7546 loot
->generateMoneyLoot(creature
->GetCreatureInfo()->mingold
,creature
->GetCreatureInfo()->maxgold
);
7548 if (Group
* group
= recipient
->GetGroup())
7550 group
->UpdateLooterGuid(creature
,true);
7552 switch (group
->GetLootMethod())
7555 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7556 group
->GroupLoot(recipient
->GetGUID(), loot
, creature
);
7558 case NEED_BEFORE_GREED
:
7559 group
->NeedBeforeGreed(recipient
->GetGUID(), loot
, creature
);
7562 group
->MasterLoot(recipient
->GetGUID(), loot
, creature
);
7570 // possible only if creature->lootForBody && loot->empty() at spell cast check
7571 if (loot_type
== LOOT_SKINNING
)
7574 loot
->FillLoot(creature
->GetCreatureInfo()->SkinLootId
, LootTemplates_Skinning
, this, false);
7576 // set group rights only for loot_type != LOOT_SKINNING
7579 if(Group
* group
= GetGroup())
7581 if (group
== recipient
->GetGroup())
7583 if (group
->GetLootMethod() == FREE_FOR_ALL
)
7584 permission
= ALL_PERMISSION
;
7585 else if (group
->GetLooterGuid() == GetGUID())
7587 if (group
->GetLootMethod() == MASTER_LOOT
)
7588 permission
= MASTER_PERMISSION
;
7590 permission
= ALL_PERMISSION
;
7593 permission
= GROUP_PERMISSION
;
7596 permission
= NONE_PERMISSION
;
7598 else if (recipient
== this)
7599 permission
= ALL_PERMISSION
;
7601 permission
= NONE_PERMISSION
;
7608 // LOOT_INSIGNIA and LOOT_FISHINGHOLE unsupported by client
7611 case LOOT_INSIGNIA
: loot_type
= LOOT_SKINNING
; break;
7612 case LOOT_FISHINGHOLE
: loot_type
= LOOT_FISHING
; break;
7616 // need know merged fishing/corpse loot type for achievements
7617 loot
->loot_type
= loot_type
;
7619 WorldPacket
data(SMSG_LOOT_RESPONSE
, (9+50)); // we guess size
7621 data
<< uint64(guid
);
7622 data
<< uint8(loot_type
);
7623 data
<< LootView(*loot
, this, permission
);
7625 SendDirectMessage(&data
);
7627 // add 'this' player as one of the players that are looting 'loot'
7628 if (permission
!= NONE_PERMISSION
)
7629 loot
->AddLooter(GetGUID());
7631 if (loot_type
== LOOT_CORPSE
&& !IS_ITEM_GUID(guid
))
7632 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_LOOTING
);
7635 void Player::SendNotifyLootMoneyRemoved()
7637 WorldPacket
data(SMSG_LOOT_CLEAR_MONEY
, 0);
7638 GetSession()->SendPacket( &data
);
7641 void Player::SendNotifyLootItemRemoved(uint8 lootSlot
)
7643 WorldPacket
data(SMSG_LOOT_REMOVED
, 1);
7644 data
<< uint8(lootSlot
);
7645 GetSession()->SendPacket( &data
);
7648 void Player::SendUpdateWorldState(uint32 Field
, uint32 Value
)
7650 WorldPacket
data(SMSG_UPDATE_WORLD_STATE
, 8);
7653 GetSession()->SendPacket(&data
);
7656 void Player::SendInitWorldStates(uint32 zoneid
, uint32 areaid
)
7658 // data depends on zoneid/mapid...
7659 BattleGround
* bg
= GetBattleGround();
7660 uint16 NumberOfFields
= 0;
7661 uint32 mapid
= GetMapId();
7663 sLog
.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid
, zoneid
);
7665 // may be exist better way to do this...
7688 NumberOfFields
= 41;
7691 NumberOfFields
= 15;
7694 NumberOfFields
= 83;
7697 NumberOfFields
= 16;
7701 NumberOfFields
= 40;
7704 NumberOfFields
= 27;
7707 NumberOfFields
= 39;
7710 NumberOfFields
= 38;
7713 NumberOfFields
= 37;
7718 NumberOfFields
= 11;
7721 NumberOfFields
= 11;
7724 NumberOfFields
= 12;
7728 WorldPacket
data(SMSG_INIT_WORLD_STATES
, (4+4+4+2+(NumberOfFields
*8)));
7729 data
<< uint32(mapid
); // mapid
7730 data
<< uint32(zoneid
); // zone id
7731 data
<< uint32(areaid
); // area id, new 2.1.0
7732 data
<< uint16(NumberOfFields
); // count of uint64 blocks
7733 data
<< uint32(0x8d8) << uint32(0x0); // 1
7734 data
<< uint32(0x8d7) << uint32(0x0); // 2
7735 data
<< uint32(0x8d6) << uint32(0x0); // 3
7736 data
<< uint32(0x8d5) << uint32(0x0); // 4
7737 data
<< uint32(0x8d4) << uint32(0x0); // 5
7738 data
<< uint32(0x8d3) << uint32(0x0); // 6
7739 // 7 1 - Arena season in progress, 0 - end of season
7740 data
<< uint32(0xC77) << uint32(sWorld
.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS
));
7741 // 8 Arena season id
7742 data
<< uint32(0xF3D) << uint32(sWorld
.getConfig(CONFIG_ARENA_SEASON_ID
));
7743 if(mapid
== 530) // Outland
7745 data
<< uint32(0x9bf) << uint32(0x0); // 7
7746 data
<< uint32(0x9bd) << uint32(0xF); // 8
7747 data
<< uint32(0x9bb) << uint32(0xF); // 9
7762 data
<< uint32(0x7ae) << uint32(0x1); // 7
7763 data
<< uint32(0x532) << uint32(0x1); // 8
7764 data
<< uint32(0x531) << uint32(0x0); // 9
7765 data
<< uint32(0x52e) << uint32(0x0); // 10
7766 data
<< uint32(0x571) << uint32(0x0); // 11
7767 data
<< uint32(0x570) << uint32(0x0); // 12
7768 data
<< uint32(0x567) << uint32(0x1); // 13
7769 data
<< uint32(0x566) << uint32(0x1); // 14
7770 data
<< uint32(0x550) << uint32(0x1); // 15
7771 data
<< uint32(0x544) << uint32(0x0); // 16
7772 data
<< uint32(0x536) << uint32(0x0); // 17
7773 data
<< uint32(0x535) << uint32(0x1); // 18
7774 data
<< uint32(0x518) << uint32(0x0); // 19
7775 data
<< uint32(0x517) << uint32(0x0); // 20
7776 data
<< uint32(0x574) << uint32(0x0); // 21
7777 data
<< uint32(0x573) << uint32(0x0); // 22
7778 data
<< uint32(0x572) << uint32(0x0); // 23
7779 data
<< uint32(0x56f) << uint32(0x0); // 24
7780 data
<< uint32(0x56e) << uint32(0x0); // 25
7781 data
<< uint32(0x56d) << uint32(0x0); // 26
7782 data
<< uint32(0x56c) << uint32(0x0); // 27
7783 data
<< uint32(0x56b) << uint32(0x0); // 28
7784 data
<< uint32(0x56a) << uint32(0x1); // 29
7785 data
<< uint32(0x569) << uint32(0x1); // 30
7786 data
<< uint32(0x568) << uint32(0x1); // 13
7787 data
<< uint32(0x565) << uint32(0x0); // 32
7788 data
<< uint32(0x564) << uint32(0x0); // 33
7789 data
<< uint32(0x563) << uint32(0x0); // 34
7790 data
<< uint32(0x562) << uint32(0x0); // 35
7791 data
<< uint32(0x561) << uint32(0x0); // 36
7792 data
<< uint32(0x560) << uint32(0x0); // 37
7793 data
<< uint32(0x55f) << uint32(0x0); // 38
7794 data
<< uint32(0x55e) << uint32(0x0); // 39
7795 data
<< uint32(0x55d) << uint32(0x0); // 40
7796 data
<< uint32(0x3c6) << uint32(0x4); // 41
7797 data
<< uint32(0x3c4) << uint32(0x6); // 42
7798 data
<< uint32(0x3c2) << uint32(0x4); // 43
7799 data
<< uint32(0x516) << uint32(0x1); // 44
7800 data
<< uint32(0x515) << uint32(0x0); // 45
7801 data
<< uint32(0x3b6) << uint32(0x6); // 46
7802 data
<< uint32(0x55c) << uint32(0x0); // 47
7803 data
<< uint32(0x55b) << uint32(0x0); // 48
7804 data
<< uint32(0x55a) << uint32(0x0); // 49
7805 data
<< uint32(0x559) << uint32(0x0); // 50
7806 data
<< uint32(0x558) << uint32(0x0); // 51
7807 data
<< uint32(0x557) << uint32(0x0); // 52
7808 data
<< uint32(0x556) << uint32(0x0); // 53
7809 data
<< uint32(0x555) << uint32(0x0); // 54
7810 data
<< uint32(0x554) << uint32(0x1); // 55
7811 data
<< uint32(0x553) << uint32(0x1); // 56
7812 data
<< uint32(0x552) << uint32(0x1); // 57
7813 data
<< uint32(0x551) << uint32(0x1); // 58
7814 data
<< uint32(0x54f) << uint32(0x0); // 59
7815 data
<< uint32(0x54e) << uint32(0x0); // 60
7816 data
<< uint32(0x54d) << uint32(0x1); // 61
7817 data
<< uint32(0x54c) << uint32(0x0); // 62
7818 data
<< uint32(0x54b) << uint32(0x0); // 63
7819 data
<< uint32(0x545) << uint32(0x0); // 64
7820 data
<< uint32(0x543) << uint32(0x1); // 65
7821 data
<< uint32(0x542) << uint32(0x0); // 66
7822 data
<< uint32(0x540) << uint32(0x0); // 67
7823 data
<< uint32(0x53f) << uint32(0x0); // 68
7824 data
<< uint32(0x53e) << uint32(0x0); // 69
7825 data
<< uint32(0x53d) << uint32(0x0); // 70
7826 data
<< uint32(0x53c) << uint32(0x0); // 71
7827 data
<< uint32(0x53b) << uint32(0x0); // 72
7828 data
<< uint32(0x53a) << uint32(0x1); // 73
7829 data
<< uint32(0x539) << uint32(0x0); // 74
7830 data
<< uint32(0x538) << uint32(0x0); // 75
7831 data
<< uint32(0x537) << uint32(0x0); // 76
7832 data
<< uint32(0x534) << uint32(0x0); // 77
7833 data
<< uint32(0x533) << uint32(0x0); // 78
7834 data
<< uint32(0x530) << uint32(0x0); // 79
7835 data
<< uint32(0x52f) << uint32(0x0); // 80
7836 data
<< uint32(0x52d) << uint32(0x1); // 81
7839 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_WS
)
7840 bg
->FillInitialWorldStates(data
);
7843 data
<< uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7844 data
<< uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7845 data
<< uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7846 data
<< uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7847 data
<< uint32(0x60b) << uint32(0x2); // 11 1547 unk
7848 data
<< uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7849 data
<< uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7850 data
<< uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7854 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_AB
)
7855 bg
->FillInitialWorldStates(data
);
7858 data
<< uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7859 data
<< uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7860 data
<< uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7861 data
<< uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7862 data
<< uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7863 data
<< uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7864 data
<< uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7865 data
<< uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7866 data
<< uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7867 data
<< uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7868 data
<< uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7869 data
<< uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7870 data
<< uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7871 data
<< uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7872 data
<< uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7873 data
<< uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7874 data
<< uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7875 data
<< uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7876 data
<< uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7877 data
<< uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7878 data
<< uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7879 data
<< uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7880 data
<< uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7881 data
<< uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7882 data
<< uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7883 data
<< uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7884 data
<< uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7885 data
<< uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7886 data
<< uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7887 data
<< uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7888 data
<< uint32(0x745) << uint32(0x2); // 37 1861 unk
7889 data
<< uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7893 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_EY
)
7894 bg
->FillInitialWorldStates(data
);
7897 data
<< uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7898 data
<< uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7899 data
<< uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7900 data
<< uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7901 data
<< uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7902 data
<< uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7903 data
<< uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7904 data
<< uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7905 data
<< uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7906 data
<< uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7907 data
<< uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7908 data
<< uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7909 data
<< uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7910 data
<< uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7911 data
<< uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7912 data
<< uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7913 data
<< uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7914 data
<< uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7915 data
<< uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7916 data
<< uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7917 data
<< uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7918 data
<< uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7919 data
<< uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7920 data
<< uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7921 data
<< uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7922 data
<< uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7923 data
<< uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7924 data
<< uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7925 data
<< uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7926 data
<< uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7927 data
<< uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7928 data
<< uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7929 // and some more ... unknown
7932 case 3483: // Hellfire Peninsula
7933 data
<< uint32(0x9ba) << uint32(0x1); // 10
7934 data
<< uint32(0x9b9) << uint32(0x1); // 11
7935 data
<< uint32(0x9b5) << uint32(0x0); // 12
7936 data
<< uint32(0x9b4) << uint32(0x1); // 13
7937 data
<< uint32(0x9b3) << uint32(0x0); // 14
7938 data
<< uint32(0x9b2) << uint32(0x0); // 15
7939 data
<< uint32(0x9b1) << uint32(0x1); // 16
7940 data
<< uint32(0x9b0) << uint32(0x0); // 17
7941 data
<< uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7942 data
<< uint32(0x9ac) << uint32(0x0); // 19
7943 data
<< uint32(0x9a8) << uint32(0x0); // 20
7944 data
<< uint32(0x9a7) << uint32(0x0); // 21
7945 data
<< uint32(0x9a6) << uint32(0x1); // 22
7947 case 3519: // Terokkar Forest
7948 data
<< uint32(0xa41) << uint32(0x0); // 10
7949 data
<< uint32(0xa40) << uint32(0x14); // 11
7950 data
<< uint32(0xa3f) << uint32(0x0); // 12
7951 data
<< uint32(0xa3e) << uint32(0x0); // 13
7952 data
<< uint32(0xa3d) << uint32(0x5); // 14
7953 data
<< uint32(0xa3c) << uint32(0x0); // 15
7954 data
<< uint32(0xa87) << uint32(0x0); // 16
7955 data
<< uint32(0xa86) << uint32(0x0); // 17
7956 data
<< uint32(0xa85) << uint32(0x0); // 18
7957 data
<< uint32(0xa84) << uint32(0x0); // 19
7958 data
<< uint32(0xa83) << uint32(0x0); // 20
7959 data
<< uint32(0xa82) << uint32(0x0); // 21
7960 data
<< uint32(0xa81) << uint32(0x0); // 22
7961 data
<< uint32(0xa80) << uint32(0x0); // 23
7962 data
<< uint32(0xa7e) << uint32(0x0); // 24
7963 data
<< uint32(0xa7d) << uint32(0x0); // 25
7964 data
<< uint32(0xa7c) << uint32(0x0); // 26
7965 data
<< uint32(0xa7b) << uint32(0x0); // 27
7966 data
<< uint32(0xa7a) << uint32(0x0); // 28
7967 data
<< uint32(0xa79) << uint32(0x0); // 29
7968 data
<< uint32(0x9d0) << uint32(0x5); // 30
7969 data
<< uint32(0x9ce) << uint32(0x0); // 31
7970 data
<< uint32(0x9cd) << uint32(0x0); // 32
7971 data
<< uint32(0x9cc) << uint32(0x0); // 33
7972 data
<< uint32(0xa88) << uint32(0x0); // 34
7973 data
<< uint32(0xad0) << uint32(0x0); // 35
7974 data
<< uint32(0xacf) << uint32(0x1); // 36
7976 case 3521: // Zangarmarsh
7977 data
<< uint32(0x9e1) << uint32(0x0); // 10
7978 data
<< uint32(0x9e0) << uint32(0x0); // 11
7979 data
<< uint32(0x9df) << uint32(0x0); // 12
7980 data
<< uint32(0xa5d) << uint32(0x1); // 13
7981 data
<< uint32(0xa5c) << uint32(0x0); // 14
7982 data
<< uint32(0xa5b) << uint32(0x1); // 15
7983 data
<< uint32(0xa5a) << uint32(0x0); // 16
7984 data
<< uint32(0xa59) << uint32(0x1); // 17
7985 data
<< uint32(0xa58) << uint32(0x0); // 18
7986 data
<< uint32(0xa57) << uint32(0x0); // 19
7987 data
<< uint32(0xa56) << uint32(0x0); // 20
7988 data
<< uint32(0xa55) << uint32(0x1); // 21
7989 data
<< uint32(0xa54) << uint32(0x0); // 22
7990 data
<< uint32(0x9e7) << uint32(0x0); // 23
7991 data
<< uint32(0x9e6) << uint32(0x0); // 24
7992 data
<< uint32(0x9e5) << uint32(0x0); // 25
7993 data
<< uint32(0xa00) << uint32(0x0); // 26
7994 data
<< uint32(0x9ff) << uint32(0x1); // 27
7995 data
<< uint32(0x9fe) << uint32(0x0); // 28
7996 data
<< uint32(0x9fd) << uint32(0x0); // 29
7997 data
<< uint32(0x9fc) << uint32(0x1); // 30
7998 data
<< uint32(0x9fb) << uint32(0x0); // 31
7999 data
<< uint32(0xa62) << uint32(0x0); // 32
8000 data
<< uint32(0xa61) << uint32(0x1); // 33
8001 data
<< uint32(0xa60) << uint32(0x1); // 34
8002 data
<< uint32(0xa5f) << uint32(0x0); // 35
8004 case 3698: // Nagrand Arena
8005 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_NA
)
8006 bg
->FillInitialWorldStates(data
);
8009 data
<< uint32(0xa0f) << uint32(0x0); // 7
8010 data
<< uint32(0xa10) << uint32(0x0); // 8
8011 data
<< uint32(0xa11) << uint32(0x0); // 9 show
8014 case 3702: // Blade's Edge Arena
8015 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_BE
)
8016 bg
->FillInitialWorldStates(data
);
8019 data
<< uint32(0x9f0) << uint32(0x0); // 7 gold
8020 data
<< uint32(0x9f1) << uint32(0x0); // 8 green
8021 data
<< uint32(0x9f3) << uint32(0x0); // 9 show
8024 case 3968: // Ruins of Lordaeron
8025 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_RL
)
8026 bg
->FillInitialWorldStates(data
);
8029 data
<< uint32(0xbb8) << uint32(0x0); // 7 gold
8030 data
<< uint32(0xbb9) << uint32(0x0); // 8 green
8031 data
<< uint32(0xbba) << uint32(0x0); // 9 show
8034 case 3703: // Shattrath City
8037 data
<< uint32(0x914) << uint32(0x0); // 7
8038 data
<< uint32(0x913) << uint32(0x0); // 8
8039 data
<< uint32(0x912) << uint32(0x0); // 9
8040 data
<< uint32(0x915) << uint32(0x0); // 10
8043 GetSession()->SendPacket(&data
);
8046 uint32
Player::GetXPRestBonus(uint32 xp
)
8048 uint32 rested_bonus
= (uint32
)GetRestBonus(); // xp for each rested bonus
8050 if(rested_bonus
> xp
) // max rested_bonus == xp or (r+x) = 200% xp
8053 SetRestBonus( GetRestBonus() - rested_bonus
);
8055 sLog
.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp
+rested_bonus
,rested_bonus
,GetRestBonus());
8056 return rested_bonus
;
8059 void Player::SetBindPoint(uint64 guid
)
8061 WorldPacket
data(SMSG_BINDER_CONFIRM
, 8);
8062 data
<< uint64(guid
);
8063 GetSession()->SendPacket( &data
);
8066 void Player::SendTalentWipeConfirm(uint64 guid
)
8068 WorldPacket
data(MSG_TALENT_WIPE_CONFIRM
, (8+4));
8069 data
<< uint64(guid
);
8070 data
<< uint32(resetTalentsCost());
8071 GetSession()->SendPacket( &data
);
8074 void Player::SendPetSkillWipeConfirm()
8076 Pet
* pet
= GetPet();
8079 WorldPacket
data(SMSG_PET_UNLEARN_CONFIRM
, (8+4));
8080 data
<< pet
->GetGUID();
8081 data
<< uint32(pet
->resetTalentsCost());
8082 GetSession()->SendPacket( &data
);
8085 /*********************************************************/
8086 /*** STORAGE SYSTEM ***/
8087 /*********************************************************/
8089 void Player::SetVirtualItemSlot( uint8 i
, Item
* item
)
8094 if(!item
->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT
))
8096 uint32 charges
= item
->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
);
8100 item
->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
,charges
-1);
8101 else if(charges
<= 1)
8103 ApplyEnchantment(item
,TEMP_ENCHANTMENT_SLOT
,false);
8104 item
->ClearEnchantment(TEMP_ENCHANTMENT_SLOT
);
8109 void Player::SetSheath( SheathState sheathed
)
8113 case SHEATH_STATE_UNARMED
: // no prepared weapon
8114 SetVirtualItemSlot(0,NULL
);
8115 SetVirtualItemSlot(1,NULL
);
8116 SetVirtualItemSlot(2,NULL
);
8118 case SHEATH_STATE_MELEE
: // prepared melee weapon
8120 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK
,true));
8121 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK
,true));
8122 SetVirtualItemSlot(2,NULL
);
8124 case SHEATH_STATE_RANGED
: // prepared ranged weapon
8125 SetVirtualItemSlot(0,NULL
);
8126 SetVirtualItemSlot(1,NULL
);
8127 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK
,true));
8130 SetVirtualItemSlot(0,NULL
);
8131 SetVirtualItemSlot(1,NULL
);
8132 SetVirtualItemSlot(2,NULL
);
8135 Unit::SetSheath(sheathed
); // this must visualize Sheath changing for other players...
8138 uint8
Player::FindEquipSlot( ItemPrototype
const* proto
, uint32 slot
, bool swap
) const
8140 uint8 pClass
= getClass();
8143 slots
[0] = NULL_SLOT
;
8144 slots
[1] = NULL_SLOT
;
8145 slots
[2] = NULL_SLOT
;
8146 slots
[3] = NULL_SLOT
;
8147 switch( proto
->InventoryType
)
8150 slots
[0] = EQUIPMENT_SLOT_HEAD
;
8153 slots
[0] = EQUIPMENT_SLOT_NECK
;
8155 case INVTYPE_SHOULDERS
:
8156 slots
[0] = EQUIPMENT_SLOT_SHOULDERS
;
8159 slots
[0] = EQUIPMENT_SLOT_BODY
;
8162 slots
[0] = EQUIPMENT_SLOT_CHEST
;
8165 slots
[0] = EQUIPMENT_SLOT_CHEST
;
8168 slots
[0] = EQUIPMENT_SLOT_WAIST
;
8171 slots
[0] = EQUIPMENT_SLOT_LEGS
;
8174 slots
[0] = EQUIPMENT_SLOT_FEET
;
8176 case INVTYPE_WRISTS
:
8177 slots
[0] = EQUIPMENT_SLOT_WRISTS
;
8180 slots
[0] = EQUIPMENT_SLOT_HANDS
;
8182 case INVTYPE_FINGER
:
8183 slots
[0] = EQUIPMENT_SLOT_FINGER1
;
8184 slots
[1] = EQUIPMENT_SLOT_FINGER2
;
8186 case INVTYPE_TRINKET
:
8187 slots
[0] = EQUIPMENT_SLOT_TRINKET1
;
8188 slots
[1] = EQUIPMENT_SLOT_TRINKET2
;
8191 slots
[0] = EQUIPMENT_SLOT_BACK
;
8193 case INVTYPE_WEAPON
:
8195 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8197 // suggest offhand slot only if know dual wielding
8198 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8200 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
8203 case INVTYPE_SHIELD
:
8204 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8206 case INVTYPE_RANGED
:
8207 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8209 case INVTYPE_2HWEAPON
:
8210 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8211 if (CanDualWield() && CanTitanGrip())
8212 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
8214 case INVTYPE_TABARD
:
8215 slots
[0] = EQUIPMENT_SLOT_TABARD
;
8217 case INVTYPE_WEAPONMAINHAND
:
8218 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8220 case INVTYPE_WEAPONOFFHAND
:
8221 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8223 case INVTYPE_HOLDABLE
:
8224 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8226 case INVTYPE_THROWN
:
8227 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8229 case INVTYPE_RANGEDRIGHT
:
8230 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8233 slots
[0] = INVENTORY_SLOT_BAG_START
+ 0;
8234 slots
[1] = INVENTORY_SLOT_BAG_START
+ 1;
8235 slots
[2] = INVENTORY_SLOT_BAG_START
+ 2;
8236 slots
[3] = INVENTORY_SLOT_BAG_START
+ 3;
8240 switch(proto
->SubClass
)
8242 case ITEM_SUBCLASS_ARMOR_LIBRAM
:
8243 if (pClass
== CLASS_PALADIN
)
8244 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8246 case ITEM_SUBCLASS_ARMOR_IDOL
:
8247 if (pClass
== CLASS_DRUID
)
8248 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8250 case ITEM_SUBCLASS_ARMOR_TOTEM
:
8251 if (pClass
== CLASS_SHAMAN
)
8252 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8254 case ITEM_SUBCLASS_ARMOR_MISC
:
8255 if (pClass
== CLASS_WARLOCK
)
8256 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8258 case ITEM_SUBCLASS_ARMOR_SIGIL
:
8259 if (pClass
== CLASS_DEATH_KNIGHT
)
8260 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8269 if( slot
!= NULL_SLOT
)
8271 if( swap
|| !GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
) )
8273 for (int i
= 0; i
< 4; ++i
)
8275 if ( slots
[i
] == slot
)
8282 // search free slot at first
8283 for (int i
= 0; i
< 4; ++i
)
8285 if ( slots
[i
] != NULL_SLOT
&& !GetItemByPos( INVENTORY_SLOT_BAG_0
, slots
[i
] ) )
8287 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8288 if(slots
[i
]!=EQUIPMENT_SLOT_OFFHAND
|| !IsTwoHandUsed())
8293 // if not found free and can swap return first appropriate from used
8294 for (int i
= 0; i
< 4; ++i
)
8296 if ( slots
[i
] != NULL_SLOT
&& swap
)
8305 uint8
Player::CanUnequipItems( uint32 item
, uint32 count
) const
8308 uint32 tempcount
= 0;
8310 uint8 res
= EQUIP_ERR_OK
;
8312 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8314 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8315 if( pItem
&& pItem
->GetEntry() == item
)
8317 uint8 ires
= CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
, false);
8318 if(ires
==EQUIP_ERR_OK
)
8320 tempcount
+= pItem
->GetCount();
8321 if( tempcount
>= count
)
8322 return EQUIP_ERR_OK
;
8328 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8330 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8331 if( pItem
&& pItem
->GetEntry() == item
)
8333 tempcount
+= pItem
->GetCount();
8334 if( tempcount
>= count
)
8335 return EQUIP_ERR_OK
;
8338 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
8340 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8341 if( pItem
&& pItem
->GetEntry() == item
)
8343 tempcount
+= pItem
->GetCount();
8344 if( tempcount
>= count
)
8345 return EQUIP_ERR_OK
;
8349 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8351 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8354 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8356 pItem
= GetItemByPos( i
, j
);
8357 if( pItem
&& pItem
->GetEntry() == item
)
8359 tempcount
+= pItem
->GetCount();
8360 if( tempcount
>= count
)
8361 return EQUIP_ERR_OK
;
8367 // not found req. item count and have unequippable items
8371 uint32
Player::GetItemCount( uint32 item
, bool inBankAlso
, Item
* skipItem
) const
8374 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8376 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8377 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8378 count
+= pItem
->GetCount();
8380 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
8382 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8383 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8384 count
+= pItem
->GetCount();
8386 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8388 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8390 count
+= pBag
->GetItemCount(item
,skipItem
);
8393 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8395 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8397 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8398 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8399 count
+= pItem
->GetGemCountWithID(item
);
8405 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; ++i
)
8407 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8408 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8409 count
+= pItem
->GetCount();
8411 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
8413 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8415 count
+= pBag
->GetItemCount(item
,skipItem
);
8418 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8420 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; ++i
)
8422 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8423 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8424 count
+= pItem
->GetGemCountWithID(item
);
8432 Item
* Player::GetItemByGuid( uint64 guid
) const
8434 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8436 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8437 if( pItem
&& pItem
->GetGUID() == guid
)
8440 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
8442 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8443 if( pItem
&& pItem
->GetGUID() == guid
)
8447 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8449 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8452 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8454 Item
* pItem
= pBag
->GetItemByPos( j
);
8455 if( pItem
&& pItem
->GetGUID() == guid
)
8460 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
8462 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8465 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8467 Item
* pItem
= pBag
->GetItemByPos( j
);
8468 if( pItem
&& pItem
->GetGUID() == guid
)
8477 Item
* Player::GetItemByPos( uint16 pos
) const
8479 uint8 bag
= pos
>> 8;
8480 uint8 slot
= pos
& 255;
8481 return GetItemByPos( bag
, slot
);
8484 Item
* Player::GetItemByPos( uint8 bag
, uint8 slot
) const
8486 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< BANK_SLOT_BAG_END
|| (slot
>= KEYRING_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)) )
8487 return m_items
[slot
];
8488 else if ((bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8489 || (bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
) )
8491 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8493 return pBag
->GetItemByPos(slot
);
8498 Item
* Player::GetWeaponForAttack(WeaponAttackType attackType
, bool useable
) const
8503 case BASE_ATTACK
: slot
= EQUIPMENT_SLOT_MAINHAND
; break;
8504 case OFF_ATTACK
: slot
= EQUIPMENT_SLOT_OFFHAND
; break;
8505 case RANGED_ATTACK
: slot
= EQUIPMENT_SLOT_RANGED
; break;
8506 default: return NULL
;
8509 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, slot
);
8510 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_WEAPON
)
8516 if( item
->IsBroken() || !IsUseEquipedWeapon(attackType
==BASE_ATTACK
) )
8522 Item
* Player::GetShield(bool useable
) const
8524 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
8525 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_ARMOR
)
8531 if( item
->IsBroken())
8537 uint32
Player::GetAttackBySlot( uint8 slot
)
8541 case EQUIPMENT_SLOT_MAINHAND
: return BASE_ATTACK
;
8542 case EQUIPMENT_SLOT_OFFHAND
: return OFF_ATTACK
;
8543 case EQUIPMENT_SLOT_RANGED
: return RANGED_ATTACK
;
8544 default: return MAX_ATTACK
;
8548 bool Player::IsInventoryPos( uint8 bag
, uint8 slot
)
8550 if( bag
== INVENTORY_SLOT_BAG_0
&& slot
== NULL_SLOT
)
8552 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
) )
8554 if( bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8556 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= KEYRING_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
) )
8561 bool Player::IsEquipmentPos( uint8 bag
, uint8 slot
)
8563 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< EQUIPMENT_SLOT_END
) )
8565 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8570 bool Player::IsBankPos( uint8 bag
, uint8 slot
)
8572 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
) )
8574 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8576 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8581 bool Player::IsBagPos( uint16 pos
)
8583 uint8 bag
= pos
>> 8;
8584 uint8 slot
= pos
& 255;
8585 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8587 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8592 bool Player::IsValidPos( uint8 bag
, uint8 slot
)
8598 if (bag
== INVENTORY_SLOT_BAG_0
)
8600 // any post selected
8601 if (slot
== NULL_SLOT
)
8605 if (slot
< EQUIPMENT_SLOT_END
)
8609 if (slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
)
8613 if (slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
)
8617 if (slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_END
)
8621 if (slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
)
8625 if (slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
8631 // bag content slots
8632 if (bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8634 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8638 // any post selected
8639 if (slot
== NULL_SLOT
)
8642 return slot
< pBag
->GetBagSize();
8645 // bank bag content slots
8646 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8648 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8652 // any post selected
8653 if (slot
== NULL_SLOT
)
8656 return slot
< pBag
->GetBagSize();
8664 bool Player::HasItemCount( uint32 item
, uint32 count
, bool inBankAlso
) const
8666 uint32 tempcount
= 0;
8667 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8669 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8670 if( pItem
&& pItem
->GetEntry() == item
)
8672 tempcount
+= pItem
->GetCount();
8673 if( tempcount
>= count
)
8677 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
8679 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8680 if( pItem
&& pItem
->GetEntry() == item
)
8682 tempcount
+= pItem
->GetCount();
8683 if( tempcount
>= count
)
8687 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8689 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8691 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8693 Item
* pItem
= GetItemByPos( i
, j
);
8694 if( pItem
&& pItem
->GetEntry() == item
)
8696 tempcount
+= pItem
->GetCount();
8697 if( tempcount
>= count
)
8706 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; ++i
)
8708 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8709 if( pItem
&& pItem
->GetEntry() == item
)
8711 tempcount
+= pItem
->GetCount();
8712 if( tempcount
>= count
)
8716 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
8718 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8720 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8722 Item
* pItem
= GetItemByPos( i
, j
);
8723 if( pItem
&& pItem
->GetEntry() == item
)
8725 tempcount
+= pItem
->GetCount();
8726 if( tempcount
>= count
)
8737 bool Player::HasItemOrGemWithIdEquipped( uint32 item
, uint32 count
, uint8 except_slot
) const
8739 uint32 tempcount
= 0;
8740 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
8742 if(i
==int(except_slot
))
8745 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8746 if( pItem
&& pItem
->GetEntry() == item
)
8748 tempcount
+= pItem
->GetCount();
8749 if( tempcount
>= count
)
8754 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(item
);
8755 if (pProto
&& pProto
->GemProperties
)
8757 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
8759 if(i
==int(except_slot
))
8762 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8763 if( pItem
&& pItem
->GetProto()->Socket
[0].Color
)
8765 tempcount
+= pItem
->GetGemCountWithID(item
);
8766 if( tempcount
>= count
)
8775 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory
, uint32 count
, uint8 except_slot
) const
8777 uint32 tempcount
= 0;
8778 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
8780 if(i
==int(except_slot
))
8783 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8787 ItemPrototype
const *pProto
= pItem
->GetProto();
8791 if (pProto
->ItemLimitCategory
== limitCategory
)
8793 tempcount
+= pItem
->GetCount();
8794 if( tempcount
>= count
)
8798 if( pProto
->Socket
[0].Color
)
8800 tempcount
+= pItem
->GetGemCountWithLimitCategory(limitCategory
);
8801 if( tempcount
>= count
)
8809 uint8
Player::_CanTakeMoreSimilarItems(uint32 entry
, uint32 count
, Item
* pItem
, uint32
* no_space_count
) const
8811 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
8815 *no_space_count
= count
;
8816 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8820 if(pProto
->MaxCount
<= 0)
8821 return EQUIP_ERR_OK
;
8823 uint32 curcount
= GetItemCount(pProto
->ItemId
,true,pItem
);
8825 if (curcount
+ count
> uint32(pProto
->MaxCount
))
8828 *no_space_count
= count
+curcount
- pProto
->MaxCount
;
8829 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8832 return EQUIP_ERR_OK
;
8835 bool Player::HasItemTotemCategory( uint32 TotemCategory
) const
8838 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8840 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8841 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8844 for(uint8 i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
8846 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8847 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8850 for(uint8 i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8852 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8854 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8856 pItem
= GetItemByPos( i
, j
);
8857 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8865 uint8
Player::_CanStoreItem_InSpecificSlot( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, ItemPrototype
const *pProto
, uint32
& count
, bool swap
, Item
* pSrcItem
) const
8867 Item
* pItem2
= GetItemByPos( bag
, slot
);
8869 // ignore move item (this slot will be empty at move)
8870 if (pItem2
==pSrcItem
)
8875 // empty specific slot - check item fit to slot
8876 if (!pItem2
|| swap
)
8878 if (bag
== INVENTORY_SLOT_BAG_0
)
8881 if (slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_START
+GetMaxKeyringSize() && !(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
))
8882 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8884 // currencytoken case
8885 if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
&& !(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
))
8886 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8889 if (slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
|| slot
>= PLAYER_SLOT_END
)
8890 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8894 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8896 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8898 ItemPrototype
const* pBagProto
= pBag
->GetProto();
8900 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8902 if (slot
>= pBagProto
->ContainerSlots
)
8903 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8905 if (!ItemCanGoIntoBag(pProto
,pBagProto
))
8906 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8909 // non empty stack with space
8910 need_space
= pProto
->GetMaxStackSize();
8912 // non empty slot, check item type
8916 if (pItem2
->GetEntry() != pProto
->ItemId
)
8917 return EQUIP_ERR_ITEM_CANT_STACK
;
8920 if (pItem2
->GetCount() >= pProto
->GetMaxStackSize())
8921 return EQUIP_ERR_ITEM_CANT_STACK
;
8923 // free stack space or infinity
8924 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
8927 if (need_space
> count
)
8930 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | slot
, need_space
);
8931 if (!newPosition
.isContainedIn(dest
))
8933 dest
.push_back(newPosition
);
8934 count
-= need_space
;
8936 return EQUIP_ERR_OK
;
8939 uint8
Player::_CanStoreItem_InBag( uint8 bag
, ItemPosCountVec
&dest
, ItemPrototype
const *pProto
, uint32
& count
, bool merge
, bool non_specialized
, Item
* pSrcItem
, uint8 skip_bag
, uint8 skip_slot
) const
8941 // skip specific bag already processed in first called _CanStoreItem_InBag
8943 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8945 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8947 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8949 ItemPrototype
const* pBagProto
= pBag
->GetProto();
8951 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8953 // specialized bag mode or non-specilized
8954 if (non_specialized
!= (pBagProto
->Class
== ITEM_CLASS_CONTAINER
&& pBagProto
->SubClass
== ITEM_SUBCLASS_CONTAINER
))
8955 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8957 if (!ItemCanGoIntoBag(pProto
,pBagProto
))
8958 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8960 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8962 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8966 Item
* pItem2
= GetItemByPos( bag
, j
);
8968 // ignore move item (this slot will be empty at move)
8969 if (pItem2
==pSrcItem
)
8972 // if merge skip empty, if !merge skip non-empty
8973 if ((pItem2
!=NULL
)!=merge
)
8978 if (pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->GetMaxStackSize())
8980 uint32 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
8981 if(need_space
> count
)
8984 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
8985 if (!newPosition
.isContainedIn(dest
))
8987 dest
.push_back(newPosition
);
8988 count
-= need_space
;
8991 return EQUIP_ERR_OK
;
8997 uint32 need_space
= pProto
->GetMaxStackSize();
8998 if (need_space
> count
)
9001 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
9002 if (!newPosition
.isContainedIn(dest
))
9004 dest
.push_back(newPosition
);
9005 count
-= need_space
;
9008 return EQUIP_ERR_OK
;
9012 return EQUIP_ERR_OK
;
9015 uint8
Player::_CanStoreItem_InInventorySlots( uint8 slot_begin
, uint8 slot_end
, ItemPosCountVec
&dest
, ItemPrototype
const *pProto
, uint32
& count
, bool merge
, Item
* pSrcItem
, uint8 skip_bag
, uint8 skip_slot
) const
9017 for(uint32 j
= slot_begin
; j
< slot_end
; ++j
)
9019 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
9020 if (INVENTORY_SLOT_BAG_0
==skip_bag
&& j
==skip_slot
)
9023 Item
* pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, j
);
9025 // ignore move item (this slot will be empty at move)
9026 if (pItem2
==pSrcItem
)
9029 // if merge skip empty, if !merge skip non-empty
9030 if ((pItem2
!=NULL
)!=merge
)
9035 if (pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->GetMaxStackSize())
9037 uint32 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
9038 if (need_space
> count
)
9040 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
9041 if (!newPosition
.isContainedIn(dest
))
9043 dest
.push_back(newPosition
);
9044 count
-= need_space
;
9047 return EQUIP_ERR_OK
;
9053 uint32 need_space
= pProto
->GetMaxStackSize();
9054 if (need_space
> count
)
9057 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
9058 if (!newPosition
.isContainedIn(dest
))
9060 dest
.push_back(newPosition
);
9061 count
-= need_space
;
9064 return EQUIP_ERR_OK
;
9068 return EQUIP_ERR_OK
;
9071 uint8
Player::_CanStoreItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, uint32 entry
, uint32 count
, Item
*pItem
, bool swap
, uint32
* no_space_count
) const
9073 sLog
.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, entry
, count
);
9075 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
9079 *no_space_count
= count
;
9080 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
:EQUIP_ERR_ITEM_NOT_FOUND
;
9083 if (pItem
&& pItem
->IsBindedNotWith(this))
9086 *no_space_count
= count
;
9087 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9090 // check count of items (skip for auto move for same player from bank)
9091 uint32 no_similar_count
= 0; // can't store this amount similar items
9092 uint8 res
= _CanTakeMoreSimilarItems(entry
,count
,pItem
,&no_similar_count
);
9093 if (res
!=EQUIP_ERR_OK
)
9095 if (count
==no_similar_count
)
9098 *no_space_count
= no_similar_count
;
9101 count
-= no_similar_count
;
9105 if (bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
9107 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
9108 if (res
!=EQUIP_ERR_OK
)
9111 *no_space_count
= count
+ no_similar_count
;
9117 if (no_similar_count
==0)
9118 return EQUIP_ERR_OK
;
9121 *no_space_count
= count
+ no_similar_count
;
9122 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9126 // not specific slot or have space for partly store only in specific slot
9129 if (bag
!= NULL_BAG
)
9131 // search stack in bag for merge to
9132 if (pProto
->Stackable
!= 1)
9134 if (bag
== INVENTORY_SLOT_BAG_0
) // inventory
9136 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9137 if (res
!=EQUIP_ERR_OK
)
9140 *no_space_count
= count
+ no_similar_count
;
9146 if (no_similar_count
==0)
9147 return EQUIP_ERR_OK
;
9150 *no_space_count
= count
+ no_similar_count
;
9151 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9154 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9155 if (res
!=EQUIP_ERR_OK
)
9158 *no_space_count
= count
+ no_similar_count
;
9164 if (no_similar_count
==0)
9165 return EQUIP_ERR_OK
;
9168 *no_space_count
= count
+ no_similar_count
;
9169 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9172 else // equipped bag
9174 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
9175 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
9176 if (res
!=EQUIP_ERR_OK
)
9177 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
9179 if (res
!=EQUIP_ERR_OK
)
9182 *no_space_count
= count
+ no_similar_count
;
9188 if (no_similar_count
==0)
9189 return EQUIP_ERR_OK
;
9192 *no_space_count
= count
+ no_similar_count
;
9193 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9198 // search free slot in bag for place to
9199 if(bag
== INVENTORY_SLOT_BAG_0
) // inventory
9201 // search free slot - keyring case
9202 if (pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9204 uint32 keyringSize
= GetMaxKeyringSize();
9205 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9206 if (res
!=EQUIP_ERR_OK
)
9209 *no_space_count
= count
+ no_similar_count
;
9215 if (no_similar_count
==0)
9216 return EQUIP_ERR_OK
;
9219 *no_space_count
= count
+ no_similar_count
;
9220 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9223 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9224 if (res
!=EQUIP_ERR_OK
)
9227 *no_space_count
= count
+ no_similar_count
;
9233 if (no_similar_count
==0)
9234 return EQUIP_ERR_OK
;
9237 *no_space_count
= count
+ no_similar_count
;
9238 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9241 else if (pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
9243 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9244 if (res
!=EQUIP_ERR_OK
)
9247 *no_space_count
= count
+ no_similar_count
;
9253 if (no_similar_count
==0)
9254 return EQUIP_ERR_OK
;
9257 *no_space_count
= count
+ no_similar_count
;
9258 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9262 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9263 if (res
!=EQUIP_ERR_OK
)
9266 *no_space_count
= count
+ no_similar_count
;
9272 if (no_similar_count
==0)
9273 return EQUIP_ERR_OK
;
9276 *no_space_count
= count
+ no_similar_count
;
9277 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9280 else // equipped bag
9282 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
9283 if (res
!=EQUIP_ERR_OK
)
9284 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
9286 if (res
!=EQUIP_ERR_OK
)
9289 *no_space_count
= count
+ no_similar_count
;
9295 if (no_similar_count
==0)
9296 return EQUIP_ERR_OK
;
9299 *no_space_count
= count
+ no_similar_count
;
9300 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9305 // not specific bag or have space for partly store only in specific bag
9307 // search stack for merge to
9308 if (pProto
->Stackable
!= 1)
9310 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9311 if (res
!=EQUIP_ERR_OK
)
9314 *no_space_count
= count
+ no_similar_count
;
9320 if (no_similar_count
==0)
9321 return EQUIP_ERR_OK
;
9324 *no_space_count
= count
+ no_similar_count
;
9325 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9328 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9329 if (res
!=EQUIP_ERR_OK
)
9332 *no_space_count
= count
+ no_similar_count
;
9338 if (no_similar_count
==0)
9339 return EQUIP_ERR_OK
;
9342 *no_space_count
= count
+ no_similar_count
;
9343 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9346 if (pProto
->BagFamily
)
9348 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9350 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
9351 if (res
!=EQUIP_ERR_OK
)
9356 if (no_similar_count
==0)
9357 return EQUIP_ERR_OK
;
9360 *no_space_count
= count
+ no_similar_count
;
9361 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9366 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9368 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
9369 if (res
!=EQUIP_ERR_OK
)
9374 if (no_similar_count
==0)
9375 return EQUIP_ERR_OK
;
9378 *no_space_count
= count
+ no_similar_count
;
9379 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9384 // search free slot - special bag case
9385 if (pProto
->BagFamily
)
9387 if (pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9389 uint32 keyringSize
= GetMaxKeyringSize();
9390 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9391 if (res
!=EQUIP_ERR_OK
)
9394 *no_space_count
= count
+ no_similar_count
;
9400 if (no_similar_count
==0)
9401 return EQUIP_ERR_OK
;
9404 *no_space_count
= count
+ no_similar_count
;
9405 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9408 else if (pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
9410 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9411 if (res
!=EQUIP_ERR_OK
)
9414 *no_space_count
= count
+ no_similar_count
;
9420 if (no_similar_count
==0)
9421 return EQUIP_ERR_OK
;
9424 *no_space_count
= count
+ no_similar_count
;
9425 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9429 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9431 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
9432 if (res
!=EQUIP_ERR_OK
)
9437 if (no_similar_count
==0)
9438 return EQUIP_ERR_OK
;
9441 *no_space_count
= count
+ no_similar_count
;
9442 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9448 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9449 if (res
!=EQUIP_ERR_OK
)
9452 *no_space_count
= count
+ no_similar_count
;
9458 if (no_similar_count
==0)
9459 return EQUIP_ERR_OK
;
9462 *no_space_count
= count
+ no_similar_count
;
9463 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9466 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9468 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
9469 if (res
!=EQUIP_ERR_OK
)
9474 if (no_similar_count
==0)
9475 return EQUIP_ERR_OK
;
9478 *no_space_count
= count
+ no_similar_count
;
9479 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9484 *no_space_count
= count
+ no_similar_count
;
9486 return EQUIP_ERR_INVENTORY_FULL
;
9489 //////////////////////////////////////////////////////////////////////////
9490 uint8
Player::CanStoreItems( Item
**pItems
,int count
) const
9495 int inv_slot_items
[INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
];
9496 int inv_bags
[INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
][MAX_BAG_SIZE
];
9497 int inv_keys
[KEYRING_SLOT_END
-KEYRING_SLOT_START
];
9498 int inv_tokens
[CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
];
9500 memset(inv_slot_items
,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
));
9501 memset(inv_bags
,0,sizeof(int)*(INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
)*MAX_BAG_SIZE
);
9502 memset(inv_keys
,0,sizeof(int)*(KEYRING_SLOT_END
-KEYRING_SLOT_START
));
9503 memset(inv_tokens
,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
));
9505 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
9507 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9509 if (pItem2
&& !pItem2
->IsInTrade())
9511 inv_slot_items
[i
-INVENTORY_SLOT_ITEM_START
] = pItem2
->GetCount();
9515 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; ++i
)
9517 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9519 if (pItem2
&& !pItem2
->IsInTrade())
9521 inv_keys
[i
-KEYRING_SLOT_START
] = pItem2
->GetCount();
9525 for(int i
= CURRENCYTOKEN_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
9527 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9529 if (pItem2
&& !pItem2
->IsInTrade())
9531 inv_tokens
[i
-CURRENCYTOKEN_SLOT_START
] = pItem2
->GetCount();
9535 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9537 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
9539 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9541 pItem2
= GetItemByPos( i
, j
);
9542 if (pItem2
&& !pItem2
->IsInTrade())
9544 inv_bags
[i
-INVENTORY_SLOT_BAG_START
][j
] = pItem2
->GetCount();
9550 // check free space for all items
9551 for (int k
= 0; k
< count
; ++k
)
9553 Item
*pItem
= pItems
[k
];
9556 if (!pItem
) continue;
9558 sLog
.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k
+1, pItem
->GetEntry(), pItem
->GetCount());
9559 ItemPrototype
const *pProto
= pItem
->GetProto();
9563 return EQUIP_ERR_ITEM_NOT_FOUND
;
9566 if(pItem
->IsBindedNotWith(this))
9567 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9570 ItemPrototype
const *pBagProto
;
9572 // item is 'one item only'
9573 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9574 if(res
!= EQUIP_ERR_OK
)
9577 // search stack for merge to
9578 if( pProto
->Stackable
!= 1 )
9580 bool b_found
= false;
9582 for(int t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_END
; ++t
)
9584 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9585 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_keys
[t
-KEYRING_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9587 inv_keys
[t
-KEYRING_SLOT_START
] += pItem
->GetCount();
9592 if (b_found
) continue;
9594 for(int t
= CURRENCYTOKEN_SLOT_START
; t
< CURRENCYTOKEN_SLOT_END
; ++t
)
9596 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9597 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9599 inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] += pItem
->GetCount();
9604 if (b_found
) continue;
9606 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; ++t
)
9608 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9609 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9611 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] += pItem
->GetCount();
9616 if (b_found
) continue;
9618 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; ++t
)
9620 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9623 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9625 pItem2
= GetItemByPos( t
, j
);
9626 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9628 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] += pItem
->GetCount();
9635 if (b_found
) continue;
9639 if( pProto
->BagFamily
)
9641 bool b_found
= false;
9642 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9644 uint32 keyringSize
= GetMaxKeyringSize();
9645 for(uint32 t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_START
+keyringSize
; ++t
)
9647 if( inv_keys
[t
-KEYRING_SLOT_START
] == 0 )
9649 inv_keys
[t
-KEYRING_SLOT_START
] = 1;
9656 if (b_found
) continue;
9658 if(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
9660 for(uint32 t
= CURRENCYTOKEN_SLOT_START
; t
< CURRENCYTOKEN_SLOT_END
; ++t
)
9662 if( inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] == 0 )
9664 inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] = 1;
9671 if (b_found
) continue;
9673 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; ++t
)
9675 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9678 pBagProto
= pBag
->GetProto();
9680 // not plain container check
9681 if( pBagProto
&& (pBagProto
->Class
!= ITEM_CLASS_CONTAINER
|| pBagProto
->SubClass
!= ITEM_SUBCLASS_CONTAINER
) &&
9682 ItemCanGoIntoBag(pProto
,pBagProto
) )
9684 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9686 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9688 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9696 if (b_found
) continue;
9700 bool b_found
= false;
9701 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; ++t
)
9703 if( inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] == 0 )
9705 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] = 1;
9710 if (b_found
) continue;
9712 // search free slot in bags
9713 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; ++t
)
9715 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9718 pBagProto
= pBag
->GetProto();
9720 // special bag already checked
9721 if( pBagProto
&& (pBagProto
->Class
!= ITEM_CLASS_CONTAINER
|| pBagProto
->SubClass
!= ITEM_SUBCLASS_CONTAINER
))
9724 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
9726 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9728 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9736 // no free slot found?
9738 return EQUIP_ERR_INVENTORY_FULL
;
9741 return EQUIP_ERR_OK
;
9744 //////////////////////////////////////////////////////////////////////////
9745 uint8
Player::CanEquipNewItem( uint8 slot
, uint16
&dest
, uint32 item
, bool swap
) const
9748 Item
*pItem
= Item::CreateItem( item
, 1, this );
9751 uint8 result
= CanEquipItem(slot
, dest
, pItem
, swap
);
9756 return EQUIP_ERR_ITEM_NOT_FOUND
;
9759 uint8
Player::CanEquipItem( uint8 slot
, uint16
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
9764 sLog
.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot
, pItem
->GetEntry(), pItem
->GetCount());
9765 ItemPrototype
const *pProto
= pItem
->GetProto();
9768 if(pItem
->IsBindedNotWith(this))
9769 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9771 // check count of items (skip for auto move for same player from bank)
9772 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9773 if(res
!= EQUIP_ERR_OK
)
9776 // check this only in game
9779 // May be here should be more stronger checks; STUNNED checked
9780 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9781 if (hasUnitState(UNIT_STAT_STUNNED
))
9782 return EQUIP_ERR_YOU_ARE_STUNNED
;
9784 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9786 // - in-progress arenas
9787 if( !pProto
->CanChangeEquipStateInCombat() )
9790 return EQUIP_ERR_NOT_IN_COMBAT
;
9792 if(BattleGround
* bg
= GetBattleGround())
9793 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
9794 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
9797 if(isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
!= 0)
9798 return EQUIP_ERR_CANT_DO_RIGHT_NOW
; // maybe exist better err
9800 if(IsNonMeleeSpellCasted(false))
9801 return EQUIP_ERR_CANT_DO_RIGHT_NOW
;
9804 ScalingStatDistributionEntry
const *ssd
= pProto
->ScalingStatDistribution
? sScalingStatDistributionStore
.LookupEntry(pProto
->ScalingStatDistribution
) : 0;
9805 // check allowed level (extend range to upper values if MaxLevel more or equal max player level, this let GM set high level with 1...max range items)
9806 if (ssd
&& ssd
->MaxLevel
< DEFAULT_MAX_LEVEL
&& ssd
->MaxLevel
< getLevel())
9807 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9809 uint8 eslot
= FindEquipSlot( pProto
, slot
, swap
);
9810 if (eslot
== NULL_SLOT
)
9811 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9813 uint8 msg
= CanUseItem(pItem
, not_loading
);
9814 if (msg
!= EQUIP_ERR_OK
)
9816 if (!swap
&& GetItemByPos(INVENTORY_SLOT_BAG_0
, eslot
))
9817 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE
;
9819 // if swap ignore item (equipped also)
9820 if (uint8 res2
= CanEquipUniqueItem(pItem
, swap
? eslot
: NULL_SLOT
))
9823 // check unique-equipped special item classes
9824 if (pProto
->Class
== ITEM_CLASS_QUIVER
)
9826 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9828 if (Item
* pBag
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
9832 if (ItemPrototype
const* pBagProto
= pBag
->GetProto())
9834 if (pBagProto
->Class
==pProto
->Class
&& (!swap
|| pBag
->GetSlot() != eslot
))
9835 return (pBagProto
->SubClass
== ITEM_SUBCLASS_AMMO_POUCH
)
9836 ? EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
9837 : EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER
;
9844 uint32 type
= pProto
->InventoryType
;
9846 if (eslot
== EQUIPMENT_SLOT_OFFHAND
)
9848 if (type
== INVTYPE_WEAPON
|| type
== INVTYPE_WEAPONOFFHAND
)
9850 if (!CanDualWield())
9851 return EQUIP_ERR_CANT_DUAL_WIELD
;
9853 else if (type
== INVTYPE_2HWEAPON
)
9855 if (!CanDualWield() || !CanTitanGrip())
9856 return EQUIP_ERR_CANT_DUAL_WIELD
;
9859 if (IsTwoHandUsed())
9860 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED
;
9863 // equip two-hand weapon case (with possible unequip 2 items)
9864 if (type
== INVTYPE_2HWEAPON
)
9866 if (eslot
== EQUIPMENT_SLOT_OFFHAND
)
9868 if (!CanTitanGrip())
9869 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9871 else if (eslot
!= EQUIPMENT_SLOT_MAINHAND
)
9872 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9874 if (!CanTitanGrip())
9876 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9877 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
9878 ItemPosCountVec off_dest
;
9879 if (offItem
&& (!not_loading
||
9880 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0
) << 8 | EQUIPMENT_SLOT_OFFHAND
,false) != EQUIP_ERR_OK
||
9881 CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false ) != EQUIP_ERR_OK
))
9882 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_INVENTORY_FULL
;
9885 dest
= ((INVENTORY_SLOT_BAG_0
<< 8) | eslot
);
9886 return EQUIP_ERR_OK
;
9890 return !swap
? EQUIP_ERR_ITEM_NOT_FOUND
: EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
;
9893 uint8
Player::CanUnequipItem( uint16 pos
, bool swap
) const
9895 // Applied only to equipped items and bank bags
9896 if(!IsEquipmentPos(pos
) && !IsBagPos(pos
))
9897 return EQUIP_ERR_OK
;
9899 Item
* pItem
= GetItemByPos(pos
);
9901 // Applied only to existed equipped item
9903 return EQUIP_ERR_OK
;
9905 sLog
.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos
, pItem
->GetEntry(), pItem
->GetCount());
9907 ItemPrototype
const *pProto
= pItem
->GetProto();
9909 return EQUIP_ERR_ITEM_NOT_FOUND
;
9911 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9913 // - in-progress arenas
9914 if( !pProto
->CanChangeEquipStateInCombat() )
9917 return EQUIP_ERR_NOT_IN_COMBAT
;
9919 if(BattleGround
* bg
= GetBattleGround())
9920 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
9921 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
9924 if(!swap
&& pItem
->IsBag() && !((Bag
*)pItem
)->IsEmpty())
9925 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS
;
9927 return EQUIP_ERR_OK
;
9930 uint8
Player::CanBankItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
9933 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
9935 uint32 count
= pItem
->GetCount();
9937 sLog
.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), pItem
->GetCount());
9938 ItemPrototype
const *pProto
= pItem
->GetProto();
9940 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
9942 if (pItem
->IsBindedNotWith(this))
9943 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9945 // check count of items (skip for auto move for same player from bank)
9946 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9947 if (res
!= EQUIP_ERR_OK
)
9951 if (bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
9953 if (slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
9955 if (!pItem
->IsBag())
9956 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
;
9958 if (slot
- BANK_SLOT_BAG_START
>= GetBankBagSlotCount())
9959 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT
;
9961 if (uint8 cantuse
= CanUseItem( pItem
, not_loading
) != EQUIP_ERR_OK
)
9965 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
9966 if (res
!=EQUIP_ERR_OK
)
9970 return EQUIP_ERR_OK
;
9973 // not specific slot or have space for partly store only in specific slot
9976 if( bag
!= NULL_BAG
)
9978 if( pProto
->InventoryType
== INVTYPE_BAG
)
9980 Bag
*pBag
= (Bag
*)pItem
;
9981 if( pBag
&& !pBag
->IsEmpty() )
9982 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
;
9985 // search stack in bag for merge to
9986 if( pProto
->Stackable
!= 1 )
9988 if( bag
== INVENTORY_SLOT_BAG_0
)
9990 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9991 if(res
!=EQUIP_ERR_OK
)
9995 return EQUIP_ERR_OK
;
9999 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
10000 if(res
!=EQUIP_ERR_OK
)
10001 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
10003 if(res
!=EQUIP_ERR_OK
)
10007 return EQUIP_ERR_OK
;
10011 // search free slot in bag
10012 if( bag
== INVENTORY_SLOT_BAG_0
)
10014 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
10015 if(res
!=EQUIP_ERR_OK
)
10019 return EQUIP_ERR_OK
;
10023 res
= _CanStoreItem_InBag(bag
, dest
, pProto
, count
, false, false, pItem
, NULL_BAG
, slot
);
10024 if(res
!= EQUIP_ERR_OK
)
10025 res
= _CanStoreItem_InBag(bag
, dest
, pProto
, count
, false, true, pItem
, NULL_BAG
, slot
);
10027 if(res
!= EQUIP_ERR_OK
)
10031 return EQUIP_ERR_OK
;
10035 // not specific bag or have space for partly store only in specific bag
10037 // search stack for merge to
10038 if( pProto
->Stackable
!= 1 )
10041 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
10042 if(res
!= EQUIP_ERR_OK
)
10046 return EQUIP_ERR_OK
;
10049 if( pProto
->BagFamily
)
10051 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
10053 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
10054 if(res
!=EQUIP_ERR_OK
)
10058 return EQUIP_ERR_OK
;
10062 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
10064 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
10065 if(res
!=EQUIP_ERR_OK
)
10069 return EQUIP_ERR_OK
;
10073 // search free place in special bag
10074 if( pProto
->BagFamily
)
10076 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
10078 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
10079 if(res
!=EQUIP_ERR_OK
)
10083 return EQUIP_ERR_OK
;
10087 // search free space
10088 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
10089 if(res
!=EQUIP_ERR_OK
)
10093 return EQUIP_ERR_OK
;
10095 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; ++i
)
10097 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
10098 if(res
!=EQUIP_ERR_OK
)
10102 return EQUIP_ERR_OK
;
10104 return EQUIP_ERR_BANK_FULL
;
10107 uint8
Player::CanUseItem( Item
*pItem
, bool not_loading
) const
10111 sLog
.outDebug( "STORAGE: CanUseItem item = %u", pItem
->GetEntry());
10113 if (!isAlive() && not_loading
)
10114 return EQUIP_ERR_YOU_ARE_DEAD
;
10117 // return EQUIP_ERR_YOU_ARE_STUNNED;
10119 ItemPrototype
const *pProto
= pItem
->GetProto();
10122 if (pItem
->IsBindedNotWith(this))
10123 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
10125 if ((pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0)
10126 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
10128 if (uint32 item_use_skill
= pItem
->GetSkill())
10130 if (GetSkillValue(item_use_skill
) == 0)
10132 // armor items with scaling stats can downgrade armor skill reqs if related class can learn armor use at some level
10133 if (pProto
->Class
!= ITEM_CLASS_ARMOR
)
10134 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10136 ScalingStatDistributionEntry
const *ssd
= pProto
->ScalingStatDistribution
? sScalingStatDistributionStore
.LookupEntry(pProto
->ScalingStatDistribution
) : NULL
;
10138 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10140 bool allowScaleSkill
= false;
10141 for (uint32 i
= 0; i
< sSkillLineAbilityStore
.GetNumRows(); ++i
)
10143 SkillLineAbilityEntry
const *skillInfo
= sSkillLineAbilityStore
.LookupEntry(i
);
10147 if (skillInfo
->skillId
!= item_use_skill
)
10151 if (skillInfo
->classmask
&& (skillInfo
->classmask
& getClassMask()) == 0)
10154 if (skillInfo
->racemask
&& (skillInfo
->racemask
& getRaceMask()) == 0)
10157 allowScaleSkill
= true;
10161 if (!allowScaleSkill
)
10162 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10166 if (pProto
->RequiredSkill
!= 0)
10168 if (GetSkillValue( pProto
->RequiredSkill
) == 0)
10169 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10171 if (GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10172 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
10175 if (pProto
->RequiredSpell
!= 0 && !HasSpell(pProto
->RequiredSpell
))
10176 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10178 if (pProto
->RequiredReputationFaction
&& uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
10179 return EQUIP_ERR_CANT_EQUIP_REPUTATION
;
10181 if (getLevel() < pProto
->RequiredLevel
)
10182 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
10184 return EQUIP_ERR_OK
;
10187 return EQUIP_ERR_ITEM_NOT_FOUND
;
10190 bool Player::CanUseItem( ItemPrototype
const *pProto
)
10192 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10196 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
10198 if( pProto
->RequiredSkill
!= 0 )
10200 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
10202 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10205 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
10207 if( getLevel() < pProto
->RequiredLevel
)
10214 uint8
Player::CanUseAmmo( uint32 item
) const
10216 sLog
.outDebug( "STORAGE: CanUseAmmo item = %u", item
);
10218 return EQUIP_ERR_YOU_ARE_DEAD
;
10219 //if( isStunned() )
10220 // return EQUIP_ERR_YOU_ARE_STUNNED;
10221 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
10224 if( pProto
->InventoryType
!= INVTYPE_AMMO
)
10225 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE
;
10226 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
10227 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
10228 if( pProto
->RequiredSkill
!= 0 )
10230 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
10231 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10232 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10233 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
10235 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
10236 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10237 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
10238 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10240 if( getLevel() < pProto
->RequiredLevel
)
10241 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
10243 // Requires No Ammo
10244 if(GetDummyAura(46699))
10245 return EQUIP_ERR_BAG_FULL6
;
10247 return EQUIP_ERR_OK
;
10249 return EQUIP_ERR_ITEM_NOT_FOUND
;
10252 void Player::SetAmmo( uint32 item
)
10258 if( GetUInt32Value(PLAYER_AMMO_ID
) == item
)
10264 uint8 msg
= CanUseAmmo( item
);
10265 if( msg
!= EQUIP_ERR_OK
)
10267 SendEquipError( msg
, NULL
, NULL
);
10272 SetUInt32Value(PLAYER_AMMO_ID
, item
);
10274 _ApplyAmmoBonuses();
10277 void Player::RemoveAmmo()
10279 SetUInt32Value(PLAYER_AMMO_ID
, 0);
10283 if(CanModifyStats())
10284 UpdateDamagePhysical(RANGED_ATTACK
);
10287 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10288 Item
* Player::StoreNewItem( ItemPosCountVec
const& dest
, uint32 item
, bool update
,int32 randomPropertyId
)
10291 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); ++itr
)
10292 count
+= itr
->count
;
10294 Item
*pItem
= Item::CreateItem( item
, count
, this );
10297 ItemAddedQuestCheck( item
, count
);
10298 if(randomPropertyId
)
10299 pItem
->SetItemRandomProperties(randomPropertyId
);
10300 pItem
= StoreItem( dest
, pItem
, update
);
10305 Item
* Player::StoreItem( ItemPosCountVec
const& dest
, Item
* pItem
, bool update
)
10310 Item
* lastItem
= pItem
;
10311 uint32 entry
= pItem
->GetEntry();
10312 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); )
10314 uint16 pos
= itr
->pos
;
10315 uint32 count
= itr
->count
;
10319 if(itr
== dest
.end())
10321 lastItem
= _StoreItem(pos
,pItem
,count
,false,update
);
10325 lastItem
= _StoreItem(pos
,pItem
,count
,true,update
);
10327 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM
, entry
);
10331 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10332 Item
* Player::_StoreItem( uint16 pos
, Item
*pItem
, uint32 count
, bool clone
, bool update
)
10337 uint8 bag
= pos
>> 8;
10338 uint8 slot
= pos
& 255;
10340 sLog
.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), count
);
10342 Item
*pItem2
= GetItemByPos( bag
, slot
);
10347 pItem
= pItem
->CloneItem(count
, this);
10349 pItem
->SetCount(count
);
10354 if (pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10355 pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10356 (pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
)))
10357 pItem
->SetBinding( true );
10359 if (bag
== INVENTORY_SLOT_BAG_0
)
10361 m_items
[slot
] = pItem
;
10362 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2), pItem
->GetGUID() );
10363 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10364 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10366 pItem
->SetSlot( slot
);
10367 pItem
->SetContainer( NULL
);
10369 // need update known currency
10370 if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)
10371 UpdateKnownCurrencies(pItem
->GetEntry(), true);
10373 if (IsInWorld() && update
)
10375 pItem
->AddToWorld();
10376 pItem
->SendUpdateToPlayer( this );
10379 pItem
->SetState(ITEM_CHANGED
, this);
10381 else if (Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
))
10383 pBag
->StoreItem( slot
, pItem
, update
);
10384 if( IsInWorld() && update
)
10386 pItem
->AddToWorld();
10387 pItem
->SendUpdateToPlayer( this );
10389 pItem
->SetState(ITEM_CHANGED
, this);
10390 pBag
->SetState(ITEM_CHANGED
, this);
10393 AddEnchantmentDurations(pItem
);
10394 AddItemDurations(pItem
);
10400 if (pItem2
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10401 pItem2
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10402 (pItem2
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
)))
10403 pItem2
->SetBinding( true );
10405 pItem2
->SetCount( pItem2
->GetCount() + count
);
10406 if (IsInWorld() && update
)
10407 pItem2
->SendUpdateToPlayer( this );
10411 // delete item (it not in any slot currently)
10412 if (IsInWorld() && update
)
10414 pItem
->RemoveFromWorld();
10415 pItem
->DestroyForPlayer( this );
10418 RemoveEnchantmentDurations(pItem
);
10419 RemoveItemDurations(pItem
);
10421 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10422 pItem
->SetState(ITEM_REMOVED
, this);
10425 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10426 AddEnchantmentDurations(pItem2
);
10428 pItem2
->SetState(ITEM_CHANGED
, this);
10434 Item
* Player::EquipNewItem( uint16 pos
, uint32 item
, bool update
)
10436 if (Item
*pItem
= Item::CreateItem( item
, 1, this ))
10438 ItemAddedQuestCheck( item
, 1 );
10439 return EquipItem( pos
, pItem
, update
);
10445 Item
* Player::EquipItem( uint16 pos
, Item
*pItem
, bool update
)
10447 AddEnchantmentDurations(pItem
);
10448 AddItemDurations(pItem
);
10450 uint8 bag
= pos
>> 8;
10451 uint8 slot
= pos
& 255;
10453 Item
*pItem2
= GetItemByPos( bag
, slot
);
10457 VisualizeItem( slot
, pItem
);
10461 ItemPrototype
const *pProto
= pItem
->GetProto();
10463 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10464 if(pProto
&& pProto
->ItemSet
)
10465 AddItemsSetItem(this, pItem
);
10467 _ApplyItemMods(pItem
, slot
, true);
10469 if(pProto
&& isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
== 0)
10471 uint32 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s
;
10473 if (getClass() == CLASS_ROGUE
)
10474 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s
;
10476 SpellEntry
const* spellProto
= sSpellStore
.LookupEntry(cooldownSpell
);
10479 sLog
.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell
);
10482 m_weaponChangeTimer
= spellProto
->StartRecoveryTime
;
10484 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+4);
10485 data
<< uint64(GetGUID());
10487 data
<< uint32(cooldownSpell
);
10489 GetSession()->SendPacket(&data
);
10494 if( IsInWorld() && update
)
10496 pItem
->AddToWorld();
10497 pItem
->SendUpdateToPlayer( this );
10500 ApplyEquipCooldown(pItem
);
10502 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
10504 UpdateExpertise(BASE_ATTACK
);
10505 UpdateArmorPenetration();
10507 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10509 UpdateExpertise(OFF_ATTACK
);
10510 UpdateArmorPenetration();
10515 pItem2
->SetCount( pItem2
->GetCount() + pItem
->GetCount() );
10516 if( IsInWorld() && update
)
10517 pItem2
->SendUpdateToPlayer( this );
10519 // delete item (it not in any slot currently)
10520 //pItem->DeleteFromDB();
10521 if( IsInWorld() && update
)
10523 pItem
->RemoveFromWorld();
10524 pItem
->DestroyForPlayer( this );
10527 RemoveEnchantmentDurations(pItem
);
10528 RemoveItemDurations(pItem
);
10530 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10531 pItem
->SetState(ITEM_REMOVED
, this);
10532 pItem2
->SetState(ITEM_CHANGED
, this);
10534 ApplyEquipCooldown(pItem2
);
10539 // only for full equip instead adding to stack
10540 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM
, pItem
->GetEntry());
10545 void Player::QuickEquipItem( uint16 pos
, Item
*pItem
)
10549 AddEnchantmentDurations(pItem
);
10550 AddItemDurations(pItem
);
10552 uint8 slot
= pos
& 255;
10553 VisualizeItem( slot
, pItem
);
10557 pItem
->AddToWorld();
10558 pItem
->SendUpdateToPlayer( this );
10561 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM
, pItem
->GetEntry());
10565 void Player::SetVisibleItemSlot(uint8 slot
, Item
*pItem
)
10569 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID
+ (slot
* 2), pItem
->GetEntry());
10570 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT
+ (slot
* 2), 0, pItem
->GetEnchantmentId(PERM_ENCHANTMENT_SLOT
));
10571 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT
+ (slot
* 2), 1, pItem
->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT
));
10575 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENTRYID
+ (slot
* 2), 0);
10576 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT
+ (slot
* 2), 0);
10580 void Player::VisualizeItem( uint8 slot
, Item
*pItem
)
10585 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10586 if( pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
|| pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
|| pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
)
10587 pItem
->SetBinding( true );
10589 sLog
.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot
, pItem
->GetEntry());
10591 m_items
[slot
] = pItem
;
10592 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2), pItem
->GetGUID() );
10593 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10594 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10595 pItem
->SetSlot( slot
);
10596 pItem
->SetContainer( NULL
);
10598 if( slot
< EQUIPMENT_SLOT_END
)
10599 SetVisibleItemSlot(slot
, pItem
);
10601 pItem
->SetState(ITEM_CHANGED
, this);
10604 void Player::RemoveItem( uint8 bag
, uint8 slot
, bool update
)
10606 // note: removeitem does not actually change the item
10607 // it only takes the item out of storage temporarily
10608 // note2: if removeitem is to be used for delinking
10609 // the item must be removed from the player's updatequeue
10611 Item
*pItem
= GetItemByPos( bag
, slot
);
10614 sLog
.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10616 RemoveEnchantmentDurations(pItem
);
10617 RemoveItemDurations(pItem
);
10619 if( bag
== INVENTORY_SLOT_BAG_0
)
10621 if ( slot
< INVENTORY_SLOT_BAG_END
)
10623 ItemPrototype
const *pProto
= pItem
->GetProto();
10624 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10626 if(pProto
&& pProto
->ItemSet
)
10627 RemoveItemsSetItem(this, pProto
);
10629 _ApplyItemMods(pItem
, slot
, false);
10631 // remove item dependent auras and casts (only weapon and armor slots)
10632 if(slot
< EQUIPMENT_SLOT_END
)
10634 RemoveItemDependentAurasAndCasts(pItem
);
10636 // remove held enchantments, update expertise
10637 if ( slot
== EQUIPMENT_SLOT_MAINHAND
)
10639 if (pItem
->GetItemSuffixFactor())
10641 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3
);
10642 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4
);
10646 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0
);
10647 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1
);
10650 UpdateExpertise(BASE_ATTACK
);
10651 UpdateArmorPenetration();
10653 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10655 UpdateExpertise(OFF_ATTACK
);
10656 UpdateArmorPenetration();
10660 // need update known currency
10661 else if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)
10662 UpdateKnownCurrencies(pItem
->GetEntry(), false);
10664 m_items
[slot
] = NULL
;
10665 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2), 0);
10667 if ( slot
< EQUIPMENT_SLOT_END
)
10668 SetVisibleItemSlot(slot
, NULL
);
10672 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
10674 pBag
->RemoveItem(slot
, update
);
10676 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10677 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10678 pItem
->SetSlot( NULL_SLOT
);
10679 if( IsInWorld() && update
)
10680 pItem
->SendUpdateToPlayer( this );
10684 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10685 void Player::MoveItemFromInventory(uint8 bag
, uint8 slot
, bool update
)
10687 if(Item
* it
= GetItemByPos(bag
,slot
))
10689 ItemRemovedQuestCheck(it
->GetEntry(), it
->GetCount());
10690 RemoveItem(bag
, slot
, update
);
10691 it
->RemoveFromUpdateQueueOf(this);
10692 if(it
->IsInWorld())
10694 it
->RemoveFromWorld();
10695 it
->DestroyForPlayer( this );
10700 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10701 void Player::MoveItemToInventory(ItemPosCountVec
const& dest
, Item
* pItem
, bool update
, bool in_characterInventoryDB
)
10703 // update quest counters
10704 ItemAddedQuestCheck(pItem
->GetEntry(), pItem
->GetCount());
10707 Item
* pLastItem
= StoreItem(dest
, pItem
, update
);
10709 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10710 if(pLastItem
== pItem
)
10712 // update owner for last item (this can be original item with wrong owner
10713 if(pLastItem
->GetOwnerGUID() != GetGUID())
10714 pLastItem
->SetOwnerGUID(GetGUID());
10716 // if this original item then it need create record in inventory
10717 // in case trade we already have item in other player inventory
10718 pLastItem
->SetState(in_characterInventoryDB
? ITEM_CHANGED
: ITEM_NEW
, this);
10722 void Player::DestroyItem( uint8 bag
, uint8 slot
, bool update
)
10724 Item
*pItem
= GetItemByPos( bag
, slot
);
10727 sLog
.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10729 // start from destroy contained items (only equipped bag can have its)
10730 if (pItem
->IsBag() && pItem
->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10732 for (int i
= 0; i
< MAX_BAG_SIZE
; ++i
)
10733 DestroyItem(slot
, i
, update
);
10736 if(pItem
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_WRAPPED
))
10737 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem
->GetGUIDLow());
10739 RemoveEnchantmentDurations(pItem
);
10740 RemoveItemDurations(pItem
);
10742 ItemRemovedQuestCheck( pItem
->GetEntry(), pItem
->GetCount() );
10744 if( bag
== INVENTORY_SLOT_BAG_0
)
10746 SetUInt64Value(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2), 0);
10748 // equipment and equipped bags can have applied bonuses
10749 if ( slot
< INVENTORY_SLOT_BAG_END
)
10751 ItemPrototype
const *pProto
= pItem
->GetProto();
10753 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10754 if(pProto
&& pProto
->ItemSet
)
10755 RemoveItemsSetItem(this, pProto
);
10757 _ApplyItemMods(pItem
, slot
, false);
10760 if ( slot
< EQUIPMENT_SLOT_END
)
10762 // remove item dependent auras and casts (only weapon and armor slots)
10763 RemoveItemDependentAurasAndCasts(pItem
);
10765 // update expertise
10766 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
10768 UpdateExpertise(BASE_ATTACK
);
10769 UpdateArmorPenetration();
10771 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10773 UpdateExpertise(OFF_ATTACK
);
10774 UpdateArmorPenetration();
10777 // equipment visual show
10778 SetVisibleItemSlot(slot
, NULL
);
10780 // need update known currency
10781 else if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)
10782 UpdateKnownCurrencies(pItem
->GetEntry(), false);
10784 m_items
[slot
] = NULL
;
10786 else if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
))
10787 pBag
->RemoveItem(slot
, update
);
10789 if( IsInWorld() && update
)
10791 pItem
->RemoveFromWorld();
10792 pItem
->DestroyForPlayer(this);
10795 //pItem->SetOwnerGUID(0);
10796 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10797 pItem
->SetSlot( NULL_SLOT
);
10798 pItem
->SetState(ITEM_REMOVED
, this);
10802 void Player::DestroyItemCount( uint32 item
, uint32 count
, bool update
, bool unequip_check
)
10804 sLog
.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item
, count
);
10805 uint32 remcount
= 0;
10808 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
10810 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10812 if (pItem
->GetEntry() == item
)
10814 if (pItem
->GetCount() + remcount
<= count
)
10816 // all items in inventory can unequipped
10817 remcount
+= pItem
->GetCount();
10818 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10820 if (remcount
>= count
)
10825 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10826 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10827 if (IsInWorld() & update
)
10828 pItem
->SendUpdateToPlayer( this );
10829 pItem
->SetState(ITEM_CHANGED
, this);
10836 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
10838 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10840 if (pItem
->GetEntry() == item
)
10842 if (pItem
->GetCount() + remcount
<= count
)
10844 // all keys can be unequipped
10845 remcount
+= pItem
->GetCount();
10846 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10848 if (remcount
>= count
)
10853 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10854 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10855 if (IsInWorld() & update
)
10856 pItem
->SendUpdateToPlayer( this );
10857 pItem
->SetState(ITEM_CHANGED
, this);
10864 // in inventory bags
10865 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
10867 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10869 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
10871 if(Item
* pItem
= pBag
->GetItemByPos(j
))
10873 if (pItem
->GetEntry() == item
)
10875 // all items in bags can be unequipped
10876 if (pItem
->GetCount() + remcount
<= count
)
10878 remcount
+= pItem
->GetCount();
10879 DestroyItem( i
, j
, update
);
10881 if (remcount
>= count
)
10886 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10887 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10888 if (IsInWorld() && update
)
10889 pItem
->SendUpdateToPlayer( this );
10890 pItem
->SetState(ITEM_CHANGED
, this);
10899 // in equipment and bag list
10900 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
10902 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10904 if (pItem
&& pItem
->GetEntry() == item
)
10906 if (pItem
->GetCount() + remcount
<= count
)
10908 if (!unequip_check
|| CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
, false) == EQUIP_ERR_OK
)
10910 remcount
+= pItem
->GetCount();
10911 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10913 if (remcount
>= count
)
10919 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10920 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10921 if (IsInWorld() & update
)
10922 pItem
->SendUpdateToPlayer( this );
10923 pItem
->SetState(ITEM_CHANGED
, this);
10931 void Player::DestroyZoneLimitedItem( bool update
, uint32 new_zone
)
10933 sLog
.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone
);
10936 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
10937 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10938 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone
))
10939 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10941 for(int i
= KEYRING_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; ++i
)
10942 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10943 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone
))
10944 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10946 // in inventory bags
10947 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
10948 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10949 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
10950 if (Item
* pItem
= pBag
->GetItemByPos(j
))
10951 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone
))
10952 DestroyItem(i
, j
, update
);
10954 // in equipment and bag list
10955 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
10956 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10957 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(), new_zone
))
10958 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10961 void Player::DestroyConjuredItems( bool update
)
10963 // used when entering arena
10964 // destroys all conjured items
10965 sLog
.outDebug( "STORAGE: DestroyConjuredItems" );
10968 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
10969 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10970 if (pItem
->IsConjuredConsumable())
10971 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10973 // in inventory bags
10974 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
10975 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10976 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
10977 if (Item
* pItem
= pBag
->GetItemByPos(j
))
10978 if (pItem
->IsConjuredConsumable())
10979 DestroyItem( i
, j
, update
);
10981 // in equipment and bag list
10982 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
10983 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10984 if (pItem
->IsConjuredConsumable())
10985 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10988 void Player::DestroyItemCount( Item
* pItem
, uint32
&count
, bool update
)
10993 sLog
.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem
->GetGUIDLow(),pItem
->GetEntry(), count
);
10995 if( pItem
->GetCount() <= count
)
10997 count
-= pItem
->GetCount();
10999 DestroyItem( pItem
->GetBagSlot(),pItem
->GetSlot(), update
);
11003 ItemRemovedQuestCheck( pItem
->GetEntry(), count
);
11004 pItem
->SetCount( pItem
->GetCount() - count
);
11006 if( IsInWorld() & update
)
11007 pItem
->SendUpdateToPlayer( this );
11008 pItem
->SetState(ITEM_CHANGED
, this);
11012 void Player::SplitItem( uint16 src
, uint16 dst
, uint32 count
)
11014 uint8 srcbag
= src
>> 8;
11015 uint8 srcslot
= src
& 255;
11017 uint8 dstbag
= dst
>> 8;
11018 uint8 dstslot
= dst
& 255;
11020 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
11023 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
11027 // not let split all items (can be only at cheating)
11028 if(pSrcItem
->GetCount() == count
)
11030 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
11034 // not let split more existed items (can be only at cheating)
11035 if(pSrcItem
->GetCount() < count
)
11037 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT
, pSrcItem
, NULL
);
11041 if(pSrcItem
->m_lootGenerated
) // prevent split looting item (item
11043 //best error message found for attempting to split while looting
11044 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
11048 sLog
.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag
, dstslot
, pSrcItem
->GetEntry(), count
);
11049 Item
*pNewItem
= pSrcItem
->CloneItem( count
, this );
11052 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
11056 if( IsInventoryPos( dst
) )
11058 // change item amount before check (for unique max count check)
11059 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11061 ItemPosCountVec dest
;
11062 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pNewItem
, false );
11063 if( msg
!= EQUIP_ERR_OK
)
11066 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11067 SendEquipError( msg
, pSrcItem
, NULL
);
11072 pSrcItem
->SendUpdateToPlayer( this );
11073 pSrcItem
->SetState(ITEM_CHANGED
, this);
11074 StoreItem( dest
, pNewItem
, true);
11076 else if( IsBankPos ( dst
) )
11078 // change item amount before check (for unique max count check)
11079 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11081 ItemPosCountVec dest
;
11082 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pNewItem
, false );
11083 if( msg
!= EQUIP_ERR_OK
)
11086 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11087 SendEquipError( msg
, pSrcItem
, NULL
);
11092 pSrcItem
->SendUpdateToPlayer( this );
11093 pSrcItem
->SetState(ITEM_CHANGED
, this);
11094 BankItem( dest
, pNewItem
, true);
11096 else if( IsEquipmentPos ( dst
) )
11098 // change item amount before check (for unique max count check), provide space for splitted items
11099 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11102 uint8 msg
= CanEquipItem( dstslot
, dest
, pNewItem
, false );
11103 if( msg
!= EQUIP_ERR_OK
)
11106 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11107 SendEquipError( msg
, pSrcItem
, NULL
);
11112 pSrcItem
->SendUpdateToPlayer( this );
11113 pSrcItem
->SetState(ITEM_CHANGED
, this);
11114 EquipItem( dest
, pNewItem
, true);
11115 AutoUnequipOffhandIfNeed();
11119 void Player::SwapItem( uint16 src
, uint16 dst
)
11121 uint8 srcbag
= src
>> 8;
11122 uint8 srcslot
= src
& 255;
11124 uint8 dstbag
= dst
>> 8;
11125 uint8 dstslot
= dst
& 255;
11127 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
11128 Item
*pDstItem
= GetItemByPos( dstbag
, dstslot
);
11133 sLog
.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag
, dstslot
, pSrcItem
->GetEntry());
11137 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD
, pSrcItem
, pDstItem
);
11143 if(pSrcItem
->m_lootGenerated
) // prevent swap looting item
11145 //best error message found for attempting to swap while looting
11146 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pSrcItem
, NULL
);
11150 // check unequip potability for equipped items and bank bags
11151 if(IsEquipmentPos ( src
) || IsBagPos ( src
))
11153 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11154 uint8 msg
= CanUnequipItem( src
, !IsBagPos ( src
) || IsBagPos ( dst
) || (pDstItem
&& pDstItem
->IsBag() && ((Bag
*)pDstItem
)->IsEmpty()));
11155 if(msg
!= EQUIP_ERR_OK
)
11157 SendEquipError( msg
, pSrcItem
, pDstItem
);
11162 // prevent put equipped/bank bag in self
11163 if( IsBagPos ( src
) && srcslot
== dstbag
)
11165 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
11173 if(pDstItem
->m_lootGenerated
) // prevent swap looting item
11175 //best error message found for attempting to swap while looting
11176 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pDstItem
, NULL
);
11180 // check unequip potability for equipped items and bank bags
11181 if(IsEquipmentPos ( dst
) || IsBagPos ( dst
))
11183 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
11184 uint8 msg
= CanUnequipItem( dst
, !IsBagPos ( dst
) || IsBagPos ( src
) || (pSrcItem
->IsBag() && ((Bag
*)pSrcItem
)->IsEmpty()));
11185 if(msg
!= EQUIP_ERR_OK
)
11187 SendEquipError( msg
, pSrcItem
, pDstItem
);
11193 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
11194 // or swap empty bag with another empty or not empty bag (with items exchange)
11199 if( IsInventoryPos( dst
) )
11201 ItemPosCountVec dest
;
11202 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pSrcItem
, false );
11203 if( msg
!= EQUIP_ERR_OK
)
11205 SendEquipError( msg
, pSrcItem
, NULL
);
11209 RemoveItem(srcbag
, srcslot
, true);
11210 StoreItem( dest
, pSrcItem
, true);
11212 else if( IsBankPos ( dst
) )
11214 ItemPosCountVec dest
;
11215 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pSrcItem
, false);
11216 if( msg
!= EQUIP_ERR_OK
)
11218 SendEquipError( msg
, pSrcItem
, NULL
);
11222 RemoveItem(srcbag
, srcslot
, true);
11223 BankItem( dest
, pSrcItem
, true);
11225 else if( IsEquipmentPos ( dst
) )
11228 uint8 msg
= CanEquipItem( dstslot
, dest
, pSrcItem
, false );
11229 if( msg
!= EQUIP_ERR_OK
)
11231 SendEquipError( msg
, pSrcItem
, NULL
);
11235 RemoveItem(srcbag
, srcslot
, true);
11236 EquipItem(dest
, pSrcItem
, true);
11237 AutoUnequipOffhandIfNeed();
11243 // attempt merge to / fill target item
11244 if(!pSrcItem
->IsBag() && !pDstItem
->IsBag())
11247 ItemPosCountVec sDest
;
11249 if( IsInventoryPos( dst
) )
11250 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
11251 else if( IsBankPos ( dst
) )
11252 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
11253 else if( IsEquipmentPos ( dst
) )
11254 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, false );
11258 // can be merge/fill
11259 if(msg
== EQUIP_ERR_OK
)
11261 if( pSrcItem
->GetCount() + pDstItem
->GetCount() <= pSrcItem
->GetProto()->GetMaxStackSize())
11263 RemoveItem(srcbag
, srcslot
, true);
11265 if( IsInventoryPos( dst
) )
11266 StoreItem( sDest
, pSrcItem
, true);
11267 else if( IsBankPos ( dst
) )
11268 BankItem( sDest
, pSrcItem
, true);
11269 else if( IsEquipmentPos ( dst
) )
11271 EquipItem( eDest
, pSrcItem
, true);
11272 AutoUnequipOffhandIfNeed();
11277 pSrcItem
->SetCount( pSrcItem
->GetCount() + pDstItem
->GetCount() - pSrcItem
->GetProto()->GetMaxStackSize());
11278 pDstItem
->SetCount( pSrcItem
->GetProto()->GetMaxStackSize());
11279 pSrcItem
->SetState(ITEM_CHANGED
, this);
11280 pDstItem
->SetState(ITEM_CHANGED
, this);
11283 pSrcItem
->SendUpdateToPlayer( this );
11284 pDstItem
->SendUpdateToPlayer( this );
11291 // impossible merge/fill, do real swap
11294 // check src->dest move possibility
11295 ItemPosCountVec sDest
;
11297 if( IsInventoryPos( dst
) )
11298 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
11299 else if( IsBankPos( dst
) )
11300 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
11301 else if( IsEquipmentPos( dst
) )
11303 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, true );
11304 if( msg
== EQUIP_ERR_OK
)
11305 msg
= CanUnequipItem( eDest
, true );
11308 if( msg
!= EQUIP_ERR_OK
)
11310 SendEquipError( msg
, pSrcItem
, pDstItem
);
11314 // check dest->src move possibility
11315 ItemPosCountVec sDest2
;
11317 if( IsInventoryPos( src
) )
11318 msg
= CanStoreItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11319 else if( IsBankPos( src
) )
11320 msg
= CanBankItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11321 else if( IsEquipmentPos( src
) )
11323 msg
= CanEquipItem( srcslot
, eDest2
, pDstItem
, true);
11324 if( msg
== EQUIP_ERR_OK
)
11325 msg
= CanUnequipItem( eDest2
, true);
11328 if( msg
!= EQUIP_ERR_OK
)
11330 SendEquipError( msg
, pDstItem
, pSrcItem
);
11334 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11335 if(pSrcItem
->IsBag() && pDstItem
->IsBag())
11337 Bag
* emptyBag
= NULL
;
11338 Bag
* fullBag
= NULL
;
11339 if(((Bag
*)pSrcItem
)->IsEmpty() && !IsBagPos(src
))
11341 emptyBag
= (Bag
*)pSrcItem
;
11342 fullBag
= (Bag
*)pDstItem
;
11344 else if(((Bag
*)pDstItem
)->IsEmpty() && !IsBagPos(dst
))
11346 emptyBag
= (Bag
*)pDstItem
;
11347 fullBag
= (Bag
*)pSrcItem
;
11350 // bag swap (with items exchange) case
11351 if(emptyBag
&& fullBag
)
11353 ItemPrototype
const* emotyProto
= emptyBag
->GetProto();
11357 for(int i
=0; i
< fullBag
->GetBagSize(); ++i
)
11359 Item
*bagItem
= fullBag
->GetItemByPos(i
);
11363 ItemPrototype
const* bagItemProto
= bagItem
->GetProto();
11364 if (!bagItemProto
|| !ItemCanGoIntoBag(bagItemProto
, emotyProto
))
11366 // one from items not go to empty target bag
11367 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
11375 if (count
> emptyBag
->GetBagSize())
11377 // too small targeted bag
11378 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
, pSrcItem
, pDstItem
);
11383 count
= 0; // will pos in new bag
11384 for(int i
= 0; i
< fullBag
->GetBagSize(); ++i
)
11386 Item
*bagItem
= fullBag
->GetItemByPos(i
);
11390 fullBag
->RemoveItem(i
, true);
11391 emptyBag
->StoreItem(count
, bagItem
, true);
11392 bagItem
->SetState(ITEM_CHANGED
, this);
11399 // now do moves, remove...
11400 RemoveItem(dstbag
, dstslot
, false);
11401 RemoveItem(srcbag
, srcslot
, false);
11404 if (IsInventoryPos(dst
))
11405 StoreItem(sDest
, pSrcItem
, true);
11406 else if (IsBankPos(dst
))
11407 BankItem(sDest
, pSrcItem
, true);
11408 else if (IsEquipmentPos(dst
))
11409 EquipItem(eDest
, pSrcItem
, true);
11412 if (IsInventoryPos(src
))
11413 StoreItem(sDest2
, pDstItem
, true);
11414 else if (IsBankPos(src
))
11415 BankItem(sDest2
, pDstItem
, true);
11416 else if (IsEquipmentPos(src
))
11417 EquipItem(eDest2
, pDstItem
, true);
11419 AutoUnequipOffhandIfNeed();
11422 void Player::AddItemToBuyBackSlot( Item
*pItem
)
11426 uint32 slot
= m_currentBuybackSlot
;
11427 // if current back slot non-empty search oldest or free
11430 uint32 oldest_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
);
11431 uint32 oldest_slot
= BUYBACK_SLOT_START
;
11433 for(uint32 i
= BUYBACK_SLOT_START
+1; i
< BUYBACK_SLOT_END
; ++i
)
11442 uint32 i_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ i
- BUYBACK_SLOT_START
);
11444 if (oldest_time
> i_time
)
11446 oldest_time
= i_time
;
11452 slot
= oldest_slot
;
11455 RemoveItemFromBuyBackSlot( slot
, true );
11456 sLog
.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem
->GetEntry(), slot
);
11458 m_items
[slot
] = pItem
;
11459 time_t base
= time(NULL
);
11460 uint32 etime
= uint32(base
- m_logintime
+ (30 * 3600));
11461 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11463 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ (eslot
* 2), pItem
->GetGUID() );
11464 if (ItemPrototype
const *pProto
= pItem
->GetProto())
11465 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, pProto
->SellPrice
* pItem
->GetCount() );
11467 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11468 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, (uint32
)etime
);
11470 // move to next (for non filled list is move most optimized choice)
11471 if (m_currentBuybackSlot
< BUYBACK_SLOT_END
- 1)
11472 ++m_currentBuybackSlot
;
11476 Item
* Player::GetItemFromBuyBackSlot( uint32 slot
)
11478 sLog
.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot
);
11479 if (slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11480 return m_items
[slot
];
11484 void Player::RemoveItemFromBuyBackSlot( uint32 slot
, bool del
)
11486 sLog
.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot
);
11487 if (slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11489 Item
*pItem
= m_items
[slot
];
11492 pItem
->RemoveFromWorld();
11493 if(del
) pItem
->SetState(ITEM_REMOVED
, this);
11496 m_items
[slot
] = NULL
;
11498 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11499 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ (eslot
* 2), 0 );
11500 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11501 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, 0 );
11503 // if current backslot is filled set to now free slot
11504 if (m_items
[m_currentBuybackSlot
])
11505 m_currentBuybackSlot
= slot
;
11509 void Player::SendEquipError( uint8 msg
, Item
* pItem
, Item
*pItem2
)
11511 sLog
.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)", msg
);
11512 WorldPacket
data(SMSG_INVENTORY_CHANGE_FAILURE
, (msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
? 22 : (msg
== EQUIP_ERR_OK
? 1 : 18)));
11513 data
<< uint8(msg
);
11515 if (msg
!= EQUIP_ERR_OK
)
11517 data
<< uint64(pItem
? pItem
->GetGUID() : 0);
11518 data
<< uint64(pItem2
? pItem2
->GetGUID() : 0);
11519 data
<< uint8(0); // not 0 there...
11521 if (msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
)
11526 if (ItemPrototype
const* proto
= pItem
->GetProto())
11527 level
= proto
->RequiredLevel
;
11529 data
<< uint32(level
); // new 2.4.0
11532 GetSession()->SendPacket(&data
);
11535 void Player::SendBuyError( uint8 msg
, Creature
* pCreature
, uint32 item
, uint32 param
)
11537 sLog
.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11538 WorldPacket
data( SMSG_BUY_FAILED
, (8+4+4+1) );
11539 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11540 data
<< uint32(item
);
11542 data
<< uint32(param
);
11543 data
<< uint8(msg
);
11544 GetSession()->SendPacket(&data
);
11547 void Player::SendSellError( uint8 msg
, Creature
* pCreature
, uint64 guid
, uint32 param
)
11549 sLog
.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11550 WorldPacket
data( SMSG_SELL_ITEM
,(8+8+(param
?4:0)+1)); // last check 2.0.10
11551 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11552 data
<< uint64(guid
);
11554 data
<< uint32(param
);
11555 data
<< uint8(msg
);
11556 GetSession()->SendPacket(&data
);
11559 void Player::ClearTrade()
11562 acceptTrade
= false;
11563 for(int i
= 0; i
< TRADE_SLOT_COUNT
; ++i
)
11564 tradeItems
[i
] = NULL_SLOT
;
11567 void Player::TradeCancel(bool sendback
)
11571 // send yellow "Trade canceled" message to both traders
11575 ws
->SendCancelTrade();
11576 ws
= pTrader
->GetSession();
11577 if (!ws
->PlayerLogout())
11578 ws
->SendCancelTrade();
11582 pTrader
->ClearTrade();
11583 // prevent loss of reference
11584 pTrader
->pTrader
= NULL
;
11589 void Player::UpdateItemDuration(uint32 time
, bool realtimeonly
)
11591 if (m_itemDuration
.empty())
11594 sLog
.outDebug("Player::UpdateItemDuration(%u,%u)", time
, realtimeonly
);
11596 for(ItemDurationList::const_iterator itr
= m_itemDuration
.begin(); itr
!= m_itemDuration
.end(); )
11599 ++itr
; // current element can be erased in UpdateDuration
11601 if ((realtimeonly
&& item
->GetProto()->Duration
< 0) || !realtimeonly
)
11602 item
->UpdateDuration(this,time
);
11606 void Player::UpdateEnchantTime(uint32 time
)
11608 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11612 if (!itr
->item
->GetEnchantmentId(itr
->slot
))
11614 next
= m_enchantDuration
.erase(itr
);
11616 else if (itr
->leftduration
<= time
)
11618 ApplyEnchantment(itr
->item
, itr
->slot
, false, false);
11619 itr
->item
->ClearEnchantment(itr
->slot
);
11620 next
= m_enchantDuration
.erase(itr
);
11622 else if (itr
->leftduration
> time
)
11624 itr
->leftduration
-= time
;
11630 void Player::AddEnchantmentDurations(Item
*item
)
11632 for(int x
= 0; x
< MAX_ENCHANTMENT_SLOT
; ++x
)
11634 if (!item
->GetEnchantmentId(EnchantmentSlot(x
)))
11637 uint32 duration
= item
->GetEnchantmentDuration(EnchantmentSlot(x
));
11639 AddEnchantmentDuration(item
, EnchantmentSlot(x
), duration
);
11643 void Player::RemoveEnchantmentDurations(Item
*item
)
11645 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(); itr
!= m_enchantDuration
.end();)
11647 if (itr
->item
== item
)
11649 // save duration in item
11650 item
->SetEnchantmentDuration(EnchantmentSlot(itr
->slot
), itr
->leftduration
);
11651 itr
= m_enchantDuration
.erase(itr
);
11658 void Player::RemoveAllEnchantments(EnchantmentSlot slot
)
11660 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11661 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(), next
; itr
!= m_enchantDuration
.end(); itr
= next
)
11664 if (itr
->slot
== slot
)
11666 if (itr
->item
&& itr
->item
->GetEnchantmentId(slot
))
11668 // remove from stats
11669 ApplyEnchantment(itr
->item
, slot
, false, false);
11671 itr
->item
->ClearEnchantment(slot
);
11673 // remove from update list
11674 next
= m_enchantDuration
.erase(itr
);
11680 // remove enchants from inventory items
11681 // NOTE: no need to remove these from stats, since these aren't equipped
11683 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
11684 if (Item
* pItem
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
))
11685 if (pItem
->GetEnchantmentId(slot
))
11686 pItem
->ClearEnchantment(slot
);
11688 // in inventory bags
11689 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
11690 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
11691 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
11692 if (Item
* pItem
= pBag
->GetItemByPos(j
))
11693 if (pItem
->GetEnchantmentId(slot
))
11694 pItem
->ClearEnchantment(slot
);
11697 // duration == 0 will remove item enchant
11698 void Player::AddEnchantmentDuration(Item
*item
,EnchantmentSlot slot
,uint32 duration
)
11703 if (slot
>= MAX_ENCHANTMENT_SLOT
)
11706 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(); itr
!= m_enchantDuration
.end(); ++itr
)
11708 if (itr
->item
== item
&& itr
->slot
== slot
)
11710 itr
->item
->SetEnchantmentDuration(itr
->slot
, itr
->leftduration
);
11711 m_enchantDuration
.erase(itr
);
11715 if (item
&& duration
> 0 )
11717 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item
->GetGUID(), slot
, uint32(duration
/1000));
11718 m_enchantDuration
.push_back(EnchantDuration(item
, slot
, duration
));
11722 void Player::ApplyEnchantment(Item
*item
,bool apply
)
11724 for(uint32 slot
= 0; slot
< MAX_ENCHANTMENT_SLOT
; ++slot
)
11725 ApplyEnchantment(item
, EnchantmentSlot(slot
), apply
);
11728 void Player::ApplyEnchantment(Item
*item
, EnchantmentSlot slot
, bool apply
, bool apply_dur
, bool ignore_condition
)
11733 if (!item
->IsEquipped())
11736 if (slot
>= MAX_ENCHANTMENT_SLOT
)
11739 uint32 enchant_id
= item
->GetEnchantmentId(slot
);
11743 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
11747 if (!ignore_condition
&& pEnchant
->EnchantmentCondition
&& !((Player
*)this)->EnchantmentFitsRequirements(pEnchant
->EnchantmentCondition
, -1))
11750 if (!item
->IsBroken())
11752 for (int s
= 0; s
< 3; ++s
)
11754 uint32 enchant_display_type
= pEnchant
->type
[s
];
11755 uint32 enchant_amount
= pEnchant
->amount
[s
];
11756 uint32 enchant_spell_id
= pEnchant
->spellid
[s
];
11758 switch(enchant_display_type
)
11760 case ITEM_ENCHANTMENT_TYPE_NONE
:
11762 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
:
11763 // processed in Player::CastItemCombatSpell
11765 case ITEM_ENCHANTMENT_TYPE_DAMAGE
:
11766 if (item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
11767 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11768 else if (item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
11769 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11770 else if (item
->GetSlot() == EQUIPMENT_SLOT_RANGED
)
11771 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11773 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL
:
11774 if (enchant_spell_id
)
11778 int32 basepoints
= 0;
11779 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11780 if (item
->GetItemRandomPropertyId())
11782 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11785 // Search enchant_amount
11786 for (int k
= 0; k
< 3; ++k
)
11788 if(item_rand
->enchant_id
[k
] == enchant_id
)
11790 basepoints
= int32((item_rand
->prefix
[k
] * item
->GetItemSuffixFactor()) / 10000 );
11796 // Cast custom spell vs all equal basepoints getted from enchant_amount
11798 CastCustomSpell(this, enchant_spell_id
, &basepoints
, &basepoints
, &basepoints
, true, item
);
11800 CastSpell(this, enchant_spell_id
, true, item
);
11803 RemoveAurasDueToItemSpell(item
, enchant_spell_id
);
11806 case ITEM_ENCHANTMENT_TYPE_RESISTANCE
:
11807 if (!enchant_amount
)
11809 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11812 for (int k
= 0; k
< 3; ++k
)
11814 if(item_rand
->enchant_id
[k
] == enchant_id
)
11816 enchant_amount
= uint32((item_rand
->prefix
[k
] * item
->GetItemSuffixFactor()) / 10000 );
11823 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START
+ enchant_spell_id
), TOTAL_VALUE
, float(enchant_amount
), apply
);
11825 case ITEM_ENCHANTMENT_TYPE_STAT
:
11827 if (!enchant_amount
)
11829 ItemRandomSuffixEntry
const *item_rand_suffix
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11830 if(item_rand_suffix
)
11832 for (int k
= 0; k
< 3; ++k
)
11834 if(item_rand_suffix
->enchant_id
[k
] == enchant_id
)
11836 enchant_amount
= uint32((item_rand_suffix
->prefix
[k
] * item
->GetItemSuffixFactor()) / 10000 );
11843 sLog
.outDebug("Adding %u to stat nb %u",enchant_amount
,enchant_spell_id
);
11844 switch (enchant_spell_id
)
11846 case ITEM_MOD_MANA
:
11847 sLog
.outDebug("+ %u MANA",enchant_amount
);
11848 HandleStatModifier(UNIT_MOD_MANA
, BASE_VALUE
, float(enchant_amount
), apply
);
11850 case ITEM_MOD_HEALTH
:
11851 sLog
.outDebug("+ %u HEALTH",enchant_amount
);
11852 HandleStatModifier(UNIT_MOD_HEALTH
, BASE_VALUE
, float(enchant_amount
), apply
);
11854 case ITEM_MOD_AGILITY
:
11855 sLog
.outDebug("+ %u AGILITY",enchant_amount
);
11856 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11857 ApplyStatBuffMod(STAT_AGILITY
, enchant_amount
, apply
);
11859 case ITEM_MOD_STRENGTH
:
11860 sLog
.outDebug("+ %u STRENGTH",enchant_amount
);
11861 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11862 ApplyStatBuffMod(STAT_STRENGTH
, enchant_amount
, apply
);
11864 case ITEM_MOD_INTELLECT
:
11865 sLog
.outDebug("+ %u INTELLECT",enchant_amount
);
11866 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11867 ApplyStatBuffMod(STAT_INTELLECT
, enchant_amount
, apply
);
11869 case ITEM_MOD_SPIRIT
:
11870 sLog
.outDebug("+ %u SPIRIT",enchant_amount
);
11871 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11872 ApplyStatBuffMod(STAT_SPIRIT
, enchant_amount
, apply
);
11874 case ITEM_MOD_STAMINA
:
11875 sLog
.outDebug("+ %u STAMINA",enchant_amount
);
11876 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11877 ApplyStatBuffMod(STAT_STAMINA
, enchant_amount
, apply
);
11879 case ITEM_MOD_DEFENSE_SKILL_RATING
:
11880 ((Player
*)this)->ApplyRatingMod(CR_DEFENSE_SKILL
, enchant_amount
, apply
);
11881 sLog
.outDebug("+ %u DEFENCE", enchant_amount
);
11883 case ITEM_MOD_DODGE_RATING
:
11884 ((Player
*)this)->ApplyRatingMod(CR_DODGE
, enchant_amount
, apply
);
11885 sLog
.outDebug("+ %u DODGE", enchant_amount
);
11887 case ITEM_MOD_PARRY_RATING
:
11888 ((Player
*)this)->ApplyRatingMod(CR_PARRY
, enchant_amount
, apply
);
11889 sLog
.outDebug("+ %u PARRY", enchant_amount
);
11891 case ITEM_MOD_BLOCK_RATING
:
11892 ((Player
*)this)->ApplyRatingMod(CR_BLOCK
, enchant_amount
, apply
);
11893 sLog
.outDebug("+ %u SHIELD_BLOCK", enchant_amount
);
11895 case ITEM_MOD_HIT_MELEE_RATING
:
11896 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
11897 sLog
.outDebug("+ %u MELEE_HIT", enchant_amount
);
11899 case ITEM_MOD_HIT_RANGED_RATING
:
11900 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
11901 sLog
.outDebug("+ %u RANGED_HIT", enchant_amount
);
11903 case ITEM_MOD_HIT_SPELL_RATING
:
11904 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
11905 sLog
.outDebug("+ %u SPELL_HIT", enchant_amount
);
11907 case ITEM_MOD_CRIT_MELEE_RATING
:
11908 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
11909 sLog
.outDebug("+ %u MELEE_CRIT", enchant_amount
);
11911 case ITEM_MOD_CRIT_RANGED_RATING
:
11912 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
11913 sLog
.outDebug("+ %u RANGED_CRIT", enchant_amount
);
11915 case ITEM_MOD_CRIT_SPELL_RATING
:
11916 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
11917 sLog
.outDebug("+ %u SPELL_CRIT", enchant_amount
);
11919 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11921 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11922 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11924 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11925 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11927 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11928 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11930 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11931 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11933 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11934 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11936 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11937 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11939 // case ITEM_MOD_HASTE_MELEE_RATING:
11940 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11942 // case ITEM_MOD_HASTE_RANGED_RATING:
11943 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11945 case ITEM_MOD_HASTE_SPELL_RATING
:
11946 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
11948 case ITEM_MOD_HIT_RATING
:
11949 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
11950 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
11951 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
11952 sLog
.outDebug("+ %u HIT", enchant_amount
);
11954 case ITEM_MOD_CRIT_RATING
:
11955 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
11956 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
11957 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
11958 sLog
.outDebug("+ %u CRITICAL", enchant_amount
);
11960 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11961 // case ITEM_MOD_HIT_TAKEN_RATING:
11962 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11963 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11964 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11966 // case ITEM_MOD_CRIT_TAKEN_RATING:
11967 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11968 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11969 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11971 case ITEM_MOD_RESILIENCE_RATING
:
11972 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, enchant_amount
, apply
);
11973 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, enchant_amount
, apply
);
11974 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, enchant_amount
, apply
);
11975 sLog
.outDebug("+ %u RESILIENCE", enchant_amount
);
11977 case ITEM_MOD_HASTE_RATING
:
11978 ((Player
*)this)->ApplyRatingMod(CR_HASTE_MELEE
, enchant_amount
, apply
);
11979 ((Player
*)this)->ApplyRatingMod(CR_HASTE_RANGED
, enchant_amount
, apply
);
11980 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
11981 sLog
.outDebug("+ %u HASTE", enchant_amount
);
11983 case ITEM_MOD_EXPERTISE_RATING
:
11984 ((Player
*)this)->ApplyRatingMod(CR_EXPERTISE
, enchant_amount
, apply
);
11985 sLog
.outDebug("+ %u EXPERTISE", enchant_amount
);
11987 case ITEM_MOD_ATTACK_POWER
:
11988 HandleStatModifier(UNIT_MOD_ATTACK_POWER
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11989 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11990 sLog
.outDebug("+ %u ATTACK_POWER", enchant_amount
);
11992 case ITEM_MOD_RANGED_ATTACK_POWER
:
11993 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11994 sLog
.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount
);
11996 case ITEM_MOD_FERAL_ATTACK_POWER
:
11997 ((Player
*)this)->ApplyFeralAPBonus(enchant_amount
, apply
);
11998 sLog
.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount
);
12000 case ITEM_MOD_MANA_REGENERATION
:
12001 ((Player
*)this)->ApplyManaRegenBonus(enchant_amount
, apply
);
12002 sLog
.outDebug("+ %u MANA_REGENERATION", enchant_amount
);
12004 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
12005 ((Player
*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION
, enchant_amount
, apply
);
12006 sLog
.outDebug("+ %u ARMOR PENETRATION", enchant_amount
);
12008 case ITEM_MOD_SPELL_POWER
:
12009 ((Player
*)this)->ApplySpellPowerBonus(enchant_amount
, apply
);
12010 sLog
.outDebug("+ %u SPELL_POWER", enchant_amount
);
12012 case ITEM_MOD_SPELL_HEALING_DONE
: // deprecated
12013 case ITEM_MOD_SPELL_DAMAGE_DONE
: // deprecated
12019 case ITEM_ENCHANTMENT_TYPE_TOTEM
: // Shaman Rockbiter Weapon
12021 if(getClass() == CLASS_SHAMAN
)
12023 float addValue
= 0.0f
;
12024 if(item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
12026 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/ 1000.0f
);
12027 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, addValue
, apply
);
12029 else if(item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
12031 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/ 1000.0f
);
12032 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, addValue
, apply
);
12037 case ITEM_ENCHANTMENT_TYPE_USE_SPELL
:
12038 // processed in Player::CastItemUseSpell
12040 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET
:
12044 sLog
.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id
, enchant_display_type
);
12046 } /*switch(enchant_display_type)*/
12050 // visualize enchantment at player and equipped items
12051 if(slot
== PERM_ENCHANTMENT_SLOT
)
12052 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT
+ (item
->GetSlot() * 2), 0, apply
? item
->GetEnchantmentId(slot
) : 0);
12054 if(slot
== TEMP_ENCHANTMENT_SLOT
)
12055 SetUInt16Value(PLAYER_VISIBLE_ITEM_1_ENCHANTMENT
+ (item
->GetSlot() * 2), 1, apply
? item
->GetEnchantmentId(slot
) : 0);
12063 uint32 duration
= item
->GetEnchantmentDuration(slot
);
12065 AddEnchantmentDuration(item
, slot
, duration
);
12069 // duration == 0 will remove EnchantDuration
12070 AddEnchantmentDuration(item
, slot
, 0);
12075 void Player::SendEnchantmentDurations()
12077 for(EnchantDurationList::const_iterator itr
= m_enchantDuration
.begin(); itr
!= m_enchantDuration
.end(); ++itr
)
12079 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr
->item
->GetGUID(), itr
->slot
, uint32(itr
->leftduration
) / 1000);
12083 void Player::SendItemDurations()
12085 for(ItemDurationList::const_iterator itr
= m_itemDuration
.begin(); itr
!= m_itemDuration
.end(); ++itr
)
12087 (*itr
)->SendTimeUpdate(this);
12091 void Player::SendNewItem(Item
*item
, uint32 count
, bool received
, bool created
, bool broadcast
)
12093 if(!item
) // prevent crash
12096 // last check 2.0.10
12097 WorldPacket
data( SMSG_ITEM_PUSH_RESULT
, (8+4+4+4+1+4+4+4+4+4) );
12098 data
<< uint64(GetGUID()); // player GUID
12099 data
<< uint32(received
); // 0=looted, 1=from npc
12100 data
<< uint32(created
); // 0=received, 1=created
12101 data
<< uint32(1); // always 0x01 (probably meant to be count of listed items)
12102 data
<< uint8(item
->GetBagSlot()); // bagslot
12103 // item slot, but when added to stack: 0xFFFFFFFF
12104 data
<< uint32((item
->GetCount() == count
) ? item
->GetSlot() : -1);
12105 data
<< uint32(item
->GetEntry()); // item id
12106 data
<< uint32(item
->GetItemSuffixFactor()); // SuffixFactor
12107 data
<< uint32(item
->GetItemRandomPropertyId()); // random item property id
12108 data
<< uint32(count
); // count of items
12109 data
<< uint32(GetItemCount(item
->GetEntry())); // count of items in inventory
12111 if (broadcast
&& GetGroup())
12112 GetGroup()->BroadcastPacket(&data
, true);
12114 GetSession()->SendPacket(&data
);
12117 /*********************************************************/
12118 /*** QUEST SYSTEM ***/
12119 /*********************************************************/
12121 void Player::PrepareQuestMenu( uint64 guid
)
12124 QuestRelations
* pObjectQR
;
12125 QuestRelations
* pObjectQIR
;
12127 // pets also can have quests
12128 Creature
*pCreature
= ObjectAccessor::GetCreatureOrPetOrVehicle(*this, guid
);
12131 pObject
= (Object
*)pCreature
;
12132 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
12133 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
12137 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12138 //only for quests which cast teleport spells on player
12139 Map
* _map
= IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
12141 GameObject
*pGameObject
= _map
->GetGameObject(guid
);
12144 pObject
= (Object
*)pGameObject
;
12145 pObjectQR
= &objmgr
.mGOQuestRelations
;
12146 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
12152 QuestMenu
&qm
= PlayerTalkClass
->GetQuestMenu();
12155 for(QuestRelations::const_iterator i
= pObjectQIR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQIR
->upper_bound(pObject
->GetEntry()); ++i
)
12157 uint32 quest_id
= i
->second
;
12158 QuestStatus status
= GetQuestStatus( quest_id
);
12159 if ( status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus( quest_id
) )
12160 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_UNK2
);
12161 else if ( status
== QUEST_STATUS_INCOMPLETE
)
12162 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_UNK2
);
12163 else if (status
== QUEST_STATUS_AVAILABLE
)
12164 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_CHAT
);
12167 for(QuestRelations::const_iterator i
= pObjectQR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++i
)
12169 uint32 quest_id
= i
->second
;
12170 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
12171 if(!pQuest
) continue;
12173 QuestStatus status
= GetQuestStatus( quest_id
);
12175 if (pQuest
->IsAutoComplete() && CanTakeQuest(pQuest
, false))
12176 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_UNK2
);
12177 else if ( status
== QUEST_STATUS_NONE
&& CanTakeQuest( pQuest
, false ) )
12178 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_CHAT
);
12182 void Player::SendPreparedQuest(uint64 guid
)
12184 QuestMenu
& questMenu
= PlayerTalkClass
->GetQuestMenu();
12186 if (questMenu
.Empty())
12189 QuestMenuItem
const& qmi0
= questMenu
.GetItem(0);
12191 uint32 status
= qmi0
.m_qIcon
;
12193 // single element case
12194 if (questMenu
.MenuItemCount() == 1)
12196 // Auto open -- maybe also should verify there is no greeting
12197 uint32 quest_id
= qmi0
.m_qId
;
12198 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
12202 if (status
== DIALOG_STATUS_UNK2
&& !GetQuestRewardStatus(quest_id
))
12203 PlayerTalkClass
->SendQuestGiverRequestItems(pQuest
, guid
, CanRewardQuest(pQuest
, false), true);
12204 else if (status
== DIALOG_STATUS_UNK2
)
12205 PlayerTalkClass
->SendQuestGiverRequestItems(pQuest
, guid
, CanRewardQuest(pQuest
, false), true);
12206 // Send completable on repeatable and autoCompletable quest if player don't have quest
12207 // TODO: verify if check for !pQuest->IsDaily() is really correct (possibly not)
12208 else if (pQuest
->IsAutoComplete() && pQuest
->IsRepeatable() && !pQuest
->IsDaily())
12209 PlayerTalkClass
->SendQuestGiverRequestItems(pQuest
, guid
, CanCompleteRepeatableQuest(pQuest
), true);
12211 PlayerTalkClass
->SendQuestGiverQuestDetails(pQuest
, guid
, true);
12214 // multiply entries
12220 std::string title
= "";
12222 // need pet case for some quests
12223 Creature
*pCreature
= ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid
);
12226 uint32 textid
= pCreature
->GetNpcTextId();
12227 GossipText
const* gossiptext
= objmgr
.GetGossipText(textid
);
12230 qe
._Delay
= 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12231 qe
._Emote
= 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12236 qe
= gossiptext
->Options
[0].Emotes
[0];
12238 if(!gossiptext
->Options
[0].Text_0
.empty())
12240 title
= gossiptext
->Options
[0].Text_0
;
12242 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
12245 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
12248 if (nl
->Text_0
[0].size() > loc_idx
&& !nl
->Text_0
[0][loc_idx
].empty())
12249 title
= nl
->Text_0
[0][loc_idx
];
12255 title
= gossiptext
->Options
[0].Text_1
;
12257 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
12260 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
12263 if (nl
->Text_1
[0].size() > loc_idx
&& !nl
->Text_1
[0][loc_idx
].empty())
12264 title
= nl
->Text_1
[0][loc_idx
];
12270 PlayerTalkClass
->SendQuestGiverQuestList(qe
, title
, guid
);
12274 bool Player::IsActiveQuest( uint32 quest_id
) const
12276 QuestStatusMap::const_iterator itr
= mQuestStatus
.find(quest_id
);
12278 return itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
;
12281 Quest
const * Player::GetNextQuest( uint64 guid
, Quest
const *pQuest
)
12284 QuestRelations
* pObjectQR
;
12285 QuestRelations
* pObjectQIR
;
12287 Creature
*pCreature
= ObjectAccessor::GetCreatureOrPetOrVehicle(*this,guid
);
12290 pObject
= (Object
*)pCreature
;
12291 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
12292 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
12296 //we should obtain map pointer from GetMap() in 99% of cases. Special case
12297 //only for quests which cast teleport spells on player
12298 Map
* _map
= IsInWorld() ? GetMap() : MapManager::Instance().FindMap(GetMapId(), GetInstanceId());
12300 GameObject
*pGameObject
= _map
->GetGameObject(guid
);
12303 pObject
= (Object
*)pGameObject
;
12304 pObjectQR
= &objmgr
.mGOQuestRelations
;
12305 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
12311 uint32 nextQuestID
= pQuest
->GetNextQuestInChain();
12312 for(QuestRelations::const_iterator itr
= pObjectQR
->lower_bound(pObject
->GetEntry()); itr
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++itr
)
12314 if (itr
->second
== nextQuestID
)
12315 return objmgr
.GetQuestTemplate(nextQuestID
);
12321 bool Player::CanSeeStartQuest( Quest
const *pQuest
)
12323 if( SatisfyQuestRace( pQuest
, false ) && SatisfyQuestSkillOrClass( pQuest
, false ) &&
12324 SatisfyQuestExclusiveGroup( pQuest
, false ) && SatisfyQuestReputation( pQuest
, false ) &&
12325 SatisfyQuestPreviousQuest( pQuest
, false ) && SatisfyQuestNextChain( pQuest
, false ) &&
12326 SatisfyQuestPrevChain( pQuest
, false ) && SatisfyQuestDay( pQuest
, false ) )
12328 return getLevel() + sWorld
.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF
) >= pQuest
->GetMinLevel();
12334 bool Player::CanTakeQuest( Quest
const *pQuest
, bool msg
)
12336 return SatisfyQuestStatus( pQuest
, msg
) && SatisfyQuestExclusiveGroup( pQuest
, msg
)
12337 && SatisfyQuestRace( pQuest
, msg
) && SatisfyQuestLevel( pQuest
, msg
)
12338 && SatisfyQuestSkillOrClass( pQuest
, msg
) && SatisfyQuestReputation( pQuest
, msg
)
12339 && SatisfyQuestPreviousQuest( pQuest
, msg
) && SatisfyQuestTimed( pQuest
, msg
)
12340 && SatisfyQuestNextChain( pQuest
, msg
) && SatisfyQuestPrevChain( pQuest
, msg
)
12341 && SatisfyQuestDay( pQuest
, msg
);
12344 bool Player::CanAddQuest( Quest
const *pQuest
, bool msg
)
12346 if( !SatisfyQuestLog( msg
) )
12349 uint32 srcitem
= pQuest
->GetSrcItemId();
12352 uint32 count
= pQuest
->GetSrcItemCount();
12353 ItemPosCountVec dest
;
12354 uint8 msg2
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
12356 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12357 if( msg2
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
12359 else if( msg2
!= EQUIP_ERR_OK
)
12361 SendEquipError( msg2
, NULL
, NULL
);
12368 bool Player::CanCompleteQuest( uint32 quest_id
)
12372 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12373 if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
12374 return false; // not allow re-complete quest
12376 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12381 // auto complete quest
12382 if (qInfo
->IsAutoComplete() && CanTakeQuest(qInfo
, false))
12385 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
12388 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12390 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12392 if( qInfo
->ReqItemCount
[i
]!= 0 && q_status
.m_itemcount
[i
] < qInfo
->ReqItemCount
[i
] )
12397 if ( qInfo
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
12399 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12401 if( qInfo
->ReqCreatureOrGOId
[i
] == 0 )
12404 if( qInfo
->ReqCreatureOrGOCount
[i
] != 0 && q_status
.m_creatureOrGOcount
[i
] < qInfo
->ReqCreatureOrGOCount
[i
] )
12409 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT
) && !q_status
.m_explored
)
12412 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && q_status
.m_timer
== 0 )
12415 if ( qInfo
->GetRewOrReqMoney() < 0 )
12417 if ( GetMoney() < uint32(-qInfo
->GetRewOrReqMoney()) )
12421 uint32 repFacId
= qInfo
->GetRepObjectiveFaction();
12422 if ( repFacId
&& GetReputationMgr().GetReputation(repFacId
) < qInfo
->GetRepObjectiveValue() )
12431 bool Player::CanCompleteRepeatableQuest( Quest
const *pQuest
)
12433 // Solve problem that player don't have the quest and try complete it.
12434 // if repeatable she must be able to complete event if player don't have it.
12435 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12436 if( !CanTakeQuest(pQuest
, false) )
12439 if (pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12440 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12441 if( pQuest
->ReqItemId
[i
] && pQuest
->ReqItemCount
[i
] && !HasItemCount(pQuest
->ReqItemId
[i
],pQuest
->ReqItemCount
[i
]) )
12444 if( !CanRewardQuest(pQuest
, false) )
12450 bool Player::CanRewardQuest( Quest
const *pQuest
, bool msg
)
12452 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12453 if(!pQuest
->IsAutoComplete() && GetQuestStatus(pQuest
->GetQuestId()) != QUEST_STATUS_COMPLETE
)
12456 // daily quest can't be rewarded (25 daily quest already completed)
12457 if(!SatisfyQuestDay(pQuest
,true))
12460 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12461 if(GetQuestRewardStatus(pQuest
->GetQuestId()))
12464 // prevent receive reward with quest items in bank
12465 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12467 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12469 if( pQuest
->ReqItemCount
[i
]!= 0 &&
12470 GetItemCount(pQuest
->ReqItemId
[i
]) < pQuest
->ReqItemCount
[i
] )
12473 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, NULL
, NULL
);
12479 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12480 if(pQuest
->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest
->GetRewOrReqMoney()) )
12486 bool Player::CanRewardQuest( Quest
const *pQuest
, uint32 reward
, bool msg
)
12488 // prevent receive reward with quest items in bank or for not completed quest
12489 if(!CanRewardQuest(pQuest
,msg
))
12492 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
12494 if( pQuest
->RewChoiceItemId
[reward
] )
12496 ItemPosCountVec dest
;
12497 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] );
12498 if( res
!= EQUIP_ERR_OK
)
12500 SendEquipError( res
, NULL
, NULL
);
12506 if ( pQuest
->GetRewItemsCount() > 0 )
12508 for (uint32 i
= 0; i
< pQuest
->GetRewItemsCount(); ++i
)
12510 if( pQuest
->RewItemId
[i
] )
12512 ItemPosCountVec dest
;
12513 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] );
12514 if( res
!= EQUIP_ERR_OK
)
12516 SendEquipError( res
, NULL
, NULL
);
12526 void Player::AddQuest( Quest
const *pQuest
, Object
*questGiver
)
12528 uint16 log_slot
= FindQuestSlot( 0 );
12529 assert(log_slot
< MAX_QUEST_LOG_SIZE
);
12531 uint32 quest_id
= pQuest
->GetQuestId();
12533 // if not exist then created with set uState==NEW and rewarded=false
12534 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
12536 // check for repeatable quests status reset
12537 questStatusData
.m_status
= QUEST_STATUS_INCOMPLETE
;
12538 questStatusData
.m_explored
= false;
12540 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12542 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12543 questStatusData
.m_itemcount
[i
] = 0;
12546 if ( pQuest
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
12548 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12549 questStatusData
.m_creatureOrGOcount
[i
] = 0;
12552 GiveQuestSourceItem( pQuest
);
12553 AdjustQuestReqItemCount( pQuest
, questStatusData
);
12555 if( pQuest
->GetRepObjectiveFaction() )
12556 if(FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(pQuest
->GetRepObjectiveFaction()))
12557 GetReputationMgr().SetVisible(factionEntry
);
12560 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
12562 uint32 limittime
= pQuest
->GetLimitTime();
12564 // shared timed quest
12565 if(questGiver
&& questGiver
->GetTypeId()==TYPEID_PLAYER
)
12566 limittime
= ((Player
*)questGiver
)->getQuestStatusMap()[quest_id
].m_timer
/ IN_MILISECONDS
;
12568 AddTimedQuest( quest_id
);
12569 questStatusData
.m_timer
= limittime
* IN_MILISECONDS
;
12570 qtime
= static_cast<uint32
>(time(NULL
)) + limittime
;
12573 questStatusData
.m_timer
= 0;
12575 SetQuestSlot(log_slot
, quest_id
, qtime
);
12577 if (questStatusData
.uState
!= QUEST_NEW
)
12578 questStatusData
.uState
= QUEST_CHANGED
;
12580 //starting initial quest script
12581 if(questGiver
&& pQuest
->GetQuestStartScript()!=0)
12582 GetMap()->ScriptsStart(sQuestStartScripts
, pQuest
->GetQuestStartScript(), questGiver
, this);
12584 // Some spells applied at quest activation
12585 SpellAreaForQuestMapBounds saBounds
= spellmgr
.GetSpellAreaForQuestMapBounds(quest_id
,true);
12586 if(saBounds
.first
!= saBounds
.second
)
12589 GetZoneAndAreaId(zone
,area
);
12591 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
12592 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,zone
,area
))
12593 if( !HasAura(itr
->second
->spellId
,0) )
12594 CastSpell(this,itr
->second
->spellId
,true);
12597 UpdateForQuestWorldObjects();
12600 void Player::CompleteQuest( uint32 quest_id
)
12604 SetQuestStatus( quest_id
, QUEST_STATUS_COMPLETE
);
12606 uint16 log_slot
= FindQuestSlot( quest_id
);
12607 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12608 SetQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
12610 if(Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
))
12612 if( qInfo
->HasFlag(QUEST_FLAGS_AUTO_REWARDED
) )
12613 RewardQuest(qInfo
,0,this,false);
12615 SendQuestComplete( quest_id
);
12620 void Player::IncompleteQuest( uint32 quest_id
)
12624 SetQuestStatus( quest_id
, QUEST_STATUS_INCOMPLETE
);
12626 uint16 log_slot
= FindQuestSlot( quest_id
);
12627 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12628 RemoveQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
12632 void Player::RewardQuest( Quest
const *pQuest
, uint32 reward
, Object
* questGiver
, bool announce
)
12634 //this THING should be here to protect code from quest, which cast on player far teleport as a reward
12635 //should work fine, cause far teleport will be executed in Player::Update()
12636 SetCanDelayTeleport(true);
12638 uint32 quest_id
= pQuest
->GetQuestId();
12640 for (int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12642 if (pQuest
->ReqItemId
[i
])
12643 DestroyItemCount( pQuest
->ReqItemId
[i
], pQuest
->ReqItemCount
[i
], true);
12646 RemoveTimedQuest(quest_id
);
12648 if (pQuest
->GetRewChoiceItemsCount() > 0)
12650 if (uint32 itemId
= pQuest
->RewChoiceItemId
[reward
])
12652 ItemPosCountVec dest
;
12653 if (CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, itemId
, pQuest
->RewChoiceItemCount
[reward
] ) == EQUIP_ERR_OK
)
12655 Item
* item
= StoreNewItem( dest
, itemId
, true, Item::GenerateItemRandomPropertyId(itemId
));
12656 SendNewItem(item
, pQuest
->RewChoiceItemCount
[reward
], true, false);
12661 if (pQuest
->GetRewItemsCount() > 0)
12663 for (uint32 i
=0; i
< pQuest
->GetRewItemsCount(); ++i
)
12665 if (uint32 itemId
= pQuest
->RewItemId
[i
])
12667 ItemPosCountVec dest
;
12668 if (CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, itemId
, pQuest
->RewItemCount
[i
] ) == EQUIP_ERR_OK
)
12670 Item
* item
= StoreNewItem( dest
, itemId
, true, Item::GenerateItemRandomPropertyId(itemId
));
12671 SendNewItem(item
, pQuest
->RewItemCount
[i
], true, false);
12677 RewardReputation( pQuest
);
12679 uint16 log_slot
= FindQuestSlot( quest_id
);
12680 if (log_slot
< MAX_QUEST_LOG_SIZE
)
12681 SetQuestSlot(log_slot
,0);
12683 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12685 // Not give XP in case already completed once repeatable quest
12686 uint32 XP
= q_status
.m_rewarded
? 0 : uint32(pQuest
->XPValue( this )*sWorld
.getRate(RATE_XP_QUEST
));
12688 if (getLevel() < sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
12689 GiveXP( XP
, NULL
);
12692 uint32 money
= uint32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getRate(RATE_DROP_MONEY
));
12693 ModifyMoney( money
);
12694 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD
, money
);
12697 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12698 if (pQuest
->GetRewOrReqMoney())
12700 ModifyMoney( pQuest
->GetRewOrReqMoney() );
12702 if (pQuest
->GetRewOrReqMoney() > 0)
12703 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD
, pQuest
->GetRewOrReqMoney());
12707 if (pQuest
->GetRewHonorableKills())
12708 RewardHonor(NULL
, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorableKills()));
12711 if (pQuest
->GetCharTitleId())
12713 if (CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
12714 SetTitle(titleEntry
);
12717 if (pQuest
->GetBonusTalents())
12719 m_questRewardTalentCount
+=pQuest
->GetBonusTalents();
12720 InitTalentForLevel();
12723 // Send reward mail
12724 if (pQuest
->GetRewMailTemplateId())
12726 MailMessageType mailType
;
12727 uint32 senderGuidOrEntry
;
12728 switch(questGiver
->GetTypeId())
12731 mailType
= MAIL_CREATURE
;
12732 senderGuidOrEntry
= questGiver
->GetEntry();
12734 case TYPEID_GAMEOBJECT
:
12735 mailType
= MAIL_GAMEOBJECT
;
12736 senderGuidOrEntry
= questGiver
->GetEntry();
12739 mailType
= MAIL_ITEM
;
12740 senderGuidOrEntry
= questGiver
->GetEntry();
12742 case TYPEID_PLAYER
:
12743 mailType
= MAIL_NORMAL
;
12744 senderGuidOrEntry
= questGiver
->GetGUIDLow();
12747 mailType
= MAIL_NORMAL
;
12748 senderGuidOrEntry
= GetGUIDLow();
12752 Loot questMailLoot
;
12754 questMailLoot
.FillLoot(pQuest
->GetQuestId(), LootTemplates_QuestMail
, this,true);
12757 MailItemsInfo mi
; // item list preparing
12759 uint32 max_slot
= questMailLoot
.GetMaxSlotInLootFor(this);
12760 for(uint32 i
= 0; mi
.size() < MAX_MAIL_ITEMS
&& i
< max_slot
; ++i
)
12762 if (LootItem
* lootitem
= questMailLoot
.LootItemInSlot(i
,this))
12764 if (Item
* item
= Item::CreateItem(lootitem
->itemid
,lootitem
->count
,this))
12766 item
->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12767 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
12772 WorldSession::SendMailTo(this, mailType
, MAIL_STATIONERY_NORMAL
, senderGuidOrEntry
, GetGUIDLow(), "", 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
,pQuest
->GetRewMailDelaySecs(),pQuest
->GetRewMailTemplateId());
12775 if (pQuest
->IsDaily())
12777 SetDailyQuestStatus(quest_id
);
12778 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST
, 1);
12781 if (!pQuest
->IsRepeatable())
12782 SetQuestStatus(quest_id
, QUEST_STATUS_COMPLETE
);
12784 SetQuestStatus(quest_id
, QUEST_STATUS_NONE
);
12786 q_status
.m_rewarded
= true;
12787 if (q_status
.uState
!= QUEST_NEW
)
12788 q_status
.uState
= QUEST_CHANGED
;
12791 SendQuestReward( pQuest
, XP
, questGiver
);
12793 // cast spells after mark quest complete (some spells have quest completed state reqyurements in spell_area data)
12794 if (pQuest
->GetRewSpellCast() > 0)
12795 CastSpell( this, pQuest
->GetRewSpellCast(), true);
12796 else if ( pQuest
->GetRewSpell() > 0)
12797 CastSpell( this, pQuest
->GetRewSpell(), true);
12799 if (pQuest
->GetZoneOrSort() > 0)
12800 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE
, pQuest
->GetZoneOrSort());
12801 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT
);
12802 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST
, pQuest
->GetQuestId());
12807 // remove auras from spells with quest reward state limitations
12808 SpellAreaForQuestMapBounds saEndBounds
= spellmgr
.GetSpellAreaForQuestEndMapBounds(quest_id
);
12809 if(saEndBounds
.first
!= saEndBounds
.second
)
12811 GetZoneAndAreaId(zone
,area
);
12813 for(SpellAreaForAreaMap::const_iterator itr
= saEndBounds
.first
; itr
!= saEndBounds
.second
; ++itr
)
12814 if(!itr
->second
->IsFitToRequirements(this,zone
,area
))
12815 RemoveAurasDueToSpell(itr
->second
->spellId
);
12818 // Some spells applied at quest reward
12819 SpellAreaForQuestMapBounds saBounds
= spellmgr
.GetSpellAreaForQuestMapBounds(quest_id
,false);
12820 if(saBounds
.first
!= saBounds
.second
)
12823 GetZoneAndAreaId(zone
,area
);
12825 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
12826 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,zone
,area
))
12827 if( !HasAura(itr
->second
->spellId
,0) )
12828 CastSpell(this,itr
->second
->spellId
,true);
12831 //lets remove flag for delayed teleports
12832 SetCanDelayTeleport(false);
12835 void Player::FailQuest(uint32 questId
)
12837 if (Quest
const* pQuest
= objmgr
.GetQuestTemplate(questId
))
12839 SetQuestStatus(questId
, QUEST_STATUS_FAILED
);
12841 uint16 log_slot
= FindQuestSlot(questId
);
12843 if (log_slot
< MAX_QUEST_LOG_SIZE
)
12845 SetQuestSlotTimer(log_slot
, 1);
12846 SetQuestSlotState(log_slot
, QUEST_STATE_FAIL
);
12849 if (pQuest
->HasFlag(QUEST_MANGOS_FLAGS_TIMED
))
12851 QuestStatusData
& q_status
= mQuestStatus
[questId
];
12853 RemoveTimedQuest(questId
);
12854 q_status
.m_timer
= 0;
12856 SendQuestTimerFailed(questId
);
12859 SendQuestFailed(questId
);
12863 bool Player::SatisfyQuestSkillOrClass( Quest
const* qInfo
, bool msg
)
12865 int32 zoneOrSort
= qInfo
->GetZoneOrSort();
12866 int32 skillOrClass
= qInfo
->GetSkillOrClass();
12868 // skip zone zoneOrSort and 0 case skillOrClass
12869 if( zoneOrSort
>= 0 && skillOrClass
== 0 )
12872 int32 questSort
= -zoneOrSort
;
12873 uint8 reqSortClass
= ClassByQuestSort(questSort
);
12875 // check class sort cases in zoneOrSort
12876 if( reqSortClass
!= 0 && getClass() != reqSortClass
)
12879 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12884 if( skillOrClass
< 0 )
12886 uint8 reqClass
= -int32(skillOrClass
);
12887 if(getClass() != reqClass
)
12890 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12895 else if( skillOrClass
> 0 )
12897 uint32 reqSkill
= skillOrClass
;
12898 if( GetSkillValue( reqSkill
) < qInfo
->GetRequiredSkillValue() )
12901 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12909 bool Player::SatisfyQuestLevel( Quest
const* qInfo
, bool msg
)
12911 if( getLevel() < qInfo
->GetMinLevel() )
12914 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12920 bool Player::SatisfyQuestLog( bool msg
)
12923 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE
)
12928 WorldPacket
data( SMSG_QUESTLOG_FULL
, 0 );
12929 GetSession()->SendPacket( &data
);
12930 sLog
.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12935 bool Player::SatisfyQuestPreviousQuest( Quest
const* qInfo
, bool msg
)
12937 // No previous quest (might be first quest in a series)
12938 if( qInfo
->prevQuests
.empty())
12941 for(Quest::PrevQuests::const_iterator iter
= qInfo
->prevQuests
.begin(); iter
!= qInfo
->prevQuests
.end(); ++iter
)
12943 uint32 prevId
= abs(*iter
);
12945 QuestStatusMap::const_iterator i_prevstatus
= mQuestStatus
.find( prevId
);
12946 Quest
const* qPrevInfo
= objmgr
.GetQuestTemplate(prevId
);
12948 if( qPrevInfo
&& i_prevstatus
!= mQuestStatus
.end() )
12950 // If any of the positive previous quests completed, return true
12951 if( *iter
> 0 && i_prevstatus
->second
.m_rewarded
)
12953 // skip one-from-all exclusive group
12954 if(qPrevInfo
->GetExclusiveGroup() >= 0)
12957 // each-from-all exclusive group ( < 0)
12958 // can be start if only all quests in prev quest exclusive group completed and rewarded
12959 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
12960 ObjectMgr::ExclusiveQuestGroups::const_iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
12962 assert(iter2
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
12964 for(; iter2
!= end
; ++iter2
)
12966 uint32 exclude_Id
= iter2
->second
;
12968 // skip checked quest id, only state of other quests in group is interesting
12969 if(exclude_Id
== prevId
)
12972 QuestStatusMap::const_iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12974 // alternative quest from group also must be completed and rewarded(reported)
12975 if( i_exstatus
== mQuestStatus
.end() || !i_exstatus
->second
.m_rewarded
)
12978 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12984 // If any of the negative previous quests active, return true
12985 if( *iter
< 0 && (i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
12986 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
))))
12988 // skip one-from-all exclusive group
12989 if(qPrevInfo
->GetExclusiveGroup() >= 0)
12992 // each-from-all exclusive group ( < 0)
12993 // can be start if only all quests in prev quest exclusive group active
12994 ObjectMgr::ExclusiveQuestGroups::const_iterator iter2
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
12995 ObjectMgr::ExclusiveQuestGroups::const_iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
12997 assert(iter2
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
12999 for(; iter2
!= end
; ++iter2
)
13001 uint32 exclude_Id
= iter2
->second
;
13003 // skip checked quest id, only state of other quests in group is interesting
13004 if(exclude_Id
== prevId
)
13007 QuestStatusMap::const_iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
13009 // alternative quest from group also must be active
13010 if( i_exstatus
== mQuestStatus
.end() ||
13011 i_exstatus
->second
.m_status
!= QUEST_STATUS_INCOMPLETE
&&
13012 (i_prevstatus
->second
.m_status
!= QUEST_STATUS_COMPLETE
|| GetQuestRewardStatus(prevId
)) )
13015 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13024 // Has only positive prev. quests in non-rewarded state
13025 // and negative prev. quests in non-active state
13027 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13032 bool Player::SatisfyQuestRace( Quest
const* qInfo
, bool msg
)
13034 uint32 reqraces
= qInfo
->GetRequiredRaces();
13035 if ( reqraces
== 0 )
13037 if( (reqraces
& getRaceMask()) == 0 )
13040 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE
);
13046 bool Player::SatisfyQuestReputation( Quest
const* qInfo
, bool msg
)
13048 uint32 fIdMin
= qInfo
->GetRequiredMinRepFaction(); //Min required rep
13049 if(fIdMin
&& GetReputationMgr().GetReputation(fIdMin
) < qInfo
->GetRequiredMinRepValue())
13052 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13056 uint32 fIdMax
= qInfo
->GetRequiredMaxRepFaction(); //Max required rep
13057 if(fIdMax
&& GetReputationMgr().GetReputation(fIdMax
) >= qInfo
->GetRequiredMaxRepValue())
13060 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13067 bool Player::SatisfyQuestStatus( Quest
const* qInfo
, bool msg
)
13069 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( qInfo
->GetQuestId() );
13070 if ( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
)
13073 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON
);
13079 bool Player::SatisfyQuestTimed(Quest
const* qInfo
, bool msg
)
13081 if (!m_timedquests
.empty() && qInfo
->HasFlag(QUEST_MANGOS_FLAGS_TIMED
))
13084 SendCanTakeQuestResponse(INVALIDREASON_QUEST_ONLY_ONE_TIMED
);
13091 bool Player::SatisfyQuestExclusiveGroup( Quest
const* qInfo
, bool msg
)
13093 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
13094 if(qInfo
->GetExclusiveGroup() <= 0)
13097 ObjectMgr::ExclusiveQuestGroups::const_iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qInfo
->GetExclusiveGroup());
13098 ObjectMgr::ExclusiveQuestGroups::const_iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qInfo
->GetExclusiveGroup());
13100 assert(iter
!=end
); // always must be found if qInfo->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
== qInfo
->GetQuestId())
13110 // not allow have daily quest if daily quest from exclusive group already recently completed
13111 Quest
const* Nquest
= objmgr
.GetQuestTemplate(exclude_Id
);
13112 if( !SatisfyQuestDay(Nquest
, false) )
13115 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13119 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
13121 // alternative quest already started or completed
13122 if( i_exstatus
!= mQuestStatus
.end()
13123 && (i_exstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
|| i_exstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
13126 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13133 bool Player::SatisfyQuestNextChain( Quest
const* qInfo
, bool msg
)
13135 if(!qInfo
->GetNextQuestInChain())
13138 // next quest in chain already started or completed
13139 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( qInfo
->GetNextQuestInChain() );
13140 if( itr
!= mQuestStatus
.end()
13141 && (itr
->second
.m_status
== QUEST_STATUS_COMPLETE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
13144 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13148 // check for all quests further up the chain
13149 // only necessary if there are quest chains with more than one quest that can be skipped
13150 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
13154 bool Player::SatisfyQuestPrevChain( Quest
const* qInfo
, bool msg
)
13156 // No previous quest in chain
13157 if( qInfo
->prevChainQuests
.empty())
13160 for(Quest::PrevChainQuests::const_iterator iter
= qInfo
->prevChainQuests
.begin(); iter
!= qInfo
->prevChainQuests
.end(); ++iter
)
13162 uint32 prevId
= *iter
;
13164 QuestStatusMap::const_iterator i_prevstatus
= mQuestStatus
.find( prevId
);
13166 if( i_prevstatus
!= mQuestStatus
.end() )
13168 // If any of the previous quests in chain active, return false
13169 if( i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
13170 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
)))
13173 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13178 // check for all quests further down the chain
13179 // only necessary if there are quest chains with more than one quest that can be skipped
13180 //if( !SatisfyQuestPrevChain( prevId, msg ) )
13184 // No previous quest in chain active
13188 bool Player::SatisfyQuestDay( Quest
const* qInfo
, bool msg
)
13190 if(!qInfo
->IsDaily())
13193 bool have_slot
= false;
13194 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
13196 uint32 id
= GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
);
13197 if(qInfo
->GetQuestId()==id
)
13207 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING
);
13214 bool Player::GiveQuestSourceItem( Quest
const *pQuest
)
13216 uint32 srcitem
= pQuest
->GetSrcItemId();
13219 uint32 count
= pQuest
->GetSrcItemCount();
13223 ItemPosCountVec dest
;
13224 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
13225 if( msg
== EQUIP_ERR_OK
)
13227 Item
* item
= StoreNewItem(dest
, srcitem
, true);
13228 SendNewItem(item
, count
, true, false);
13231 // player already have max amount required item, just report success
13232 else if( msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
13235 SendEquipError( msg
, NULL
, NULL
);
13242 bool Player::TakeQuestSourceItem( uint32 quest_id
, bool msg
)
13244 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13247 uint32 srcitem
= qInfo
->GetSrcItemId();
13250 uint32 count
= qInfo
->GetSrcItemCount();
13254 // exist one case when destroy source quest item not possible:
13255 // non un-equippable item (equipped non-empty bag, for example)
13256 uint8 res
= CanUnequipItems(srcitem
,count
);
13257 if(res
!= EQUIP_ERR_OK
)
13260 SendEquipError( res
, NULL
, NULL
);
13264 DestroyItemCount(srcitem
, count
, true, true);
13270 bool Player::GetQuestRewardStatus( uint32 quest_id
) const
13272 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13275 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13276 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13277 if( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
13278 && !qInfo
->IsRepeatable() )
13279 return itr
->second
.m_rewarded
;
13286 QuestStatus
Player::GetQuestStatus( uint32 quest_id
) const
13290 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13291 if( itr
!= mQuestStatus
.end() )
13292 return itr
->second
.m_status
;
13294 return QUEST_STATUS_NONE
;
13297 bool Player::CanShareQuest(uint32 quest_id
) const
13299 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13300 if( qInfo
&& qInfo
->HasFlag(QUEST_FLAGS_SHARABLE
) )
13302 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13303 if( itr
!= mQuestStatus
.end() )
13304 return itr
->second
.m_status
== QUEST_STATUS_NONE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
;
13309 void Player::SetQuestStatus(uint32 quest_id
, QuestStatus status
)
13311 if (Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
))
13313 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
13315 q_status
.m_status
= status
;
13317 if (q_status
.uState
!= QUEST_NEW
)
13318 q_status
.uState
= QUEST_CHANGED
;
13321 UpdateForQuestWorldObjects();
13324 // not used in MaNGOS, but used in scripting code
13325 uint32
Player::GetReqKillOrCastCurrentCount(uint32 quest_id
, int32 entry
)
13327 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13331 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13332 if ( qInfo
->ReqCreatureOrGOId
[j
] == entry
)
13333 return mQuestStatus
[quest_id
].m_creatureOrGOcount
[j
];
13338 void Player::AdjustQuestReqItemCount( Quest
const* pQuest
, QuestStatusData
& questStatusData
)
13340 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13342 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
13344 uint32 reqitemcount
= pQuest
->ReqItemCount
[i
];
13345 if( reqitemcount
!= 0 )
13347 uint32 curitemcount
= GetItemCount(pQuest
->ReqItemId
[i
],true);
13349 questStatusData
.m_itemcount
[i
] = std::min(curitemcount
, reqitemcount
);
13350 if (questStatusData
.uState
!= QUEST_NEW
) questStatusData
.uState
= QUEST_CHANGED
;
13356 uint16
Player::FindQuestSlot( uint32 quest_id
) const
13358 for ( uint16 i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13359 if ( GetQuestSlotQuestId(i
) == quest_id
)
13362 return MAX_QUEST_LOG_SIZE
;
13365 void Player::AreaExploredOrEventHappens( uint32 questId
)
13369 uint16 log_slot
= FindQuestSlot( questId
);
13370 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13372 QuestStatusData
& q_status
= mQuestStatus
[questId
];
13374 if(!q_status
.m_explored
)
13376 q_status
.m_explored
= true;
13377 if (q_status
.uState
!= QUEST_NEW
)
13378 q_status
.uState
= QUEST_CHANGED
;
13381 if( CanCompleteQuest( questId
) )
13382 CompleteQuest( questId
);
13386 //not used in mangosd, function for external script library
13387 void Player::GroupEventHappens( uint32 questId
, WorldObject
const* pEventObject
)
13389 if( Group
*pGroup
= GetGroup() )
13391 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
13393 Player
*pGroupGuy
= itr
->getSource();
13395 // for any leave or dead (with not released body) group member at appropriate distance
13396 if( pGroupGuy
&& pGroupGuy
->IsAtGroupRewardDistance(pEventObject
) && !pGroupGuy
->GetCorpse() )
13397 pGroupGuy
->AreaExploredOrEventHappens(questId
);
13401 AreaExploredOrEventHappens(questId
);
13404 void Player::ItemAddedQuestCheck( uint32 entry
, uint32 count
)
13406 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13408 uint32 questid
= GetQuestSlotQuestId(i
);
13409 if ( questid
== 0 )
13412 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13414 if ( q_status
.m_status
!= QUEST_STATUS_INCOMPLETE
)
13417 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13418 if( !qInfo
|| !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13421 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13423 uint32 reqitem
= qInfo
->ReqItemId
[j
];
13424 if ( reqitem
== entry
)
13426 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
13427 uint32 curitemcount
= q_status
.m_itemcount
[j
];
13428 if ( curitemcount
< reqitemcount
)
13430 uint32 additemcount
= ( curitemcount
+ count
<= reqitemcount
? count
: reqitemcount
- curitemcount
);
13431 q_status
.m_itemcount
[j
] += additemcount
;
13432 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13434 SendQuestUpdateAddItem( qInfo
, j
, additemcount
);
13436 if ( CanCompleteQuest( questid
) )
13437 CompleteQuest( questid
);
13442 UpdateForQuestWorldObjects();
13445 void Player::ItemRemovedQuestCheck( uint32 entry
, uint32 count
)
13447 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13449 uint32 questid
= GetQuestSlotQuestId(i
);
13452 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13455 if( !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13458 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13460 uint32 reqitem
= qInfo
->ReqItemId
[j
];
13461 if ( reqitem
== entry
)
13463 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13465 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
13466 uint32 curitemcount
;
13467 if( q_status
.m_status
!= QUEST_STATUS_COMPLETE
)
13468 curitemcount
= q_status
.m_itemcount
[j
];
13470 curitemcount
= GetItemCount(entry
,true);
13471 if ( curitemcount
< reqitemcount
+ count
)
13473 uint32 remitemcount
= ( curitemcount
<= reqitemcount
? count
: count
+ reqitemcount
- curitemcount
);
13474 q_status
.m_itemcount
[j
] = curitemcount
- remitemcount
;
13475 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13477 IncompleteQuest( questid
);
13483 UpdateForQuestWorldObjects();
13486 void Player::KilledMonster( CreatureInfo
const* cInfo
, uint64 guid
)
13489 KilledMonsterCredit(cInfo
->Entry
,guid
);
13491 for(int i
= 0; i
< MAX_KILL_CREDIT
; ++i
)
13492 if(cInfo
->KillCredit
[i
])
13493 KilledMonsterCredit(cInfo
->KillCredit
[i
],guid
);
13496 void Player::KilledMonsterCredit( uint32 entry
, uint64 guid
)
13498 uint32 addkillcount
= 1;
13499 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE
, entry
, addkillcount
);
13500 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13502 uint32 questid
= GetQuestSlotQuestId(i
);
13506 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13509 // just if !ingroup || !noraidgroup || raidgroup
13510 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13511 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
&& (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo
->GetType() == QUEST_TYPE_RAID
))
13513 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
13515 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13517 // skip GO activate objective or none
13518 if(qInfo
->ReqCreatureOrGOId
[j
] <=0)
13521 // skip Cast at creature objective
13522 if(qInfo
->ReqSpell
[j
] !=0 )
13525 uint32 reqkill
= qInfo
->ReqCreatureOrGOId
[j
];
13527 if ( reqkill
== entry
)
13529 uint32 reqkillcount
= qInfo
->ReqCreatureOrGOCount
[j
];
13530 uint32 curkillcount
= q_status
.m_creatureOrGOcount
[j
];
13531 if ( curkillcount
< reqkillcount
)
13533 q_status
.m_creatureOrGOcount
[j
] = curkillcount
+ addkillcount
;
13534 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13536 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curkillcount
, addkillcount
);
13538 if ( CanCompleteQuest( questid
) )
13539 CompleteQuest( questid
);
13541 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13550 void Player::CastedCreatureOrGO( uint32 entry
, uint64 guid
, uint32 spell_id
)
13552 bool isCreature
= IS_CREATURE_GUID(guid
);
13554 uint32 addCastCount
= 1;
13555 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13557 uint32 questid
= GetQuestSlotQuestId(i
);
13561 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13565 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13567 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13569 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
13571 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13573 // skip kill creature objective (0) or wrong spell casts
13574 if(qInfo
->ReqSpell
[j
] != spell_id
)
13577 uint32 reqTarget
= 0;
13581 // creature activate objectives
13582 if(qInfo
->ReqCreatureOrGOId
[j
] > 0)
13583 // checked at quest_template loading
13584 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
13588 // GO activate objective
13589 if(qInfo
->ReqCreatureOrGOId
[j
] < 0)
13590 // checked at quest_template loading
13591 reqTarget
= - qInfo
->ReqCreatureOrGOId
[j
];
13594 // other not this creature/GO related objectives
13595 if( reqTarget
!= entry
)
13598 uint32 reqCastCount
= qInfo
->ReqCreatureOrGOCount
[j
];
13599 uint32 curCastCount
= q_status
.m_creatureOrGOcount
[j
];
13600 if ( curCastCount
< reqCastCount
)
13602 q_status
.m_creatureOrGOcount
[j
] = curCastCount
+ addCastCount
;
13603 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13605 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curCastCount
, addCastCount
);
13608 if ( CanCompleteQuest( questid
) )
13609 CompleteQuest( questid
);
13611 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13619 void Player::TalkedToCreature( uint32 entry
, uint64 guid
)
13621 uint32 addTalkCount
= 1;
13622 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13624 uint32 questid
= GetQuestSlotQuestId(i
);
13628 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13632 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13634 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13636 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
13638 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13640 // skip spell casts and Gameobject objectives
13641 if(qInfo
->ReqSpell
[j
] > 0 || qInfo
->ReqCreatureOrGOId
[j
] < 0)
13644 uint32 reqTarget
= 0;
13646 if(qInfo
->ReqCreatureOrGOId
[j
] > 0) // creature activate objectives
13647 // checked at quest_template loading
13648 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
13652 if ( reqTarget
== entry
)
13654 uint32 reqTalkCount
= qInfo
->ReqCreatureOrGOCount
[j
];
13655 uint32 curTalkCount
= q_status
.m_creatureOrGOcount
[j
];
13656 if ( curTalkCount
< reqTalkCount
)
13658 q_status
.m_creatureOrGOcount
[j
] = curTalkCount
+ addTalkCount
;
13659 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13661 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curTalkCount
, addTalkCount
);
13663 if ( CanCompleteQuest( questid
) )
13664 CompleteQuest( questid
);
13666 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13675 void Player::MoneyChanged( uint32 count
)
13677 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13679 uint32 questid
= GetQuestSlotQuestId(i
);
13683 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13684 if( qInfo
&& qInfo
->GetRewOrReqMoney() < 0 )
13686 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13688 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13690 if(int32(count
) >= -qInfo
->GetRewOrReqMoney())
13692 if ( CanCompleteQuest( questid
) )
13693 CompleteQuest( questid
);
13696 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
13698 if(int32(count
) < -qInfo
->GetRewOrReqMoney())
13699 IncompleteQuest( questid
);
13705 void Player::ReputationChanged(FactionEntry
const* factionEntry
)
13707 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13709 if(uint32 questid
= GetQuestSlotQuestId(i
))
13711 if(Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
))
13713 if(qInfo
->GetRepObjectiveFaction() == factionEntry
->ID
)
13715 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13716 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13718 if(GetReputationMgr().GetReputation(factionEntry
) >= qInfo
->GetRepObjectiveValue())
13719 if ( CanCompleteQuest( questid
) )
13720 CompleteQuest( questid
);
13722 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
13724 if(GetReputationMgr().GetReputation(factionEntry
) < qInfo
->GetRepObjectiveValue())
13725 IncompleteQuest( questid
);
13733 bool Player::HasQuestForItem( uint32 itemid
) const
13735 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13737 uint32 questid
= GetQuestSlotQuestId(i
);
13738 if ( questid
== 0 )
13741 QuestStatusMap::const_iterator qs_itr
= mQuestStatus
.find(questid
);
13742 if(qs_itr
== mQuestStatus
.end())
13745 QuestStatusData
const& q_status
= qs_itr
->second
;
13747 if (q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13749 Quest
const* qinfo
= objmgr
.GetQuestTemplate(questid
);
13753 // hide quest if player is in raid-group and quest is no raid quest
13754 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
13757 // There should be no mixed ReqItem/ReqSource drop
13758 // This part for ReqItem drop
13759 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13761 if(itemid
== qinfo
->ReqItemId
[j
] && q_status
.m_itemcount
[j
] < qinfo
->ReqItemCount
[j
] )
13764 // This part - for ReqSource
13765 for (int j
= 0; j
< QUEST_SOURCE_ITEM_IDS_COUNT
; ++j
)
13767 // examined item is a source item
13768 if (qinfo
->ReqSourceId
[j
] == itemid
)
13770 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(itemid
);
13773 if (pProto
->MaxCount
&& GetItemCount(itemid
,true) < pProto
->MaxCount
)
13776 // allows custom amount drop when not 0
13777 if (qinfo
->ReqSourceCount
[j
])
13779 if (GetItemCount(itemid
,true) < qinfo
->ReqSourceCount
[j
])
13781 } else if (GetItemCount(itemid
,true) < pProto
->Stackable
)
13790 void Player::SendQuestComplete( uint32 quest_id
)
13794 WorldPacket
data( SMSG_QUESTUPDATE_COMPLETE
, 4 );
13795 data
<< uint32(quest_id
);
13796 GetSession()->SendPacket( &data
);
13797 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id
);
13801 void Player::SendQuestReward( Quest
const *pQuest
, uint32 XP
, Object
* questGiver
)
13803 uint32 questid
= pQuest
->GetQuestId();
13804 sLog
.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid
);
13805 WorldPacket
data( SMSG_QUESTGIVER_QUEST_COMPLETE
, (4+4+4+4+4) );
13806 data
<< uint32(questid
);
13808 if ( getLevel() < sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
13810 data
<< uint32(XP
);
13811 data
<< uint32(pQuest
->GetRewOrReqMoney());
13816 data
<< uint32(pQuest
->GetRewOrReqMoney() + int32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getRate(RATE_DROP_MONEY
)));
13819 data
<< uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorableKills()));
13820 data
<< uint32(pQuest
->GetBonusTalents()); // bonus talents
13821 GetSession()->SendPacket( &data
);
13823 if (pQuest
->GetQuestCompleteScript() != 0)
13824 GetMap()->ScriptsStart(sQuestEndScripts
, pQuest
->GetQuestCompleteScript(), questGiver
, this);
13827 void Player::SendQuestFailed( uint32 quest_id
)
13831 WorldPacket
data( SMSG_QUESTGIVER_QUEST_FAILED
, 4+4 );
13832 data
<< uint32(quest_id
);
13833 data
<< uint32(0); // failed reason (4 for inventory is full)
13834 GetSession()->SendPacket( &data
);
13835 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13839 void Player::SendQuestTimerFailed( uint32 quest_id
)
13843 WorldPacket
data( SMSG_QUESTUPDATE_FAILEDTIMER
, 4 );
13844 data
<< uint32(quest_id
);
13845 GetSession()->SendPacket( &data
);
13846 sLog
.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13850 void Player::SendCanTakeQuestResponse( uint32 msg
)
13852 WorldPacket
data( SMSG_QUESTGIVER_QUEST_INVALID
, 4 );
13853 data
<< uint32(msg
);
13854 GetSession()->SendPacket( &data
);
13855 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13858 void Player::SendPushToPartyResponse( Player
*pPlayer
, uint32 msg
)
13862 WorldPacket
data( MSG_QUEST_PUSH_RESULT
, (8+1) );
13863 data
<< uint64(pPlayer
->GetGUID());
13864 data
<< uint8(msg
); // valid values: 0-8
13865 GetSession()->SendPacket( &data
);
13866 sLog
.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13870 void Player::SendQuestUpdateAddItem( Quest
const* pQuest
, uint32 item_idx
, uint32 count
)
13872 WorldPacket
data( SMSG_QUESTUPDATE_ADD_ITEM
, 0 );
13873 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13874 //data << pQuest->ReqItemId[item_idx];
13876 GetSession()->SendPacket( &data
);
13879 void Player::SendQuestUpdateAddCreatureOrGo( Quest
const* pQuest
, uint64 guid
, uint32 creatureOrGO_idx
, uint32 old_count
, uint32 add_count
)
13881 assert(old_count
+ add_count
< 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13883 int32 entry
= pQuest
->ReqCreatureOrGOId
[ creatureOrGO_idx
];
13885 // client expected gameobject template id in form (id|0x80000000)
13886 entry
= (-entry
) | 0x80000000;
13888 WorldPacket
data( SMSG_QUESTUPDATE_ADD_KILL
, (4*4+8) );
13889 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13890 data
<< uint32(pQuest
->GetQuestId());
13891 data
<< uint32(entry
);
13892 data
<< uint32(old_count
+ add_count
);
13893 data
<< uint32(pQuest
->ReqCreatureOrGOCount
[ creatureOrGO_idx
]);
13894 data
<< uint64(guid
);
13895 GetSession()->SendPacket(&data
);
13897 uint16 log_slot
= FindQuestSlot( pQuest
->GetQuestId() );
13898 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13899 SetQuestSlotCounter(log_slot
,creatureOrGO_idx
,GetQuestSlotCounter(log_slot
,creatureOrGO_idx
)+add_count
);
13902 /*********************************************************/
13903 /*** LOAD SYSTEM ***/
13904 /*********************************************************/
13906 void Player::_LoadDeclinedNames(QueryResult
* result
)
13912 delete m_declinedname
;
13914 m_declinedname
= new DeclinedName
;
13915 Field
*fields
= result
->Fetch();
13916 for(int i
= 0; i
< MAX_DECLINED_NAME_CASES
; ++i
)
13917 m_declinedname
->name
[i
] = fields
[i
].GetCppString();
13922 void Player::_LoadArenaTeamInfo(QueryResult
*result
)
13924 // arenateamid, played_week, played_season, personal_rating
13925 memset((void*)&m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
], 0, sizeof(uint32
) * MAX_ARENA_SLOT
* ARENA_TEAM_END
);
13931 Field
*fields
= result
->Fetch();
13933 uint32 arenateamid
= fields
[0].GetUInt32();
13934 uint32 played_week
= fields
[1].GetUInt32();
13935 uint32 played_season
= fields
[2].GetUInt32();
13936 uint32 wons_season
= fields
[3].GetUInt32();
13937 uint32 personal_rating
= fields
[4].GetUInt32();
13939 ArenaTeam
* aTeam
= objmgr
.GetArenaTeamById(arenateamid
);
13942 sLog
.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u", arenateamid
);
13945 uint8 arenaSlot
= aTeam
->GetSlot();
13947 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ (arenaSlot
* ARENA_TEAM_END
) + ARENA_TEAM_ID
] = arenateamid
; // TeamID
13948 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ (arenaSlot
* ARENA_TEAM_END
) + ARENA_TEAM_TYPE
] = aTeam
->GetType(); // team type
13949 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ (arenaSlot
* ARENA_TEAM_END
) + ARENA_TEAM_MEMBER
] = ((aTeam
->GetCaptain() == GetGUID()) ? (uint32
)0 : (uint32
)1); // Captain 0, member 1
13950 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ (arenaSlot
* ARENA_TEAM_END
) + ARENA_TEAM_GAMES_WEEK
] = played_week
; // Played Week
13951 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ (arenaSlot
* ARENA_TEAM_END
) + ARENA_TEAM_GAMES_SEASON
] = played_season
; // Played Season
13952 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ (arenaSlot
* ARENA_TEAM_END
) + ARENA_TEAM_WINS_SEASON
] = wons_season
; // wins season
13953 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ (arenaSlot
* ARENA_TEAM_END
) + ARENA_TEAM_PERSONAL_RATING
] = personal_rating
; // Personal Rating
13955 } while (result
->NextRow());
13959 void Player::_LoadEquipmentSets(QueryResult
*result
)
13961 // SetPQuery(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS, "SELECT setguid, setindex, name, iconname, item0, item1, item2, item3, item4, item5, item6, item7, item8, item9, item10, item11, item12, item13, item14, item15, item16, item17, item18 FROM character_equipmentsets WHERE guid = '%u' ORDER BY setindex", GUID_LOPART(m_guid));
13968 Field
*fields
= result
->Fetch();
13970 EquipmentSet eqSet
;
13972 eqSet
.Guid
= fields
[0].GetUInt64();
13973 uint32 index
= fields
[1].GetUInt32();
13974 eqSet
.Name
= fields
[2].GetCppString();
13975 eqSet
.IconName
= fields
[3].GetCppString();
13976 eqSet
.state
= EQUIPMENT_SET_UNCHANGED
;
13978 for(uint32 i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
13979 eqSet
.Items
[i
] = fields
[4+i
].GetUInt32();
13981 m_EquipmentSets
[index
] = eqSet
;
13985 if(count
>= MAX_EQUIPMENT_SET_INDEX
) // client limit
13987 } while (result
->NextRow());
13991 void Player::_LoadBGData(QueryResult
* result
)
13996 // Expecting only one row
13997 Field
*fields
= result
->Fetch();
13998 /* bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
13999 m_bgData
.bgInstanceID
= fields
[0].GetUInt32();
14000 m_bgData
.bgTeam
= fields
[1].GetUInt32();
14001 m_bgData
.joinPos
= WorldLocation(fields
[6].GetUInt32(), // Map
14002 fields
[2].GetFloat(), // X
14003 fields
[3].GetFloat(), // Y
14004 fields
[4].GetFloat(), // Z
14005 fields
[5].GetFloat()); // Orientation
14006 m_bgData
.taxiPath
[0] = fields
[7].GetUInt32();
14007 m_bgData
.taxiPath
[1] = fields
[8].GetUInt32();
14008 m_bgData
.mountSpell
= fields
[9].GetUInt32();
14013 bool Player::LoadPositionFromDB(uint32
& mapid
, float& x
,float& y
,float& z
,float& o
, bool& in_flight
, uint64 guid
)
14015 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid
));
14019 Field
*fields
= result
->Fetch();
14021 x
= fields
[0].GetFloat();
14022 y
= fields
[1].GetFloat();
14023 z
= fields
[2].GetFloat();
14024 o
= fields
[3].GetFloat();
14025 mapid
= fields
[4].GetUInt32();
14026 in_flight
= !fields
[5].GetCppString().empty();
14032 bool Player::LoadValuesArrayFromDB(Tokens
& data
, uint64 guid
)
14034 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid
));
14038 Field
*fields
= result
->Fetch();
14040 data
= StrSplit(fields
[0].GetCppString(), " ");
14047 uint32
Player::GetUInt32ValueFromArray(Tokens
const& data
, uint16 index
)
14049 if(index
>= data
.size())
14052 return (uint32
)atoi(data
[index
].c_str());
14055 float Player::GetFloatValueFromArray(Tokens
const& data
, uint16 index
)
14058 uint32 temp
= Player::GetUInt32ValueFromArray(data
,index
);
14059 memcpy(&result
, &temp
, sizeof(result
));
14064 uint32
Player::GetUInt32ValueFromDB(uint16 index
, uint64 guid
)
14067 if(!LoadValuesArrayFromDB(data
,guid
))
14070 return GetUInt32ValueFromArray(data
,index
);
14073 float Player::GetFloatValueFromDB(uint16 index
, uint64 guid
)
14076 uint32 temp
= Player::GetUInt32ValueFromDB(index
, guid
);
14077 memcpy(&result
, &temp
, sizeof(result
));
14082 bool Player::LoadFromDB( uint32 guid
, SqlQueryHolder
*holder
)
14084 //// 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
14085 //QueryResult *result = CharacterDatabase.PQuery("SELECT guid, account, data, name, race, class, gender, level, xp, money, playerBytes, playerBytes2, playerFlags, position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, dungeon_difficulty, arena_pending_points FROM characters WHERE guid = '%u'", guid);
14086 QueryResult
*result
= holder
->GetResult(PLAYER_LOGIN_QUERY_LOADFROM
);
14090 sLog
.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid
);
14094 Field
*fields
= result
->Fetch();
14096 uint32 dbAccountId
= fields
[1].GetUInt32();
14098 // check if the character's account in the db and the logged in account match.
14099 // player should be able to load/delete character only with correct account!
14100 if( dbAccountId
!= GetSession()->GetAccountId() )
14102 sLog
.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid
,GetSession()->GetAccountId(),dbAccountId
);
14107 Object::_Create( guid
, 0, HIGHGUID_PLAYER
);
14109 m_name
= fields
[3].GetCppString();
14111 // check name limitations
14112 if (ObjectMgr::CheckPlayerName(m_name
) != CHAR_NAME_SUCCESS
||
14113 (GetSession()->GetSecurity() == SEC_PLAYER
&& objmgr
.IsReservedName(m_name
)))
14116 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME
),guid
);
14120 if(!LoadValues( fields
[2].GetString()))
14122 sLog
.outError("Player #%d have broken data in `data` field. Can't be loaded.", GUID_LOPART(guid
));
14127 // overwrite possible wrong/corrupted guid
14128 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
14130 // overwrite some data fields
14131 uint32 bytes0
= GetUInt32Value(UNIT_FIELD_BYTES_0
) & 0xFF000000;
14132 bytes0
|= fields
[4].GetUInt8(); // race
14133 bytes0
|= fields
[5].GetUInt8() << 8; // class
14134 bytes0
|= fields
[6].GetUInt8() << 16; // gender
14135 SetUInt32Value(UNIT_FIELD_BYTES_0
, bytes0
);
14137 SetUInt32Value(UNIT_FIELD_LEVEL
, fields
[7].GetUInt8());
14138 SetUInt32Value(PLAYER_XP
, fields
[8].GetUInt32());
14139 SetUInt32Value(PLAYER_FIELD_COINAGE
, fields
[9].GetUInt32());
14140 SetUInt32Value(PLAYER_BYTES
, fields
[10].GetUInt32());
14141 SetUInt32Value(PLAYER_BYTES_2
, fields
[11].GetUInt32());
14142 SetUInt32Value(PLAYER_BYTES_3
, (GetUInt32Value(PLAYER_BYTES_3
) & ~1) | fields
[6].GetUInt8());
14143 SetUInt32Value(PLAYER_FLAGS
, fields
[12].GetUInt32());
14147 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
14148 for(uint8 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
14150 SetUInt64Value( PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2), 0 );
14151 SetVisibleItemSlot(slot
, NULL
);
14155 delete m_items
[slot
];
14156 m_items
[slot
] = NULL
;
14160 // update money limits
14161 if(GetMoney() > MAX_MONEY_AMOUNT
)
14162 SetMoney(MAX_MONEY_AMOUNT
);
14164 sLog
.outDebug("Load Basic value of player %s is: ", m_name
.c_str());
14167 //Need to call it to initialize m_team (m_team can be calculated from race)
14168 //Other way is to saves m_team into characters table.
14169 setFactionForRace(getRace());
14172 // load home bind and check in same time class/race pair, it used later for restore broken positions
14173 if(!_LoadHomeBind(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND
)))
14179 InitPrimaryProfessions(); // to max set before any spell loaded
14181 // init saved position, and fix it later if problematic
14182 uint32 transGUID
= fields
[31].GetUInt32();
14183 Relocate(fields
[13].GetFloat(),fields
[14].GetFloat(),fields
[15].GetFloat(),fields
[17].GetFloat());
14184 SetLocationMapId(fields
[16].GetUInt32());
14186 uint32 difficulty
= fields
[39].GetUInt32();
14187 if(difficulty
>= MAX_DUNGEON_DIFFICULTY
)
14188 difficulty
= DUNGEON_DIFFICULTY_NORMAL
;
14189 SetDungeonDifficulty(Difficulty(difficulty
)); // may be changed in _LoadGroup
14191 _LoadGroup(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP
));
14193 _LoadArenaTeamInfo(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO
));
14195 uint32 arena_currency
= GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
) + fields
[40].GetUInt32();
14196 if (arena_currency
> sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
))
14197 arena_currency
= sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
);
14199 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, arena_currency
);
14201 // check arena teams integrity
14202 for(uint32 arena_slot
= 0; arena_slot
< MAX_ARENA_SLOT
; ++arena_slot
)
14204 uint32 arena_team_id
= GetArenaTeamId(arena_slot
);
14208 if(ArenaTeam
* at
= objmgr
.GetArenaTeamById(arena_team_id
))
14209 if(at
->HaveMember(GetGUID()))
14212 // arena team not exist or not member, cleanup fields
14213 for(int j
= 0; j
< ARENA_TEAM_END
; ++j
)
14214 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ (arena_slot
* ARENA_TEAM_END
) + j
, 0);
14217 _LoadBoundInstances(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES
));
14219 if(!IsPositionValid())
14221 sLog
.outError("Player (guidlow %d) have invalid coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",guid
,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
14222 RelocateToHomebind();
14226 m_movementInfo
.t_x
= 0.0f
;
14227 m_movementInfo
.t_y
= 0.0f
;
14228 m_movementInfo
.t_z
= 0.0f
;
14229 m_movementInfo
.t_o
= 0.0f
;
14230 m_movementInfo
.t_time
= 0;
14231 m_movementInfo
.t_seat
= -1;
14234 _LoadBGData(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADBGDATA
));
14236 if(m_bgData
.bgInstanceID
) //saved in BattleGround
14238 BattleGround
*currentBg
= sBattleGroundMgr
.GetBattleGround(m_bgData
.bgInstanceID
, BATTLEGROUND_TYPE_NONE
);
14240 if(currentBg
&& currentBg
->IsPlayerInBattleGround(GetGUID()))
14242 BattleGroundQueueTypeId bgQueueTypeId
= sBattleGroundMgr
.BGQueueTypeId(currentBg
->GetTypeID(), currentBg
->GetArenaType());
14243 AddBattleGroundQueueId(bgQueueTypeId
);
14245 m_bgData
.bgTypeID
= currentBg
->GetTypeID();
14247 //join player to battleground group
14248 currentBg
->EventPlayerLoggedIn(this, GetGUID());
14249 currentBg
->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), m_bgData
.bgTeam
);
14251 SetInviteForBattleGroundQueueType(bgQueueTypeId
,currentBg
->GetInstanceID());
14255 const WorldLocation
& _loc
= GetBattleGroundEntryPoint();
14256 SetLocationMapId(_loc
.mapid
);
14257 Relocate(_loc
.coord_x
, _loc
.coord_y
, _loc
.coord_z
, _loc
.orientation
);
14259 // We are not in BG anymore
14260 m_bgData
.bgInstanceID
= 0;
14265 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(GetMapId());
14266 // if server restart after player save in BG or area
14267 // player can have current coordinates in to BG/Arena map, fix this
14268 if(!mapEntry
|| mapEntry
->IsBattleGroundOrArena())
14270 const WorldLocation
& _loc
= GetBattleGroundEntryPoint();
14271 SetLocationMapId(_loc
.mapid
);
14272 Relocate(_loc
.coord_x
, _loc
.coord_y
, _loc
.coord_z
, _loc
.orientation
);
14276 if (transGUID
!= 0)
14278 m_movementInfo
.t_x
= fields
[27].GetFloat();
14279 m_movementInfo
.t_y
= fields
[28].GetFloat();
14280 m_movementInfo
.t_z
= fields
[29].GetFloat();
14281 m_movementInfo
.t_o
= fields
[30].GetFloat();
14283 if( !MaNGOS::IsValidMapCoord(
14284 GetPositionX()+m_movementInfo
.t_x
,GetPositionY()+m_movementInfo
.t_y
,
14285 GetPositionZ()+m_movementInfo
.t_z
,GetOrientation()+m_movementInfo
.t_o
) ||
14286 // transport size limited
14287 m_movementInfo
.t_x
> 50 || m_movementInfo
.t_y
> 50 || m_movementInfo
.t_z
> 50 )
14289 sLog
.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
14290 guid
,GetPositionX()+m_movementInfo
.t_x
,GetPositionY()+m_movementInfo
.t_y
,
14291 GetPositionZ()+m_movementInfo
.t_z
,GetOrientation()+m_movementInfo
.t_o
);
14293 RelocateToHomebind();
14295 m_movementInfo
.t_x
= 0.0f
;
14296 m_movementInfo
.t_y
= 0.0f
;
14297 m_movementInfo
.t_z
= 0.0f
;
14298 m_movementInfo
.t_o
= 0.0f
;
14299 m_movementInfo
.t_time
= 0;
14300 m_movementInfo
.t_seat
= -1;
14306 if (transGUID
!= 0)
14308 for (MapManager::TransportSet::const_iterator iter
= MapManager::Instance().m_Transports
.begin(); iter
!= MapManager::Instance().m_Transports
.end(); ++iter
)
14310 if( (*iter
)->GetGUIDLow() == transGUID
)
14312 MapEntry
const* transMapEntry
= sMapStore
.LookupEntry((*iter
)->GetMapId());
14313 // client without expansion support
14314 if(GetSession()->Expansion() < transMapEntry
->Expansion())
14316 sLog
.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter
)->GetMapId());
14320 m_transport
= *iter
;
14321 m_transport
->AddPassenger(this);
14322 SetLocationMapId(m_transport
->GetMapId());
14329 sLog
.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
14332 RelocateToHomebind();
14334 m_movementInfo
.t_x
= 0.0f
;
14335 m_movementInfo
.t_y
= 0.0f
;
14336 m_movementInfo
.t_z
= 0.0f
;
14337 m_movementInfo
.t_o
= 0.0f
;
14338 m_movementInfo
.t_time
= 0;
14339 m_movementInfo
.t_seat
= -1;
14344 else // not transport case
14346 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(GetMapId());
14347 // client without expansion support
14348 if(GetSession()->Expansion() < mapEntry
->Expansion())
14350 sLog
.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
14351 RelocateToHomebind();
14355 // NOW player must have valid map
14356 // load the player's map here if it's not already loaded
14357 SetMap(MapManager::Instance().CreateMap(GetMapId(), this));
14359 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14360 if(GetInstanceId() && !sInstanceSaveManager
.GetInstanceSave(GetInstanceId()))
14362 AreaTrigger
const* at
= objmgr
.GetMapEntranceTrigger(GetMapId());
14364 Relocate(at
->target_X
, at
->target_Y
, at
->target_Z
, at
->target_Orientation
);
14366 sLog
.outError("Player %s(GUID: %u) logged in to a reset instance (map: %u) and there is no area-trigger leading to this map. Thus he can't be ported back to the entrance. This _might_ be an exploit attempt.", GetName(), GetGUIDLow(), GetMapId());
14369 SaveRecallPosition();
14371 time_t now
= time(NULL
);
14372 time_t logoutTime
= time_t(fields
[23].GetUInt64());
14374 // since last logout (in seconds)
14375 uint64 time_diff
= uint64(now
- logoutTime
);
14377 // set value, including drunk invisibility detection
14378 // calculate sobering. after 15 minutes logged out, the player will be sober again
14380 if(time_diff
> 15*MINUTE
)
14383 soberFactor
= 1-time_diff
/(15.0f
*MINUTE
);
14384 uint16 newDrunkenValue
= uint16(soberFactor
*(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFE));
14385 SetDrunkValue(newDrunkenValue
);
14387 m_rest_bonus
= fields
[22].GetFloat();
14388 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14389 float bubble0
= 0.031;
14390 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14391 float bubble1
= 0.125;
14395 float bubble
= fields
[24].GetUInt32() > 0
14396 ? bubble1
*sWorld
.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY
)
14397 : bubble0
*sWorld
.getRate(RATE_REST_OFFLINE_IN_WILDERNESS
);
14399 SetRestBonus(GetRestBonus()+ time_diff
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
14402 m_cinematic
= fields
[19].GetUInt32();
14403 m_Played_time
[PLAYED_TIME_TOTAL
]= fields
[20].GetUInt32();
14404 m_Played_time
[PLAYED_TIME_LEVEL
]= fields
[21].GetUInt32();
14406 m_resetTalentsCost
= fields
[25].GetUInt32();
14407 m_resetTalentsTime
= time_t(fields
[26].GetUInt64());
14409 // reserve some flags
14410 uint32 old_safe_flags
= GetUInt32Value(PLAYER_FLAGS
) & ( PLAYER_FLAGS_HIDE_CLOAK
| PLAYER_FLAGS_HIDE_HELM
);
14412 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
) )
14413 SetUInt32Value(PLAYER_FLAGS
, 0 | old_safe_flags
);
14415 m_taxi
.LoadTaxiMask( fields
[18].GetString() ); // must be before InitTaxiNodesForLevel
14417 uint32 extraflags
= fields
[32].GetUInt32();
14419 m_stableSlots
= fields
[33].GetUInt32();
14420 if(m_stableSlots
> MAX_PET_STABLES
)
14422 sLog
.outError("Player can have not more %u stable slots, but have in DB %u",MAX_PET_STABLES
,uint32(m_stableSlots
));
14423 m_stableSlots
= MAX_PET_STABLES
;
14426 m_atLoginFlags
= fields
[34].GetUInt32();
14429 // Update Honor kills data
14430 m_lastHonorUpdateTime
= logoutTime
;
14431 UpdateHonorFields();
14433 m_deathExpireTime
= (time_t)fields
[37].GetUInt64();
14434 if(m_deathExpireTime
> now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
)
14435 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
-1;
14437 std::string taxi_nodes
= fields
[38].GetCppString();
14441 // clear channel spell data (if saved at channel spell casting)
14442 SetChannelObjectGUID(0);
14443 SetUInt32Value(UNIT_CHANNEL_SPELL
,0);
14445 // clear charm/summon related fields
14452 // reset some aura modifiers before aura apply
14453 SetFarSightGUID(0);
14454 SetUInt32Value(PLAYER_TRACK_CREATURES
, 0 );
14455 SetUInt32Value(PLAYER_TRACK_RESOURCES
, 0 );
14459 // make sure the unit is considered out of combat for proper loading
14462 // make sure the unit is considered not in duel for proper loading
14463 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
14464 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
14466 // remember loaded power/health values to restore after stats initialization and modifier applying
14467 uint32 savedHealth
= GetHealth();
14468 uint32 savedPower
[MAX_POWERS
];
14469 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
14470 savedPower
[i
] = GetPower(Powers(i
));
14472 // reset stats before loading any modifiers
14473 InitStatsForLevel();
14474 InitTaxiNodesForLevel();
14475 InitGlyphsForLevel();
14478 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14480 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14483 _LoadAuras(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS
), time_diff
);
14486 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14487 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
14488 m_deathState
= DEAD
;
14490 _LoadSpells(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS
));
14492 // after spell load, learn rewarded spell if need also
14493 _LoadQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS
));
14494 _LoadDailyQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS
));
14496 // after spell and quest load
14497 InitTalentForLevel();
14498 learnDefaultSpells();
14500 // must be before inventory (some items required reputation check)
14501 m_reputationMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION
));
14503 _LoadInventory(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY
), time_diff
);
14505 // update items with duration and realtime
14506 UpdateItemDuration(time_diff
, true);
14508 _LoadActions(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS
));
14510 // unread mails and next delivery time, actual mails not loaded
14511 _LoadMailInit(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT
), holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE
));
14513 m_social
= sSocialMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST
), GetGUIDLow());
14515 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14516 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14517 if(uint32 curTitle
= GetUInt32Value(PLAYER_CHOSEN_TITLE
))
14519 if(!HasTitle(curTitle
))
14520 SetUInt32Value(PLAYER_CHOSEN_TITLE
, 0);
14523 // Not finish taxi flight path
14524 if(m_bgData
.HasTaxiPath())
14526 m_taxi
.ClearTaxiDestinations();
14527 for (int i
= 0; i
< 2; ++i
)
14528 m_taxi
.AddTaxiDestination(m_bgData
.taxiPath
[i
]);
14530 else if(!m_taxi
.LoadTaxiDestinationsFromString(taxi_nodes
,GetTeam()))
14532 // problems with taxi path loading
14533 TaxiNodesEntry
const* nodeEntry
= NULL
;
14534 if(uint32 node_id
= m_taxi
.GetTaxiSource())
14535 nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
14537 if(!nodeEntry
) // don't know taxi start node, to homebind
14539 sLog
.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14540 RelocateToHomebind();
14542 else // have start node, to it
14544 sLog
.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14545 SetLocationMapId(nodeEntry
->map_id
);
14546 Relocate(nodeEntry
->x
, nodeEntry
->y
, nodeEntry
->z
,0.0f
);
14549 //we can be relocated from taxi and still have an outdated Map pointer!
14550 //so we need to get a new Map pointer!
14551 SetMap(MapManager::Instance().CreateMap(GetMapId(), this));
14552 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14554 m_taxi
.ClearTaxiDestinations();
14557 if(uint32 node_id
= m_taxi
.GetTaxiSource())
14559 // save source node as recall coord to prevent recall and fall from sky
14560 TaxiNodesEntry
const* nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
14561 assert(nodeEntry
); // checked in m_taxi.LoadTaxiDestinationsFromString
14562 m_recallMap
= nodeEntry
->map_id
;
14563 m_recallX
= nodeEntry
->x
;
14564 m_recallY
= nodeEntry
->y
;
14565 m_recallZ
= nodeEntry
->z
;
14567 // flight will started later
14570 // has to be called after last Relocate() in Player::LoadFromDB
14571 SetFallInformation(0, GetPositionZ());
14573 _LoadSpellCooldowns(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS
));
14575 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14576 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14578 RemoveAllAurasOnDeath();
14580 //apply all stat bonuses from items and auras
14581 SetCanModifyStats(true);
14584 // restore remembered power/health values (but not more max values)
14585 SetHealth(savedHealth
> GetMaxHealth() ? GetMaxHealth() : savedHealth
);
14586 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
14587 SetPower(Powers(i
),savedPower
[i
] > GetMaxPower(Powers(i
)) ? GetMaxPower(Powers(i
)) : savedPower
[i
]);
14589 sLog
.outDebug("The value of player %s after load item and aura is: ", m_name
.c_str());
14593 if(GetSession()->GetSecurity() > SEC_PLAYER
)
14595 switch(sWorld
.getConfig(CONFIG_GM_LOGIN_STATE
))
14598 case 0: break; // disable
14599 case 1: SetGameMaster(true); break; // enable
14600 case 2: // save state
14601 if(extraflags
& PLAYER_EXTRA_GM_ON
)
14602 SetGameMaster(true);
14606 switch(sWorld
.getConfig(CONFIG_GM_VISIBLE_STATE
))
14609 case 0: SetGMVisible(false); break; // invisible
14610 case 1: break; // visible
14611 case 2: // save state
14612 if(extraflags
& PLAYER_EXTRA_GM_INVISIBLE
)
14613 SetGMVisible(false);
14617 switch(sWorld
.getConfig(CONFIG_GM_ACCEPT_TICKETS
))
14620 case 0: break; // disable
14621 case 1: SetAcceptTicket(true); break; // enable
14622 case 2: // save state
14623 if(extraflags
& PLAYER_EXTRA_GM_ACCEPT_TICKETS
)
14624 SetAcceptTicket(true);
14628 switch(sWorld
.getConfig(CONFIG_GM_CHAT
))
14631 case 0: break; // disable
14632 case 1: SetGMChat(true); break; // enable
14633 case 2: // save state
14634 if(extraflags
& PLAYER_EXTRA_GM_CHAT
)
14639 switch(sWorld
.getConfig(CONFIG_GM_WISPERING_TO
))
14642 case 0: break; // disable
14643 case 1: SetAcceptWhispers(true); break; // enable
14644 case 2: // save state
14645 if(extraflags
& PLAYER_EXTRA_ACCEPT_WHISPERS
)
14646 SetAcceptWhispers(true);
14651 _LoadDeclinedNames(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES
));
14653 m_achievementMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS
), holder
->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS
));
14654 m_achievementMgr
.CheckAllAchievementCriteria();
14656 _LoadEquipmentSets(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADEQUIPMENTSETS
));
14661 bool Player::isAllowedToLoot(Creature
* creature
)
14663 if(Player
* recipient
= creature
->GetLootRecipient())
14665 if (recipient
== this)
14667 if( Group
* otherGroup
= recipient
->GetGroup())
14669 Group
* thisGroup
= GetGroup();
14672 return thisGroup
== otherGroup
;
14677 // prevent other players from looting if the recipient got disconnected
14678 return !creature
->hasLootRecipient();
14681 void Player::_LoadActions(QueryResult
*result
)
14683 m_actionButtons
.clear();
14685 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14691 Field
*fields
= result
->Fetch();
14693 uint8 button
= fields
[0].GetUInt8();
14694 uint32 action
= fields
[1].GetUInt32();
14695 uint8 type
= fields
[2].GetUInt8();
14697 if(ActionButton
* ab
= addActionButton(button
, action
, type
))
14698 ab
->uState
= ACTIONBUTTON_UNCHANGED
;
14701 sLog
.outError( " ...at loading, and will deleted in DB also");
14703 // Will deleted in DB at next save (it can create data until save but marked as deleted)
14704 m_actionButtons
[button
].uState
= ACTIONBUTTON_DELETED
;
14707 while( result
->NextRow() );
14713 void Player::_LoadAuras(QueryResult
*result
, uint32 timediff
)
14716 for (int i
= 0; i
< TOTAL_AURAS
; ++i
)
14717 m_modAuras
[i
].clear();
14719 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14725 Field
*fields
= result
->Fetch();
14726 uint64 caster_guid
= fields
[0].GetUInt64();
14727 uint32 spellid
= fields
[1].GetUInt32();
14728 uint32 effindex
= fields
[2].GetUInt32();
14729 uint32 stackcount
= fields
[3].GetUInt32();
14730 int32 damage
= (int32
)fields
[4].GetUInt32();
14731 int32 maxduration
= (int32
)fields
[5].GetUInt32();
14732 int32 remaintime
= (int32
)fields
[6].GetUInt32();
14733 int32 remaincharges
= (int32
)fields
[7].GetUInt32();
14735 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellid
);
14738 sLog
.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid
,effindex
);
14744 sLog
.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid
,effindex
);
14748 // negative effects should continue counting down after logout
14749 if (remaintime
!= -1 && !IsPositiveEffect(spellid
, effindex
))
14751 if(remaintime
<= int32(timediff
))
14754 remaintime
-= timediff
;
14757 // prevent wrong values of remaincharges
14758 if(spellproto
->procCharges
)
14760 if(remaincharges
<= 0 || remaincharges
> spellproto
->procCharges
)
14761 remaincharges
= spellproto
->procCharges
;
14767 for(uint32 i
=0; i
<stackcount
; ++i
)
14769 Aura
* aura
= CreateAura(spellproto
, effindex
, NULL
, this, NULL
);
14771 damage
= aura
->GetModifier()->m_amount
;
14773 // reset stolen single target auras
14774 if (caster_guid
!= GetGUID() && aura
->IsSingleTarget())
14775 aura
->SetIsSingleTarget(false);
14777 aura
->SetLoadedState(caster_guid
,damage
,maxduration
,remaintime
,remaincharges
);
14779 sLog
.outDetail("Added aura spellid %u, effect %u", spellproto
->Id
, effindex
);
14782 while( result
->NextRow() );
14787 if(getClass() == CLASS_WARRIOR
&& !HasAuraType(SPELL_AURA_MOD_SHAPESHIFT
))
14788 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
14791 void Player::_LoadGlyphAuras()
14793 for (uint8 i
= 0; i
< MAX_GLYPH_SLOT_INDEX
; ++i
)
14795 if (uint32 glyph
= GetGlyph(i
))
14797 if (GlyphPropertiesEntry
const *gp
= sGlyphPropertiesStore
.LookupEntry(glyph
))
14799 if (GlyphSlotEntry
const *gs
= sGlyphSlotStore
.LookupEntry(GetGlyphSlot(i
)))
14801 if(gp
->TypeFlags
== gs
->TypeFlags
)
14803 CastSpell(this, gp
->SpellId
, true);
14807 sLog
.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name
.c_str(), gp
->TypeFlags
, gs
->TypeFlags
);
14810 sLog
.outError("Player %s has not existing glyph slot entry %u on index %u", m_name
.c_str(), GetGlyphSlot(i
), i
);
14813 sLog
.outError("Player %s has not existing glyph entry %u on index %u", m_name
.c_str(), glyph
, i
);
14815 // On any error remove glyph
14821 void Player::LoadCorpse()
14825 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14829 if(Corpse
*corpse
= GetCorpse())
14831 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, corpse
&& !sMapStore
.LookupEntry(corpse
->GetMapId())->Instanceable() );
14835 //Prevent Dead Player login without corpse
14836 ResurrectPlayer(0.5f
);
14841 void Player::_LoadInventory(QueryResult
*result
, uint32 timediff
)
14843 //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());
14844 std::map
<uint64
, Bag
*> bagMap
; // fast guid lookup for bags
14845 //NOTE: the "order by `bag`" is important because it makes sure
14846 //the bagMap is filled before items in the bags are loaded
14847 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14848 //expected to be equipped before offhand items (TODO: fixme)
14850 uint32 zone
= GetZoneId();
14854 std::list
<Item
*> problematicItems
;
14856 // prevent items from being added to the queue when stored
14857 m_itemUpdateQueueBlocked
= true;
14860 Field
*fields
= result
->Fetch();
14861 uint32 bag_guid
= fields
[1].GetUInt32();
14862 uint8 slot
= fields
[2].GetUInt8();
14863 uint32 item_guid
= fields
[3].GetUInt32();
14864 uint32 item_id
= fields
[4].GetUInt32();
14866 ItemPrototype
const * proto
= objmgr
.GetItemPrototype(item_id
);
14870 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14871 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid
);
14872 sLog
.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id
);
14876 Item
*item
= NewItemOrBag(proto
);
14878 if(!item
->LoadFromDB(item_guid
, GetGUID(), result
))
14880 sLog
.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id
);
14881 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14882 item
->FSetState(ITEM_REMOVED
);
14883 item
->SaveToDB(); // it also deletes item object !
14887 // not allow have in alive state item limited to another map/zone
14888 if(isAlive() && item
->IsLimitedToAnotherMapOrZone(GetMapId(),zone
) )
14890 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14891 item
->FSetState(ITEM_REMOVED
);
14892 item
->SaveToDB(); // it also deletes item object !
14896 // "Conjured items disappear if you are logged out for more than 15 minutes"
14897 if ((timediff
> 15*60) && (item
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_CONJURED
)))
14899 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14900 item
->FSetState(ITEM_REMOVED
);
14901 item
->SaveToDB(); // it also deletes item object !
14905 bool success
= true;
14909 // the item is not in a bag
14910 item
->SetContainer( NULL
);
14911 item
->SetSlot(slot
);
14913 if( IsInventoryPos( INVENTORY_SLOT_BAG_0
, slot
) )
14915 ItemPosCountVec dest
;
14916 if( CanStoreItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false ) == EQUIP_ERR_OK
)
14917 item
= StoreItem(dest
, item
, true);
14921 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0
, slot
) )
14924 if( CanEquipItem( slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
14925 QuickEquipItem(dest
, item
);
14929 else if( IsBankPos( INVENTORY_SLOT_BAG_0
, slot
) )
14931 ItemPosCountVec dest
;
14932 if( CanBankItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
14933 item
= BankItem(dest
, item
, true);
14940 // store bags that may contain items in them
14941 if(item
->IsBag() && IsBagPos(item
->GetPos()))
14942 bagMap
[item_guid
] = (Bag
*)item
;
14947 item
->SetSlot(NULL_SLOT
);
14948 // the item is in a bag, find the bag
14949 std::map
<uint64
, Bag
*>::const_iterator itr
= bagMap
.find(bag_guid
);
14950 if(itr
!= bagMap
.end() && slot
< itr
->second
->GetBagSize())
14951 itr
->second
->StoreItem(slot
, item
, true );
14956 // item's state may have changed after stored
14958 item
->SetState(ITEM_UNCHANGED
, this);
14961 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
);
14962 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14963 problematicItems
.push_back(item
);
14965 } while (result
->NextRow());
14968 m_itemUpdateQueueBlocked
= false;
14970 // send by mail problematic items
14971 while(!problematicItems
.empty())
14974 MailItemsInfo mi
; // item list preparing
14976 for(int i
= 0; !problematicItems
.empty() && i
< MAX_MAIL_ITEMS
; ++i
)
14978 Item
* item
= problematicItems
.front();
14979 problematicItems
.pop_front();
14981 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
14984 std::string subject
= GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM
);
14986 WorldSession::SendMailTo(this, MAIL_NORMAL
, MAIL_STATIONERY_GM
, GetGUIDLow(), GetGUIDLow(), subject
, 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
);
14990 _ApplyAllItemMods();
14993 // load mailed item which should receive current player
14994 void Player::_LoadMailedItems(Mail
*mail
)
14996 // data needs to be at first place for Item::LoadFromDB
14997 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
);
15003 Field
*fields
= result
->Fetch();
15004 uint32 item_guid_low
= fields
[1].GetUInt32();
15005 uint32 item_template
= fields
[2].GetUInt32();
15007 mail
->AddItem(item_guid_low
, item_template
);
15009 ItemPrototype
const *proto
= objmgr
.GetItemPrototype(item_template
);
15013 sLog
.outError( "Player %u has unknown item_template (ProtoType) in mailed items(GUID: %u template: %u) in mail (%u), deleted.", GetGUIDLow(), item_guid_low
, item_template
,mail
->messageID
);
15014 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
15015 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low
);
15019 Item
*item
= NewItemOrBag(proto
);
15021 if(!item
->LoadFromDB(item_guid_low
, 0, result
))
15023 sLog
.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail
->messageID
, item_guid_low
);
15024 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
15025 item
->FSetState(ITEM_REMOVED
);
15026 item
->SaveToDB(); // it also deletes item object !
15031 } while (result
->NextRow());
15036 void Player::_LoadMailInit(QueryResult
*resultUnread
, QueryResult
*resultDelivery
)
15038 //set a count of unread mails
15039 //QueryResult *resultMails = CharacterDatabase.PQuery("SELECT COUNT(id) FROM mail WHERE receiver = '%u' AND (checked & 1)=0 AND deliver_time <= '" UI64FMTD "'", GUID_LOPART(playerGuid),(uint64)cTime);
15042 Field
*fieldMail
= resultUnread
->Fetch();
15043 unReadMails
= fieldMail
[0].GetUInt8();
15044 delete resultUnread
;
15047 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
15048 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
15049 if (resultDelivery
)
15051 Field
*fieldMail
= resultDelivery
->Fetch();
15052 m_nextMailDelivereTime
= (time_t)fieldMail
[0].GetUInt64();
15053 delete resultDelivery
;
15057 void Player::_LoadMail()
15060 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
15061 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());
15066 Field
*fields
= result
->Fetch();
15067 Mail
*m
= new Mail
;
15068 m
->messageID
= fields
[0].GetUInt32();
15069 m
->messageType
= fields
[1].GetUInt8();
15070 m
->sender
= fields
[2].GetUInt32();
15071 m
->receiver
= fields
[3].GetUInt32();
15072 m
->subject
= fields
[4].GetCppString();
15073 m
->itemTextId
= fields
[5].GetUInt32();
15074 bool has_items
= fields
[6].GetBool();
15075 m
->expire_time
= (time_t)fields
[7].GetUInt64();
15076 m
->deliver_time
= (time_t)fields
[8].GetUInt64();
15077 m
->money
= fields
[9].GetUInt32();
15078 m
->COD
= fields
[10].GetUInt32();
15079 m
->checked
= fields
[11].GetUInt32();
15080 m
->stationery
= fields
[12].GetUInt8();
15081 m
->mailTemplateId
= fields
[13].GetInt16();
15083 if(m
->mailTemplateId
&& !sMailTemplateStore
.LookupEntry(m
->mailTemplateId
))
15085 sLog
.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m
->messageID
, m
->mailTemplateId
);
15086 m
->mailTemplateId
= 0;
15089 m
->state
= MAIL_STATE_UNCHANGED
;
15092 _LoadMailedItems(m
);
15094 m_mail
.push_back(m
);
15095 } while( result
->NextRow() );
15098 m_mailsLoaded
= true;
15101 void Player::LoadPet()
15103 //fixme: the pet should still be loaded if the player is not in world
15104 // just not added to the map
15107 Pet
*pet
= new Pet
;
15108 if(!pet
->LoadPetFromDB(this,0,0,true))
15113 void Player::_LoadQuestStatus(QueryResult
*result
)
15115 mQuestStatus
.clear();
15119 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
15120 //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());
15126 Field
*fields
= result
->Fetch();
15128 uint32 quest_id
= fields
[0].GetUInt32();
15129 // used to be new, no delete?
15130 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
15134 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
15136 uint32 qstatus
= fields
[1].GetUInt32();
15137 if(qstatus
< MAX_QUEST_STATUS
)
15138 questStatusData
.m_status
= QuestStatus(qstatus
);
15141 questStatusData
.m_status
= QUEST_STATUS_NONE
;
15142 sLog
.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id
,qstatus
);
15145 questStatusData
.m_rewarded
= ( fields
[2].GetUInt8() > 0 );
15146 questStatusData
.m_explored
= ( fields
[3].GetUInt8() > 0 );
15148 time_t quest_time
= time_t(fields
[4].GetUInt64());
15150 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && !GetQuestRewardStatus(quest_id
) && questStatusData
.m_status
!= QUEST_STATUS_NONE
)
15152 AddTimedQuest( quest_id
);
15154 if (quest_time
<= sWorld
.GetGameTime())
15155 questStatusData
.m_timer
= 1;
15157 questStatusData
.m_timer
= (quest_time
- sWorld
.GetGameTime()) * IN_MILISECONDS
;
15162 questStatusData
.m_creatureOrGOcount
[0] = fields
[5].GetUInt32();
15163 questStatusData
.m_creatureOrGOcount
[1] = fields
[6].GetUInt32();
15164 questStatusData
.m_creatureOrGOcount
[2] = fields
[7].GetUInt32();
15165 questStatusData
.m_creatureOrGOcount
[3] = fields
[8].GetUInt32();
15166 questStatusData
.m_itemcount
[0] = fields
[9].GetUInt32();
15167 questStatusData
.m_itemcount
[1] = fields
[10].GetUInt32();
15168 questStatusData
.m_itemcount
[2] = fields
[11].GetUInt32();
15169 questStatusData
.m_itemcount
[3] = fields
[12].GetUInt32();
15171 questStatusData
.uState
= QUEST_UNCHANGED
;
15173 // add to quest log
15174 if (slot
< MAX_QUEST_LOG_SIZE
&&
15175 ((questStatusData
.m_status
== QUEST_STATUS_INCOMPLETE
||
15176 questStatusData
.m_status
== QUEST_STATUS_COMPLETE
||
15177 questStatusData
.m_status
== QUEST_STATUS_FAILED
) &&
15178 (!questStatusData
.m_rewarded
|| pQuest
->IsRepeatable())))
15180 SetQuestSlot(slot
, quest_id
, quest_time
);
15182 if (questStatusData
.m_status
== QUEST_STATUS_COMPLETE
)
15183 SetQuestSlotState(slot
, QUEST_STATE_COMPLETE
);
15185 if (questStatusData
.m_status
== QUEST_STATUS_FAILED
)
15186 SetQuestSlotState(slot
, QUEST_STATE_FAIL
);
15188 for(uint8 idx
= 0; idx
< QUEST_OBJECTIVES_COUNT
; ++idx
)
15189 if(questStatusData
.m_creatureOrGOcount
[idx
])
15190 SetQuestSlotCounter(slot
, idx
, questStatusData
.m_creatureOrGOcount
[idx
]);
15195 if(questStatusData
.m_rewarded
)
15197 // learn rewarded spell if unknown
15198 learnQuestRewardedSpells(pQuest
);
15200 // set rewarded title if any
15201 if(pQuest
->GetCharTitleId())
15203 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
15204 SetTitle(titleEntry
);
15207 if(pQuest
->GetBonusTalents())
15208 m_questRewardTalentCount
+= pQuest
->GetBonusTalents();
15211 sLog
.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData
.m_status
, quest_id
, GetGUIDLow());
15214 while( result
->NextRow() );
15219 // clear quest log tail
15220 for ( uint16 i
= slot
; i
< MAX_QUEST_LOG_SIZE
; ++i
)
15221 SetQuestSlot(i
, 0);
15224 void Player::_LoadDailyQuestStatus(QueryResult
*result
)
15226 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
15227 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
15229 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
15233 uint32 quest_daily_idx
= 0;
15237 if(quest_daily_idx
>= PLAYER_MAX_DAILY_QUESTS
) // max amount with exist data in query
15239 sLog
.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15243 Field
*fields
= result
->Fetch();
15245 uint32 quest_id
= fields
[0].GetUInt32();
15247 // save _any_ from daily quest times (it must be after last reset anyway)
15248 m_lastDailyQuestTime
= (time_t)fields
[1].GetUInt64();
15250 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
15254 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
15257 sLog
.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id
, GetGUIDLow());
15259 while( result
->NextRow() );
15264 m_DailyQuestChanged
= false;
15267 void Player::_LoadSpells(QueryResult
*result
)
15269 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
15275 Field
*fields
= result
->Fetch();
15277 addSpell(fields
[0].GetUInt32(), fields
[1].GetBool(), false, false, fields
[2].GetBool());
15279 while( result
->NextRow() );
15285 void Player::_LoadGroup(QueryResult
*result
)
15287 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
15290 uint64 leaderGuid
= MAKE_NEW_GUID((*result
)[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
15293 if (Group
* group
= objmgr
.GetGroupByLeader(leaderGuid
))
15295 uint8 subgroup
= group
->GetMemberGroup(GetGUID());
15296 SetGroup(group
, subgroup
);
15297 if (getLevel() >= LEVELREQUIREMENT_HEROIC
)
15299 // the group leader may change the instance difficulty while the player is offline
15300 SetDungeonDifficulty(group
->GetDungeonDifficulty());
15301 SetRaidDifficulty(group
->GetRaidDifficulty());
15307 void Player::_LoadBoundInstances(QueryResult
*result
)
15309 for(uint8 i
= 0; i
< MAX_DIFFICULTY
; ++i
)
15310 m_boundInstances
[i
].clear();
15312 Group
*group
= GetGroup();
15314 //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));
15319 Field
*fields
= result
->Fetch();
15320 bool perm
= fields
[1].GetBool();
15321 uint32 mapId
= fields
[2].GetUInt32();
15322 uint32 instanceId
= fields
[0].GetUInt32();
15323 uint8 difficulty
= fields
[3].GetUInt8();
15325 time_t resetTime
= (time_t)fields
[4].GetUInt64();
15326 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15327 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15328 // and in that case it is not used
15330 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(mapId
);
15331 if(!mapEntry
|| !mapEntry
->IsDungeon())
15333 sLog
.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId
);
15334 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
15338 if(difficulty
>= MAX_DIFFICULTY
)
15340 sLog
.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty
, mapId
);
15341 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
15345 MapDifficulty
const* mapDiff
= GetMapDifficultyData(mapId
,Difficulty(difficulty
));
15348 sLog
.outError("_LoadBoundInstances: player %s(%d) has bind to not existed difficulty %d instance for map %u", GetName(), GetGUIDLow(), difficulty
, mapId
);
15349 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
15355 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
);
15356 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
15360 // since non permanent binds are always solo bind, they can always be reset
15361 InstanceSave
*save
= sInstanceSaveManager
.AddInstanceSave(mapId
, instanceId
, Difficulty(difficulty
), resetTime
, !perm
, true);
15362 if(save
) BindToInstance(save
, perm
, true);
15363 } while(result
->NextRow());
15368 InstancePlayerBind
* Player::GetBoundInstance(uint32 mapid
, Difficulty difficulty
)
15370 // some instances only have one difficulty
15371 MapDifficulty
const* mapDiff
= GetMapDifficultyData(mapid
,difficulty
);
15375 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
15376 if(itr
!= m_boundInstances
[difficulty
].end())
15377 return &itr
->second
;
15382 void Player::UnbindInstance(uint32 mapid
, Difficulty difficulty
, bool unload
)
15384 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
15385 UnbindInstance(itr
, difficulty
, unload
);
15388 void Player::UnbindInstance(BoundInstancesMap::iterator
&itr
, Difficulty difficulty
, bool unload
)
15390 if(itr
!= m_boundInstances
[difficulty
].end())
15392 if(!unload
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr
->second
.save
->GetInstanceId());
15393 itr
->second
.save
->RemovePlayer(this); // save can become invalid
15394 m_boundInstances
[difficulty
].erase(itr
++);
15398 InstancePlayerBind
* Player::BindToInstance(InstanceSave
*save
, bool permanent
, bool load
)
15402 InstancePlayerBind
& bind
= m_boundInstances
[save
->GetDifficulty()][save
->GetMapId()];
15405 // update the save when the group kills a boss
15406 if(permanent
!= bind
.perm
|| save
!= bind
.save
)
15407 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());
15410 if(!load
) CharacterDatabase
.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save
->GetInstanceId(), permanent
);
15412 if(bind
.save
!= save
)
15414 if(bind
.save
) bind
.save
->RemovePlayer(this);
15415 save
->AddPlayer(this);
15418 if(permanent
) save
->SetCanReset(false);
15421 bind
.perm
= permanent
;
15422 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());
15429 void Player::SendRaidInfo()
15431 uint32 counter
= 0;
15433 WorldPacket
data(SMSG_RAID_INSTANCE_INFO
, 4);
15435 size_t p_counter
= data
.wpos();
15436 data
<< uint32(counter
); // placeholder
15438 time_t now
= time(NULL
);
15440 for(int i
= 0; i
< MAX_DIFFICULTY
; ++i
)
15442 for (BoundInstancesMap::const_iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15444 if(itr
->second
.perm
)
15446 InstanceSave
*save
= itr
->second
.save
;
15447 data
<< uint32(save
->GetMapId()); // map id
15448 data
<< uint32(save
->GetDifficulty()); // difficulty
15449 data
<< uint64(save
->GetInstanceId()); // instance id
15450 data
<< uint8(1); // expired = 0
15451 data
<< uint8(0); // extended = 1
15452 data
<< uint32(save
->GetResetTime() - now
); // reset time
15457 data
.put
<uint32
>(p_counter
, counter
);
15458 GetSession()->SendPacket(&data
);
15462 - called on every successful teleportation to a map
15464 void Player::SendSavedInstances()
15466 bool hasBeenSaved
= false;
15469 for(uint8 i
= 0; i
< MAX_DIFFICULTY
; ++i
)
15471 for (BoundInstancesMap::const_iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15473 if(itr
->second
.perm
) // only permanent binds are sent
15475 hasBeenSaved
= true;
15481 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15482 data
.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP
);
15483 data
<< uint32(hasBeenSaved
);
15484 GetSession()->SendPacket(&data
);
15489 for(uint8 i
= 0; i
< MAX_DIFFICULTY
; ++i
)
15491 for (BoundInstancesMap::const_iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15493 if(itr
->second
.perm
)
15495 data
.Initialize(SMSG_UPDATE_LAST_INSTANCE
);
15496 data
<< uint32(itr
->second
.save
->GetMapId());
15497 GetSession()->SendPacket(&data
);
15503 /// convert the player's binds to the group
15504 void Player::ConvertInstancesToGroup(Player
*player
, Group
*group
, uint64 player_guid
)
15506 bool has_binds
= false;
15507 bool has_solo
= false;
15509 if(player
) { player_guid
= player
->GetGUID(); if(!group
) group
= player
->GetGroup(); }
15510 assert(player_guid
);
15512 // copy all binds to the group, when changing leader it's assumed the character
15513 // will not have any solo binds
15517 for(uint8 i
= 0; i
< MAX_DIFFICULTY
; ++i
)
15519 for (BoundInstancesMap::iterator itr
= player
->m_boundInstances
[i
].begin(); itr
!= player
->m_boundInstances
[i
].end();)
15522 if(group
) group
->BindToInstance(itr
->second
.save
, itr
->second
.perm
, true);
15523 // permanent binds are not removed
15524 if(!itr
->second
.perm
)
15526 // increments itr in call
15527 player
->UnbindInstance(itr
, Difficulty(i
), true);
15536 // if the player's not online we don't know what binds it has
15537 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
));
15538 // the following should not get executed when changing leaders
15539 if(!player
|| has_solo
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid
));
15542 bool Player::_LoadHomeBind(QueryResult
*result
)
15544 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(), getClass());
15547 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
15552 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15555 Field
*fields
= result
->Fetch();
15556 m_homebindMapId
= fields
[0].GetUInt32();
15557 m_homebindZoneId
= fields
[1].GetUInt16();
15558 m_homebindX
= fields
[2].GetFloat();
15559 m_homebindY
= fields
[3].GetFloat();
15560 m_homebindZ
= fields
[4].GetFloat();
15563 MapEntry
const* bindMapEntry
= sMapStore
.LookupEntry(m_homebindMapId
);
15565 // accept saved data only for valid position (and non instanceable), and accessable
15566 if( MapManager::IsValidMapCoord(m_homebindMapId
,m_homebindX
,m_homebindY
,m_homebindZ
) &&
15567 !bindMapEntry
->Instanceable() && GetSession()->Expansion() >= bindMapEntry
->Expansion())
15572 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15577 m_homebindMapId
= info
->mapId
;
15578 m_homebindZoneId
= info
->zoneId
;
15579 m_homebindX
= info
->positionX
;
15580 m_homebindY
= info
->positionY
;
15581 m_homebindZ
= info
->positionZ
;
15583 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
);
15586 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
15587 m_homebindMapId
, m_homebindZoneId
, m_homebindX
, m_homebindY
, m_homebindZ
);
15592 /*********************************************************/
15593 /*** SAVE SYSTEM ***/
15594 /*********************************************************/
15596 void Player::SaveToDB()
15598 // delay auto save at any saves (manual, in code, or autosave)
15599 m_nextSave
= sWorld
.getConfig(CONFIG_INTERVAL_SAVE
);
15601 //lets allow only players in world to be saved
15602 if(IsBeingTeleportedFar())
15604 ScheduleDelayedOperation(DELAYED_SAVE_PLAYER
);
15608 // first save/honor gain after midnight will also update the player's honor fields
15609 UpdateHonorFields();
15611 sLog
.outDebug("The value of player %s at save: ", m_name
.c_str());
15614 CharacterDatabase
.BeginTransaction();
15616 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15618 std::string sql_name
= m_name
;
15619 CharacterDatabase
.escape_string(sql_name
);
15621 std::ostringstream ss
;
15622 ss
<< "INSERT INTO characters (guid,account,name,race,class,gender,level,xp,money,playerBytes,playerBytes2,playerFlags,"
15623 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15624 "taximask, online, cinematic, "
15625 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15626 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15627 "death_expire_time, taxi_path, arena_pending_points) VALUES ("
15628 << GetGUIDLow() << ", "
15629 << GetSession()->GetAccountId() << ", '"
15630 << sql_name
<< "', "
15631 << (uint32
)getRace() << ", "
15632 << (uint32
)getClass() << ", "
15633 << (uint32
)getGender() << ", "
15634 << getLevel() << ", "
15635 << GetUInt32Value(PLAYER_XP
) << ", "
15636 << GetMoney() << ", "
15637 << GetUInt32Value(PLAYER_BYTES
) << ", "
15638 << GetUInt32Value(PLAYER_BYTES_2
) << ", "
15639 << GetUInt32Value(PLAYER_FLAGS
) << ", ";
15641 if(!IsBeingTeleported())
15643 ss
<< GetMapId() << ", "
15644 << (uint32
)GetDungeonDifficulty() << ", "
15645 << finiteAlways(GetPositionX()) << ", "
15646 << finiteAlways(GetPositionY()) << ", "
15647 << finiteAlways(GetPositionZ()) << ", "
15648 << finiteAlways(GetOrientation()) << ", '";
15652 ss
<< GetTeleportDest().mapid
<< ", "
15653 << (uint32
)GetDungeonDifficulty() << ", "
15654 << finiteAlways(GetTeleportDest().coord_x
) << ", "
15655 << finiteAlways(GetTeleportDest().coord_y
) << ", "
15656 << finiteAlways(GetTeleportDest().coord_z
) << ", "
15657 << finiteAlways(GetTeleportDest().orientation
) << ", '";
15661 for( i
= 0; i
< m_valuesCount
; ++i
)
15663 ss
<< GetUInt32Value(i
) << " ";
15668 ss
<< m_taxi
<< ", "; // string with TaxiMaskSize numbers
15670 ss
<< (IsInWorld() ? 1 : 0) << ", ";
15672 ss
<< m_cinematic
<< ", ";
15674 ss
<< m_Played_time
[PLAYED_TIME_TOTAL
] << ", ";
15675 ss
<< m_Played_time
[PLAYED_TIME_LEVEL
] << ", ";
15677 ss
<< finiteAlways(m_rest_bonus
) << ", ";
15678 ss
<< (uint64
)time(NULL
) << ", ";
15679 ss
<< (HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
) ? 1 : 0) << ", ";
15680 //save, far from tavern/city
15681 //save, but in tavern/city
15682 ss
<< m_resetTalentsCost
<< ", ";
15683 ss
<< (uint64
)m_resetTalentsTime
<< ", ";
15685 ss
<< finiteAlways(m_movementInfo
.t_x
) << ", ";
15686 ss
<< finiteAlways(m_movementInfo
.t_y
) << ", ";
15687 ss
<< finiteAlways(m_movementInfo
.t_z
) << ", ";
15688 ss
<< finiteAlways(m_movementInfo
.t_o
) << ", ";
15690 ss
<< m_transport
->GetGUIDLow();
15695 ss
<< m_ExtraFlags
<< ", ";
15697 ss
<< uint32(m_stableSlots
) << ", "; // to prevent save uint8 as char
15699 ss
<< uint32(m_atLoginFlags
) << ", ";
15701 ss
<< GetZoneId() << ", ";
15703 ss
<< (uint64
)m_deathExpireTime
<< ", '";
15705 ss
<< m_taxi
.SaveTaxiDestinationsToString() << "', ";
15706 ss
<< "'0' "; // arena_pending_points
15709 CharacterDatabase
.Execute( ss
.str().c_str() );
15711 if(m_mailsUpdated
) //save mails only when needed
15716 _SaveQuestStatus();
15717 _SaveDailyQuestStatus();
15719 _SaveSpellCooldowns();
15722 m_achievementMgr
.SaveToDB();
15723 m_reputationMgr
.SaveToDB();
15724 _SaveEquipmentSets();
15725 GetSession()->SaveTutorialsData(); // changed only while character in game
15727 CharacterDatabase
.CommitTransaction();
15729 // save pet (hunter pet level and experience and all type pets health/mana).
15730 if(Pet
* pet
= GetPet())
15731 pet
->SavePetToDB(PET_SAVE_AS_CURRENT
);
15734 // fast save function for item/money cheating preventing - save only inventory and money state
15735 void Player::SaveInventoryAndGoldToDB()
15741 void Player::SaveGoldToDB()
15743 CharacterDatabase
.PExecute("UPDATE characters SET money = '%u' WHERE guid = '%u'", GetMoney(), GetGUIDLow());
15746 void Player::_SaveActions()
15748 for(ActionButtonList::iterator itr
= m_actionButtons
.begin(); itr
!= m_actionButtons
.end(); )
15750 switch (itr
->second
.uState
)
15752 case ACTIONBUTTON_NEW
:
15753 CharacterDatabase
.PExecute("INSERT INTO character_action (guid,button,action,type) VALUES ('%u', '%u', '%u', '%u')",
15754 GetGUIDLow(), (uint32
)itr
->first
, (uint32
)itr
->second
.GetAction(), (uint32
)itr
->second
.GetType() );
15755 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
15758 case ACTIONBUTTON_CHANGED
:
15759 CharacterDatabase
.PExecute("UPDATE character_action SET action = '%u', type = '%u' WHERE guid= '%u' AND button= '%u' ",
15760 (uint32
)itr
->second
.GetAction(), (uint32
)itr
->second
.GetType(), GetGUIDLow(), (uint32
)itr
->first
);
15761 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
15764 case ACTIONBUTTON_DELETED
:
15765 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32
)itr
->first
);
15766 m_actionButtons
.erase(itr
++);
15775 void Player::_SaveAuras()
15777 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15779 AuraMap
const& auras
= GetAuras();
15784 spellEffectPair lastEffectPair
= auras
.begin()->first
;
15785 uint32 stackCounter
= 1;
15787 for(AuraMap::const_iterator itr
= auras
.begin(); ; ++itr
)
15789 if(itr
== auras
.end() || lastEffectPair
!= itr
->first
)
15791 AuraMap::const_iterator itr2
= itr
;
15792 // save previous spellEffectPair to db
15795 //skip all auras from spells that are passive
15796 //do not save single target auras (unless they were cast by the player)
15797 if (!itr2
->second
->IsPassive() && (itr2
->second
->GetCasterGUID() == GetGUID() || !itr2
->second
->IsSingleTarget()))
15799 CharacterDatabase
.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15800 "VALUES ('%u', '" UI64FMTD
"' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15801 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()));
15804 if(itr
== auras
.end())
15808 if (lastEffectPair
== itr
->first
)
15812 lastEffectPair
= itr
->first
;
15818 void Player::_SaveInventory()
15820 // force items in buyback slots to new state
15821 // and remove those that aren't already
15822 for (uint8 i
= BUYBACK_SLOT_START
; i
< BUYBACK_SLOT_END
; ++i
)
15824 Item
*item
= m_items
[i
];
15825 if (!item
|| item
->GetState() == ITEM_NEW
) continue;
15826 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
15827 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item
->GetGUIDLow());
15828 m_items
[i
]->FSetState(ITEM_NEW
);
15831 // update enchantment durations
15832 for(EnchantDurationList::const_iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
15834 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
15838 if (m_itemUpdateQueue
.empty()) return;
15840 // do not save if the update queue is corrupt
15841 bool error
= false;
15842 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); ++i
)
15844 Item
*item
= m_itemUpdateQueue
[i
];
15845 if(!item
|| item
->GetState() == ITEM_REMOVED
) continue;
15846 Item
*test
= GetItemByPos( item
->GetBagSlot(), item
->GetSlot());
15850 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());
15853 else if (test
!= item
)
15855 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());
15862 sLog
.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15863 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED
);
15867 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); ++i
)
15869 Item
*item
= m_itemUpdateQueue
[i
];
15870 if(!item
) continue;
15872 Bag
*container
= item
->GetContainer();
15873 uint32 bag_guid
= container
? container
->GetGUIDLow() : 0;
15875 switch(item
->GetState())
15878 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());
15881 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());
15884 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
15886 case ITEM_UNCHANGED
:
15890 item
->SaveToDB(); // item have unchanged inventory record and can be save standalone
15892 m_itemUpdateQueue
.clear();
15895 void Player::_SaveMail()
15897 if (!m_mailsLoaded
)
15900 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
15903 if (m
->state
== MAIL_STATE_CHANGED
)
15905 CharacterDatabase
.PExecute("UPDATE mail SET itemTextId = '%u',has_items = '%u',expire_time = '" UI64FMTD
"', deliver_time = '" UI64FMTD
"',money = '%u',cod = '%u',checked = '%u' WHERE id = '%u'",
15906 m
->itemTextId
, m
->HasItems() ? 1 : 0, (uint64
)m
->expire_time
, (uint64
)m
->deliver_time
, m
->money
, m
->COD
, m
->checked
, m
->messageID
);
15907 if(m
->removedItems
.size())
15909 for(std::vector
<uint32
>::const_iterator itr2
= m
->removedItems
.begin(); itr2
!= m
->removedItems
.end(); ++itr2
)
15910 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2
);
15911 m
->removedItems
.clear();
15913 m
->state
= MAIL_STATE_UNCHANGED
;
15915 else if (m
->state
== MAIL_STATE_DELETED
)
15918 for(std::vector
<MailItemInfo
>::const_iterator itr2
= m
->items
.begin(); itr2
!= m
->items
.end(); ++itr2
)
15919 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2
->item_guid
);
15921 CharacterDatabase
.PExecute("DELETE FROM item_text WHERE id = '%u'", m
->itemTextId
);
15922 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", m
->messageID
);
15923 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m
->messageID
);
15927 //deallocate deleted mails...
15928 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); )
15930 if ((*itr
)->state
== MAIL_STATE_DELETED
)
15935 itr
= m_mail
.begin();
15941 m_mailsUpdated
= false;
15944 void Player::_SaveQuestStatus()
15946 // we don't need transactions here.
15947 for( QuestStatusMap::iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
15949 switch (i
->second
.uState
)
15952 CharacterDatabase
.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15953 "VALUES ('%u', '%u', '%u', '%u', '%u', '" UI64FMTD
"', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15954 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]);
15956 case QUEST_CHANGED
:
15957 CharacterDatabase
.PExecute("UPDATE character_queststatus SET status = '%u',rewarded = '%u',explored = '%u',timer = '" UI64FMTD
"',mobcount1 = '%u',mobcount2 = '%u',mobcount3 = '%u',mobcount4 = '%u',itemcount1 = '%u',itemcount2 = '%u',itemcount3 = '%u',itemcount4 = '%u' WHERE guid = '%u' AND quest = '%u' ",
15958 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
);
15960 case QUEST_UNCHANGED
:
15963 i
->second
.uState
= QUEST_UNCHANGED
;
15967 void Player::_SaveDailyQuestStatus()
15969 if(!m_DailyQuestChanged
)
15972 m_DailyQuestChanged
= false;
15974 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15976 // we don't need transactions here.
15977 CharacterDatabase
.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15978 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
15979 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
15980 CharacterDatabase
.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" UI64FMTD
"')",
15981 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
),uint64(m_lastDailyQuestTime
));
15984 void Player::_SaveSpells()
15986 for (PlayerSpellMap::iterator itr
= m_spells
.begin(), next
= m_spells
.begin(); itr
!= m_spells
.end();)
15988 if (itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->second
->state
== PLAYERSPELL_CHANGED
)
15989 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr
->first
);
15991 // add only changed/new not dependent spells
15992 if (!itr
->second
->dependent
&& (itr
->second
->state
== PLAYERSPELL_NEW
|| itr
->second
->state
== PLAYERSPELL_CHANGED
))
15993 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);
15995 if (itr
->second
->state
== PLAYERSPELL_REMOVED
)
15997 delete itr
->second
;
15998 m_spells
.erase(itr
++);
16002 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
16009 void Player::outDebugValues() const
16011 if(!sLog
.IsOutDebug()) // optimize disabled debug output
16014 sLog
.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA
));
16015 sLog
.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY
), GetStat(STAT_STRENGTH
));
16016 sLog
.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT
), GetStat(STAT_SPIRIT
));
16017 sLog
.outDebug("STAMINA is: \t\t%f",GetStat(STAT_STAMINA
));
16018 sLog
.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE
));
16019 sLog
.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY
), GetResistance(SPELL_SCHOOL_FIRE
));
16020 sLog
.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE
), GetResistance(SPELL_SCHOOL_FROST
));
16021 sLog
.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW
), GetResistance(SPELL_SCHOOL_ARCANE
));
16022 sLog
.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE
), GetFloatValue(UNIT_FIELD_MAXDAMAGE
));
16023 sLog
.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
));
16024 sLog
.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
));
16025 sLog
.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK
), GetAttackTime(RANGED_ATTACK
));
16028 /*********************************************************/
16029 /*** FLOOD FILTER SYSTEM ***/
16030 /*********************************************************/
16032 void Player::UpdateSpeakTime()
16034 // ignore chat spam protection for GMs in any mode
16035 if(GetSession()->GetSecurity() > SEC_PLAYER
)
16038 time_t current
= time (NULL
);
16039 if(m_speakTime
> current
)
16041 uint32 max_count
= sWorld
.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT
);
16046 if(m_speakCount
>= max_count
)
16048 // prevent overwrite mute time, if message send just before mutes set, for example.
16049 time_t new_mute
= current
+ sWorld
.getConfig(CONFIG_CHATFLOOD_MUTE_TIME
);
16050 if(GetSession()->m_muteTime
< new_mute
)
16051 GetSession()->m_muteTime
= new_mute
;
16059 m_speakTime
= current
+ sWorld
.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY
);
16062 bool Player::CanSpeak() const
16064 return GetSession()->m_muteTime
<= time (NULL
);
16067 /*********************************************************/
16068 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
16069 /*********************************************************/
16071 void Player::SendAttackSwingNotInRange()
16073 WorldPacket
data(SMSG_ATTACKSWING_NOTINRANGE
, 0);
16074 GetSession()->SendPacket( &data
);
16077 void Player::SavePositionInDB(uint32 mapid
, float x
,float y
,float z
,float o
,uint32 zone
,uint64 guid
)
16079 std::ostringstream ss
;
16080 ss
<< "UPDATE characters SET position_x='"<<x
<<"',position_y='"<<y
16081 << "',position_z='"<<z
<<"',orientation='"<<o
<<"',map='"<<mapid
16082 << "',zone='"<<zone
<<"',trans_x='0',trans_y='0',trans_z='0',"
16083 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
16084 sLog
.outDebug(ss
.str().c_str());
16085 CharacterDatabase
.Execute(ss
.str().c_str());
16088 void Player::SaveDataFieldToDB()
16090 std::ostringstream ss
;
16091 ss
<<"UPDATE characters SET data='";
16093 for(uint16 i
= 0; i
< m_valuesCount
; ++i
)
16095 ss
<< GetUInt32Value(i
) << " ";
16097 ss
<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
16099 CharacterDatabase
.Execute(ss
.str().c_str());
16102 bool Player::SaveValuesArrayInDB(Tokens
const& tokens
, uint64 guid
)
16104 std::ostringstream ss2
;
16105 ss2
<<"UPDATE characters SET data='";
16107 for (Tokens::const_iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
, ++i
)
16109 ss2
<<tokens
[i
]<<" ";
16111 ss2
<<"' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
16113 return CharacterDatabase
.Execute(ss2
.str().c_str());
16116 void Player::SetUInt32ValueInArray(Tokens
& tokens
,uint16 index
, uint32 value
)
16119 snprintf(buf
,11,"%u",value
);
16121 if(index
>= tokens
.size())
16124 tokens
[index
] = buf
;
16127 void Player::SetUInt32ValueInDB(uint16 index
, uint32 value
, uint64 guid
)
16130 if(!LoadValuesArrayFromDB(tokens
,guid
))
16133 if(index
>= tokens
.size())
16137 snprintf(buf
,11,"%u",value
);
16138 tokens
[index
] = buf
;
16140 SaveValuesArrayInDB(tokens
,guid
);
16143 void Player::SetFloatValueInDB(uint16 index
, float value
, uint64 guid
)
16146 memcpy(&temp
, &value
, sizeof(value
));
16147 Player::SetUInt32ValueInDB(index
, temp
, guid
);
16150 void Player::Customize(uint64 guid
, uint8 gender
, uint8 skin
, uint8 face
, uint8 hairStyle
, uint8 hairColor
, uint8 facialHair
)
16153 QueryResult
* result
= CharacterDatabase
.PQuery("SELECT playerBytes2 FROM characters WHERE guid = '%u'", GUID_LOPART(guid
));
16157 Field
* fields
= result
->Fetch();
16159 uint32 player_bytes2
= fields
[0].GetUInt32();
16160 player_bytes2
&= ~0xFF;
16161 player_bytes2
|= facialHair
;
16163 CharacterDatabase
.PExecute("UPDATE characters SET gender = '%u', playerBytes = '%u', playerBytes2 = '%u' WHERE guid = '%u'", gender
, skin
| (face
<< 8) | (hairStyle
<< 16) | (hairColor
<< 24), player_bytes2
, GUID_LOPART(guid
));
16168 void Player::SendAttackSwingDeadTarget()
16170 WorldPacket
data(SMSG_ATTACKSWING_DEADTARGET
, 0);
16171 GetSession()->SendPacket( &data
);
16174 void Player::SendAttackSwingCantAttack()
16176 WorldPacket
data(SMSG_ATTACKSWING_CANT_ATTACK
, 0);
16177 GetSession()->SendPacket( &data
);
16180 void Player::SendAttackSwingCancelAttack()
16182 WorldPacket
data(SMSG_CANCEL_COMBAT
, 0);
16183 GetSession()->SendPacket( &data
);
16186 void Player::SendAttackSwingBadFacingAttack()
16188 WorldPacket
data(SMSG_ATTACKSWING_BADFACING
, 0);
16189 GetSession()->SendPacket( &data
);
16192 void Player::SendAutoRepeatCancel(Unit
*target
)
16194 WorldPacket
data(SMSG_CANCEL_AUTO_REPEAT
, target
->GetPackGUID().size());
16195 data
.append(target
->GetPackGUID()); // may be it's target guid
16196 GetSession()->SendPacket( &data
);
16199 void Player::SendExplorationExperience(uint32 Area
, uint32 Experience
)
16201 WorldPacket
data( SMSG_EXPLORATION_EXPERIENCE
, 8 );
16203 data
<< Experience
;
16204 GetSession()->SendPacket(&data
);
16207 void Player::SendDungeonDifficulty(bool IsInGroup
)
16209 uint8 val
= 0x00000001;
16210 WorldPacket
data(MSG_SET_DUNGEON_DIFFICULTY
, 12);
16211 data
<< (uint32
)GetDungeonDifficulty();
16212 data
<< uint32(val
);
16213 data
<< uint32(IsInGroup
);
16214 GetSession()->SendPacket(&data
);
16217 void Player::SendRaidDifficulty(bool IsInGroup
)
16219 uint8 val
= 0x00000001;
16220 WorldPacket
data(MSG_SET_RAID_DIFFICULTY
, 12);
16221 data
<< uint32(GetRaidDifficulty());
16222 data
<< uint32(val
);
16223 data
<< uint32(IsInGroup
);
16224 GetSession()->SendPacket(&data
);
16227 void Player::SendResetFailedNotify(uint32 mapid
)
16229 WorldPacket
data(SMSG_RESET_FAILED_NOTIFY
, 4);
16230 data
<< uint32(mapid
);
16231 GetSession()->SendPacket(&data
);
16234 /// Reset all solo instances and optionally send a message on success for each
16235 void Player::ResetInstances(uint8 method
, bool isRaid
)
16237 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
16239 // we assume that when the difficulty changes, all instances that can be reset will be
16240 Difficulty diff
= GetDifficulty(isRaid
);
16242 for (BoundInstancesMap::iterator itr
= m_boundInstances
[diff
].begin(); itr
!= m_boundInstances
[diff
].end();)
16244 InstanceSave
*p
= itr
->second
.save
;
16245 const MapEntry
*entry
= sMapStore
.LookupEntry(itr
->first
);
16246 if(!entry
|| entry
->IsRaid() != isRaid
|| !p
->CanReset())
16252 if(method
== INSTANCE_RESET_ALL
)
16254 // the "reset all instances" method can only reset normal maps
16255 if(entry
->map_type
== MAP_RAID
|| diff
== DUNGEON_DIFFICULTY_HEROIC
)
16262 // if the map is loaded, reset it
16263 Map
*map
= MapManager::Instance().FindMap(p
->GetMapId(), p
->GetInstanceId());
16264 if(map
&& map
->IsDungeon())
16265 ((InstanceMap
*)map
)->Reset(method
);
16267 // since this is a solo instance there should not be any players inside
16268 if(method
== INSTANCE_RESET_ALL
|| method
== INSTANCE_RESET_CHANGE_DIFFICULTY
)
16269 SendResetInstanceSuccess(p
->GetMapId());
16272 m_boundInstances
[diff
].erase(itr
++);
16274 // the following should remove the instance save from the manager and delete it as well
16275 p
->RemovePlayer(this);
16279 void Player::SendResetInstanceSuccess(uint32 MapId
)
16281 WorldPacket
data(SMSG_INSTANCE_RESET
, 4);
16283 GetSession()->SendPacket(&data
);
16286 void Player::SendResetInstanceFailed(uint32 reason
, uint32 MapId
)
16288 // TODO: find what other fail reasons there are besides players in the instance
16289 WorldPacket
data(SMSG_INSTANCE_RESET_FAILED
, 4);
16292 GetSession()->SendPacket(&data
);
16295 /*********************************************************/
16296 /*** Update timers ***/
16297 /*********************************************************/
16299 ///checks the 15 afk reports per 5 minutes limit
16300 void Player::UpdateAfkReport(time_t currTime
)
16302 if(m_bgData
.bgAfkReportedTimer
<= currTime
)
16304 m_bgData
.bgAfkReportedCount
= 0;
16305 m_bgData
.bgAfkReportedTimer
= currTime
+5*MINUTE
;
16309 void Player::UpdateContestedPvP(uint32 diff
)
16311 if(!m_contestedPvPTimer
||isInCombat())
16313 if(m_contestedPvPTimer
<= diff
)
16315 ResetContestedPvP();
16318 m_contestedPvPTimer
-= diff
;
16321 void Player::UpdatePvPFlag(time_t currTime
)
16325 if(pvpInfo
.endTimer
== 0 || currTime
< (pvpInfo
.endTimer
+ 300))
16331 void Player::UpdateDuelFlag(time_t currTime
)
16333 if(!duel
|| duel
->startTimer
== 0 ||currTime
< duel
->startTimer
+ 3)
16336 SetUInt32Value(PLAYER_DUEL_TEAM
, 1);
16337 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 2);
16339 duel
->startTimer
= 0;
16340 duel
->startTime
= currTime
;
16341 duel
->opponent
->duel
->startTimer
= 0;
16342 duel
->opponent
->duel
->startTime
= currTime
;
16345 void Player::RemovePet(Pet
* pet
, PetSaveMode mode
, bool returnreagent
)
16350 if(returnreagent
&& (pet
|| m_temporaryUnsummonedPetNumber
))
16352 //returning of reagents only for players, so best done here
16353 uint32 spellId
= pet
? pet
->GetUInt32Value(UNIT_CREATED_BY_SPELL
) : m_oldpetspell
;
16354 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellId
);
16358 for(uint32 i
= 0; i
< 7; ++i
)
16360 if(spellInfo
->Reagent
[i
] > 0)
16362 ItemPosCountVec dest
; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16363 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, spellInfo
->Reagent
[i
], spellInfo
->ReagentCount
[i
] );
16364 if( msg
== EQUIP_ERR_OK
)
16366 Item
* item
= StoreNewItem( dest
, spellInfo
->Reagent
[i
], true);
16368 SendNewItem(item
,spellInfo
->ReagentCount
[i
],true,false);
16373 m_temporaryUnsummonedPetNumber
= 0;
16376 if(!pet
|| pet
->GetOwnerGUID()!=GetGUID())
16379 // only if current pet in slot
16380 switch(pet
->getPetType())
16386 RemoveGuardian(pet
);
16389 if(GetPetGUID() == pet
->GetGUID())
16398 switch(pet
->GetEntry())
16400 //warlock pets except imp are removed(?) when logging out
16405 mode
= PET_SAVE_NOT_IN_SLOT
;
16410 pet
->SavePetToDB(mode
);
16412 pet
->AddObjectToRemoveList();
16413 pet
->m_removed
= true;
16415 if(pet
->isControlled())
16417 RemovePetActionBar();
16420 SetGroupUpdateFlag(GROUP_UPDATE_PET
);
16424 void Player::RemoveMiniPet()
16426 if(Pet
* pet
= GetMiniPet())
16428 pet
->Remove(PET_SAVE_AS_DELETED
);
16433 Pet
* Player::GetMiniPet()
16437 return ObjectAccessor::GetPet(m_miniPet
);
16440 void Player::Uncharm()
16442 Unit
* charm
= GetCharm();
16446 charm
->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM
);
16447 charm
->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS
);
16450 void Player::BuildPlayerChat(WorldPacket
*data
, uint8 msgtype
, const std::string
& text
, uint32 language
) const
16452 *data
<< (uint8
)msgtype
;
16453 *data
<< (uint32
)language
;
16454 *data
<< (uint64
)GetGUID();
16455 *data
<< (uint32
)language
; //language 2.1.0 ?
16456 *data
<< (uint64
)GetGUID();
16457 *data
<< (uint32
)(text
.length()+1);
16459 *data
<< (uint8
)chatTag();
16462 void Player::Say(const std::string
& text
, const uint32 language
)
16464 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16465 BuildPlayerChat(&data
, CHAT_MSG_SAY
, text
, language
);
16466 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_SAY
),true);
16469 void Player::Yell(const std::string
& text
, const uint32 language
)
16471 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16472 BuildPlayerChat(&data
, CHAT_MSG_YELL
, text
, language
);
16473 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_YELL
),true);
16476 void Player::TextEmote(const std::string
& text
)
16478 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16479 BuildPlayerChat(&data
, CHAT_MSG_EMOTE
, text
, LANG_UNIVERSAL
);
16480 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE
),true, !sWorld
.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT
) );
16483 void Player::Whisper(const std::string
& text
, uint32 language
,uint64 receiver
)
16485 if (language
!= LANG_ADDON
) // if not addon data
16486 language
= LANG_UNIVERSAL
; // whispers should always be readable
16488 Player
*rPlayer
= objmgr
.GetPlayer(receiver
);
16490 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16491 if(!rPlayer
->isDND() || isGameMaster())
16493 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16494 BuildPlayerChat(&data
, CHAT_MSG_WHISPER
, text
, language
);
16495 rPlayer
->GetSession()->SendPacket(&data
);
16497 data
.Initialize(SMSG_MESSAGECHAT
, 200);
16498 rPlayer
->BuildPlayerChat(&data
, CHAT_MSG_REPLY
, text
, language
);
16499 GetSession()->SendPacket(&data
);
16503 // announce to player that player he is whispering to is dnd and cannot receive his message
16504 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND
, rPlayer
->GetName(), rPlayer
->dndMsg
.c_str());
16507 if(!isAcceptWhispers())
16509 SetAcceptWhispers(true);
16510 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON
);
16513 // announce to player that player he is whispering to is afk
16514 if(rPlayer
->isAFK())
16515 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK
, rPlayer
->GetName(), rPlayer
->afkMsg
.c_str());
16517 // if player whisper someone, auto turn of dnd to be able to receive an answer
16518 if(isDND() && !rPlayer
->isGameMaster())
16522 void Player::PetSpellInitialize()
16524 Pet
* pet
= GetPet();
16529 sLog
.outDebug("Pet Spells Groups");
16531 CharmInfo
*charmInfo
= pet
->GetCharmInfo();
16533 WorldPacket
data(SMSG_PET_SPELLS
, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX
+1+1);
16534 data
<< uint64(pet
->GetGUID());
16535 data
<< uint16(pet
->GetCreatureInfo()->family
); // creature family (required for pet talents)
16537 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState()) << uint16(0);
16540 charmInfo
->BuildActionBar(&data
);
16542 size_t spellsCountPos
= data
.wpos();
16546 data
<< uint8(addlist
); // placeholder
16548 if (pet
->IsPermanentPetFor(this))
16551 for (PetSpellMap::const_iterator itr
= pet
->m_spells
.begin(); itr
!= pet
->m_spells
.end(); ++itr
)
16553 if(itr
->second
.state
== PETSPELL_REMOVED
)
16556 data
<< uint32(MAKE_UNIT_ACTION_BUTTON(itr
->first
,itr
->second
.active
));
16561 data
.put
<uint8
>(spellsCountPos
, addlist
);
16563 uint8 cooldownsCount
= pet
->m_CreatureSpellCooldowns
.size() + pet
->m_CreatureCategoryCooldowns
.size();
16564 data
<< uint8(cooldownsCount
);
16566 time_t curTime
= time(NULL
);
16568 for(CreatureSpellCooldowns::const_iterator itr
= pet
->m_CreatureSpellCooldowns
.begin(); itr
!= pet
->m_CreatureSpellCooldowns
.end(); ++itr
)
16570 time_t cooldown
= (itr
->second
> curTime
) ? (itr
->second
- curTime
) * IN_MILISECONDS
: 0;
16572 data
<< uint32(itr
->first
); // spellid
16573 data
<< uint16(0); // spell category?
16574 data
<< uint32(cooldown
); // cooldown
16575 data
<< uint32(0); // category cooldown
16578 for(CreatureSpellCooldowns::const_iterator itr
= pet
->m_CreatureCategoryCooldowns
.begin(); itr
!= pet
->m_CreatureCategoryCooldowns
.end(); ++itr
)
16580 time_t cooldown
= (itr
->second
> curTime
) ? (itr
->second
- curTime
) * IN_MILISECONDS
: 0;
16582 data
<< uint32(itr
->first
); // spellid
16583 data
<< uint16(0); // spell category?
16584 data
<< uint32(0); // cooldown
16585 data
<< uint32(cooldown
); // category cooldown
16588 GetSession()->SendPacket(&data
);
16591 void Player::PossessSpellInitialize()
16593 Unit
* charm
= GetCharm();
16598 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
16602 sLog
.outError("Player::PossessSpellInitialize(): charm (GUID: %u TypeId: %u) has no charminfo!", charm
->GetGUIDLow(),charm
->GetTypeId());
16606 WorldPacket
data(SMSG_PET_SPELLS
, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX
+1+1);
16607 data
<< uint64(charm
->GetGUID());
16612 charmInfo
->BuildActionBar(&data
);
16614 data
<< uint8(0); // spells count
16615 data
<< uint8(0); // cooldowns count
16617 GetSession()->SendPacket(&data
);
16620 void Player::CharmSpellInitialize()
16622 Unit
* charm
= GetCharm();
16627 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
16630 sLog
.outError("Player::CharmSpellInitialize(): the player's charm (GUID: %u TypeId: %u) has no charminfo!", charm
->GetGUIDLow(),charm
->GetTypeId());
16636 if(charm
->GetTypeId() != TYPEID_PLAYER
)
16638 CreatureInfo
const *cinfo
= ((Creature
*)charm
)->GetCreatureInfo();
16640 if(cinfo
&& cinfo
->type
== CREATURE_TYPE_DEMON
&& getClass() == CLASS_WARLOCK
)
16642 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
16644 if(charmInfo
->GetCharmSpell(i
)->GetAction())
16650 WorldPacket
data(SMSG_PET_SPELLS
, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX
+1+4*addlist
+1);
16651 data
<< uint64(charm
->GetGUID());
16655 if(charm
->GetTypeId() != TYPEID_PLAYER
)
16656 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState()) << uint16(0);
16658 data
<< uint8(0) << uint8(0) << uint16(0);
16660 charmInfo
->BuildActionBar(&data
);
16662 data
<< uint8(addlist
);
16666 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
16668 CharmSpellEntry
*cspell
= charmInfo
->GetCharmSpell(i
);
16669 if(cspell
->GetAction())
16670 data
<< uint32(cspell
->packedData
);
16674 data
<< uint8(0); // cooldowns count
16676 GetSession()->SendPacket(&data
);
16679 void Player::RemovePetActionBar()
16681 WorldPacket
data(SMSG_PET_SPELLS
, 8);
16683 SendDirectMessage(&data
);
16686 bool Player::IsAffectedBySpellmod(SpellEntry
const *spellInfo
, SpellModifier
*mod
, Spell
const* spell
)
16688 if (!mod
|| !spellInfo
)
16691 if(mod
->charges
== -1 && mod
->lastAffected
) // marked as expired but locked until spell casting finish
16693 // prevent apply to any spell except spell that trigger expire
16696 if(mod
->lastAffected
!= spell
)
16699 else if(mod
->lastAffected
!= FindCurrentSpellBySpellId(spellInfo
->Id
))
16703 return spellmgr
.IsAffectedByMod(spellInfo
, mod
);
16706 void Player::AddSpellMod(SpellModifier
* mod
, bool apply
)
16708 uint16 Opcode
= (mod
->type
== SPELLMOD_FLAT
) ? SMSG_SET_FLAT_SPELL_MODIFIER
: SMSG_SET_PCT_SPELL_MODIFIER
;
16710 for(int eff
=0;eff
<96;++eff
)
16714 if (eff
<64) _mask
= uint64(1) << (eff
- 0);
16715 else _mask2
= uint64(1) << (eff
-64);
16716 if ( mod
->mask
& _mask
|| mod
->mask2
& _mask2
)
16719 for (SpellModList::const_iterator itr
= m_spellMods
[mod
->op
].begin(); itr
!= m_spellMods
[mod
->op
].end(); ++itr
)
16721 if ((*itr
)->type
== mod
->type
&& ((*itr
)->mask
& _mask
|| (*itr
)->mask2
& _mask2
))
16722 val
+= (*itr
)->value
;
16724 val
+= apply
? mod
->value
: -(mod
->value
);
16725 WorldPacket
data(Opcode
, (1+1+4));
16726 data
<< uint8(eff
);
16727 data
<< uint8(mod
->op
);
16728 data
<< int32(val
);
16729 SendDirectMessage(&data
);
16734 m_spellMods
[mod
->op
].push_back(mod
);
16737 if (mod
->charges
== -1)
16738 --m_SpellModRemoveCount
;
16739 m_spellMods
[mod
->op
].remove(mod
);
16744 void Player::RemoveSpellMods(Spell
const* spell
)
16746 if(!spell
|| (m_SpellModRemoveCount
== 0))
16749 for(int i
=0;i
<MAX_SPELLMOD
;++i
)
16751 for (SpellModList::const_iterator itr
= m_spellMods
[i
].begin(); itr
!= m_spellMods
[i
].end();)
16753 SpellModifier
*mod
= *itr
;
16756 if (mod
&& mod
->charges
== -1 && (mod
->lastAffected
== spell
|| mod
->lastAffected
==NULL
))
16758 RemoveAurasDueToSpell(mod
->spellId
);
16759 if (m_spellMods
[i
].empty())
16762 itr
= m_spellMods
[i
].begin();
16768 // send Proficiency
16769 void Player::SendProficiency(uint8 pr1
, uint32 pr2
)
16771 WorldPacket
data(SMSG_SET_PROFICIENCY
, 8);
16772 data
<< pr1
<< pr2
;
16773 GetSession()->SendPacket (&data
);
16776 void Player::RemovePetitionsAndSigns(uint64 guid
, uint32 type
)
16778 QueryResult
*result
= NULL
;
16780 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
16782 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16785 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.
16786 { // and SendPetitionQueryOpcode reads data from the DB
16787 Field
*fields
= result
->Fetch();
16788 uint64 ownerguid
= MAKE_NEW_GUID(fields
[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
16789 uint64 petitionguid
= MAKE_NEW_GUID(fields
[1].GetUInt32(), 0, HIGHGUID_ITEM
);
16791 // send update if charter owner in game
16792 Player
* owner
= objmgr
.GetPlayer(ownerguid
);
16794 owner
->GetSession()->SendPetitionQueryOpcode(petitionguid
);
16796 } while ( result
->NextRow() );
16801 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
16803 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16806 CharacterDatabase
.BeginTransaction();
16809 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid
));
16810 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid
));
16814 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16815 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16817 CharacterDatabase
.CommitTransaction();
16820 void Player::LeaveAllArenaTeams(uint64 guid
)
16822 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
));
16828 Field
*fields
= result
->Fetch();
16829 uint32 at_id
= fields
[0].GetUInt32();
16832 ArenaTeam
* at
= objmgr
.GetArenaTeamById(at_id
);
16834 at
->DelMember(guid
);
16836 } while (result
->NextRow());
16841 void Player::SetRestBonus (float rest_bonus_new
)
16843 // Prevent resting on max level
16844 if(getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
16845 rest_bonus_new
= 0;
16847 if(rest_bonus_new
< 0)
16848 rest_bonus_new
= 0;
16850 float rest_bonus_max
= (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)*1.5/2;
16852 if(rest_bonus_new
> rest_bonus_max
)
16853 m_rest_bonus
= rest_bonus_max
;
16855 m_rest_bonus
= rest_bonus_new
;
16857 // update data for client
16858 if(m_rest_bonus
>10)
16859 SetByteValue(PLAYER_BYTES_2
, 3, 0x01); // Set Reststate = Rested
16860 else if(m_rest_bonus
<=1)
16861 SetByteValue(PLAYER_BYTES_2
, 3, 0x02); // Set Reststate = Normal
16864 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE
, uint32(m_rest_bonus
));
16867 void Player::HandleStealthedUnitsDetection()
16869 std::list
<Unit
*> stealthedUnits
;
16871 CellPair
p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16873 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
16874 cell
.SetNoCreate();
16876 MaNGOS::AnyStealthedCheck u_check
;
16877 MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
> searcher(this,stealthedUnits
, u_check
);
16879 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, WorldTypeMapContainer
> world_unit_searcher(searcher
);
16880 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, GridTypeMapContainer
> grid_unit_searcher(searcher
);
16882 CellLock
<GridReadGuard
> cell_lock(cell
, p
);
16883 cell_lock
->Visit(cell_lock
, world_unit_searcher
, *GetMap(), *this, MAX_PLAYER_STEALTH_DETECT_RANGE
);
16884 cell_lock
->Visit(cell_lock
, grid_unit_searcher
, *GetMap(), *this, MAX_PLAYER_STEALTH_DETECT_RANGE
);
16886 WorldObject
const* viewPoint
= GetViewPoint();
16888 for (std::list
<Unit
*>::const_iterator i
= stealthedUnits
.begin(); i
!= stealthedUnits
.end(); ++i
)
16893 bool hasAtClient
= HaveAtClient((*i
));
16894 bool hasDetected
= (*i
)->isVisibleForOrDetect(this, viewPoint
, true);
16900 (*i
)->SendUpdateToPlayer(this);
16901 m_clientGUIDs
.insert((*i
)->GetGUID());
16903 #ifdef MANGOS_DEBUG
16904 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
16905 sLog
.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i
)->GetGUIDLow(),(*i
)->GetTypeId(),GetGUIDLow(),GetDistance(*i
));
16908 // target aura duration for caster show only if target exist at caster client
16909 // send data at target visibility change (adding to client)
16910 if((*i
)!=this && (*i
)->isType(TYPEMASK_UNIT
))
16911 SendAurasForTarget(*i
);
16918 (*i
)->DestroyForPlayer(this);
16919 m_clientGUIDs
.erase((*i
)->GetGUID());
16925 bool Player::ActivateTaxiPathTo(std::vector
<uint32
> const& nodes
, Creature
* npc
/*= NULL*/, uint32 spellid
/*= 0*/)
16927 if(nodes
.size() < 2)
16930 // 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
16931 if(GetSession()->isLogingOut() || isInCombat())
16933 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16934 data
<< uint32(ERR_TAXIPLAYERBUSY
);
16935 GetSession()->SendPacket(&data
);
16939 if(HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_DISABLE_MOVE
))
16945 // not let cheating with start flight mounted
16948 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16949 data
<< uint32(ERR_TAXIPLAYERALREADYMOUNTED
);
16950 GetSession()->SendPacket(&data
);
16954 if( m_ShapeShiftFormSpellId
&& m_form
!= FORM_BATTLESTANCE
&& m_form
!= FORM_BERSERKERSTANCE
&& m_form
!= FORM_DEFENSIVESTANCE
&& m_form
!= FORM_SHADOW
)
16956 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16957 data
<< uint32(ERR_TAXIPLAYERSHAPESHIFTED
);
16958 GetSession()->SendPacket(&data
);
16962 // 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
16963 if(IsNonMeleeSpellCasted(false))
16965 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16966 data
<< uint32(ERR_TAXIPLAYERBUSY
);
16967 GetSession()->SendPacket(&data
);
16971 // cast case or scripted call case
16974 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED
);
16976 if( m_ShapeShiftFormSpellId
&& m_form
!= FORM_BATTLESTANCE
&& m_form
!= FORM_BERSERKERSTANCE
&& m_form
!= FORM_DEFENSIVESTANCE
&& m_form
!= FORM_SHADOW
)
16977 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId
);
16979 if (Spell
* spell
= GetCurrentSpell(CURRENT_GENERIC_SPELL
))
16980 if (spell
->m_spellInfo
->Id
!= spellid
)
16981 InterruptSpell(CURRENT_GENERIC_SPELL
,false);
16983 InterruptSpell(CURRENT_AUTOREPEAT_SPELL
,false);
16985 if (Spell
* spell
= GetCurrentSpell(CURRENT_CHANNELED_SPELL
))
16986 if (spell
->m_spellInfo
->Id
!= spellid
)
16987 InterruptSpell(CURRENT_CHANNELED_SPELL
,true);
16990 uint32 sourcenode
= nodes
[0];
16992 // starting node too far away (cheat?)
16993 TaxiNodesEntry
const* node
= sTaxiNodesStore
.LookupEntry(sourcenode
);
16996 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16997 data
<< uint32(ERR_TAXINOSUCHPATH
);
16998 GetSession()->SendPacket(&data
);
17002 // check node starting pos data set case if provided
17003 if (node
->x
!= 0.0f
|| node
->y
!= 0.0f
|| node
->z
!= 0.0f
)
17005 if (node
->map_id
!= GetMapId() ||
17006 (node
->x
- GetPositionX())*(node
->x
- GetPositionX())+
17007 (node
->y
- GetPositionY())*(node
->y
- GetPositionY())+
17008 (node
->z
- GetPositionZ())*(node
->z
- GetPositionZ()) >
17009 (2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
))
17011 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17012 data
<< uint32(ERR_TAXITOOFARAWAY
);
17013 GetSession()->SendPacket(&data
);
17017 // node must have pos if taxi master case (npc != NULL)
17020 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17021 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
17022 GetSession()->SendPacket(&data
);
17026 // Prepare to flight start now
17028 // stop combat at start taxi flight if any
17031 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
17034 // clean not finished taxi path if any
17035 m_taxi
.ClearTaxiDestinations();
17037 // 0 element current node
17038 m_taxi
.AddTaxiDestination(sourcenode
);
17040 // fill destinations path tail
17041 uint32 sourcepath
= 0;
17042 uint32 totalcost
= 0;
17044 uint32 prevnode
= sourcenode
;
17045 uint32 lastnode
= 0;
17047 for(uint32 i
= 1; i
< nodes
.size(); ++i
)
17051 lastnode
= nodes
[i
];
17052 objmgr
.GetTaxiPath(prevnode
, lastnode
, path
, cost
);
17056 m_taxi
.ClearTaxiDestinations();
17062 if(prevnode
== sourcenode
)
17065 m_taxi
.AddTaxiDestination(lastnode
);
17067 prevnode
= lastnode
;
17070 // get mount model (in case non taximaster (npc==NULL) allow more wide lookup)
17071 uint32 mount_display_id
= objmgr
.GetTaxiMountDisplayId(sourcenode
, GetTeam(), npc
== NULL
);
17073 // in spell case allow 0 model
17074 if ((mount_display_id
== 0 && spellid
== 0) || sourcepath
== 0)
17076 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17077 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
17078 GetSession()->SendPacket(&data
);
17079 m_taxi
.ClearTaxiDestinations();
17083 uint32 money
= GetMoney();
17086 totalcost
= (uint32
)ceil(totalcost
*GetReputationPriceDiscount(npc
));
17088 if(money
< totalcost
)
17090 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17091 data
<< uint32(ERR_TAXINOTENOUGHMONEY
);
17092 GetSession()->SendPacket(&data
);
17093 m_taxi
.ClearTaxiDestinations();
17097 //Checks and preparations done, DO FLIGHT
17098 ModifyMoney(-(int32
)totalcost
);
17099 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING
, totalcost
);
17100 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN
, 1);
17102 // prevent stealth flight
17103 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH
);
17105 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17106 data
<< uint32(ERR_TAXIOK
);
17107 GetSession()->SendPacket(&data
);
17109 sLog
.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
17111 GetSession()->SendDoFlight(mount_display_id
, sourcepath
);
17116 bool Player::ActivateTaxiPathTo( uint32 taxi_path_id
, uint32 spellid
/*= 0*/ )
17118 TaxiPathEntry
const* entry
= sTaxiPathStore
.LookupEntry(taxi_path_id
);
17122 std::vector
<uint32
> nodes
;
17125 nodes
[0] = entry
->from
;
17126 nodes
[1] = entry
->to
;
17128 return ActivateTaxiPathTo(nodes
,NULL
,spellid
);
17131 void Player::ContinueTaxiFlight()
17133 uint32 sourceNode
= m_taxi
.GetTaxiSource();
17137 sLog
.outDebug( "WORLD: Restart character %u taxi flight", GetGUIDLow() );
17139 uint32 mountDisplayId
= objmgr
.GetTaxiMountDisplayId(sourceNode
, GetTeam(),true);
17140 uint32 path
= m_taxi
.GetCurrentTaxiPath();
17142 // search appropriate start path node
17143 uint32 startNode
= 0;
17145 TaxiPathNodeList
const& nodeList
= sTaxiPathNodesByPath
[path
];
17147 float distPrev
= MAP_SIZE
*MAP_SIZE
;
17149 (nodeList
[0].x
-GetPositionX())*(nodeList
[0].x
-GetPositionX())+
17150 (nodeList
[0].y
-GetPositionY())*(nodeList
[0].y
-GetPositionY())+
17151 (nodeList
[0].z
-GetPositionZ())*(nodeList
[0].z
-GetPositionZ());
17153 for(uint32 i
= 1; i
< nodeList
.size(); ++i
)
17155 TaxiPathNode
const& node
= nodeList
[i
];
17156 TaxiPathNode
const& prevNode
= nodeList
[i
-1];
17158 // skip nodes at another map
17159 if(node
.mapid
!= GetMapId())
17162 distPrev
= distNext
;
17165 (node
.x
-GetPositionX())*(node
.x
-GetPositionX())+
17166 (node
.y
-GetPositionY())*(node
.y
-GetPositionY())+
17167 (node
.z
-GetPositionZ())*(node
.z
-GetPositionZ());
17170 (node
.x
-prevNode
.x
)*(node
.x
-prevNode
.x
)+
17171 (node
.y
-prevNode
.y
)*(node
.y
-prevNode
.y
)+
17172 (node
.z
-prevNode
.z
)*(node
.z
-prevNode
.z
);
17174 if(distNext
+ distPrev
< distNodes
)
17181 GetSession()->SendDoFlight(mountDisplayId
, path
, startNode
);
17184 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask
, uint32 unTimeMs
)
17186 // last check 2.0.10
17187 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+m_spells
.size()*8);
17189 data
<< uint8(0x0); // flags (0x1, 0x2)
17190 time_t curTime
= time(NULL
);
17191 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
17193 if (itr
->second
->state
== PLAYERSPELL_REMOVED
)
17195 uint32 unSpellId
= itr
->first
;
17196 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(unSpellId
);
17203 // Not send cooldown for this spells
17204 if (spellInfo
->Attributes
& SPELL_ATTR_DISABLED_WHILE_ACTIVE
)
17207 if((idSchoolMask
& GetSpellSchoolMask(spellInfo
)) && GetSpellCooldownDelay(unSpellId
) < unTimeMs
)
17209 data
<< uint32(unSpellId
);
17210 data
<< uint32(unTimeMs
); // in m.secs
17211 AddSpellCooldown(unSpellId
, 0, curTime
+ unTimeMs
/IN_MILISECONDS
);
17214 GetSession()->SendPacket(&data
);
17217 void Player::InitDataForForm(bool reapplyMods
)
17219 SpellShapeshiftEntry
const* ssEntry
= sSpellShapeshiftStore
.LookupEntry(m_form
);
17220 if(ssEntry
&& ssEntry
->attackSpeed
)
17222 SetAttackTime(BASE_ATTACK
,ssEntry
->attackSpeed
);
17223 SetAttackTime(OFF_ATTACK
,ssEntry
->attackSpeed
);
17224 SetAttackTime(RANGED_ATTACK
, BASE_ATTACK_TIME
);
17227 SetRegularAttackTime();
17233 if(getPowerType()!=POWER_ENERGY
)
17234 setPowerType(POWER_ENERGY
);
17238 case FORM_DIREBEAR
:
17240 if(getPowerType()!=POWER_RAGE
)
17241 setPowerType(POWER_RAGE
);
17244 default: // 0, for example
17246 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(getClass());
17247 if(cEntry
&& cEntry
->powerType
< MAX_POWERS
&& uint32(getPowerType()) != cEntry
->powerType
)
17248 setPowerType(Powers(cEntry
->powerType
));
17253 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
17255 UpdateEquipSpellsAtFormChange();
17257 UpdateAttackPowerAndDamage();
17258 UpdateAttackPowerAndDamage(true);
17261 void Player::InitDisplayIds()
17263 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(), getClass());
17266 sLog
.outError("Player %u has incorrect race/class pair. Can't init display ids.", GetGUIDLow());
17270 uint8 gender
= getGender();
17273 case GENDER_FEMALE
:
17274 SetDisplayId(info
->displayId_f
);
17275 SetNativeDisplayId(info
->displayId_f
);
17278 SetDisplayId(info
->displayId_m
);
17279 SetNativeDisplayId(info
->displayId_m
);
17282 sLog
.outError("Invalid gender %u for player",gender
);
17287 // Return true is the bought item has a max count to force refresh of window by caller
17288 bool Player::BuyItemFromVendor(uint64 vendorguid
, uint32 item
, uint8 count
, uint8 bag
, uint8 slot
)
17290 // cheating attempt
17291 if (count
< 1) count
= 1;
17296 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
17299 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, NULL
, item
, 0);
17303 Creature
*pCreature
= GetNPCIfCanInteractWith(vendorguid
,UNIT_NPC_FLAG_VENDOR
);
17306 sLog
.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid
)) );
17307 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR
, NULL
, item
, 0);
17311 VendorItemData
const* vItems
= pCreature
->GetVendorItems();
17312 if(!vItems
|| vItems
->Empty())
17314 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
17318 size_t vendor_slot
= vItems
->FindItemSlot(item
);
17319 if (vendor_slot
>= vItems
->GetItemCount())
17321 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
17325 VendorItem
const* crItem
= vItems
->m_items
[vendor_slot
];
17327 // check current item amount if it limited
17328 if (crItem
->maxcount
!= 0)
17330 if (pCreature
->GetVendorItemCurrentCount(crItem
) < pProto
->BuyCount
* count
)
17332 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD
, pCreature
, item
, 0);
17337 if (uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
17339 SendBuyError( BUY_ERR_REPUTATION_REQUIRE
, pCreature
, item
, 0);
17343 if (crItem
->ExtendedCost
)
17345 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
17348 sLog
.outError("Item %u have wrong ExtendedCost field value %u", pProto
->ItemId
, crItem
->ExtendedCost
);
17352 // honor points price
17353 if (GetHonorPoints() < (iece
->reqhonorpoints
* count
))
17355 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS
, NULL
, NULL
);
17359 // arena points price
17360 if (GetArenaPoints() < (iece
->reqarenapoints
* count
))
17362 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS
, NULL
, NULL
);
17367 for (uint8 i
= 0; i
< 5; ++i
)
17369 if(iece
->reqitem
[i
] && !HasItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
)))
17371 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS
, NULL
, NULL
);
17376 // check for personal arena rating requirement
17377 if( GetMaxPersonalArenaRatingRequirement() < iece
->reqpersonalarenarating
)
17379 // probably not the proper equip err
17380 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK
,NULL
,NULL
);
17385 uint32 price
= pProto
->BuyPrice
* count
;
17387 // reputation discount
17388 price
= uint32(floor(price
* GetReputationPriceDiscount(pCreature
)));
17390 if (GetMoney() < price
)
17392 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, pCreature
, item
, 0);
17396 if ((bag
== NULL_BAG
&& slot
== NULL_SLOT
) || IsInventoryPos(bag
, slot
))
17398 ItemPosCountVec dest
;
17399 uint8 msg
= CanStoreNewItem( bag
, slot
, dest
, item
, pProto
->BuyCount
* count
);
17400 if (msg
!= EQUIP_ERR_OK
)
17402 SendEquipError( msg
, NULL
, NULL
);
17406 ModifyMoney( -(int32
)price
);
17407 if (crItem
->ExtendedCost
) // case for new honor system
17409 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
17410 if (iece
->reqhonorpoints
)
17411 ModifyHonorPoints( - int32(iece
->reqhonorpoints
* count
));
17412 if (iece
->reqarenapoints
)
17413 ModifyArenaPoints( - int32(iece
->reqarenapoints
* count
));
17414 for (uint8 i
= 0; i
< 5; ++i
)
17416 if (iece
->reqitem
[i
])
17417 DestroyItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
), true);
17421 if (Item
*it
= StoreNewItem( dest
, item
, true ))
17423 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
17425 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
17426 data
<< uint64(pCreature
->GetGUID());
17427 data
<< uint32(vendor_slot
+1); // numbered from 1 at client
17428 data
<< uint32(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
17429 data
<< uint32(count
);
17430 GetSession()->SendPacket(&data
);
17432 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
17435 else if (IsEquipmentPos(bag
, slot
))
17437 if (pProto
->BuyCount
* count
!= 1)
17439 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
, NULL
, NULL
);
17444 uint8 msg
= CanEquipNewItem( slot
, dest
, item
, false );
17445 if (msg
!= EQUIP_ERR_OK
)
17447 SendEquipError( msg
, NULL
, NULL
);
17451 ModifyMoney( -(int32
)price
);
17452 if (crItem
->ExtendedCost
) // case for new honor system
17454 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
17455 if (iece
->reqhonorpoints
)
17456 ModifyHonorPoints( - int32(iece
->reqhonorpoints
));
17457 if (iece
->reqarenapoints
)
17458 ModifyArenaPoints( - int32(iece
->reqarenapoints
));
17459 for (uint8 i
= 0; i
< 5; ++i
)
17461 if(iece
->reqitem
[i
])
17462 DestroyItemCount(iece
->reqitem
[i
], iece
->reqitemcount
[i
], true);
17466 if (Item
*it
= EquipNewItem( dest
, item
, true ))
17468 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
17470 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
17471 data
<< uint64(pCreature
->GetGUID());
17472 data
<< uint32(vendor_slot
+ 1); // numbered from 1 at client
17473 data
<< uint32(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
17474 data
<< uint32(count
);
17475 GetSession()->SendPacket(&data
);
17477 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
17479 AutoUnequipOffhandIfNeed();
17484 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
, NULL
, NULL
);
17488 return crItem
->maxcount
!= 0;
17491 uint32
Player::GetMaxPersonalArenaRatingRequirement()
17493 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17494 // the personal rating of the arena team must match the required limit as well
17495 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17496 uint32 max_personal_rating
= 0;
17497 for(int i
= 0; i
< MAX_ARENA_SLOT
; ++i
)
17499 if(ArenaTeam
* at
= objmgr
.GetArenaTeamById(GetArenaTeamId(i
)))
17501 uint32 p_rating
= GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ (i
* ARENA_TEAM_END
) + ARENA_TEAM_PERSONAL_RATING
);
17502 uint32 t_rating
= at
->GetRating();
17503 p_rating
= p_rating
< t_rating
? p_rating
: t_rating
;
17504 if(max_personal_rating
< p_rating
)
17505 max_personal_rating
= p_rating
;
17508 return max_personal_rating
;
17511 void Player::UpdateHomebindTime(uint32 time
)
17513 // GMs never get homebind timer online
17514 if (m_InstanceValid
|| isGameMaster())
17516 if(m_HomebindTimer
) // instance valid, but timer not reset
17519 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
17522 GetSession()->SendPacket(&data
);
17524 // instance is valid, reset homebind timer
17525 m_HomebindTimer
= 0;
17527 else if (m_HomebindTimer
> 0)
17529 if (time
>= m_HomebindTimer
)
17531 // teleport to nearest graveyard
17532 RepopAtGraveyard();
17535 m_HomebindTimer
-= time
;
17539 // instance is invalid, start homebind timer
17540 m_HomebindTimer
= 60000;
17541 // send message to player
17542 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
17543 data
<< uint32(m_HomebindTimer
);
17545 GetSession()->SendPacket(&data
);
17546 sLog
.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17550 void Player::UpdatePvP(bool state
, bool ovrride
)
17552 if(!state
|| ovrride
)
17555 pvpInfo
.endTimer
= 0;
17559 if(pvpInfo
.endTimer
!= 0)
17560 pvpInfo
.endTimer
= time(NULL
);
17566 void Player::AddSpellAndCategoryCooldowns(SpellEntry
const* spellInfo
, uint32 itemId
, Spell
* spell
, bool infinityCooldown
)
17568 // init cooldown values
17573 // some special item spells without correct cooldown in SpellInfo
17574 // cooldown information stored in item prototype
17575 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
17579 if(ItemPrototype
const* proto
= ObjectMgr::GetItemPrototype(itemId
))
17581 for(int idx
= 0; idx
< 5; ++idx
)
17583 if(proto
->Spells
[idx
].SpellId
== spellInfo
->Id
)
17585 cat
= proto
->Spells
[idx
].SpellCategory
;
17586 rec
= proto
->Spells
[idx
].SpellCooldown
;
17587 catrec
= proto
->Spells
[idx
].SpellCategoryCooldown
;
17594 // if no cooldown found above then base at DBC data
17595 if(rec
< 0 && catrec
< 0)
17597 cat
= spellInfo
->Category
;
17598 rec
= spellInfo
->RecoveryTime
;
17599 catrec
= spellInfo
->CategoryRecoveryTime
;
17602 time_t curTime
= time(NULL
);
17607 // overwrite time for selected category
17608 if(infinityCooldown
)
17610 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
17611 // but not allow ignore until reset or re-login
17612 catrecTime
= catrec
> 0 ? curTime
+infinityCooldownDelay
: 0;
17613 recTime
= rec
> 0 ? curTime
+infinityCooldownDelay
: catrecTime
;
17617 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
17618 // prevent 0 cooldowns set by another way
17619 if (rec
<= 0 && catrec
<= 0 && (cat
== 76 || IsAutoRepeatRangedSpell(spellInfo
) && spellInfo
->Id
!= SPELL_ID_AUTOSHOT
))
17620 rec
= GetAttackTime(RANGED_ATTACK
);
17622 // Now we have cooldown data (if found any), time to apply mods
17624 ApplySpellMod(spellInfo
->Id
, SPELLMOD_COOLDOWN
, rec
, spell
);
17627 ApplySpellMod(spellInfo
->Id
, SPELLMOD_COOLDOWN
, catrec
, spell
);
17629 // replace negative cooldowns by 0
17630 if (rec
< 0) rec
= 0;
17631 if (catrec
< 0) catrec
= 0;
17633 // no cooldown after applying spell mods
17634 if( rec
== 0 && catrec
== 0)
17637 catrecTime
= catrec
? curTime
+catrec
/IN_MILISECONDS
: 0;
17638 recTime
= rec
? curTime
+rec
/IN_MILISECONDS
: catrecTime
;
17641 // self spell cooldown
17643 AddSpellCooldown(spellInfo
->Id
, itemId
, recTime
);
17646 if (cat
&& catrec
> 0)
17648 SpellCategoryStore::const_iterator i_scstore
= sSpellCategoryStore
.find(cat
);
17649 if(i_scstore
!= sSpellCategoryStore
.end())
17651 for(SpellCategorySet::const_iterator i_scset
= i_scstore
->second
.begin(); i_scset
!= i_scstore
->second
.end(); ++i_scset
)
17653 if(*i_scset
== spellInfo
->Id
) // skip main spell, already handled above
17656 AddSpellCooldown(*i_scset
, itemId
, catrecTime
);
17662 void Player::AddSpellCooldown(uint32 spellid
, uint32 itemid
, time_t end_time
)
17666 sc
.itemid
= itemid
;
17667 m_spellCooldowns
[spellid
] = sc
;
17670 void Player::SendCooldownEvent(SpellEntry
const *spellInfo
, uint32 itemId
, Spell
* spell
)
17672 // start cooldowns at server side, if any
17673 AddSpellAndCategoryCooldowns(spellInfo
, itemId
, spell
);
17675 // Send activate cooldown timer (possible 0) at client side
17676 WorldPacket
data(SMSG_COOLDOWN_EVENT
, (4+8));
17677 data
<< uint32(spellInfo
->Id
);
17678 data
<< uint64(GetGUID());
17679 SendDirectMessage(&data
);
17682 void Player::UpdatePotionCooldown(Spell
* spell
)
17684 // no potion used i combat or still in combat
17685 if(!m_lastPotionId
|| isInCombat())
17688 // Call not from spell cast, send cooldown event for item spells if no in combat
17691 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
17692 if(ItemPrototype
const* proto
= ObjectMgr::GetItemPrototype(m_lastPotionId
))
17693 for(int idx
= 0; idx
< 5; ++idx
)
17694 if(proto
->Spells
[idx
].SpellId
&& proto
->Spells
[idx
].SpellTrigger
== ITEM_SPELLTRIGGER_ON_USE
)
17695 if(SpellEntry
const* spellInfo
= sSpellStore
.LookupEntry(proto
->Spells
[idx
].SpellId
))
17696 SendCooldownEvent(spellInfo
,m_lastPotionId
);
17698 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
17700 SendCooldownEvent(spell
->m_spellInfo
,m_lastPotionId
,spell
);
17702 m_lastPotionId
= 0;
17705 //slot to be excluded while counting
17706 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition
, int8 slot
)
17708 if(!enchantmentcondition
)
17711 SpellItemEnchantmentConditionEntry
const *Condition
= sSpellItemEnchantmentConditionStore
.LookupEntry(enchantmentcondition
);
17716 uint8 curcount
[4] = {0, 0, 0, 0};
17718 //counting current equipped gem colors
17719 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
17723 Item
*pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
17724 if(pItem2
&& pItem2
->GetProto()->Socket
[0].Color
)
17726 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17728 uint32 enchant_id
= pItem2
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17732 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17736 uint32 gemid
= enchantEntry
->GemID
;
17740 ItemPrototype
const* gemProto
= sItemStorage
.LookupEntry
<ItemPrototype
>(gemid
);
17744 GemPropertiesEntry
const* gemProperty
= sGemPropertiesStore
.LookupEntry(gemProto
->GemProperties
);
17748 uint8 GemColor
= gemProperty
->color
;
17750 for(uint8 b
= 0, tmpcolormask
= 1; b
< 4; b
++, tmpcolormask
<<= 1)
17752 if(tmpcolormask
& GemColor
)
17759 bool activate
= true;
17761 for(int i
= 0; i
< 5; ++i
)
17763 if(!Condition
->Color
[i
])
17766 uint32 _cur_gem
= curcount
[Condition
->Color
[i
] - 1];
17768 // if have <CompareColor> use them as count, else use <value> from Condition
17769 uint32 _cmp_gem
= Condition
->CompareColor
[i
] ? curcount
[Condition
->CompareColor
[i
] - 1]: Condition
->Value
[i
];
17771 switch(Condition
->Comparator
[i
])
17773 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17774 activate
&= (_cur_gem
< _cmp_gem
) ? true : false;
17776 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17777 activate
&= (_cur_gem
> _cmp_gem
) ? true : false;
17779 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17780 activate
&= (_cur_gem
>= _cmp_gem
) ? true : false;
17785 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");
17790 void Player::CorrectMetaGemEnchants(uint8 exceptslot
, bool apply
)
17792 //cycle all equipped items
17793 for(uint32 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
17795 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17796 if(slot
== exceptslot
)
17799 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
17801 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
)
17804 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17806 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17810 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17814 uint32 condition
= enchantEntry
->EnchantmentCondition
;
17817 //was enchant active with/without item?
17818 bool wasactive
= EnchantmentFitsRequirements(condition
, apply
? exceptslot
: -1);
17819 //should it now be?
17820 if(wasactive
!= EnchantmentFitsRequirements(condition
, apply
? -1 : exceptslot
))
17822 // ignore item gem conditions
17823 //if state changed, (dis)apply enchant
17824 ApplyEnchantment(pItem
, EnchantmentSlot(enchant_slot
), !wasactive
, true, true);
17831 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17832 void Player::ToggleMetaGemsActive(uint8 exceptslot
, bool apply
)
17834 //cycle all equipped items
17835 for(int slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
17837 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17838 if(slot
== exceptslot
)
17841 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
17843 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
) //if item has no sockets or no item is equipped go to next item
17846 //cycle all (gem)enchants
17847 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17849 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17850 if(!enchant_id
) //if no enchant go to next enchant(slot)
17853 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17857 //only metagems to be (de)activated, so only enchants with condition
17858 uint32 condition
= enchantEntry
->EnchantmentCondition
;
17860 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
), apply
);
17865 void Player::SetBattleGroundEntryPoint()
17868 if (!m_taxi
.empty())
17870 m_bgData
.mountSpell
= 0;
17871 m_bgData
.taxiPath
[0] = m_taxi
.GetTaxiSource();
17872 m_bgData
.taxiPath
[1] = m_taxi
.GetTaxiDestination();
17874 // On taxi we don't need check for dungeon
17875 m_bgData
.joinPos
= WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
17880 m_bgData
.ClearTaxiPath();
17882 // Mount spell id storing
17885 AuraList
const& auras
= GetAurasByType(SPELL_AURA_MOUNTED
);
17886 if (!auras
.empty())
17887 m_bgData
.mountSpell
= (*auras
.begin())->GetId();
17890 m_bgData
.mountSpell
= 0;
17892 // If map is dungeon find linked graveyard
17893 if(GetMap()->IsDungeon())
17895 if (const WorldSafeLocsEntry
* entry
= objmgr
.GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam()))
17897 m_bgData
.joinPos
= WorldLocation(entry
->map_id
, entry
->x
, entry
->y
, entry
->z
, 0.0f
);
17901 sLog
.outError("SetBattleGroundEntryPoint: Dungeon map %u has no linked graveyard, setting home location as entry point.", GetMapId());
17903 // If new entry point is not BG or arena set it
17904 else if (!GetMap()->IsBattleGroundOrArena())
17906 m_bgData
.joinPos
= WorldLocation(GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), GetOrientation());
17911 // In error cases use homebind position
17912 m_bgData
.joinPos
= WorldLocation(m_homebindMapId
, m_homebindX
, m_homebindY
, m_homebindZ
, 0.0f
);
17915 void Player::LeaveBattleground(bool teleportToEntryPoint
)
17917 if(BattleGround
*bg
= GetBattleGround())
17919 bg
->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint
, true);
17921 // call after remove to be sure that player resurrected for correct cast
17922 if( bg
->isBattleGround() && !isGameMaster() && sWorld
.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER
) )
17924 if( bg
->GetStatus() == STATUS_IN_PROGRESS
|| bg
->GetStatus() == STATUS_WAIT_JOIN
)
17926 //lets check if player was teleported from BG and schedule delayed Deserter spell cast
17927 if(IsBeingTeleportedFar())
17929 ScheduleDelayedOperation(DELAYED_SPELL_CAST_DESERTER
);
17933 CastSpell(this, 26013, true); // Deserter
17939 bool Player::CanJoinToBattleground() const
17941 // check Deserter debuff
17942 if(GetDummyAura(26013))
17948 bool Player::CanReportAfkDueToLimit()
17950 // a player can complain about 15 people per 5 minutes
17951 if(m_bgData
.bgAfkReportedCount
++ >= 15)
17957 ///This player has been blamed to be inactive in a battleground
17958 void Player::ReportedAfkBy(Player
* reporter
)
17960 BattleGround
*bg
= GetBattleGround();
17961 if(!bg
|| bg
!= reporter
->GetBattleGround() || GetTeam() != reporter
->GetTeam())
17964 // check if player has 'Idle' or 'Inactive' debuff
17965 if(m_bgData
.bgAfkReporter
.find(reporter
->GetGUIDLow()) == m_bgData
.bgAfkReporter
.end() && !HasAura(43680, 0) && !HasAura(43681, 0) && reporter
->CanReportAfkDueToLimit())
17967 m_bgData
.bgAfkReporter
.insert(reporter
->GetGUIDLow());
17968 // 3 players have to complain to apply debuff
17969 if(m_bgData
.bgAfkReporter
.size() >= 3)
17971 // cast 'Idle' spell
17972 CastSpell(this, 43680, true);
17973 m_bgData
.bgAfkReporter
.clear();
17978 WorldObject
const* Player::GetViewPoint() const
17980 if(uint64 far_sight
= GetFarSight())
17982 WorldObject
const* viewPoint
= ObjectAccessor::GetWorldObject(*this,far_sight
);
17983 return viewPoint
? viewPoint
: this; // always expected not NULL
17989 bool Player::IsVisibleInGridForPlayer( Player
* pl
) const
17991 // gamemaster in GM mode see all, including ghosts
17992 if(pl
->isGameMaster() && GetSession()->GetSecurity() <= pl
->GetSession()->GetSecurity())
17995 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17996 if (InBattleGround())
17998 if (!(isAlive() || m_deathTimer
> 0) && !IsFriendlyTo(pl
) )
18003 // Live player see live player or dead player with not realized corpse
18004 if(pl
->isAlive() || pl
->m_deathTimer
> 0)
18006 return isAlive() || m_deathTimer
> 0;
18009 // Ghost see other friendly ghosts, that's for sure
18010 if(!(isAlive() || m_deathTimer
> 0) && IsFriendlyTo(pl
))
18013 // Dead player see live players near own corpse
18016 Corpse
*corpse
= pl
->GetCorpse();
18019 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
18020 if(corpse
->IsWithinDistInMap(this,(20+25)*sWorld
.getRate(RATE_CREATURE_AGGRO
)))
18025 // and not see any other
18029 bool Player::IsVisibleGloballyFor( Player
* u
) const
18034 // Always can see self
18038 // Visible units, always are visible for all players
18039 if (GetVisibility() == VISIBILITY_ON
)
18042 // GMs are visible for higher gms (or players are visible for gms)
18043 if (u
->GetSession()->GetSecurity() > SEC_PLAYER
)
18044 return GetSession()->GetSecurity() <= u
->GetSession()->GetSecurity();
18046 // non faction visibility non-breakable for non-GMs
18047 if (GetVisibility() == VISIBILITY_OFF
)
18050 // non-gm stealth/invisibility not hide from global player lists
18054 void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, WorldObject
* target
)
18056 if(HaveAtClient(target
))
18058 if(!target
->isVisibleForInState(this, viewPoint
, true))
18060 target
->DestroyForPlayer(this);
18061 m_clientGUIDs
.erase(target
->GetGUID());
18063 #ifdef MANGOS_DEBUG
18064 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
18065 sLog
.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
18071 if(target
->isVisibleForInState(this, viewPoint
, false))
18073 target
->SendUpdateToPlayer(this);
18074 if(target
->GetTypeId()!=TYPEID_GAMEOBJECT
||!((GameObject
*)target
)->IsTransport())
18075 m_clientGUIDs
.insert(target
->GetGUID());
18077 #ifdef MANGOS_DEBUG
18078 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
18079 sLog
.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
18082 // target aura duration for caster show only if target exist at caster client
18083 // send data at target visibility change (adding to client)
18084 if(target
!=this && target
->isType(TYPEMASK_UNIT
))
18085 SendAurasForTarget((Unit
*)target
);
18087 if(target
->GetTypeId()==TYPEID_UNIT
&& ((Creature
*)target
)->isAlive())
18088 ((Creature
*)target
)->SendMonsterMoveWithSpeedToCurrentDestination(this);
18094 inline void UpdateVisibilityOf_helper(std::set
<uint64
>& s64
, T
* target
)
18096 s64
.insert(target
->GetGUID());
18100 inline void UpdateVisibilityOf_helper(std::set
<uint64
>& s64
, GameObject
* target
)
18102 if(!target
->IsTransport())
18103 s64
.insert(target
->GetGUID());
18107 void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, T
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
)
18109 if(HaveAtClient(target
))
18111 if(!target
->isVisibleForInState(this,viewPoint
,true))
18113 target
->BuildOutOfRangeUpdateBlock(&data
);
18114 m_clientGUIDs
.erase(target
->GetGUID());
18116 #ifdef MANGOS_DEBUG
18117 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
18118 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
));
18124 if(target
->isVisibleForInState(this,viewPoint
,false))
18126 visibleNow
.insert(target
);
18127 target
->BuildUpdate(data_updates
);
18128 target
->BuildCreateUpdateBlockForPlayer(&data
, this);
18129 UpdateVisibilityOf_helper(m_clientGUIDs
,target
);
18131 #ifdef MANGOS_DEBUG
18132 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
18133 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
));
18139 template void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, Player
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
18140 template void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, Creature
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
18141 template void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, Corpse
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
18142 template void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, GameObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
18143 template void Player::UpdateVisibilityOf(WorldObject
const* viewPoint
, DynamicObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
18145 void Player::InitPrimaryProfessions()
18147 SetFreePrimaryProfessions(sWorld
.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL
));
18150 void Player::SendComboPoints()
18152 Unit
*combotarget
= ObjectAccessor::GetUnit(*this, m_comboTarget
);
18155 WorldPacket
data(SMSG_UPDATE_COMBO_POINTS
, combotarget
->GetPackGUID().size()+1);
18156 data
.append(combotarget
->GetPackGUID());
18157 data
<< uint8(m_comboPoints
);
18158 GetSession()->SendPacket(&data
);
18162 void Player::AddComboPoints(Unit
* target
, int8 count
)
18167 // without combo points lost (duration checked in aura)
18168 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
18170 if(target
->GetGUID() == m_comboTarget
)
18172 m_comboPoints
+= count
;
18177 if(Unit
* target2
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
18178 target2
->RemoveComboPointHolder(GetGUIDLow());
18180 m_comboTarget
= target
->GetGUID();
18181 m_comboPoints
= count
;
18183 target
->AddComboPointHolder(GetGUIDLow());
18186 if (m_comboPoints
> 5) m_comboPoints
= 5;
18187 if (m_comboPoints
< 0) m_comboPoints
= 0;
18192 void Player::ClearComboPoints()
18197 // without combopoints lost (duration checked in aura)
18198 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
18204 if(Unit
* target
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
18205 target
->RemoveComboPointHolder(GetGUIDLow());
18210 void Player::SetGroup(Group
*group
, int8 subgroup
)
18216 // never use SetGroup without a subgroup unless you specify NULL for group
18217 assert(subgroup
>= 0);
18218 m_group
.link(group
, this);
18219 m_group
.setSubGroup((uint8
)subgroup
);
18223 void Player::SendInitialPacketsBeforeAddToMap()
18225 GetSocial()->SendSocialList();
18227 // guild bank list wtf?
18230 WorldPacket
data(SMSG_BINDPOINTUPDATE
, 5*4);
18231 data
<< m_homebindX
<< m_homebindY
<< m_homebindZ
;
18232 data
<< (uint32
) m_homebindMapId
;
18233 data
<< (uint32
) m_homebindZoneId
;
18234 GetSession()->SendPacket(&data
);
18236 // SMSG_SET_PROFICIENCY
18237 // SMSG_SET_PCT_SPELL_MODIFIER
18238 // SMSG_SET_FLAT_SPELL_MODIFIER
18239 // SMSG_UPDATE_AURA_DURATION
18241 SendTalentsInfoData(false);
18243 // SMSG_INSTANCE_DIFFICULTY
18245 SendInitialSpells();
18247 data
.Initialize(SMSG_SEND_UNLEARN_SPELLS
, 4);
18248 data
<< uint32(0); // count, for(count) uint32;
18249 GetSession()->SendPacket(&data
);
18251 SendInitialActionButtons();
18252 m_reputationMgr
.SendInitialReputations();
18253 // SMSG_INIT_WORLD_STATES
18254 m_achievementMgr
.SendAllAchievementData();
18256 SendEquipmentSetList();
18258 data
.Initialize(SMSG_LOGIN_SETTIMESPEED
, 4 + 4 + 4);
18259 data
<< uint32(secsToTimeBitFields(sWorld
.GetGameTime()));
18260 data
<< (float)0.01666667f
; // game speed
18261 data
<< uint32(0); // added in 3.1.2
18262 GetSession()->SendPacket( &data
);
18264 // SMSG_TALENTS_INFO x 2 for pet (unspent points and talents in separate packets...)
18266 // SMSG_UPDATE_WORLD_STATE
18267 // SMSG_POWER_UPDATE
18269 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
18270 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
) || HasAuraType(SPELL_AURA_FLY
) || isInFlight())
18271 m_movementInfo
.AddMovementFlag(MOVEMENTFLAG_FLYING2
);
18276 void Player::SendInitialPacketsAfterAddToMap()
18279 uint32 newzone
, newarea
;
18280 GetZoneAndAreaId(newzone
,newarea
);
18281 UpdateZone(newzone
,newarea
); // also call SendInitWorldStates();
18283 WorldPacket
data(SMSG_TIME_SYNC_REQ
, 4); // new 2.0.x, enable movement
18284 data
<< uint32(0x00000000); // on blizz it increments periodically
18285 GetSession()->SendPacket(&data
);
18287 CastSpell(this, 836, true); // LOGINEFFECT
18289 // set some aura effects that send packet to player client after add player to map
18290 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
18291 // same auras state lost at far teleport, send it one more time in this case also
18292 static const AuraType auratypes
[] =
18294 SPELL_AURA_MOD_FEAR
, SPELL_AURA_TRANSFORM
, SPELL_AURA_WATER_WALK
,
18295 SPELL_AURA_FEATHER_FALL
, SPELL_AURA_HOVER
, SPELL_AURA_SAFE_FALL
,
18296 SPELL_AURA_FLY
, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
, SPELL_AURA_NONE
18298 for(AuraType
const* itr
= &auratypes
[0]; itr
&& itr
[0] != SPELL_AURA_NONE
; ++itr
)
18300 Unit::AuraList
const& auraList
= GetAurasByType(*itr
);
18301 if(!auraList
.empty())
18302 auraList
.front()->ApplyModifier(true,true);
18305 if(HasAuraType(SPELL_AURA_MOD_STUN
))
18306 SetMovement(MOVE_ROOT
);
18308 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
18309 if(HasAuraType(SPELL_AURA_MOD_ROOT
))
18311 WorldPacket
data2(SMSG_FORCE_MOVE_ROOT
, 10);
18312 data2
.append(GetPackGUID());
18313 data2
<< (uint32
)2;
18314 SendMessageToSet(&data2
,true);
18317 SendAurasForTarget(this);
18318 SendEnchantmentDurations(); // must be after add to map
18319 SendItemDurations(); // must be after add to map
18322 void Player::SendUpdateToOutOfRangeGroupMembers()
18324 if (m_groupUpdateMask
== GROUP_UPDATE_FLAG_NONE
)
18326 if(Group
* group
= GetGroup())
18327 group
->UpdatePlayerOutOfRange(this);
18329 m_groupUpdateMask
= GROUP_UPDATE_FLAG_NONE
;
18330 m_auraUpdateMask
= 0;
18331 if(Pet
*pet
= GetPet())
18332 pet
->ResetAuraUpdateMask();
18335 void Player::SendTransferAborted(uint32 mapid
, uint8 reason
, uint8 arg
)
18337 WorldPacket
data(SMSG_TRANSFER_ABORTED
, 4+2);
18338 data
<< uint32(mapid
);
18339 data
<< uint8(reason
); // transfer abort reason
18342 case TRANSFER_ABORT_INSUF_EXPAN_LVL
:
18343 case TRANSFER_ABORT_DIFFICULTY
:
18344 case TRANSFER_ABORT_UNIQUE_MESSAGE
:
18345 data
<< uint8(arg
);
18348 GetSession()->SendPacket(&data
);
18351 void Player::SendInstanceResetWarning( uint32 mapid
, Difficulty difficulty
, uint32 time
)
18353 // type of warning, based on the time remaining until reset
18356 type
= RAID_INSTANCE_WELCOME
;
18357 else if(time
> 900 && time
<= 3600)
18358 type
= RAID_INSTANCE_WARNING_HOURS
;
18359 else if(time
> 300 && time
<= 900)
18360 type
= RAID_INSTANCE_WARNING_MIN
;
18362 type
= RAID_INSTANCE_WARNING_MIN_SOON
;
18364 WorldPacket
data(SMSG_RAID_INSTANCE_MESSAGE
, 4+4+4+4);
18365 data
<< uint32(type
);
18366 data
<< uint32(mapid
);
18367 data
<< uint32(difficulty
); // difficulty
18368 data
<< uint32(time
);
18369 if(type
== RAID_INSTANCE_WELCOME
)
18371 data
<< uint8(0); // is your (1)
18372 data
<< uint8(0); // is extended (1), ignored if prev field is 0
18374 GetSession()->SendPacket(&data
);
18377 void Player::ApplyEquipCooldown( Item
* pItem
)
18379 for(int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
18381 _Spell
const& spellData
= pItem
->GetProto()->Spells
[i
];
18384 if( !spellData
.SpellId
)
18387 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
18388 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
)
18391 AddSpellCooldown(spellData
.SpellId
, pItem
->GetEntry(), time(NULL
) + 30);
18393 WorldPacket
data(SMSG_ITEM_COOLDOWN
, 12);
18394 data
<< pItem
->GetGUID();
18395 data
<< uint32(spellData
.SpellId
);
18396 GetSession()->SendPacket(&data
);
18400 void Player::resetSpells()
18402 // not need after this call
18403 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS
))
18404 RemoveAtLoginFlag(AT_LOGIN_RESET_SPELLS
,true);
18406 // make full copy of map (spells removed and marked as deleted at another spell remove
18407 // and we can't use original map for safe iterative with visit each spell at loop end
18408 PlayerSpellMap smap
= GetSpellMap();
18410 for(PlayerSpellMap::const_iterator iter
= smap
.begin();iter
!= smap
.end(); ++iter
)
18411 removeSpell(iter
->first
,false,false); // only iter->first can be accessed, object by iter->second can be deleted already
18413 learnDefaultSpells();
18414 learnQuestRewardedSpells();
18417 void Player::learnDefaultSpells()
18419 // learn default race/class spells
18420 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(),getClass());
18421 for (PlayerCreateInfoSpells::const_iterator itr
= info
->spell
.begin(); itr
!=info
->spell
.end(); ++itr
)
18423 uint32 tspell
= *itr
;
18424 sLog
.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell
);
18425 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
18426 addSpell(tspell
,true,true,true,false);
18427 else // but send in normal spell in game learn case
18428 learnSpell(tspell
,true);
18432 void Player::learnQuestRewardedSpells(Quest
const* quest
)
18434 uint32 spell_id
= quest
->GetRewSpellCast();
18436 // skip quests without rewarded spell
18440 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
18444 // check learned spells state
18445 bool found
= false;
18446 for(int i
=0; i
< 3; ++i
)
18448 if(spellInfo
->Effect
[i
] == SPELL_EFFECT_LEARN_SPELL
&& !HasSpell(spellInfo
->EffectTriggerSpell
[i
]))
18455 // skip quests with not teaching spell or already known spell
18459 // prevent learn non first rank unknown profession and second specialization for same profession)
18460 uint32 learned_0
= spellInfo
->EffectTriggerSpell
[0];
18461 if( spellmgr
.GetSpellRank(learned_0
) > 1 && !HasSpell(learned_0
) )
18463 // not have first rank learned (unlearned prof?)
18464 uint32 first_spell
= spellmgr
.GetFirstSpellInChain(learned_0
);
18465 if( !HasSpell(first_spell
) )
18468 SpellEntry
const *learnedInfo
= sSpellStore
.LookupEntry(learned_0
);
18473 if(learnedInfo
->Effect
[0]==SPELL_EFFECT_TRADE_SKILL
&& learnedInfo
->Effect
[1]==0)
18475 // search other specialization for same prof
18476 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
18478 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->first
==learned_0
)
18481 SpellEntry
const *itrInfo
= sSpellStore
.LookupEntry(itr
->first
);
18485 // compare only specializations
18486 if(itrInfo
->Effect
[0]!=SPELL_EFFECT_TRADE_SKILL
|| itrInfo
->Effect
[1]!=0)
18489 // compare same chain spells
18490 if(spellmgr
.GetFirstSpellInChain(itr
->first
) != first_spell
)
18493 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18494 if(!spellmgr
.IsHighRankOfSpell(learned_0
,itr
->first
))
18500 CastSpell( this, spell_id
, true);
18503 void Player::learnQuestRewardedSpells()
18505 // learn spells received from quest completing
18506 for(QuestStatusMap::const_iterator itr
= mQuestStatus
.begin(); itr
!= mQuestStatus
.end(); ++itr
)
18508 // skip no rewarded quests
18509 if(!itr
->second
.m_rewarded
)
18512 Quest
const* quest
= objmgr
.GetQuestTemplate(itr
->first
);
18516 learnQuestRewardedSpells(quest
);
18520 void Player::learnSkillRewardedSpells(uint32 skill_id
, uint32 skill_value
)
18522 uint32 raceMask
= getRaceMask();
18523 uint32 classMask
= getClassMask();
18524 for (uint32 j
=0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
18526 SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
);
18527 if (!pAbility
|| pAbility
->skillId
!=skill_id
|| pAbility
->learnOnGetSkill
!= ABILITY_LEARNED_ON_GET_PROFESSION_SKILL
)
18529 // Check race if set
18530 if (pAbility
->racemask
&& !(pAbility
->racemask
& raceMask
))
18532 // Check class if set
18533 if (pAbility
->classmask
&& !(pAbility
->classmask
& classMask
))
18536 if (sSpellStore
.LookupEntry(pAbility
->spellId
))
18538 // need unlearn spell
18539 if (skill_value
< pAbility
->req_skill_value
)
18540 removeSpell(pAbility
->spellId
);
18542 else if (!IsInWorld())
18543 addSpell(pAbility
->spellId
,true,true,true,false);
18545 learnSpell(pAbility
->spellId
,true);
18550 void Player::SendAurasForTarget(Unit
*target
)
18552 if(target
->GetVisibleAuras()->empty()) // speedup things
18555 WorldPacket
data(SMSG_AURA_UPDATE_ALL
);
18556 data
.append(target
->GetPackGUID());
18558 Unit::VisibleAuraMap
const *visibleAuras
= target
->GetVisibleAuras();
18559 for(Unit::VisibleAuraMap::const_iterator itr
= visibleAuras
->begin(); itr
!= visibleAuras
->end(); ++itr
)
18561 for(uint32 j
= 0; j
< 3; ++j
)
18563 if(Aura
*aura
= target
->GetAura(itr
->second
, j
))
18565 data
<< uint8(aura
->GetAuraSlot());
18566 data
<< uint32(aura
->GetId());
18570 uint8 auraFlags
= aura
->GetAuraFlags();
18572 data
<< uint8(auraFlags
);
18574 data
<< uint8(aura
->GetAuraLevel());
18576 if (aura
->GetAuraCharges())
18577 data
<< uint8(aura
->GetAuraCharges() * aura
->GetStackAmount());
18579 data
<< uint8(aura
->GetStackAmount());
18581 if(!(auraFlags
& AFLAG_NOT_CASTER
))
18583 data
<< uint8(0); // packed GUID of someone (caster?)
18586 if(auraFlags
& AFLAG_DURATION
) // include aura duration
18588 data
<< uint32(aura
->GetAuraMaxDuration());
18589 data
<< uint32(aura
->GetAuraDuration());
18597 GetSession()->SendPacket(&data
);
18600 void Player::SetDailyQuestStatus( uint32 quest_id
)
18602 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
18604 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
18606 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
18607 m_lastDailyQuestTime
= time(NULL
); // last daily quest time
18608 m_DailyQuestChanged
= true;
18614 void Player::ResetDailyQuestStatus()
18616 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
18617 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
18619 // DB data deleted in caller
18620 m_DailyQuestChanged
= false;
18621 m_lastDailyQuestTime
= 0;
18624 BattleGround
* Player::GetBattleGround() const
18626 if(GetBattleGroundId()==0)
18629 return sBattleGroundMgr
.GetBattleGround(GetBattleGroundId(), m_bgData
.bgTypeID
);
18632 bool Player::InArena() const
18634 BattleGround
*bg
= GetBattleGround();
18635 if(!bg
|| !bg
->isArena())
18641 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId
) const
18643 // get a template bg instead of running one
18644 BattleGround
*bg
= sBattleGroundMgr
.GetBattleGroundTemplate(bgTypeId
);
18648 if(getLevel() < bg
->GetMinLevel() || getLevel() > bg
->GetMaxLevel())
18654 BGQueueIdBasedOnLevel
Player::GetBattleGroundQueueIdFromLevel(BattleGroundTypeId bgTypeId
) const
18656 // for ranges 0 - 19, 20 - 29, 30 - 39, 40 - 49, 50 - 59, 60 - 69, 70 - 79, 80
18657 uint32 queue_id
= ( getLevel() / 10) - 1;
18658 if( queue_id
>= MAX_BATTLEGROUND_QUEUES
)
18660 sLog
.outError("BattleGround: too high queue_id %u this shouldn't happen", queue_id
);
18661 return QUEUE_ID_MAX_LEVEL_80
;
18663 return BGQueueIdBasedOnLevel(queue_id
);
18666 float Player::GetReputationPriceDiscount( Creature
const* pCreature
) const
18668 FactionTemplateEntry
const* vendor_faction
= pCreature
->getFactionTemplateEntry();
18669 if(!vendor_faction
|| !vendor_faction
->faction
)
18672 ReputationRank rank
= GetReputationRank(vendor_faction
->faction
);
18673 if(rank
<= REP_NEUTRAL
)
18676 return 1.0f
- 0.05f
* (rank
- REP_NEUTRAL
);
18679 bool Player::IsSpellFitByClassAndRace( uint32 spell_id
) const
18681 uint32 racemask
= getRaceMask();
18682 uint32 classmask
= getClassMask();
18684 SkillLineAbilityMapBounds bounds
= spellmgr
.GetSkillLineAbilityMapBounds(spell_id
);
18685 if (bounds
.first
==bounds
.second
)
18688 for(SkillLineAbilityMap::const_iterator _spell_idx
= bounds
.first
; _spell_idx
!= bounds
.second
; ++_spell_idx
)
18690 // skip wrong race skills
18691 if (_spell_idx
->second
->racemask
&& (_spell_idx
->second
->racemask
& racemask
) == 0)
18694 // skip wrong class skills
18695 if (_spell_idx
->second
->classmask
&& (_spell_idx
->second
->classmask
& classmask
) == 0)
18704 bool Player::HasQuestForGO(int32 GOId
) const
18706 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
18708 uint32 questid
= GetQuestSlotQuestId(i
);
18709 if ( questid
== 0 )
18712 QuestStatusMap::const_iterator qs_itr
= mQuestStatus
.find(questid
);
18713 if(qs_itr
== mQuestStatus
.end())
18716 QuestStatusData
const& qs
= qs_itr
->second
;
18718 if (qs
.m_status
== QUEST_STATUS_INCOMPLETE
)
18720 Quest
const* qinfo
= objmgr
.GetQuestTemplate(questid
);
18724 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
18727 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
18729 if (qinfo
->ReqCreatureOrGOId
[j
]>=0) //skip non GO case
18732 if((-1)*GOId
== qinfo
->ReqCreatureOrGOId
[j
] && qs
.m_creatureOrGOcount
[j
] < qinfo
->ReqCreatureOrGOCount
[j
])
18740 void Player::UpdateForQuestWorldObjects()
18742 if(m_clientGUIDs
.empty())
18746 WorldPacket packet
;
18747 for(ClientGUIDs::const_iterator itr
=m_clientGUIDs
.begin(); itr
!=m_clientGUIDs
.end(); ++itr
)
18749 if(IS_GAMEOBJECT_GUID(*itr
))
18751 GameObject
*obj
= HashMapHolder
<GameObject
>::Find(*itr
);
18753 obj
->BuildValuesUpdateBlockForPlayer(&udata
,this);
18755 else if(IS_CREATURE_GUID(*itr
) || IS_VEHICLE_GUID(*itr
))
18757 Creature
*obj
= ObjectAccessor::GetCreatureOrPetOrVehicle(*this, *itr
);
18761 // check if this unit requires quest specific flags
18762 if(!obj
->HasFlag(UNIT_NPC_FLAGS
,UNIT_NPC_FLAG_SPELLCLICK
))
18765 SpellClickInfoMapBounds clickPair
= objmgr
.GetSpellClickInfoMapBounds(obj
->GetEntry());
18766 for(SpellClickInfoMap::const_iterator _itr
= clickPair
.first
; _itr
!= clickPair
.second
; ++_itr
)
18768 if(_itr
->second
.questStart
|| _itr
->second
.questEnd
)
18770 obj
->BuildCreateUpdateBlockForPlayer(&udata
,this);
18776 udata
.BuildPacket(&packet
);
18777 GetSession()->SendPacket(&packet
);
18780 void Player::SummonIfPossible(bool agree
)
18784 m_summon_expire
= 0;
18788 // expire and auto declined
18789 if(m_summon_expire
< time(NULL
))
18792 // stop taxi flight at summon
18795 GetMotionMaster()->MovementExpired();
18796 m_taxi
.ClearTaxiDestinations();
18799 // drop flag at summon
18800 // this code can be reached only when GM is summoning player who carries flag, because player should be immune to summoning spells when he carries flag
18801 if(BattleGround
*bg
= GetBattleGround())
18802 bg
->EventPlayerDroppedFlag(this);
18804 m_summon_expire
= 0;
18806 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS
, 1);
18808 TeleportTo(m_summon_mapid
, m_summon_x
, m_summon_y
, m_summon_z
,GetOrientation());
18811 void Player::RemoveItemDurations( Item
*item
)
18813 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); ++itr
)
18817 m_itemDuration
.erase(itr
);
18823 void Player::AddItemDurations( Item
*item
)
18825 if(item
->GetUInt32Value(ITEM_FIELD_DURATION
))
18827 m_itemDuration
.push_back(item
);
18828 item
->SendTimeUpdate(this);
18832 void Player::AutoUnequipOffhandIfNeed()
18834 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
18838 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
18839 if (CanTitanGrip() || (offItem
->GetProto()->InventoryType
!= INVTYPE_2HWEAPON
&& !IsTwoHandUsed()))
18842 ItemPosCountVec off_dest
;
18843 uint8 off_msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false );
18844 if( off_msg
== EQUIP_ERR_OK
)
18846 RemoveItem(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
, true);
18847 StoreItem( off_dest
, offItem
, true );
18852 mi
.AddItem(offItem
->GetGUIDLow(), offItem
->GetEntry(), offItem
);
18853 MoveItemFromInventory(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
, true);
18854 CharacterDatabase
.BeginTransaction();
18855 offItem
->DeleteFromInventoryDB(); // deletes item from character's inventory
18856 offItem
->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
18857 CharacterDatabase
.CommitTransaction();
18859 std::string subject
= GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM
);
18860 WorldSession::SendMailTo(this, MAIL_NORMAL
, MAIL_STATIONERY_GM
, GetGUIDLow(), GetGUIDLow(), subject
, 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
);
18864 bool Player::HasItemFitToSpellReqirements(SpellEntry
const* spellInfo
, Item
const* ignoreItem
)
18866 if(spellInfo
->EquippedItemClass
< 0)
18869 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18870 // for optimize check 2 used cases only
18871 switch(spellInfo
->EquippedItemClass
)
18873 case ITEM_CLASS_WEAPON
:
18875 for(int i
= EQUIPMENT_SLOT_MAINHAND
; i
< EQUIPMENT_SLOT_TABARD
; ++i
)
18876 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
18877 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18881 case ITEM_CLASS_ARMOR
:
18883 // tabard not have dependent spells
18884 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_MAINHAND
; ++i
)
18885 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
18886 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18889 // shields can be equipped to offhand slot
18890 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
))
18891 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18894 // ranged slot can have some armor subclasses
18895 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_RANGED
))
18896 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18902 sLog
.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo
->EquippedItemClass
);
18909 bool Player::CanNoReagentCast(SpellEntry
const* spellInfo
) const
18911 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18912 if (spellInfo
->AttributesEx5
& SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
&&
18913 HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PREPARATION
))
18916 // Check no reagent use mask
18917 uint64 noReagentMask_0_1
= GetUInt64Value(PLAYER_NO_REAGENT_COST_1
);
18918 uint32 noReagentMask_2
= GetUInt64Value(PLAYER_NO_REAGENT_COST_1
+2);
18919 if (spellInfo
->SpellFamilyFlags
& noReagentMask_0_1
||
18920 spellInfo
->SpellFamilyFlags2
& noReagentMask_2
)
18926 void Player::RemoveItemDependentAurasAndCasts( Item
* pItem
)
18928 AuraMap
& auras
= GetAuras();
18929 for(AuraMap::const_iterator itr
= auras
.begin(); itr
!= auras
.end(); )
18931 Aura
* aura
= itr
->second
;
18933 // skip passive (passive item dependent spells work in another way) and not self applied auras
18934 SpellEntry
const* spellInfo
= aura
->GetSpellProto();
18935 if(aura
->IsPassive() || aura
->GetCasterGUID()!=GetGUID())
18941 // skip if not item dependent or have alternative item
18942 if(HasItemFitToSpellReqirements(spellInfo
,pItem
))
18948 // no alt item, remove aura, restart check
18949 RemoveAurasDueToSpell(aura
->GetId());
18950 itr
= auras
.begin();
18953 // currently casted spells can be dependent from item
18954 for (uint32 i
= 0; i
< CURRENT_MAX_SPELL
; ++i
)
18955 if (Spell
* spell
= GetCurrentSpell(CurrentSpellTypes(i
)))
18956 if (spell
->getState()!=SPELL_STATE_DELAYED
&& !HasItemFitToSpellReqirements(spell
->m_spellInfo
,pItem
) )
18957 InterruptSpell(CurrentSpellTypes(i
));
18960 uint32
Player::GetResurrectionSpellId()
18962 // search priceless resurrection possibilities
18964 uint32 spell_id
= 0;
18965 AuraList
const& dummyAuras
= GetAurasByType(SPELL_AURA_DUMMY
);
18966 for(AuraList::const_iterator itr
= dummyAuras
.begin(); itr
!= dummyAuras
.end(); ++itr
)
18968 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18969 if( prio
< 2 && (*itr
)->GetSpellProto()->SpellVisual
[0] == 99 && (*itr
)->GetSpellProto()->SpellIconID
== 92 )
18971 switch((*itr
)->GetId())
18973 case 20707: spell_id
= 3026; break; // rank 1
18974 case 20762: spell_id
= 20758; break; // rank 2
18975 case 20763: spell_id
= 20759; break; // rank 3
18976 case 20764: spell_id
= 20760; break; // rank 4
18977 case 20765: spell_id
= 20761; break; // rank 5
18978 case 27239: spell_id
= 27240; break; // rank 6
18979 case 47883: spell_id
= 47882; break; // rank 7
18981 sLog
.outError("Unhandled spell %u: S.Resurrection",(*itr
)->GetId());
18987 // Twisting Nether // prio: 2 (max)
18988 else if((*itr
)->GetId()==23701 && roll_chance_i(10))
18995 // Reincarnation (passive spell) // prio: 1
18996 if(prio
< 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
19002 // Used in triggers for check "Only to targets that grant experience or honor" req
19003 bool Player::isHonorOrXPTarget(Unit
* pVictim
)
19005 uint32 v_level
= pVictim
->getLevel();
19006 uint32 k_grey
= MaNGOS::XP::GetGrayLevel(getLevel());
19008 // Victim level less gray level
19009 if(v_level
<=k_grey
)
19012 if(pVictim
->GetTypeId() == TYPEID_UNIT
)
19014 if (((Creature
*)pVictim
)->isTotem() ||
19015 ((Creature
*)pVictim
)->isPet() ||
19016 ((Creature
*)pVictim
)->GetCreatureInfo()->flags_extra
& CREATURE_FLAG_EXTRA_NO_XP_AT_KILL
)
19022 bool Player::RewardPlayerAndGroupAtKill(Unit
* pVictim
)
19024 bool PvP
= pVictim
->isCharmedOwnedByPlayerOrPlayer();
19026 // prepare data for near group iteration (PvP and !PvP cases)
19028 bool honored_kill
= false;
19030 if(Group
*pGroup
= GetGroup())
19033 uint32 sum_level
= 0;
19034 Player
* member_with_max_level
= NULL
;
19035 Player
* not_gray_member_with_max_level
= NULL
;
19037 pGroup
->GetDataForXPAtKill(pVictim
,count
,sum_level
,member_with_max_level
,not_gray_member_with_max_level
);
19039 if(member_with_max_level
)
19041 /// not get Xp in PvP or no not gray players in group
19042 xp
= (PvP
|| !not_gray_member_with_max_level
) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level
, pVictim
);
19044 /// skip in check PvP case (for speed, not used)
19045 bool is_raid
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsRaid() && pGroup
->isRaidGroup();
19046 bool is_dungeon
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsDungeon();
19047 float group_rate
= MaNGOS::XP::xp_in_group_rate(count
,is_raid
);
19049 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
19051 Player
* pGroupGuy
= itr
->getSource();
19055 if(!pGroupGuy
->IsAtGroupRewardDistance(pVictim
))
19056 continue; // member (alive or dead) or his corpse at req. distance
19058 // honor can be in PvP and !PvP (racial leader) cases (for alive)
19059 if(pGroupGuy
->isAlive() && pGroupGuy
->RewardHonor(pVictim
,count
) && pGroupGuy
==this)
19060 honored_kill
= true;
19062 // xp and reputation only in !PvP case
19065 float rate
= group_rate
* float(pGroupGuy
->getLevel()) / sum_level
;
19067 // if is in dungeon then all receive full reputation at kill
19068 // rewarded any alive/dead/near_corpse group member
19069 pGroupGuy
->RewardReputation(pVictim
,is_dungeon
? 1.0f
: rate
);
19071 // XP updated only for alive group member
19072 if(pGroupGuy
->isAlive() && not_gray_member_with_max_level
&&
19073 pGroupGuy
->getLevel() <= not_gray_member_with_max_level
->getLevel())
19075 uint32 itr_xp
= (member_with_max_level
== not_gray_member_with_max_level
) ? uint32(xp
*rate
) : uint32((xp
*rate
/2)+1);
19077 pGroupGuy
->GiveXP(itr_xp
, pVictim
);
19078 if(Pet
* pet
= pGroupGuy
->GetPet())
19079 pet
->GivePetXP(itr_xp
/2);
19082 // quest objectives updated only for alive group member or dead but with not released body
19083 if(pGroupGuy
->isAlive()|| !pGroupGuy
->GetCorpse())
19085 // normal creature (not pet/etc) can be only in !PvP case
19086 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
19087 pGroupGuy
->KilledMonster(((Creature
*)pVictim
)->GetCreatureInfo(), pVictim
->GetGUID());
19093 else // if (!pGroup)
19095 xp
= PvP
? 0 : MaNGOS::XP::Gain(this, pVictim
);
19097 // honor can be in PvP and !PvP (racial leader) cases
19098 if(RewardHonor(pVictim
,1))
19099 honored_kill
= true;
19101 // xp and reputation only in !PvP case
19104 RewardReputation(pVictim
,1);
19105 GiveXP(xp
, pVictim
);
19107 if(Pet
* pet
= GetPet())
19108 pet
->GivePetXP(xp
);
19110 // normal creature (not pet/etc) can be only in !PvP case
19111 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
19112 KilledMonster(((Creature
*)pVictim
)->GetCreatureInfo(), pVictim
->GetGUID());
19115 return xp
|| honored_kill
;
19118 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id
, WorldObject
* pRewardSource
)
19120 uint64 creature_guid
= pRewardSource
->GetTypeId()==TYPEID_UNIT
? pRewardSource
->GetGUID() : uint64(0);
19122 // prepare data for near group iteration
19123 if(Group
*pGroup
= GetGroup())
19125 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
19127 Player
* pGroupGuy
= itr
->getSource();
19131 if(!pGroupGuy
->IsAtGroupRewardDistance(pRewardSource
))
19132 continue; // member (alive or dead) or his corpse at req. distance
19134 // quest objectives updated only for alive group member or dead but with not released body
19135 if(pGroupGuy
->isAlive()|| !pGroupGuy
->GetCorpse())
19136 pGroupGuy
->KilledMonsterCredit(creature_id
, creature_guid
);
19139 else // if (!pGroup)
19140 KilledMonsterCredit(creature_id
, creature_guid
);
19143 bool Player::IsAtGroupRewardDistance(WorldObject
const* pRewardSource
) const
19145 if (pRewardSource
->IsWithinDistInMap(this,sWorld
.getConfig(CONFIG_GROUP_XP_DISTANCE
)))
19151 Corpse
* corpse
= GetCorpse();
19155 return pRewardSource
->IsWithinDistInMap(corpse
,sWorld
.getConfig(CONFIG_GROUP_XP_DISTANCE
));
19158 uint32
Player::GetBaseWeaponSkillValue (WeaponAttackType attType
) const
19160 Item
* item
= GetWeaponForAttack(attType
,true);
19162 // unarmed only with base attack
19163 if(attType
!= BASE_ATTACK
&& !item
)
19166 // weapon skill or (unarmed for base attack)
19167 uint32 skill
= item
? item
->GetSkill() : uint32(SKILL_UNARMED
);
19168 return GetBaseSkillValue(skill
);
19171 void Player::ResurectUsingRequestData()
19173 /// Teleport before resurrecting by player, otherwise the player might get attacked from creatures near his corpse
19174 if(IS_PLAYER_GUID(m_resurrectGUID
))
19175 TeleportTo(m_resurrectMap
, m_resurrectX
, m_resurrectY
, m_resurrectZ
, GetOrientation());
19177 //we cannot resurrect player when we triggered far teleport
19178 //player will be resurrected upon teleportation
19179 if(IsBeingTeleportedFar())
19181 ScheduleDelayedOperation(DELAYED_RESURRECT_PLAYER
);
19185 ResurrectPlayer(0.0f
,false);
19187 if(GetMaxHealth() > m_resurrectHealth
)
19188 SetHealth( m_resurrectHealth
);
19190 SetHealth( GetMaxHealth() );
19192 if(GetMaxPower(POWER_MANA
) > m_resurrectMana
)
19193 SetPower(POWER_MANA
, m_resurrectMana
);
19195 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
) );
19197 SetPower(POWER_RAGE
, 0 );
19199 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
) );
19201 SpawnCorpseBones();
19204 void Player::SetClientControl(Unit
* target
, uint8 allowMove
)
19206 WorldPacket
data(SMSG_CLIENT_CONTROL_UPDATE
, target
->GetPackGUID().size()+1);
19207 data
.append(target
->GetPackGUID());
19208 data
<< uint8(allowMove
);
19209 GetSession()->SendPacket(&data
);
19212 void Player::UpdateZoneDependentAuras( uint32 newZone
)
19214 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
19215 SpellAreaForAreaMapBounds saBounds
= spellmgr
.GetSpellAreaForAreaMapBounds(newZone
);
19216 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
19217 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,newZone
,0))
19218 if( !HasAura(itr
->second
->spellId
,0) )
19219 CastSpell(this,itr
->second
->spellId
,true);
19222 void Player::UpdateAreaDependentAuras( uint32 newArea
)
19224 // remove auras from spells with area limitations
19225 for(AuraMap::iterator iter
= m_Auras
.begin(); iter
!= m_Auras
.end();)
19227 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
19228 if(spellmgr
.GetSpellAllowedInLocationError(iter
->second
->GetSpellProto(),GetMapId(),m_zoneUpdateId
,newArea
,this) != SPELL_CAST_OK
)
19234 // some auras applied at subzone enter
19235 SpellAreaForAreaMapBounds saBounds
= spellmgr
.GetSpellAreaForAreaMapBounds(newArea
);
19236 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
19237 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,m_zoneUpdateId
,newArea
))
19238 if( !HasAura(itr
->second
->spellId
,0) )
19239 CastSpell(this,itr
->second
->spellId
,true);
19242 uint32
Player::GetCorpseReclaimDelay(bool pvp
) const
19244 if ((pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
)) ||
19245 (!pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) ))
19247 return copseReclaimDelay
[0];
19250 time_t now
= time(NULL
);
19251 // 0..2 full period
19252 uint32 count
= (now
< m_deathExpireTime
) ? (m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
: 0;
19253 return copseReclaimDelay
[count
];
19256 void Player::UpdateCorpseReclaimDelay()
19258 bool pvp
= m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
;
19260 if ((pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
)) ||
19261 (!pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) ))
19264 time_t now
= time(NULL
);
19265 if(now
< m_deathExpireTime
)
19267 // full and partly periods 1..3
19268 uint32 count
= (m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
+1;
19269 if(count
< MAX_DEATH_COUNT
)
19270 m_deathExpireTime
= now
+(count
+1)*DEATH_EXPIRE_STEP
;
19272 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
;
19275 m_deathExpireTime
= now
+DEATH_EXPIRE_STEP
;
19278 void Player::SendCorpseReclaimDelay(bool load
)
19280 Corpse
* corpse
= GetCorpse();
19287 if(corpse
->GetGhostTime() > m_deathExpireTime
)
19290 bool pvp
= corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
;
19293 if( pvp
&& sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
19294 !pvp
&& sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
19296 count
= (m_deathExpireTime
-corpse
->GetGhostTime())/DEATH_EXPIRE_STEP
;
19297 if(count
>=MAX_DEATH_COUNT
)
19298 count
= MAX_DEATH_COUNT
-1;
19303 time_t expected_time
= corpse
->GetGhostTime()+copseReclaimDelay
[count
];
19305 time_t now
= time(NULL
);
19306 if(now
>= expected_time
)
19309 delay
= expected_time
-now
;
19312 delay
= GetCorpseReclaimDelay(corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
);
19314 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
19315 WorldPacket
data(SMSG_CORPSE_RECLAIM_DELAY
, 4);
19316 data
<< uint32(delay
*IN_MILISECONDS
);
19317 GetSession()->SendPacket( &data
);
19320 Player
* Player::GetNextRandomRaidMember(float radius
)
19322 Group
*pGroup
= GetGroup();
19326 std::vector
<Player
*> nearMembers
;
19327 nearMembers
.reserve(pGroup
->GetMembersCount());
19329 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
19331 Player
* Target
= itr
->getSource();
19333 // IsHostileTo check duel and controlled by enemy
19334 if( Target
&& Target
!= this && IsWithinDistInMap(Target
, radius
) &&
19335 !Target
->HasInvisibilityAura() && !IsHostileTo(Target
) )
19336 nearMembers
.push_back(Target
);
19339 if (nearMembers
.empty())
19342 uint32 randTarget
= urand(0,nearMembers
.size()-1);
19343 return nearMembers
[randTarget
];
19346 PartyResult
Player::CanUninviteFromGroup() const
19348 const Group
* grp
= GetGroup();
19350 return PARTY_RESULT_YOU_NOT_IN_GROUP
;
19352 if(!grp
->IsLeader(GetGUID()) && !grp
->IsAssistant(GetGUID()))
19353 return PARTY_RESULT_YOU_NOT_LEADER
;
19355 if(InBattleGround())
19356 return PARTY_RESULT_INVITE_RESTRICTED
;
19358 return PARTY_RESULT_OK
;
19361 void Player::SetBattleGroundRaid(Group
* group
, int8 subgroup
)
19363 //we must move references from m_group to m_originalGroup
19364 SetOriginalGroup(GetGroup(), GetSubGroup());
19367 m_group
.link(group
, this);
19368 m_group
.setSubGroup((uint8
)subgroup
);
19371 void Player::RemoveFromBattleGroundRaid()
19373 //remove existing reference
19375 if( Group
* group
= GetOriginalGroup() )
19377 m_group
.link(group
, this);
19378 m_group
.setSubGroup(GetOriginalSubGroup());
19380 SetOriginalGroup(NULL
);
19383 void Player::SetOriginalGroup(Group
*group
, int8 subgroup
)
19385 if( group
== NULL
)
19386 m_originalGroup
.unlink();
19389 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
19390 assert(subgroup
>= 0);
19391 m_originalGroup
.link(group
, this);
19392 m_originalGroup
.setSubGroup((uint8
)subgroup
);
19396 void Player::UpdateUnderwaterState( Map
* m
, float x
, float y
, float z
)
19398 LiquidData liquid_status
;
19399 ZLiquidStatus res
= m
->getLiquidStatus(x
, y
, z
, MAP_ALL_LIQUIDS
, &liquid_status
);
19402 m_MirrorTimerFlags
&= ~(UNDERWATER_INWATER
|UNDERWATER_INLAVA
|UNDERWATER_INSLIME
|UNDERWARER_INDARKWATER
);
19403 // Small hack for enable breath in WMO
19405 m_MirrorTimerFlags
|=UNDERWATER_INWATER
;
19409 // All liquids type - check under water position
19410 if (liquid_status
.type
&(MAP_LIQUID_TYPE_WATER
|MAP_LIQUID_TYPE_OCEAN
|MAP_LIQUID_TYPE_MAGMA
|MAP_LIQUID_TYPE_SLIME
))
19412 if ( res
& LIQUID_MAP_UNDER_WATER
)
19413 m_MirrorTimerFlags
|= UNDERWATER_INWATER
;
19415 m_MirrorTimerFlags
&= ~UNDERWATER_INWATER
;
19418 // Allow travel in dark water on taxi or transport
19419 if ((liquid_status
.type
& MAP_LIQUID_TYPE_DARK_WATER
) && !isInFlight() && !GetTransport())
19420 m_MirrorTimerFlags
|= UNDERWARER_INDARKWATER
;
19422 m_MirrorTimerFlags
&= ~UNDERWARER_INDARKWATER
;
19424 // in lava check, anywhere in lava level
19425 if (liquid_status
.type
&MAP_LIQUID_TYPE_MAGMA
)
19427 if (res
& (LIQUID_MAP_UNDER_WATER
|LIQUID_MAP_IN_WATER
|LIQUID_MAP_WATER_WALK
))
19428 m_MirrorTimerFlags
|= UNDERWATER_INLAVA
;
19430 m_MirrorTimerFlags
&= ~UNDERWATER_INLAVA
;
19432 // in slime check, anywhere in slime level
19433 if (liquid_status
.type
&MAP_LIQUID_TYPE_SLIME
)
19435 if (res
& (LIQUID_MAP_UNDER_WATER
|LIQUID_MAP_IN_WATER
|LIQUID_MAP_WATER_WALK
))
19436 m_MirrorTimerFlags
|= UNDERWATER_INSLIME
;
19438 m_MirrorTimerFlags
&= ~UNDERWATER_INSLIME
;
19442 void Player::SetCanParry( bool value
)
19444 if(m_canParry
==value
)
19447 m_canParry
= value
;
19448 UpdateParryPercentage();
19451 void Player::SetCanBlock( bool value
)
19453 if(m_canBlock
==value
)
19456 m_canBlock
= value
;
19457 UpdateBlockPercentage();
19460 bool ItemPosCount::isContainedIn(ItemPosCountVec
const& vec
) const
19462 for(ItemPosCountVec::const_iterator itr
= vec
.begin(); itr
!= vec
.end();++itr
)
19463 if(itr
->pos
== pos
)
19469 bool Player::CanUseBattleGroundObject()
19471 // TODO : some spells gives player ForceReaction to one faction (ReputationMgr::ApplyForceReaction)
19472 // maybe gameobject code should handle that ForceReaction usage
19473 // BUG: sometimes when player clicks on flag in AB - client won't send gameobject_use, only gameobject_report_use packet
19474 return ( //InBattleGround() && // in battleground - not need, check in other cases
19475 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
19476 //player cannot use object when he is invulnerable (immune)
19477 !isTotalImmune() && // not totally immune
19478 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
19479 !HasStealthAura() && // not stealthed
19480 !HasInvisibilityAura() && // not invisible
19481 !HasAura(SPELL_RECENTLY_DROPPED_FLAG
, 0) && // can't pickup
19482 isAlive() // live player
19486 bool Player::CanCaptureTowerPoint()
19488 return ( !HasStealthAura() && // not stealthed
19489 !HasInvisibilityAura() && // not invisible
19490 isAlive() // live player
19494 uint32
Player::GetBarberShopCost(uint8 newhairstyle
, uint8 newhaircolor
, uint8 newfacialhair
)
19496 uint32 level
= getLevel();
19498 if(level
> GT_MAX_LEVEL
)
19499 level
= GT_MAX_LEVEL
; // max level in this dbc
19501 uint8 hairstyle
= GetByteValue(PLAYER_BYTES
, 2);
19502 uint8 haircolor
= GetByteValue(PLAYER_BYTES
, 3);
19503 uint8 facialhair
= GetByteValue(PLAYER_BYTES_2
, 0);
19505 if((hairstyle
== newhairstyle
) && (haircolor
== newhaircolor
) && (facialhair
== newfacialhair
))
19508 GtBarberShopCostBaseEntry
const *bsc
= sGtBarberShopCostBaseStore
.LookupEntry(level
- 1);
19510 if(!bsc
) // shouldn't happen
19515 if(hairstyle
!= newhairstyle
)
19516 cost
+= bsc
->cost
; // full price
19518 if((haircolor
!= newhaircolor
) && (hairstyle
== newhairstyle
))
19519 cost
+= bsc
->cost
* 0.5f
; // +1/2 of price
19521 if(facialhair
!= newfacialhair
)
19522 cost
+= bsc
->cost
* 0.75f
; // +3/4 of price
19524 return uint32(cost
);
19527 void Player::InitGlyphsForLevel()
19529 for(uint32 i
= 0; i
< sGlyphSlotStore
.GetNumRows(); ++i
)
19530 if(GlyphSlotEntry
const * gs
= sGlyphSlotStore
.LookupEntry(i
))
19532 SetGlyphSlot(gs
->Order
- 1, gs
->Id
);
19534 uint32 level
= getLevel();
19537 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19539 value
|= (0x01 | 0x02);
19549 SetUInt32Value(PLAYER_GLYPHS_ENABLED
, value
);
19552 void Player::EnterVehicle(Vehicle
*vehicle
)
19554 VehicleEntry
const *ve
= sVehicleStore
.LookupEntry(vehicle
->GetVehicleId());
19558 VehicleSeatEntry
const *veSeat
= sVehicleSeatStore
.LookupEntry(ve
->m_seatID
[0]);
19562 vehicle
->SetCharmerGUID(GetGUID());
19563 vehicle
->RemoveFlag(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_SPELLCLICK
);
19564 vehicle
->SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PLAYER_CONTROLLED
);
19565 vehicle
->setFaction(getFaction());
19567 SetCharm(vehicle
); // charm
19568 SetFarSightGUID(vehicle
->GetGUID()); // set view
19570 SetClientControl(vehicle
, 1); // redirect controls to vehicle
19573 WorldPacket
data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA
, 0);
19574 GetSession()->SendPacket(&data
);
19576 data
.Initialize(MSG_MOVE_TELEPORT_ACK
, 30);
19577 data
.append(GetPackGUID());
19578 data
<< uint32(0); // counter?
19579 data
<< uint32(MOVEMENTFLAG_ONTRANSPORT
); // transport
19580 data
<< uint16(0); // special flags
19581 data
<< uint32(getMSTime()); // time
19582 data
<< vehicle
->GetPositionX(); // x
19583 data
<< vehicle
->GetPositionY(); // y
19584 data
<< vehicle
->GetPositionZ(); // z
19585 data
<< vehicle
->GetOrientation(); // o
19586 // transport part, TODO: load/calculate seat offsets
19587 data
<< uint64(vehicle
->GetGUID()); // transport guid
19588 data
<< float(veSeat
->m_attachmentOffsetX
); // transport offsetX
19589 data
<< float(veSeat
->m_attachmentOffsetY
); // transport offsetY
19590 data
<< float(veSeat
->m_attachmentOffsetZ
); // transport offsetZ
19591 data
<< float(0); // transport orientation
19592 data
<< uint32(getMSTime()); // transport time
19593 data
<< uint8(0); // seat
19594 // end of transport part
19595 data
<< uint32(0); // fall time
19596 GetSession()->SendPacket(&data
);
19598 data
.Initialize(SMSG_PET_SPELLS
, 8+2+4+4+4*MAX_UNIT_ACTION_BAR_INDEX
+1+1);
19599 data
<< uint64(vehicle
->GetGUID());
19602 data
<< uint32(0x00000101);
19604 for(uint32 i
= 0; i
< 10; ++i
)
19605 data
<< uint16(0) << uint8(0) << uint8(i
+8);
19609 GetSession()->SendPacket(&data
);
19612 void Player::ExitVehicle(Vehicle
*vehicle
)
19614 vehicle
->SetCharmerGUID(0);
19615 vehicle
->SetFlag(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_SPELLCLICK
);
19616 vehicle
->RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PLAYER_CONTROLLED
);
19617 vehicle
->setFaction((GetTeam() == ALLIANCE
) ? vehicle
->GetCreatureInfo()->faction_A
: vehicle
->GetCreatureInfo()->faction_H
);
19620 SetFarSightGUID(0);
19622 SetClientControl(vehicle
, 0);
19625 WorldPacket
data(MSG_MOVE_TELEPORT_ACK
, 30);
19626 data
.append(GetPackGUID());
19627 data
<< uint32(0); // counter?
19628 data
<< uint32(MOVEMENTFLAG_FLY_UNK1
); // fly unk
19629 data
<< uint16(0x40); // special flags
19630 data
<< uint32(getMSTime()); // time
19631 data
<< vehicle
->GetPositionX(); // x
19632 data
<< vehicle
->GetPositionY(); // y
19633 data
<< vehicle
->GetPositionZ(); // z
19634 data
<< vehicle
->GetOrientation(); // o
19635 data
<< uint32(0); // fall time
19636 GetSession()->SendPacket(&data
);
19638 RemovePetActionBar();
19640 // maybe called at dummy aura remove?
19641 // CastSpell(this, 45472, true); // Parachute
19644 bool Player::isTotalImmune()
19646 AuraList
const& immune
= GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY
);
19648 uint32 immuneMask
= 0;
19649 for(AuraList::const_iterator itr
= immune
.begin(); itr
!= immune
.end(); ++itr
)
19651 immuneMask
|= (*itr
)->GetModifier()->m_miscvalue
;
19652 if( immuneMask
& SPELL_SCHOOL_MASK_ALL
) // total immunity
19658 bool Player::HasTitle(uint32 bitIndex
)
19660 if (bitIndex
> MAX_TITLE_INDEX
)
19663 uint32 fieldIndexOffset
= bitIndex
/ 32;
19664 uint32 flag
= 1 << (bitIndex
% 32);
19665 return HasFlag(PLAYER__FIELD_KNOWN_TITLES
+ fieldIndexOffset
, flag
);
19668 void Player::SetTitle(CharTitlesEntry
const* title
, bool lost
)
19670 uint32 fieldIndexOffset
= title
->bit_index
/ 32;
19671 uint32 flag
= 1 << (title
->bit_index
% 32);
19675 if(!HasFlag(PLAYER__FIELD_KNOWN_TITLES
+ fieldIndexOffset
, flag
))
19678 RemoveFlag(PLAYER__FIELD_KNOWN_TITLES
+ fieldIndexOffset
, flag
);
19682 if(HasFlag(PLAYER__FIELD_KNOWN_TITLES
+ fieldIndexOffset
, flag
))
19685 SetFlag(PLAYER__FIELD_KNOWN_TITLES
+ fieldIndexOffset
, flag
);
19688 WorldPacket
data(SMSG_TITLE_EARNED
, 4 + 4);
19689 data
<< uint32(title
->bit_index
);
19690 data
<< uint32(lost
? 0 : 1); // 1 - earned, 0 - lost
19691 GetSession()->SendPacket(&data
);
19694 void Player::ConvertRune(uint8 index
, RuneType newType
)
19696 SetCurrentRune(index
, newType
);
19698 WorldPacket
data(SMSG_CONVERT_RUNE
, 2);
19699 data
<< uint8(index
);
19700 data
<< uint8(newType
);
19701 GetSession()->SendPacket(&data
);
19704 void Player::ResyncRunes(uint8 count
)
19706 WorldPacket
data(SMSG_RESYNC_RUNES
, count
* 2);
19707 for(uint32 i
= 0; i
< count
; ++i
)
19709 data
<< uint8(GetCurrentRune(i
)); // rune type
19710 data
<< uint8(255 - ((GetRuneCooldown(i
) / REGEN_TIME_FULL
) * 51)); // passed cooldown time (0-255)
19712 GetSession()->SendPacket(&data
);
19715 void Player::AddRunePower(uint8 index
)
19717 WorldPacket
data(SMSG_ADD_RUNE_POWER
, 4);
19718 data
<< uint32(1 << index
); // mask (0x00-0x3F probably)
19719 GetSession()->SendPacket(&data
);
19722 static RuneType runeSlotTypes
[MAX_RUNES
] = {
19731 void Player::InitRunes()
19733 if(getClass() != CLASS_DEATH_KNIGHT
)
19736 m_runes
= new Runes
;
19738 m_runes
->runeState
= 0;
19740 for(uint32 i
= 0; i
< MAX_RUNES
; ++i
)
19742 SetBaseRune(i
, runeSlotTypes
[i
]); // init base types
19743 SetCurrentRune(i
, runeSlotTypes
[i
]); // init current types
19744 SetRuneCooldown(i
, 0); // reset cooldowns
19745 m_runes
->SetRuneState(i
);
19748 for(uint32 i
= 0; i
< NUM_RUNE_TYPES
; ++i
)
19749 SetFloatValue(PLAYER_RUNE_REGEN_1
+ i
, 0.1f
);
19753 bool Player::IsBaseRuneSlotsOnCooldown( RuneType runeType
) const
19755 for(uint32 i
= 0; i
< MAX_RUNES
; ++i
)
19756 if (GetBaseRune(i
) == runeType
&& GetRuneCooldown(i
) == 0)
19762 void Player::AutoStoreLoot(uint8 bag
, uint8 slot
, uint32 loot_id
, LootStore
const& store
, bool broadcast
)
19765 loot
.FillLoot (loot_id
,store
,this,true);
19767 uint32 max_slot
= loot
.GetMaxSlotInLootFor(this);
19768 for(uint32 i
= 0; i
< max_slot
; ++i
)
19770 LootItem
* lootItem
= loot
.LootItemInSlot(i
,this);
19772 ItemPosCountVec dest
;
19773 uint8 msg
= CanStoreNewItem (bag
,slot
,dest
,lootItem
->itemid
,lootItem
->count
);
19774 if(msg
!= EQUIP_ERR_OK
&& slot
!= NULL_SLOT
)
19775 msg
= CanStoreNewItem( bag
, NULL_SLOT
,dest
,lootItem
->itemid
,lootItem
->count
);
19776 if( msg
!= EQUIP_ERR_OK
&& bag
!= NULL_BAG
)
19777 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
,dest
,lootItem
->itemid
,lootItem
->count
);
19778 if(msg
!= EQUIP_ERR_OK
)
19780 SendEquipError( msg
, NULL
, NULL
);
19784 Item
* pItem
= StoreNewItem (dest
,lootItem
->itemid
,true,lootItem
->randomPropertyId
);
19785 SendNewItem(pItem
, lootItem
->count
, false, false, broadcast
);
19789 uint32
Player::CalculateTalentsPoints() const
19791 uint32 base_talent
= getLevel() < 10 ? 0 : getLevel()-9;
19793 if(getClass() != CLASS_DEATH_KNIGHT
)
19794 return uint32(base_talent
* sWorld
.getRate(RATE_TALENT
));
19796 uint32 talentPointsForLevel
= getLevel() < 56 ? 0 : getLevel() - 55;
19797 talentPointsForLevel
+= m_questRewardTalentCount
;
19799 if(talentPointsForLevel
> base_talent
)
19800 talentPointsForLevel
= base_talent
;
19802 return uint32(talentPointsForLevel
* sWorld
.getRate(RATE_TALENT
));
19805 bool Player::IsKnowHowFlyIn(uint32 mapid
, uint32 zone
) const
19807 // continent checked in SpellMgr::GetSpellAllowedInLocationError at cast and area update
19808 uint32 v_map
= GetVirtualMapForMapAndZone(mapid
, zone
);
19809 return v_map
!= 571 || HasSpell(54197); // Cold Weather Flying
19812 struct DoPlayerLearnSpell
19814 DoPlayerLearnSpell(Player
& _player
) : player(_player
) {}
19815 void operator() (uint32 spell_id
) { player
.learnSpell(spell_id
,false); }
19819 void Player::learnSpellHighRank(uint32 spellid
)
19821 learnSpell(spellid
,false);
19823 DoPlayerLearnSpell
worker(*this);
19824 spellmgr
.doForHighRanks(spellid
,worker
);
19827 void Player::_LoadSkills()
19829 // Note: skill data itself loaded from `data` field. This is only cleanup part of load
19831 // reset skill modifiers and set correct unlearn flags
19832 for (uint32 i
= 0; i
< PLAYER_MAX_SKILLS
; ++i
)
19834 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
19836 // set correct unlearn bit
19837 uint32 id
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
19840 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
19841 if(!pSkill
) continue;
19843 // enable unlearn button for primary professions only
19844 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
19845 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
19847 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
19849 // set fixed skill ranges
19850 switch(GetSkillRangeType(pSkill
,false))
19852 case SKILL_RANGE_LANGUAGE
: // 300..300
19853 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(300,300));
19855 case SKILL_RANGE_MONO
: // 1..1, grey monolite bar
19856 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(1,1));
19862 uint32 vskill
= SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
19863 learnSkillRewardedSpells(id
, vskill
);
19866 // special settings
19867 if(getClass()==CLASS_DEATH_KNIGHT
)
19869 uint32 base_level
= std::min(getLevel(),sWorld
.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL
));
19872 uint32 base_skill
= (base_level
-1)*5; // 270 at starting level 55
19874 base_skill
= 1; // skill mast be known and then > 0 in any case
19876 if(GetPureSkillValue (SKILL_FIRST_AID
) < base_skill
)
19877 SetSkill(SKILL_FIRST_AID
,base_skill
, base_skill
);
19878 if(GetPureSkillValue (SKILL_AXES
) < base_skill
)
19879 SetSkill(SKILL_AXES
, base_skill
,base_skill
);
19880 if(GetPureSkillValue (SKILL_DEFENSE
) < base_skill
)
19881 SetSkill(SKILL_DEFENSE
, base_skill
,base_skill
);
19882 if(GetPureSkillValue (SKILL_POLEARMS
) < base_skill
)
19883 SetSkill(SKILL_POLEARMS
, base_skill
,base_skill
);
19884 if(GetPureSkillValue (SKILL_SWORDS
) < base_skill
)
19885 SetSkill(SKILL_SWORDS
, base_skill
,base_skill
);
19886 if(GetPureSkillValue (SKILL_2H_AXES
) < base_skill
)
19887 SetSkill(SKILL_2H_AXES
, base_skill
,base_skill
);
19888 if(GetPureSkillValue (SKILL_2H_SWORDS
) < base_skill
)
19889 SetSkill(SKILL_2H_SWORDS
, base_skill
,base_skill
);
19890 if(GetPureSkillValue (SKILL_UNARMED
) < base_skill
)
19891 SetSkill(SKILL_UNARMED
, base_skill
,base_skill
);
19895 uint32
Player::GetPhaseMaskForSpawn() const
19897 uint32 phase
= PHASEMASK_NORMAL
;
19898 if(!isGameMaster())
19899 phase
= GetPhaseMask();
19902 AuraList
const& phases
= GetAurasByType(SPELL_AURA_PHASE
);
19903 if(!phases
.empty())
19904 phase
= phases
.front()->GetMiscValue();
19907 // some aura phases include 1 normal map in addition to phase itself
19908 if(uint32 n_phase
= phase
& ~PHASEMASK_NORMAL
)
19911 return PHASEMASK_NORMAL
;
19914 uint8
Player::CanEquipUniqueItem(Item
* pItem
, uint8 eslot
, uint32 limit_count
) const
19916 ItemPrototype
const* pProto
= pItem
->GetProto();
19918 // proto based limitations
19919 if(uint8 res
= CanEquipUniqueItem(pProto
,eslot
,limit_count
))
19922 // check unique-equipped on gems
19923 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
19925 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
19928 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
19932 ItemPrototype
const* pGem
= objmgr
.GetItemPrototype(enchantEntry
->GemID
);
19936 // include for check equip another gems with same limit category for not equipped item (and then not counted)
19937 uint32 gem_limit_count
= !pItem
->IsEquipped() && pGem
->ItemLimitCategory
19938 ? pItem
->GetGemCountWithLimitCategory(pGem
->ItemLimitCategory
) : 1;
19940 if(uint8 res
= CanEquipUniqueItem(pGem
, eslot
,gem_limit_count
))
19944 return EQUIP_ERR_OK
;
19947 uint8
Player::CanEquipUniqueItem( ItemPrototype
const* itemProto
, uint8 except_slot
, uint32 limit_count
) const
19949 // check unique-equipped on item
19950 if (itemProto
->Flags
& ITEM_FLAGS_UNIQUE_EQUIPPED
)
19952 // there is an equip limit on this item
19953 if(HasItemOrGemWithIdEquipped(itemProto
->ItemId
,1,except_slot
))
19954 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
19957 // check unique-equipped limit
19958 if (itemProto
->ItemLimitCategory
)
19960 ItemLimitCategoryEntry
const* limitEntry
= sItemLimitCategoryStore
.LookupEntry(itemProto
->ItemLimitCategory
);
19962 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
19964 if(limit_count
> limitEntry
->maxCount
)
19965 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
; // attempt add too many limit category items (gems)
19967 // there is an equip limit on this item
19968 if(HasItemOrGemWithLimitCategoryEquipped(itemProto
->ItemLimitCategory
,limitEntry
->maxCount
-limit_count
+1,except_slot
))
19969 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
19972 return EQUIP_ERR_OK
;
19975 void Player::HandleFall(MovementInfo
const& movementInfo
)
19977 // calculate total z distance of the fall
19978 float z_diff
= m_lastFallZ
- movementInfo
.z
;
19979 sLog
.outDebug("zDiff = %f", z_diff
);
19981 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
19982 // 14.57 can be calculated by resolving damageperc formula below to 0
19983 if (z_diff
>= 14.57f
&& !isDead() && !isGameMaster() &&
19984 !HasAuraType(SPELL_AURA_HOVER
) && !HasAuraType(SPELL_AURA_FEATHER_FALL
) &&
19985 !HasAuraType(SPELL_AURA_FLY
) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL
) )
19987 //Safe fall, fall height reduction
19988 int32 safe_fall
= GetTotalAuraModifier(SPELL_AURA_SAFE_FALL
);
19990 float damageperc
= 0.018f
*(z_diff
-safe_fall
)-0.2426f
;
19994 uint32 damage
= (uint32
)(damageperc
* GetMaxHealth()*sWorld
.getRate(RATE_DAMAGE_FALL
));
19996 float height
= movementInfo
.z
;
19997 UpdateGroundPositionZ(movementInfo
.x
,movementInfo
.y
,height
);
20001 //Prevent fall damage from being more than the player maximum health
20002 if (damage
> GetMaxHealth())
20003 damage
= GetMaxHealth();
20006 if (GetDummyAura(43621))
20007 damage
= GetMaxHealth()/2;
20009 uint32 original_health
= GetHealth();
20010 uint32 final_damage
= EnvironmentalDamage(DAMAGE_FALL
, damage
);
20012 // recheck alive, might have died of EnvironmentalDamage, avoid cases when player die in fact like Spirit of Redemption case
20013 if (isAlive() && final_damage
< original_health
)
20014 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING
, uint32(z_diff
*100));
20017 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
20018 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
);
20023 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type
, uint32 miscvalue1
/*=0*/, uint32 miscvalue2
/*=0*/, Unit
*unit
/*=NULL*/, uint32 time
/*=0*/ )
20025 GetAchievementMgr().UpdateAchievementCriteria(type
, miscvalue1
,miscvalue2
,unit
,time
);
20028 void Player::LearnTalent(uint32 talentId
, uint32 talentRank
)
20030 uint32 CurTalentPoints
= GetFreeTalentPoints();
20032 if(CurTalentPoints
== 0)
20035 if (talentRank
>= MAX_TALENT_RANK
)
20038 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry( talentId
);
20043 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentInfo
->TalentTab
);
20048 // prevent learn talent for different class (cheating)
20049 if( (getClassMask() & talentTabInfo
->ClassMask
) == 0 )
20052 // find current max talent rank
20053 int32 curtalent_maxrank
= 0;
20054 for(int32 k
= MAX_TALENT_RANK
-1; k
> -1; --k
)
20056 if(talentInfo
->RankID
[k
] && HasSpell(talentInfo
->RankID
[k
]))
20058 curtalent_maxrank
= k
+ 1;
20063 // we already have same or higher talent rank learned
20064 if(curtalent_maxrank
>= (talentRank
+ 1))
20067 // check if we have enough talent points
20068 if(CurTalentPoints
< (talentRank
- curtalent_maxrank
+ 1))
20071 // Check if it requires another talent
20072 if (talentInfo
->DependsOn
> 0)
20074 if(TalentEntry
const *depTalentInfo
= sTalentStore
.LookupEntry(talentInfo
->DependsOn
))
20076 bool hasEnoughRank
= false;
20077 for (int i
= talentInfo
->DependsOnRank
; i
< MAX_TALENT_RANK
; ++i
)
20079 if (depTalentInfo
->RankID
[i
] != 0)
20080 if (HasSpell(depTalentInfo
->RankID
[i
]))
20081 hasEnoughRank
= true;
20083 if (!hasEnoughRank
)
20088 // Find out how many points we have in this field
20089 uint32 spentPoints
= 0;
20091 uint32 tTab
= talentInfo
->TalentTab
;
20092 if (talentInfo
->Row
> 0)
20094 unsigned int numRows
= sTalentStore
.GetNumRows();
20095 for (unsigned int i
= 0; i
< numRows
; ++i
) // Loop through all talents.
20097 // Someday, someone needs to revamp
20098 const TalentEntry
*tmpTalent
= sTalentStore
.LookupEntry(i
);
20099 if (tmpTalent
) // the way talents are tracked
20101 if (tmpTalent
->TalentTab
== tTab
)
20103 for (int j
= 0; j
< MAX_TALENT_RANK
; ++j
)
20105 if (tmpTalent
->RankID
[j
] != 0)
20107 if (HasSpell(tmpTalent
->RankID
[j
]))
20109 spentPoints
+= j
+ 1;
20118 // not have required min points spent in talent tree
20119 if(spentPoints
< (talentInfo
->Row
* MAX_TALENT_RANK
))
20122 // spell not set in talent.dbc
20123 uint32 spellid
= talentInfo
->RankID
[talentRank
];
20126 sLog
.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId
, talentRank
);
20131 if(HasSpell(spellid
))
20134 // learn! (other talent ranks will unlearned at learning)
20135 learnSpell(spellid
, false);
20136 sLog
.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId
, talentRank
, spellid
);
20138 // update free talent points
20139 SetFreeTalentPoints(CurTalentPoints
- (talentRank
- curtalent_maxrank
+ 1));
20142 void Player::LearnPetTalent(uint64 petGuid
, uint32 talentId
, uint32 talentRank
)
20144 Pet
*pet
= GetPet();
20149 if(petGuid
!= pet
->GetGUID())
20152 uint32 CurTalentPoints
= pet
->GetFreeTalentPoints();
20154 if(CurTalentPoints
== 0)
20157 if (talentRank
>= MAX_PET_TALENT_RANK
)
20160 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry(talentId
);
20165 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry(talentInfo
->TalentTab
);
20170 CreatureInfo
const *ci
= pet
->GetCreatureInfo();
20175 CreatureFamilyEntry
const *pet_family
= sCreatureFamilyStore
.LookupEntry(ci
->family
);
20180 if(pet_family
->petTalentType
< 0) // not hunter pet
20183 // prevent learn talent for different family (cheating)
20184 if(!((1 << pet_family
->petTalentType
) & talentTabInfo
->petTalentMask
))
20187 // find current max talent rank
20188 int32 curtalent_maxrank
= 0;
20189 for(int32 k
= MAX_TALENT_RANK
-1; k
> -1; --k
)
20191 if(talentInfo
->RankID
[k
] && pet
->HasSpell(talentInfo
->RankID
[k
]))
20193 curtalent_maxrank
= k
+ 1;
20198 // we already have same or higher talent rank learned
20199 if(curtalent_maxrank
>= (talentRank
+ 1))
20202 // check if we have enough talent points
20203 if(CurTalentPoints
< (talentRank
- curtalent_maxrank
+ 1))
20206 // Check if it requires another talent
20207 if (talentInfo
->DependsOn
> 0)
20209 if(TalentEntry
const *depTalentInfo
= sTalentStore
.LookupEntry(talentInfo
->DependsOn
))
20211 bool hasEnoughRank
= false;
20212 for (int i
= talentInfo
->DependsOnRank
; i
< MAX_TALENT_RANK
; ++i
)
20214 if (depTalentInfo
->RankID
[i
] != 0)
20215 if (pet
->HasSpell(depTalentInfo
->RankID
[i
]))
20216 hasEnoughRank
= true;
20218 if (!hasEnoughRank
)
20223 // Find out how many points we have in this field
20224 uint32 spentPoints
= 0;
20226 uint32 tTab
= talentInfo
->TalentTab
;
20227 if (talentInfo
->Row
> 0)
20229 unsigned int numRows
= sTalentStore
.GetNumRows();
20230 for (unsigned int i
= 0; i
< numRows
; ++i
) // Loop through all talents.
20232 // Someday, someone needs to revamp
20233 const TalentEntry
*tmpTalent
= sTalentStore
.LookupEntry(i
);
20234 if (tmpTalent
) // the way talents are tracked
20236 if (tmpTalent
->TalentTab
== tTab
)
20238 for (int j
= 0; j
< MAX_TALENT_RANK
; ++j
)
20240 if (tmpTalent
->RankID
[j
] != 0)
20242 if (pet
->HasSpell(tmpTalent
->RankID
[j
]))
20244 spentPoints
+= j
+ 1;
20253 // not have required min points spent in talent tree
20254 if(spentPoints
< (talentInfo
->Row
* MAX_PET_TALENT_RANK
))
20257 // spell not set in talent.dbc
20258 uint32 spellid
= talentInfo
->RankID
[talentRank
];
20261 sLog
.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId
, talentRank
);
20266 if(pet
->HasSpell(spellid
))
20269 // learn! (other talent ranks will unlearned at learning)
20270 pet
->learnSpell(spellid
);
20271 sLog
.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId
, talentRank
, spellid
);
20273 // update free talent points
20274 pet
->SetFreeTalentPoints(CurTalentPoints
- (talentRank
- curtalent_maxrank
+ 1));
20277 void Player::UpdateKnownCurrencies(uint32 itemId
, bool apply
)
20279 if(CurrencyTypesEntry
const* ctEntry
= sCurrencyTypesStore
.LookupEntry(itemId
))
20282 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES
,(UI64LIT(1) << (ctEntry
->BitIndex
-1)));
20284 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES
,(UI64LIT(1) << (ctEntry
->BitIndex
-1)));
20288 void Player::UpdateFallInformationIfNeed( MovementInfo
const& minfo
,uint16 opcode
)
20290 if (m_lastFallTime
>= minfo
.fallTime
|| m_lastFallZ
<=minfo
.z
|| opcode
== MSG_MOVE_FALL_LAND
)
20291 SetFallInformation(minfo
.fallTime
, minfo
.z
);
20294 void Player::UnsummonPetTemporaryIfAny()
20296 Pet
* pet
= GetPet();
20300 if(!m_temporaryUnsummonedPetNumber
&& pet
->isControlled() && !pet
->isTemporarySummoned() )
20302 m_temporaryUnsummonedPetNumber
= pet
->GetCharmInfo()->GetPetNumber();
20303 m_oldpetspell
= pet
->GetUInt32Value(UNIT_CREATED_BY_SPELL
);
20306 RemovePet(pet
, PET_SAVE_AS_CURRENT
);
20309 void Player::ResummonPetTemporaryUnSummonedIfAny()
20311 if(!m_temporaryUnsummonedPetNumber
)
20314 // not resummon in not appropriate state
20315 if(IsPetNeedBeTemporaryUnsummoned())
20321 Pet
* NewPet
= new Pet
;
20322 if(!NewPet
->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber
, true))
20325 m_temporaryUnsummonedPetNumber
= 0;
20328 bool Player::canSeeSpellClickOn(Creature
const *c
) const
20330 if(!c
->HasFlag(UNIT_NPC_FLAGS
,UNIT_NPC_FLAG_SPELLCLICK
))
20333 SpellClickInfoMapBounds clickPair
= objmgr
.GetSpellClickInfoMapBounds(c
->GetEntry());
20334 for(SpellClickInfoMap::const_iterator itr
= clickPair
.first
; itr
!= clickPair
.second
; ++itr
)
20335 if(itr
->second
.IsFitToRequirements(this))
20341 void Player::BuildPlayerTalentsInfoData(WorldPacket
*data
)
20343 *data
<< uint32(GetFreeTalentPoints()); // unspentTalentPoints
20344 *data
<< uint8(m_specsCount
); // talent group count (0, 1 or 2)
20345 *data
<< uint8(m_activeSpec
); // talent group index (0 or 1)
20349 // loop through all specs (only 1 for now)
20350 for(uint32 specIdx
= 0; specIdx
< m_specsCount
; ++specIdx
)
20352 uint8 talentIdCount
= 0;
20353 size_t pos
= data
->wpos();
20354 *data
<< uint8(talentIdCount
); // [PH], talentIdCount
20356 // find class talent tabs (all players have 3 talent tabs)
20357 uint32
const* talentTabIds
= GetTalentTabPages(getClass());
20359 for(uint32 i
= 0; i
< 3; ++i
)
20361 uint32 talentTabId
= talentTabIds
[i
];
20363 for(uint32 talentId
= 0; talentId
< sTalentStore
.GetNumRows(); ++talentId
)
20365 TalentEntry
const* talentInfo
= sTalentStore
.LookupEntry(talentId
);
20369 // skip another tab talents
20370 if(talentInfo
->TalentTab
!= talentTabId
)
20373 // find max talent rank
20374 int32 curtalent_maxrank
= -1;
20375 for(int32 k
= MAX_TALENT_RANK
-1; k
> -1; --k
)
20377 if(talentInfo
->RankID
[k
] && HasSpell(talentInfo
->RankID
[k
]))
20379 curtalent_maxrank
= k
;
20384 // not learned talent
20385 if(curtalent_maxrank
< 0)
20388 *data
<< uint32(talentInfo
->TalentID
); // Talent.dbc
20389 *data
<< uint8(curtalent_maxrank
); // talentMaxRank (0-4)
20395 data
->put
<uint8
>(pos
, talentIdCount
); // put real count
20397 *data
<< uint8(MAX_GLYPH_SLOT_INDEX
); // glyphs count
20399 for(uint8 i
= 0; i
< MAX_GLYPH_SLOT_INDEX
; ++i
)
20400 *data
<< uint16(GetGlyph(i
)); // GlyphProperties.dbc
20405 void Player::BuildPetTalentsInfoData(WorldPacket
*data
)
20407 uint32 unspentTalentPoints
= 0;
20408 size_t pointsPos
= data
->wpos();
20409 *data
<< uint32(unspentTalentPoints
); // [PH], unspentTalentPoints
20411 uint8 talentIdCount
= 0;
20412 size_t countPos
= data
->wpos();
20413 *data
<< uint8(talentIdCount
); // [PH], talentIdCount
20415 Pet
*pet
= GetPet();
20419 unspentTalentPoints
= pet
->GetFreeTalentPoints();
20421 data
->put
<uint32
>(pointsPos
, unspentTalentPoints
); // put real points
20423 CreatureInfo
const *ci
= pet
->GetCreatureInfo();
20427 CreatureFamilyEntry
const *pet_family
= sCreatureFamilyStore
.LookupEntry(ci
->family
);
20428 if(!pet_family
|| pet_family
->petTalentType
< 0)
20431 for(uint32 talentTabId
= 1; talentTabId
< sTalentTabStore
.GetNumRows(); ++talentTabId
)
20433 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentTabId
);
20437 if(!((1 << pet_family
->petTalentType
) & talentTabInfo
->petTalentMask
))
20440 for(uint32 talentId
= 0; talentId
< sTalentStore
.GetNumRows(); ++talentId
)
20442 TalentEntry
const* talentInfo
= sTalentStore
.LookupEntry(talentId
);
20446 // skip another tab talents
20447 if(talentInfo
->TalentTab
!= talentTabId
)
20450 // find max talent rank
20451 int32 curtalent_maxrank
= -1;
20452 for(int32 k
= 4; k
> -1; --k
)
20454 if(talentInfo
->RankID
[k
] && pet
->HasSpell(talentInfo
->RankID
[k
]))
20456 curtalent_maxrank
= k
;
20461 // not learned talent
20462 if(curtalent_maxrank
< 0)
20465 *data
<< uint32(talentInfo
->TalentID
); // Talent.dbc
20466 *data
<< uint8(curtalent_maxrank
); // talentMaxRank (0-4)
20471 data
->put
<uint8
>(countPos
, talentIdCount
); // put real count
20477 void Player::SendTalentsInfoData(bool pet
)
20479 WorldPacket
data(SMSG_TALENTS_INFO
, 50);
20480 data
<< uint8(pet
? 1 : 0);
20482 BuildPetTalentsInfoData(&data
);
20484 BuildPlayerTalentsInfoData(&data
);
20485 GetSession()->SendPacket(&data
);
20488 void Player::BuildEnchantmentsInfoData(WorldPacket
*data
)
20490 uint32 slotUsedMask
= 0;
20491 size_t slotUsedMaskPos
= data
->wpos();
20492 *data
<< uint32(slotUsedMask
); // slotUsedMask < 0x80000
20494 for(uint32 i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
20496 Item
*item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, i
);
20501 slotUsedMask
|= (1 << i
);
20503 *data
<< uint32(item
->GetEntry()); // item entry
20505 uint16 enchantmentMask
= 0;
20506 size_t enchantmentMaskPos
= data
->wpos();
20507 *data
<< uint16(enchantmentMask
); // enchantmentMask < 0x1000
20509 for(uint32 j
= 0; j
< MAX_ENCHANTMENT_SLOT
; ++j
)
20511 uint32 enchId
= item
->GetEnchantmentId(EnchantmentSlot(j
));
20516 enchantmentMask
|= (1 << j
);
20518 *data
<< uint16(enchId
); // enchantmentId?
20521 data
->put
<uint16
>(enchantmentMaskPos
, enchantmentMask
);
20523 *data
<< uint16(0); // ?
20524 *data
<< uint8(0); // PGUID!
20525 *data
<< uint32(0); // seed?
20528 data
->put
<uint32
>(slotUsedMaskPos
, slotUsedMask
);
20531 void Player::SendEquipmentSetList()
20534 WorldPacket
data(SMSG_EQUIPMENT_SET_LIST
, 4);
20535 size_t count_pos
= data
.wpos();
20536 data
<< uint32(count
); // count placeholder
20537 for(EquipmentSets::iterator itr
= m_EquipmentSets
.begin(); itr
!= m_EquipmentSets
.end(); ++itr
)
20539 if(itr
->second
.state
==EQUIPMENT_SET_DELETED
)
20541 data
.appendPackGUID(itr
->second
.Guid
);
20542 data
<< uint32(itr
->first
);
20543 data
<< itr
->second
.Name
;
20544 data
<< itr
->second
.IconName
;
20545 for(uint32 i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
20546 data
.appendPackGUID(MAKE_NEW_GUID(itr
->second
.Items
[i
], 0, HIGHGUID_ITEM
));
20548 ++count
; // client have limit but it checked at loading and set
20550 data
.put
<uint32
>(count_pos
, count
);
20551 GetSession()->SendPacket(&data
);
20554 void Player::SetEquipmentSet(uint32 index
, EquipmentSet eqset
)
20556 if(eqset
.Guid
!= 0)
20558 bool found
= false;
20560 for(EquipmentSets::iterator itr
= m_EquipmentSets
.begin(); itr
!= m_EquipmentSets
.end(); ++itr
)
20562 if((itr
->second
.Guid
== eqset
.Guid
) && (itr
->first
== index
))
20569 if(!found
) // something wrong...
20571 sLog
.outError("Player %s tried to save equipment set "UI64FMTD
" (index %u), but that equipment set not found!", GetName(), eqset
.Guid
, index
);
20576 EquipmentSet
& eqslot
= m_EquipmentSets
[index
];
20578 EquipmentSetUpdateState old_state
= eqslot
.state
;
20582 if(eqset
.Guid
== 0)
20584 eqslot
.Guid
= objmgr
.GenerateEquipmentSetGuid();
20586 WorldPacket
data(SMSG_EQUIPMENT_SET_SAVED
, 4 + 1);
20587 data
<< uint32(index
);
20588 data
.appendPackGUID(eqslot
.Guid
);
20589 GetSession()->SendPacket(&data
);
20592 eqslot
.state
= old_state
== EQUIPMENT_SET_NEW
? EQUIPMENT_SET_NEW
: EQUIPMENT_SET_CHANGED
;
20595 void Player::_SaveEquipmentSets()
20597 for(EquipmentSets::iterator itr
= m_EquipmentSets
.begin(); itr
!= m_EquipmentSets
.end();)
20599 uint32 index
= itr
->first
;
20600 EquipmentSet
& eqset
= itr
->second
;
20601 switch(eqset
.state
)
20603 case EQUIPMENT_SET_UNCHANGED
:
20605 break; // nothing do
20606 case EQUIPMENT_SET_CHANGED
:
20607 CharacterDatabase
.PExecute("UPDATE character_equipmentsets SET name='%s', iconname='%s', item0='%u', item1='%u', item2='%u', item3='%u', item4='%u', item5='%u', item6='%u', item7='%u', item8='%u', item9='%u', item10='%u', item11='%u', item12='%u', item13='%u', item14='%u', item15='%u', item16='%u', item17='%u', item18='%u' WHERE guid='%u' AND setguid='"UI64FMTD
"' AND setindex='%u'",
20608 eqset
.Name
.c_str(), eqset
.IconName
.c_str(), eqset
.Items
[0], eqset
.Items
[1], eqset
.Items
[2], eqset
.Items
[3], eqset
.Items
[4], eqset
.Items
[5], eqset
.Items
[6], eqset
.Items
[7],
20609 eqset
.Items
[8], eqset
.Items
[9], eqset
.Items
[10], eqset
.Items
[11], eqset
.Items
[12], eqset
.Items
[13], eqset
.Items
[14], eqset
.Items
[15], eqset
.Items
[16], eqset
.Items
[17], eqset
.Items
[18], GetGUIDLow(), eqset
.Guid
, index
);
20610 eqset
.state
= EQUIPMENT_SET_UNCHANGED
;
20613 case EQUIPMENT_SET_NEW
:
20614 CharacterDatabase
.PExecute("INSERT INTO character_equipmentsets VALUES ('%u', '"UI64FMTD
"', '%u', '%s', '%s', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
20615 GetGUIDLow(), eqset
.Guid
, index
, eqset
.Name
.c_str(), eqset
.IconName
.c_str(), eqset
.Items
[0], eqset
.Items
[1], eqset
.Items
[2], eqset
.Items
[3], eqset
.Items
[4], eqset
.Items
[5], eqset
.Items
[6], eqset
.Items
[7],
20616 eqset
.Items
[8], eqset
.Items
[9], eqset
.Items
[10], eqset
.Items
[11], eqset
.Items
[12], eqset
.Items
[13], eqset
.Items
[14], eqset
.Items
[15], eqset
.Items
[16], eqset
.Items
[17], eqset
.Items
[18]);
20617 eqset
.state
= EQUIPMENT_SET_UNCHANGED
;
20620 case EQUIPMENT_SET_DELETED
:
20621 CharacterDatabase
.PExecute("DELETE FROM character_equipmentsets WHERE setguid="UI64FMTD
, eqset
.Guid
);
20622 m_EquipmentSets
.erase(itr
++);
20628 void Player::_SaveBGData()
20630 CharacterDatabase
.PExecute("DELETE FROM character_battleground_data WHERE guid='%u'", GetGUIDLow());
20631 if (m_bgData
.bgInstanceID
)
20633 /* guid, bgInstanceID, bgTeam, x, y, z, o, map, taxi[0], taxi[1], mountSpell */
20634 CharacterDatabase
.PExecute("INSERT INTO character_battleground_data VALUES ('%u', '%u', '%u', '%f', '%f', '%f', '%f', '%u', '%u', '%u', '%u')",
20635 GetGUIDLow(), m_bgData
.bgInstanceID
, m_bgData
.bgTeam
, m_bgData
.joinPos
.coord_x
, m_bgData
.joinPos
.coord_y
, m_bgData
.joinPos
.coord_z
,
20636 m_bgData
.joinPos
.orientation
, m_bgData
.joinPos
.mapid
, m_bgData
.taxiPath
[0], m_bgData
.taxiPath
[1], m_bgData
.mountSpell
);
20640 void Player::DeleteEquipmentSet(uint64 setGuid
)
20642 for(EquipmentSets::iterator itr
= m_EquipmentSets
.begin(); itr
!= m_EquipmentSets
.end(); ++itr
)
20644 if(itr
->second
.Guid
== setGuid
)
20646 if(itr
->second
.state
== EQUIPMENT_SET_NEW
)
20647 m_EquipmentSets
.erase(itr
);
20649 itr
->second
.state
= EQUIPMENT_SET_DELETED
;
20655 void Player::ActivateSpec(uint32 specNum
)
20657 if(GetActiveSpec() == specNum
)
20660 resetTalents(true);
20663 void Player::RemoveAtLoginFlag( AtLoginFlags f
, bool in_db_also
/*= false*/ )
20665 m_atLoginFlags
&= ~f
;
20668 CharacterDatabase
.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(f
), GetGUIDLow());
20671 void Player::SendClearCooldown( uint32 spell_id
, Unit
* target
)
20673 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, 4+8);
20674 data
<< uint32(spell_id
);
20675 data
<< uint64(target
->GetGUID());
20676 SendDirectMessage(&data
);
20679 void Player::BuildTeleportAckMsg( WorldPacket
*data
, float x
, float y
, float z
, float ang
) const
20681 data
->Initialize(MSG_MOVE_TELEPORT_ACK
, 41);
20682 data
->append(GetPackGUID());
20683 *data
<< uint32(0); // this value increments every time
20684 *data
<< uint32(m_movementInfo
.GetMovementFlags()); // movement flags
20685 *data
<< uint16(0); // 2.3.0
20686 *data
<< uint32(getMSTime()); // time
20691 *data
<< uint32(0);
20694 bool Player::HasMovementFlag( MovementFlags f
) const
20696 return m_movementInfo
.HasMovementFlag(f
);
20699 void Player::SetFarSightGUID( uint64 guid
)
20701 if(GetFarSight() == guid
)
20704 SetUInt64Value(PLAYER_FARSIGHT
, guid
);
20706 // need triggering load grids around new view point
20707 UpdateVisibilityForPlayer();
20710 void Player::UpdateVisibilityForPlayer()
20712 WorldObject
const* viewPoint
= GetViewPoint();
20715 CellPair
p(MaNGOS::ComputeCellPair(GetPositionX(), GetPositionY()));
20718 m
->UpdatePlayerVisibility(this, cell
, p
);
20720 if (this != viewPoint
)
20722 CellPair
pView(MaNGOS::ComputeCellPair(viewPoint
->GetPositionX(), viewPoint
->GetPositionY()));
20723 Cell
cellView(pView
);
20725 m
->UpdateObjectsVisibilityFor(this, cellView
, pView
);
20728 m
->UpdateObjectsVisibilityFor(this, cell
, p
);
20731 void Player::SendDuelCountdown(uint32 counter
)
20733 WorldPacket
data(SMSG_DUEL_COUNTDOWN
, 4);
20734 data
<< uint32(counter
); // seconds
20735 GetSession()->SendPacket(&data
);