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"
24 #include "ObjectMgr.h"
27 #include "WorldPacket.h"
28 #include "WorldSession.h"
29 #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"
50 #include "SpellAuras.h"
52 #include "Transports.h"
54 #include "BattleGround.h"
55 #include "BattleGroundMgr.h"
56 #include "ArenaTeam.h"
58 #include "Database/DatabaseImpl.h"
60 #include "SocialMgr.h"
61 #include "AchievementMgr.h"
65 #define ZONE_UPDATE_INTERVAL 1000
67 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
68 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
69 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
71 #define SKILL_VALUE(x) PAIR32_LOPART(x)
72 #define SKILL_MAX(x) PAIR32_HIPART(x)
73 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
75 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
76 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
77 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
81 CHARACTER_FLAG_NONE
= 0x00000000,
82 CHARACTER_FLAG_UNK1
= 0x00000001,
83 CHARACTER_FLAG_UNK2
= 0x00000002,
84 CHARACTER_LOCKED_FOR_TRANSFER
= 0x00000004,
85 CHARACTER_FLAG_UNK4
= 0x00000008,
86 CHARACTER_FLAG_UNK5
= 0x00000010,
87 CHARACTER_FLAG_UNK6
= 0x00000020,
88 CHARACTER_FLAG_UNK7
= 0x00000040,
89 CHARACTER_FLAG_UNK8
= 0x00000080,
90 CHARACTER_FLAG_UNK9
= 0x00000100,
91 CHARACTER_FLAG_UNK10
= 0x00000200,
92 CHARACTER_FLAG_HIDE_HELM
= 0x00000400,
93 CHARACTER_FLAG_HIDE_CLOAK
= 0x00000800,
94 CHARACTER_FLAG_UNK13
= 0x00001000,
95 CHARACTER_FLAG_GHOST
= 0x00002000,
96 CHARACTER_FLAG_RENAME
= 0x00004000,
97 CHARACTER_FLAG_UNK16
= 0x00008000,
98 CHARACTER_FLAG_UNK17
= 0x00010000,
99 CHARACTER_FLAG_UNK18
= 0x00020000,
100 CHARACTER_FLAG_UNK19
= 0x00040000,
101 CHARACTER_FLAG_UNK20
= 0x00080000,
102 CHARACTER_FLAG_UNK21
= 0x00100000,
103 CHARACTER_FLAG_UNK22
= 0x00200000,
104 CHARACTER_FLAG_UNK23
= 0x00400000,
105 CHARACTER_FLAG_UNK24
= 0x00800000,
106 CHARACTER_FLAG_LOCKED_BY_BILLING
= 0x01000000,
107 CHARACTER_FLAG_DECLINED
= 0x02000000,
108 CHARACTER_FLAG_UNK27
= 0x04000000,
109 CHARACTER_FLAG_UNK28
= 0x08000000,
110 CHARACTER_FLAG_UNK29
= 0x10000000,
111 CHARACTER_FLAG_UNK30
= 0x20000000,
112 CHARACTER_FLAG_UNK31
= 0x40000000,
113 CHARACTER_FLAG_UNK32
= 0x80000000
116 // corpse reclaim times
117 #define DEATH_EXPIRE_STEP (5*MINUTE)
118 #define MAX_DEATH_COUNT 3
120 static uint32 copseReclaimDelay
[MAX_DEATH_COUNT
] = { 30, 60, 120 };
122 //== PlayerTaxi ================================================
124 PlayerTaxi::PlayerTaxi()
127 memset(m_taximask
, 0, sizeof(m_taximask
));
130 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race
, uint32 chrClass
, uint32 level
)
132 // capital and taxi hub masks
135 case RACE_HUMAN
: SetTaximaskNode(2); break; // Human
136 case RACE_ORC
: SetTaximaskNode(23); break; // Orc
137 case RACE_DWARF
: SetTaximaskNode(6); break; // Dwarf
138 case RACE_NIGHTELF
: SetTaximaskNode(26);
139 SetTaximaskNode(27); break; // Night Elf
140 case RACE_UNDEAD_PLAYER
: SetTaximaskNode(11); break;// Undead
141 case RACE_TAUREN
: SetTaximaskNode(22); break; // Tauren
142 case RACE_GNOME
: SetTaximaskNode(6); break; // Gnome
143 case RACE_TROLL
: SetTaximaskNode(23); break; // Troll
144 case RACE_BLOODELF
: SetTaximaskNode(82); break; // Blood Elf
145 case RACE_DRAENEI
: SetTaximaskNode(94); break; // Draenei
150 case CLASS_DEATH_KNIGHT
: // TODO: figure out initial known nodes
154 // new continent starting masks (It will be accessible only at new map)
155 switch(Player::TeamForRace(race
))
157 case ALLIANCE
: SetTaximaskNode(100); break;
158 case HORDE
: SetTaximaskNode(99); break;
160 // level dependent taxi hubs
162 SetTaximaskNode(213); //Shattered Sun Staging Area
165 void PlayerTaxi::LoadTaxiMask(const char* data
)
167 Tokens tokens
= StrSplit(data
, " ");
170 Tokens::iterator iter
;
171 for (iter
= tokens
.begin(), index
= 0;
172 (index
< TaxiMaskSize
) && (iter
!= tokens
.end()); ++iter
, ++index
)
174 // load and set bits only for existed taxi nodes
175 m_taximask
[index
] = sTaxiNodesMask
[index
] & uint32(atol((*iter
).c_str()));
179 void PlayerTaxi::AppendTaximaskTo( ByteBuffer
& data
, bool all
)
183 for (uint8 i
=0; i
<TaxiMaskSize
; i
++)
184 data
<< uint32(sTaxiNodesMask
[i
]); // all existed nodes
188 for (uint8 i
=0; i
<TaxiMaskSize
; i
++)
189 data
<< uint32(m_taximask
[i
]); // known nodes
193 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string
& values
, uint32 team
)
195 ClearTaxiDestinations();
197 Tokens tokens
= StrSplit(values
," ");
199 for(Tokens::iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
)
201 uint32 node
= uint32(atol(iter
->c_str()));
202 AddTaxiDestination(node
);
205 if(m_TaxiDestinations
.empty())
209 if(m_TaxiDestinations
.size() < 2)
212 for(size_t i
= 1; i
< m_TaxiDestinations
.size(); ++i
)
216 objmgr
.GetTaxiPath(m_TaxiDestinations
[i
-1],m_TaxiDestinations
[i
],path
,cost
);
221 // can't load taxi path without mount set (quest taxi path?)
222 if(!objmgr
.GetTaxiMount(GetTaxiSource(),team
))
228 std::string
PlayerTaxi::SaveTaxiDestinationsToString()
230 if(m_TaxiDestinations
.empty())
233 std::ostringstream ss
;
235 for(size_t i
=0; i
< m_TaxiDestinations
.size(); ++i
)
236 ss
<< m_TaxiDestinations
[i
] << " ";
241 uint32
PlayerTaxi::GetCurrentTaxiPath() const
243 if(m_TaxiDestinations
.size() < 2)
249 objmgr
.GetTaxiPath(m_TaxiDestinations
[0],m_TaxiDestinations
[1],path
,cost
);
254 std::ostringstream
& operator<< (std::ostringstream
& ss
, PlayerTaxi
const& taxi
)
257 for(int i
= 0; i
< TaxiMaskSize
; ++i
)
258 ss
<< taxi
.m_taximask
[i
] << " ";
263 //== Player ====================================================
265 const int32
Player::ReputationRank_Length
[MAX_REPUTATION_RANK
] = {36000, 3000, 3000, 3000, 6000, 12000, 21000, 1000};
267 UpdateMask
Player::updateVisualBits
;
269 Player::Player (WorldSession
*session
): Unit(), m_achievementMgr(this)
276 m_objectType
|= TYPEMASK_PLAYER
;
277 m_objectTypeId
= TYPEID_PLAYER
;
279 m_valuesCount
= PLAYER_END
;
286 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER
)
287 SetAcceptTicket(true);
289 // players always accept
290 if(GetSession()->GetSecurity() == SEC_PLAYER
)
291 SetAcceptWhispers(true);
299 m_usedTalentCount
= 0;
300 m_questRewardTalentCount
= 0;
303 m_weaponChangeTimer
= 0;
306 m_zoneUpdateTimer
= 0;
310 m_nextSave
= sWorld
.getConfig(CONFIG_INTERVAL_SAVE
);
312 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
313 // this must help in case next save after mass player load after server startup
314 m_nextSave
= urand(m_nextSave
/2,m_nextSave
*3/2);
316 clearResurrectRequestData();
318 m_SpellModRemoveCount
= 0;
320 memset(m_items
, 0, sizeof(Item
*)*PLAYER_SLOTS_COUNT
);
324 // group is initialized in the reference constructor
325 SetGroupInvite(NULL
);
326 m_groupUpdateMask
= 0;
327 m_auraUpdateMask
= 0;
331 m_GuildIdInvited
= 0;
332 m_ArenaTeamIdInvited
= 0;
334 m_atLoginFlags
= AT_LOGIN_NONE
;
343 PlayerTalkClass
= new PlayerMenu( GetSession() );
344 m_currentBuybackSlot
= BUYBACK_SLOT_START
;
346 for ( int aX
= 0 ; aX
< 8 ; aX
++ )
347 m_Tutorials
[ aX
] = 0x00;
348 m_TutorialsChanged
= false;
350 m_DailyQuestChanged
= false;
351 m_lastDailyQuestTime
= 0;
354 m_weaponChangeTimer
= 0;
356 m_isunderwater
= UNDERWATER_NONE
;
362 m_deathExpireTime
= 0;
366 m_DetectInvTimer
= 1000;
368 m_bgBattleGroundID
= 0;
369 for (int j
=0; j
< PLAYER_MAX_BATTLEGROUND_QUEUES
; j
++)
371 m_bgBattleGroundQueueID
[j
].bgQueueType
= 0;
372 m_bgBattleGroundQueueID
[j
].invitedToInstance
= 0;
376 m_logintime
= time(NULL
);
377 m_Last_tick
= m_logintime
;
378 m_WeaponProficiency
= 0;
379 m_ArmorProficiency
= 0;
382 m_canDualWield
= false;
383 m_canTitanGrip
= false;
386 m_temporaryUnsummonedPetNumber
= 0;
387 //cache for UNIT_CREATED_BY_SPELL to allow
388 //returning reagents for temporarily removed pets
389 //when dying/logging out
392 ////////////////////Rest System/////////////////////
399 rest_type
=REST_TYPE_NO
;
400 ////////////////////Rest System/////////////////////
402 m_mailsLoaded
= false;
403 m_mailsUpdated
= false;
405 m_nextMailDelivereTime
= 0;
407 m_resetTalentsCost
= 0;
408 m_resetTalentsTime
= 0;
409 m_itemUpdateQueueBlocked
= false;
411 for (int i
= 0; i
< MAX_MOVE_TYPE
; ++i
)
412 m_forced_speed_changes
[i
] = 0;
416 /////////////////// Instance System /////////////////////
419 m_InstanceValid
= true;
420 m_dungeonDifficulty
= DIFFICULTY_NORMAL
;
422 for (int i
= 0; i
< BASEMOD_END
; i
++)
424 m_auraBaseMod
[i
][FLAT_MOD
] = 0.0f
;
425 m_auraBaseMod
[i
][PCT_MOD
] = 1.0f
;
428 for (int i
= 0; i
< MAX_COMBAT_RATING
; i
++)
429 m_baseRatingValue
[i
] = 0;
431 m_baseSpellDamage
= 0;
432 m_baseSpellHealing
= 0;
437 m_lastHonorUpdateTime
= time(NULL
);
446 //Default movement to run mode
447 m_unit_movement_flags
= 0;
452 m_bgAfkReportedTimer
= 0;
453 m_contestedPvPTimer
= 0;
455 m_declinedname
= NULL
;
461 CleanupsBeforeDelete();
463 // it must be unloaded already in PlayerLogout and accessed only for loggined player
466 // Note: buy back item already deleted from DB when player was saved
467 for(int i
= 0; i
< PLAYER_SLOTS_COUNT
; ++i
)
474 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
477 //all mailed items should be deleted, also all mail should be deallocated
478 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
481 for (ItemMap::iterator iter
= mMitems
.begin(); iter
!= mMitems
.end(); ++iter
)
482 delete iter
->second
; //if item is duplicated... then server may crash ... but that item should be deallocated
484 delete PlayerTalkClass
;
488 m_transport
->RemovePassenger(this);
491 for(size_t x
= 0; x
< ItemSetEff
.size(); x
++)
493 delete ItemSetEff
[x
];
495 // clean up player-instance binds, may unload some instance saves
496 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
497 for(BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
498 itr
->second
.save
->RemovePlayer(this);
500 delete m_declinedname
;
504 void Player::CleanupsBeforeDelete()
506 if(m_uint32Values
) // only for fully created Object
509 DuelComplete(DUEL_INTERUPTED
);
511 Unit::CleanupsBeforeDelete();
514 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
)
516 //FIXME: outfitId not used in player creating
518 Object::_Create(guidlow
, 0, HIGHGUID_PLAYER
);
522 PlayerInfo
const* info
= objmgr
.GetPlayerInfo(race
, class_
);
525 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
529 for (int i
= 0; i
< PLAYER_SLOTS_COUNT
; i
++)
535 SetMapId(info
->mapId
);
536 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
);
538 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(class_
);
541 sLog
.outError("Class %u not found in DBC (Wrong DBC files?)",class_
);
545 uint8 powertype
= cEntry
->powerType
;
553 unitfield = 0x00000000;
556 unitfield = 0x00110000;
558 case POWER_RUNIC_POWER:
559 unitfield = 0x0000EE00; //TODO: find correct unitfield here
562 sLog.outError("Invalid default powertype %u for player (class %u)",powertype,class_);
566 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, DEFAULT_WORLD_OBJECT_SIZE
);
567 SetFloatValue(UNIT_FIELD_COMBATREACH
, 1.5f
);
572 SetDisplayId(info
->displayId_f
);
573 SetNativeDisplayId(info
->displayId_f
);
576 SetDisplayId(info
->displayId_m
);
577 SetNativeDisplayId(info
->displayId_m
);
580 sLog
.outError("Invalid gender %u for player",gender
);
585 setFactionForRace(m_race
);
587 uint32 RaceClassGender
= ( race
) | ( class_
<< 8 ) | ( gender
<< 16 );
589 SetUInt32Value(UNIT_FIELD_BYTES_0
, ( RaceClassGender
| ( powertype
<< 24 ) ) );
590 //SetUInt32Value(UNIT_FIELD_BYTES_1, unitfield);
591 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_PVP
);
592 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
);
593 SetFlag(UNIT_FIELD_FLAGS_2
, UNIT_FLAG2_REGENERATE_POWER
);
594 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
); // fix cast time showed in spell tooltip on client
595 SetFloatValue(UNIT_FIELD_HOVERHEIGHT
, 1.0f
); // default for players in 3.0.3
597 // -1 is default value
598 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX
, uint32(-1));
600 SetUInt32Value(PLAYER_BYTES
, (skin
| (face
<< 8) | (hairStyle
<< 16) | (hairColor
<< 24)));
601 SetUInt32Value(PLAYER_BYTES_2
, (facialHair
| (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
602 SetByteValue(PLAYER_BYTES_3
, 0, gender
);
604 SetUInt32Value( PLAYER_GUILDID
, 0 );
605 SetUInt32Value( PLAYER_GUILDRANK
, 0 );
606 SetUInt32Value( PLAYER_GUILD_TIMESTAMP
, 0 );
608 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES
, 0 ); // 0=disabled
609 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1
, 0 ); // 0=disabled
610 SetUInt32Value( PLAYER_CHOSEN_TITLE
, 0 );
611 SetUInt32Value( PLAYER_FIELD_KILLS
, 0 );
612 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 0 );
613 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION
, 0 );
614 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0 );
616 // set starting level
617 uint32 start_level
= getClass() != CLASS_DEATH_KNIGHT
618 ? sWorld
.getConfig(CONFIG_START_PLAYER_LEVEL
)
619 : sWorld
.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL
);
621 if (GetSession()->GetSecurity() >= SEC_MODERATOR
)
623 uint32 gm_level
= sWorld
.getConfig(CONFIG_START_GM_LEVEL
);
624 if(gm_level
> start_level
)
625 start_level
= gm_level
;
628 SetUInt32Value(UNIT_FIELD_LEVEL
, start_level
);
632 SetUInt32Value (PLAYER_FIELD_COINAGE
, sWorld
.getConfig(CONFIG_START_PLAYER_MONEY
));
633 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_START_HONOR_POINTS
));
634 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_START_ARENA_POINTS
));
637 m_Last_tick
= time(NULL
);
638 m_Played_time
[0] = 0;
639 m_Played_time
[1] = 0;
641 // base stats and related field values
643 InitTaxiNodesForLevel();
644 InitGlyphsForLevel();
645 InitTalentForLevel();
646 InitPrimaryProffesions(); // to max set before any spell added
648 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
649 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
650 SetHealth(GetMaxHealth());
651 if (getPowerType()==POWER_MANA
)
653 UpdateMaxPower(POWER_MANA
); // Update max Mana (for add bonus from intellect)
654 SetPower(POWER_MANA
,GetMaxPower(POWER_MANA
));
657 if(getPowerType() == POWER_RUNIC_POWER
)
659 SetPower(POWER_RUNE
, 8);
660 SetMaxPower(POWER_RUNE
, 8);
661 SetPower(POWER_RUNIC_POWER
, 0);
662 SetMaxPower(POWER_RUNIC_POWER
, 1000);
666 learnDefaultSpells();
668 // original action bar
669 std::list
<uint16
>::const_iterator action_itr
[4];
670 for(int i
=0; i
<4; i
++)
671 action_itr
[i
] = info
->action
[i
].begin();
673 for (; action_itr
[0]!=info
->action
[0].end() && action_itr
[1]!=info
->action
[1].end();)
676 for(int i
=0; i
<4 ;i
++)
677 taction
[i
] = (*action_itr
[i
]);
679 addActionButton((uint8
)taction
[0], taction
[1], (uint8
)taction
[2], (uint8
)taction
[3]);
681 for(int i
=0; i
<4 ;i
++)
686 CharStartOutfitEntry
const* oEntry
= NULL
;
687 for (uint32 i
= 1; i
< sCharStartOutfitStore
.GetNumRows(); ++i
)
689 if(CharStartOutfitEntry
const* entry
= sCharStartOutfitStore
.LookupEntry(i
))
691 if(entry
->RaceClassGender
== RaceClassGender
)
701 for(int j
= 0; j
< MAX_OUTFIT_ITEMS
; ++j
)
703 if(oEntry
->ItemId
[j
] <= 0)
706 uint32 item_id
= oEntry
->ItemId
[j
];
709 // Hack for not existed item id in dbc 3.0.3
713 ItemPrototype
const* iProto
= objmgr
.GetItemPrototype(item_id
);
716 sLog
.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id
,getRace(),getClass());
720 // max stack by default (mostly 1), 1 for infinity stackable
721 uint32 count
= iProto
->Stackable
> 0 ? uint32(iProto
->Stackable
) : 1;
723 if(iProto
->Class
==ITEM_CLASS_CONSUMABLE
&& iProto
->SubClass
==ITEM_SUBCLASS_FOOD
)
725 switch(iProto
->Spells
[0].SpellCategory
)
728 if(iProto
->Stackable
> 4)
732 if(iProto
->Stackable
> 2)
738 StoreNewItemInBestSlots(item_id
, count
);
742 for (PlayerCreateInfoItems::const_iterator item_id_itr
= info
->item
.begin(); item_id_itr
!=info
->item
.end(); ++item_id_itr
++)
743 StoreNewItemInBestSlots(item_id_itr
->item_id
, item_id_itr
->item_amount
);
745 // bags and main-hand weapon must equipped at this moment
746 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
747 // or ammo not equipped in special bag
748 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
750 if(Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
753 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
754 uint8 msg
= CanEquipItem( NULL_SLOT
, eDest
, pItem
, false );
755 if( msg
== EQUIP_ERR_OK
)
757 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
758 EquipItem( eDest
, pItem
, true);
760 // move other items to more appropriate slots (ammo not equipped in special bag)
763 ItemPosCountVec sDest
;
764 msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, sDest
, pItem
, false );
765 if( msg
== EQUIP_ERR_OK
)
767 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
768 pItem
= StoreItem( sDest
, pItem
, true);
771 // if this is ammo then use it
772 uint8 msg
= CanUseAmmo( pItem
->GetProto()->ItemId
);
773 if( msg
== EQUIP_ERR_OK
)
774 SetAmmo( pItem
->GetProto()->ItemId
);
778 // all item positions resolved
783 bool Player::StoreNewItemInBestSlots(uint32 titem_id
, uint32 titem_amount
)
785 sLog
.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id
, titem_amount
);
787 // attempt equip by one
788 while(titem_amount
> 0)
791 uint8 msg
= CanEquipNewItem( NULL_SLOT
, eDest
, titem_id
, false );
792 if( msg
!= EQUIP_ERR_OK
)
795 EquipNewItem( eDest
, titem_id
, true);
796 AutoUnequipOffhandIfNeed();
800 if(titem_amount
== 0)
801 return true; // equipped
804 ItemPosCountVec sDest
;
805 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
806 uint8 msg
= CanStoreNewItem( INVENTORY_SLOT_BAG_0
, NULL_SLOT
, sDest
, titem_id
, titem_amount
);
807 if( msg
== EQUIP_ERR_OK
)
809 StoreNewItem( sDest
, titem_id
, true, Item::GenerateItemRandomPropertyId(titem_id
) );
810 return true; // stored
813 // item can't be added
814 sLog
.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id
,getRace(),getClass(),msg
);
818 void Player::StartMirrorTimer(MirrorTimerType Type
, uint32 MaxValue
)
820 uint32 BreathRegen
= (uint32
)-1;
822 WorldPacket
data(SMSG_START_MIRROR_TIMER
, (21));
823 data
<< (uint32
)Type
;
828 data
<< (uint32
)0; // spell id
829 GetSession()->SendPacket(&data
);
832 void Player::ModifyMirrorTimer(MirrorTimerType Type
, uint32 MaxValue
, uint32 CurrentValue
, uint32 Regen
)
834 if(Type
==BREATH_TIMER
)
835 m_breathTimer
= ((MaxValue
+ 1000) - CurrentValue
) / Regen
;
837 WorldPacket
data(SMSG_START_MIRROR_TIMER
, (21));
838 data
<< (uint32
)Type
;
839 data
<< CurrentValue
;
843 data
<< (uint32
)0; // spell id
844 GetSession()->SendPacket( &data
);
847 void Player::StopMirrorTimer(MirrorTimerType Type
)
849 if(Type
==BREATH_TIMER
)
852 WorldPacket
data(SMSG_STOP_MIRROR_TIMER
, 4);
853 data
<< (uint32
)Type
;
854 GetSession()->SendPacket( &data
);
857 void Player::EnvironmentalDamage(uint64 guid
, EnviromentalDamage type
, uint32 damage
)
859 WorldPacket
data(SMSG_ENVIRONMENTALDAMAGELOG
, (21));
860 data
<< (uint64
)guid
;
861 data
<< (uint8
)(type
!=DAMAGE_FALL_TO_VOID
? type
: DAMAGE_FALL
);
862 data
<< (uint32
)damage
;
865 SendMessageToSet(&data
, true);
867 DealDamage(this, damage
, NULL
, SELF_DAMAGE
, SPELL_SCHOOL_MASK_NORMAL
, NULL
, false);
869 if(type
==DAMAGE_FALL
&& !isAlive()) // DealDamage not apply item durability loss at self damage
871 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
872 DurabilityLossAll(0.10f
,false);
873 // durability lost message
874 WorldPacket
data(SMSG_DURABILITY_DAMAGE_DEATH
, 0);
875 GetSession()->SendPacket(&data
);
879 void Player::HandleDrowning()
881 if(!(m_isunderwater
&~UNDERWATER_INLAVA
))
884 //if player is GM, have waterbreath, is dead or if breathing is disabled then return
885 if(isGameMaster() || !isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING
) || GetSession()->GetSecurity() >= sWorld
.getConfig(CONFIG_DISABLE_BREATHING
))
887 StopMirrorTimer(BREATH_TIMER
);
888 // drop every flag _except_ LAVA - otherwise waterbreathing will prevent lava damage
889 m_isunderwater
&= UNDERWATER_INLAVA
;
893 uint32 UnderWaterTime
= 1*MINUTE
*1000; // default length 1 min
895 AuraList
const& mModWaterBreathing
= GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING
);
896 for(AuraList::const_iterator i
= mModWaterBreathing
.begin(); i
!= mModWaterBreathing
.end(); ++i
)
897 UnderWaterTime
= uint32(UnderWaterTime
* (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
);
899 if ((m_isunderwater
& UNDERWATER_INWATER
) && !(m_isunderwater
& UNDERWATER_INLAVA
) && isAlive())
901 //single trigger timer
902 if (!(m_isunderwater
& UNDERWATER_WATER_TRIGGER
))
904 m_isunderwater
|= UNDERWATER_WATER_TRIGGER
;
905 m_breathTimer
= UnderWaterTime
+ 1000;
907 //single trigger "show Breathbar"
908 if ( m_breathTimer
<= UnderWaterTime
&& !(m_isunderwater
& UNDERWATER_WATER_BREATHB
))
910 m_isunderwater
|= UNDERWATER_WATER_BREATHB
;
911 StartMirrorTimer(BREATH_TIMER
, UnderWaterTime
);
913 //continuous trigger drowning "Damage"
914 if ((m_breathTimer
== 0) && (m_isunderwater
& UNDERWATER_INWATER
))
916 //TODO: Check this formula
917 uint64 guid
= GetGUID();
918 uint32 damage
= GetMaxHealth() / 5 + urand(0, getLevel()-1);
920 EnvironmentalDamage(guid
, DAMAGE_DROWNING
,damage
);
921 m_breathTimer
= 2000;
924 //single trigger retract bar
925 else if (!(m_isunderwater
& UNDERWATER_INWATER
) && (m_isunderwater
& UNDERWATER_WATER_TRIGGER
) && (m_breathTimer
> 0) && isAlive())
927 uint32 BreathRegen
= 10;
928 // m_breathTimer will be reduced in ModifyMirrorTimer
929 ModifyMirrorTimer(BREATH_TIMER
, UnderWaterTime
, m_breathTimer
,BreathRegen
);
930 m_isunderwater
= UNDERWATER_WATER_BREATHB_RETRACTING
;
933 else if ((m_breathTimer
< 50) && !(m_isunderwater
& UNDERWATER_INWATER
) && (m_isunderwater
== UNDERWATER_WATER_BREATHB_RETRACTING
))
935 StopMirrorTimer(BREATH_TIMER
);
936 m_isunderwater
= UNDERWATER_NONE
;
940 void Player::HandleLava()
942 if ((m_isunderwater
& UNDERWATER_INLAVA
) && isAlive())
945 * arrai: how is this supposed to work? UNDERWATER_INLAVA is always set in this scope!
946 // Single trigger Set BreathTimer
947 if (!(m_isunderwater & UNDERWATER_INLAVA))
949 m_isunderwater|= UNDERWATER_WATER_BREATHB;
950 m_breathTimer = 1000;
953 // Reset BreathTimer and still in the lava
956 uint64 guid
= GetGUID();
957 uint32 damage
= urand(600, 700); // TODO: Get more detailed information about lava damage
959 // if not gamemaster then deal damage
960 if ( !isGameMaster() )
961 EnvironmentalDamage(guid
, DAMAGE_LAVA
, damage
);
963 m_breathTimer
= 1000;
966 else if (!isAlive()) // Disable breath timer and reset underwater flags
969 m_isunderwater
= UNDERWATER_NONE
;
973 ///The player sobers by 256 every 10 seconds
974 void Player::HandleSobering()
978 uint32 drunk
= (m_drunk
<= 256) ? 0 : (m_drunk
- 256);
979 SetDrunkValue(drunk
);
982 DrunkenState
Player::GetDrunkenstateByValue(uint16 value
)
985 return DRUNKEN_SMASHED
;
987 return DRUNKEN_DRUNK
;
989 return DRUNKEN_TIPSY
;
990 return DRUNKEN_SOBER
;
993 void Player::SetDrunkValue(uint16 newDrunkenValue
, uint32 itemId
)
995 uint32 oldDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
997 m_drunk
= newDrunkenValue
;
998 SetUInt32Value(PLAYER_BYTES_3
,(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFF0001) | (m_drunk
& 0xFFFE));
1000 uint32 newDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
1002 // special drunk invisibility detection
1003 if(newDrunkenState
>= DRUNKEN_DRUNK
)
1004 m_detectInvisibilityMask
|= (1<<6);
1006 m_detectInvisibilityMask
&= ~(1<<6);
1008 if(newDrunkenState
== oldDrunkenState
)
1011 WorldPacket
data(SMSG_CROSSED_INEBRIATION_THRESHOLD
, (8+4+4));
1012 data
<< uint64(GetGUID());
1013 data
<< uint32(newDrunkenState
);
1014 data
<< uint32(itemId
);
1016 SendMessageToSet(&data
, true);
1019 void Player::Update( uint32 p_time
)
1025 if(m_nextMailDelivereTime
&& m_nextMailDelivereTime
<= time(NULL
))
1030 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1031 m_nextMailDelivereTime
= 0;
1034 Unit::Update( p_time
);
1036 // update player only attacks
1037 if(uint32 ranged_att
= getAttackTimer(RANGED_ATTACK
))
1039 setAttackTimer(RANGED_ATTACK
, (p_time
>= ranged_att
? 0 : ranged_att
- p_time
) );
1042 if(uint32 off_att
= getAttackTimer(OFF_ATTACK
))
1044 setAttackTimer(OFF_ATTACK
, (p_time
>= off_att
? 0 : off_att
- p_time
) );
1047 time_t now
= time (NULL
);
1051 UpdateContestedPvP(p_time
);
1053 UpdateDuelFlag(now
);
1055 CheckDuelDistance(now
);
1057 UpdateAfkReport(now
);
1059 CheckExploreSystem();
1061 // Update items that have just a limited lifetime
1062 if (now
>m_Last_tick
)
1063 UpdateItemDuration(uint32(now
- m_Last_tick
));
1065 if (!m_timedquests
.empty())
1067 std::set
<uint32
>::iterator iter
= m_timedquests
.begin();
1068 while (iter
!= m_timedquests
.end())
1070 QuestStatusData
& q_status
= mQuestStatus
[*iter
];
1071 if( q_status
.m_timer
<= p_time
)
1073 uint32 quest_id
= *iter
;
1074 ++iter
; // current iter will be removed in FailTimedQuest
1075 FailTimedQuest( quest_id
);
1079 q_status
.m_timer
-= p_time
;
1080 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
1086 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING
))
1088 Unit
*pVictim
= getVictim();
1089 if( !IsNonMeleeSpellCasted(false) && pVictim
)
1091 // default combat reach 10
1092 // TODO add weapon,skill check
1094 float pldistance
= ATTACK_DISTANCE
;
1096 if (isAttackReady(BASE_ATTACK
))
1098 if(!IsWithinDistInMap(pVictim
, pldistance
))
1100 setAttackTimer(BASE_ATTACK
,100);
1101 if(m_swingErrorMsg
!= 1) // send single time (client auto repeat)
1103 SendAttackSwingNotInRange();
1104 m_swingErrorMsg
= 1;
1107 //120 degrees of radiant range
1108 else if( !HasInArc( 2*M_PI
/3, pVictim
))
1110 setAttackTimer(BASE_ATTACK
,100);
1111 if(m_swingErrorMsg
!= 2) // send single time (client auto repeat)
1113 SendAttackSwingBadFacingAttack();
1114 m_swingErrorMsg
= 2;
1119 m_swingErrorMsg
= 0; // reset swing error state
1121 // prevent base and off attack in same time, delay attack at 0.2 sec
1122 if(haveOffhandWeapon())
1124 uint32 off_att
= getAttackTimer(OFF_ATTACK
);
1125 if(off_att
< ATTACK_DISPLAY_DELAY
)
1126 setAttackTimer(OFF_ATTACK
,ATTACK_DISPLAY_DELAY
);
1128 AttackerStateUpdate(pVictim
, BASE_ATTACK
);
1129 resetAttackTimer(BASE_ATTACK
);
1133 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK
))
1135 if(!IsWithinDistInMap(pVictim
, pldistance
))
1137 setAttackTimer(OFF_ATTACK
,100);
1139 else if( !HasInArc( 2*M_PI
/3, pVictim
))
1141 setAttackTimer(OFF_ATTACK
,100);
1145 // prevent base and off attack in same time, delay attack at 0.2 sec
1146 uint32 base_att
= getAttackTimer(BASE_ATTACK
);
1147 if(base_att
< ATTACK_DISPLAY_DELAY
)
1148 setAttackTimer(BASE_ATTACK
,ATTACK_DISPLAY_DELAY
);
1150 AttackerStateUpdate(pVictim
, OFF_ATTACK
);
1151 resetAttackTimer(OFF_ATTACK
);
1155 Unit
*owner
= pVictim
->GetOwner();
1156 Unit
*u
= owner
? owner
: pVictim
;
1157 if(u
->IsPvP() && (!duel
|| duel
->opponent
!= u
))
1160 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT
);
1165 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
))
1167 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1169 int time_inn
= time(NULL
)-GetTimeInnEnter();
1170 if (time_inn
>= 10) //freeze update
1172 float bubble
= 0.125*sWorld
.getRate(RATE_REST_INGAME
);
1173 //speed collect rest bonus (section/in hour)
1174 SetRestBonus( GetRestBonus()+ time_inn
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
1175 UpdateInnerTime(time(NULL
));
1180 if(m_regenTimer
> 0)
1182 if(p_time
>= m_regenTimer
)
1185 m_regenTimer
-= p_time
;
1188 if (m_weaponChangeTimer
> 0)
1190 if(p_time
>= m_weaponChangeTimer
)
1191 m_weaponChangeTimer
= 0;
1193 m_weaponChangeTimer
-= p_time
;
1196 if (m_zoneUpdateTimer
> 0)
1198 if(p_time
>= m_zoneUpdateTimer
)
1200 uint32 newzone
= GetZoneId();
1201 if( m_zoneUpdateId
!= newzone
)
1202 UpdateZone(newzone
); // also update area
1205 // use area updates as well
1206 // needed for free far all arenas for example
1207 uint32 newarea
= GetAreaId();
1208 if( m_areaUpdateId
!= newarea
)
1209 UpdateArea(newarea
);
1211 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
1215 m_zoneUpdateTimer
-= p_time
;
1223 if (m_deathState
== JUST_DIED
)
1230 if(p_time
>= m_nextSave
)
1232 // m_nextSave reseted in SaveToDB call
1234 sLog
.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1238 m_nextSave
-= p_time
;
1243 if(m_breathTimer
> 0)
1245 if(p_time
>= m_breathTimer
)
1248 m_breathTimer
-= p_time
;
1252 //Handle Water/drowning
1258 //Handle detect stealth players
1259 if (m_DetectInvTimer
> 0)
1261 if (p_time
>= m_DetectInvTimer
)
1263 m_DetectInvTimer
= 3000;
1264 HandleStealthedUnitsDetection();
1267 m_DetectInvTimer
-= p_time
;
1271 if (now
> m_Last_tick
)
1273 uint32 elapsed
= uint32(now
- m_Last_tick
);
1274 m_Played_time
[0] += elapsed
; // Total played time
1275 m_Played_time
[1] += elapsed
; // Level played time
1281 m_drunkTimer
+= p_time
;
1283 if (m_drunkTimer
> 10000)
1287 // not auto-free ghost from body in instances
1288 if(m_deathTimer
> 0 && !GetBaseMap()->Instanceable())
1290 if(p_time
>= m_deathTimer
)
1297 m_deathTimer
-= p_time
;
1300 UpdateEnchantTime(p_time
);
1301 UpdateHomebindTime(p_time
);
1304 SendUpdateToOutOfRangeGroupMembers();
1306 Pet
* pet
= GetPet();
1307 if(pet
&& !IsWithinDistInMap(pet
, OWNER_MAX_DISTANCE
) && (GetCharmGUID() && (pet
->GetGUID() != GetCharmGUID())))
1309 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
, true);
1314 void Player::setDeathState(DeathState s
)
1316 uint32 ressSpellId
= 0;
1318 bool cur
= isAlive();
1320 if(s
== JUST_DIED
&& cur
)
1322 // drunken state is cleared on death
1324 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1327 clearResurrectRequestData();
1329 // remove form before other mods to prevent incorrect stats calculation
1330 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId
);
1332 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1333 RemovePet(NULL
, PET_SAVE_NOT_IN_SLOT
, true);
1335 // remove uncontrolled pets
1339 // save value before aura remove in Unit::setDeathState
1340 ressSpellId
= GetUInt32Value(PLAYER_SELF_RES_SPELL
);
1344 ressSpellId
= GetResurrectionSpellId();
1345 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP
, 1);
1347 Unit::setDeathState(s
);
1349 // restore resurrection spell id for player after aura remove
1350 if(s
== JUST_DIED
&& cur
&& ressSpellId
)
1351 SetUInt32Value(PLAYER_SELF_RES_SPELL
, ressSpellId
);
1353 if(isAlive() && !cur
)
1355 //clear aura case after resurrection by another way (spells will be applied before next death)
1356 SetUInt32Value(PLAYER_SELF_RES_SPELL
, 0);
1358 // restore default warrior stance
1359 if(getClass()== CLASS_WARRIOR
)
1360 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
1364 void Player::BuildEnumData( QueryResult
* result
, WorldPacket
* p_data
)
1366 Field
*fields
= result
->Fetch();
1368 *p_data
<< uint64(GetGUID());
1371 *p_data
<< uint8(getRace());
1372 uint8 pClass
= getClass();
1373 *p_data
<< uint8(pClass
);
1374 *p_data
<< uint8(getGender());
1376 uint32 bytes
= GetUInt32Value(PLAYER_BYTES
);
1377 *p_data
<< uint8(bytes
);
1378 *p_data
<< uint8(bytes
>> 8);
1379 *p_data
<< uint8(bytes
>> 16);
1380 *p_data
<< uint8(bytes
>> 24);
1382 bytes
= GetUInt32Value(PLAYER_BYTES_2
);
1383 *p_data
<< uint8(bytes
);
1385 *p_data
<< uint8(getLevel()); // player level
1386 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1387 uint32 zoneId
= MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY(),GetPositionZ());
1388 sLog
.outDebug("Player::BuildEnumData: m:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId
);
1389 *p_data
<< uint32(zoneId
);
1390 *p_data
<< uint32(GetMapId());
1392 *p_data
<< GetPositionX();
1393 *p_data
<< GetPositionY();
1394 *p_data
<< GetPositionZ();
1397 *p_data
<< (result
? fields
[13].GetUInt32() : 0);
1399 uint32 char_flags
= 0;
1400 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
1401 char_flags
|= CHARACTER_FLAG_HIDE_HELM
;
1402 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
1403 char_flags
|= CHARACTER_FLAG_HIDE_CLOAK
;
1404 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
))
1405 char_flags
|= CHARACTER_FLAG_GHOST
;
1406 if(HasAtLoginFlag(AT_LOGIN_RENAME
))
1407 char_flags
|= CHARACTER_FLAG_RENAME
;
1408 if(sWorld
.getConfig(CONFIG_DECLINED_NAMES_USED
) && (fields
[14].GetCppString() != ""))
1409 char_flags
|= CHARACTER_FLAG_DECLINED
;
1411 *p_data
<< uint32(char_flags
); // character flags
1412 // character customize (flags?)
1413 *p_data
<< uint32(HasAtLoginFlag(AT_LOGIN_CUSTOMIZE
) ? 1 : 0);
1414 *p_data
<< uint8(1); // unknown
1418 uint32 petDisplayId
= 0;
1419 uint32 petLevel
= 0;
1420 uint32 petFamily
= 0;
1422 // show pet at selection character in character list only for non-ghost character
1423 if(result
&& isAlive() && (pClass
== CLASS_WARLOCK
|| pClass
== CLASS_HUNTER
))
1425 uint32 entry
= fields
[10].GetUInt32();
1426 CreatureInfo
const* cInfo
= sCreatureStorage
.LookupEntry
<CreatureInfo
>(entry
);
1429 petDisplayId
= fields
[11].GetUInt32();
1430 petLevel
= fields
[12].GetUInt32();
1431 petFamily
= cInfo
->family
;
1435 *p_data
<< uint32(petDisplayId
);
1436 *p_data
<< uint32(petLevel
);
1437 *p_data
<< uint32(petFamily
);
1440 for (uint8 slot
= 0; slot
< EQUIPMENT_SLOT_END
; slot
++)
1442 uint32 visualbase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
1443 uint32 item_id
= GetUInt32Value(visualbase
);
1444 const ItemPrototype
* proto
= objmgr
.GetItemPrototype(item_id
);
1445 SpellItemEnchantmentEntry
const *enchant
= NULL
;
1447 for(uint8 enchantSlot
= PERM_ENCHANTMENT_SLOT
; enchantSlot
<=TEMP_ENCHANTMENT_SLOT
; enchantSlot
++)
1449 uint32 enchantId
= GetUInt32Value(visualbase
+1+enchantSlot
);
1450 if(enchant
= sSpellItemEnchantmentStore
.LookupEntry(enchantId
))
1456 *p_data
<< uint32(proto
->DisplayInfoID
);
1457 *p_data
<< uint8(proto
->InventoryType
);
1458 *p_data
<< uint32(enchant
? enchant
->aura_id
: 0);
1462 *p_data
<< uint32(0);
1463 *p_data
<< uint8(0);
1464 *p_data
<< uint32(0); // enchant?
1467 *p_data
<< uint32(0); // first bag display id
1468 *p_data
<< uint8(0); // first bag inventory type
1469 *p_data
<< uint32(0); // enchant?
1472 bool Player::ToggleAFK()
1474 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1476 bool state
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1478 // afk player not allowed in battleground
1479 if(state
&& InBattleGround())
1480 LeaveBattleground();
1485 bool Player::ToggleDND()
1487 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1489 return HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1492 uint8
Player::chatTag() const
1509 bool Player::TeleportTo(uint32 mapid
, float x
, float y
, float z
, float orientation
, uint32 options
)
1511 if(!MapManager::IsValidMapCoord(mapid
, x
, y
, z
, orientation
))
1513 sLog
.outError("TeleportTo: invalid map %d or absent instance template.", mapid
);
1517 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1518 Pet
* pet
= GetPet();
1520 MapEntry
const* mEntry
= sMapStore
.LookupEntry(mapid
);
1522 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1523 // don't let gm level > 1 either
1524 if(!InBattleGround() && mEntry
->IsBattleGroundOrArena())
1527 // client without expansion support
1528 if(GetSession()->Expansion() < mEntry
->Expansion())
1530 sLog
.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid
);
1533 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1535 SendTransferAborted(mapid
, TRANSFER_ABORT_INSUF_EXPAN_LVL
, mEntry
->Expansion());
1537 return false; // normal client can't teleport to this map...
1541 sLog
.outDebug("Player %s will teleported to map %u", GetName(), mapid
);
1544 // if we were on a transport, leave
1545 if (!(options
& TELE_TO_NOT_LEAVE_TRANSPORT
) && m_transport
)
1547 m_transport
->RemovePassenger(this);
1549 m_movementInfo
.t_x
= 0.0f
;
1550 m_movementInfo
.t_y
= 0.0f
;
1551 m_movementInfo
.t_z
= 0.0f
;
1552 m_movementInfo
.t_o
= 0.0f
;
1553 m_movementInfo
.t_time
= 0;
1556 SetSemaphoreTeleport(true);
1558 // The player was ported to another map and looses the duel immediately.
1559 // We have to perform this check before the teleport, otherwise the
1560 // ObjectAccessor won't find the flag.
1561 if (duel
&& GetMapId()!=mapid
)
1563 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER
));
1565 DuelComplete(DUEL_FLED
);
1568 // reset movement flags at teleport, because player will continue move with these flags after teleport
1569 SetUnitMovementFlags(0);
1571 if ((GetMapId() == mapid
) && (!m_transport
))
1573 // prepare zone change detect
1574 uint32 old_zone
= GetZoneId();
1577 if(!GetSession()->PlayerLogout())
1580 BuildTeleportAckMsg(&data
, x
, y
, z
, orientation
);
1581 GetSession()->SendPacket(&data
);
1582 SetPosition( x
, y
, z
, orientation
, true);
1585 // this will be used instead of the current location in SaveToDB
1586 m_teleport_dest
= WorldLocation(mapid
, x
, y
, z
, orientation
);
1587 SetFallInformation(0, z
);
1589 //BuildHeartBeatMsg(&data);
1590 //SendMessageToSet(&data, true);
1591 if (!(options
& TELE_TO_NOT_UNSUMMON_PET
))
1593 //same map, only remove pet if out of range
1594 if(pet
&& !IsWithinDistInMap(pet
, OWNER_MAX_DISTANCE
))
1596 if(pet
->isControlled() && !pet
->isTemporarySummoned() )
1597 m_temporaryUnsummonedPetNumber
= pet
->GetCharmInfo()->GetPetNumber();
1599 m_temporaryUnsummonedPetNumber
= 0;
1601 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
);
1605 if(!(options
& TELE_TO_NOT_LEAVE_COMBAT
))
1608 if (!(options
& TELE_TO_NOT_UNSUMMON_PET
))
1611 if(pet
&& m_temporaryUnsummonedPetNumber
)
1613 Pet
* NewPet
= new Pet
;
1614 if(!NewPet
->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber
, true))
1617 m_temporaryUnsummonedPetNumber
= 0;
1621 if(!GetSession()->PlayerLogout())
1623 // don't reset teleport semaphore while logging out, otherwise m_teleport_dest won't be used in Player::SaveToDB
1624 SetSemaphoreTeleport(false);
1626 UpdateZone(GetZoneId());
1630 if(old_zone
!= GetZoneId())
1633 if(pvpInfo
.inHostileArea
)
1634 CastSpell(this, 2479, true);
1639 // far teleport to another map
1640 Map
* oldmap
= IsInWorld() ? GetMap() : NULL
;
1641 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1643 // Check enter rights before map getting to avoid creating instance copy for player
1644 // this check not dependent from map instance copy and same for all instance copies of selected map
1645 if (!MapManager::Instance().CanPlayerEnter(mapid
, this))
1647 SetSemaphoreTeleport(false);
1651 // If the map is not created, assume it is possible to enter it.
1652 // It will be created in the WorldPortAck.
1653 Map
*map
= MapManager::Instance().FindMap(mapid
);
1654 if (!map
|| map
->CanEnter(this))
1660 ResetContestedPvP();
1662 // remove player from battleground on far teleport (when changing maps)
1663 if(BattleGround
const* bg
= GetBattleGround())
1665 // Note: at battleground join battleground id set before teleport
1666 // and we already will found "current" battleground
1667 // just need check that this is targeted map or leave
1668 if(bg
->GetMapId() != mapid
)
1669 LeaveBattleground(false); // don't teleport to entry point
1672 // remove pet on map change
1675 //leaving map -> delete pet right away (doing this later will cause problems)
1676 if(pet
->isControlled() && !pet
->isTemporarySummoned())
1677 m_temporaryUnsummonedPetNumber
= pet
->GetCharmInfo()->GetPetNumber();
1679 m_temporaryUnsummonedPetNumber
= 0;
1681 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
);
1684 // remove all dyn objects
1685 RemoveAllDynObjects();
1687 // stop spellcasting
1688 // not attempt interrupt teleportation spell at caster teleport
1689 if(!(options
& TELE_TO_SPELL
))
1690 if(IsNonMeleeSpellCasted(true))
1691 InterruptNonMeleeSpells(true);
1693 if(!GetSession()->PlayerLogout())
1695 // send transfer packets
1696 WorldPacket
data(SMSG_TRANSFER_PENDING
, (4+4+4));
1697 data
<< uint32(mapid
);
1700 data
<< m_transport
->GetEntry() << GetMapId();
1702 GetSession()->SendPacket(&data
);
1704 data
.Initialize(SMSG_NEW_WORLD
, (20));
1707 data
<< (uint32
)mapid
<< m_movementInfo
.t_x
<< m_movementInfo
.t_y
<< m_movementInfo
.t_z
<< m_movementInfo
.t_o
;
1711 data
<< (uint32
)mapid
<< (float)x
<< (float)y
<< (float)z
<< (float)orientation
;
1713 GetSession()->SendPacket( &data
);
1714 SendSavedInstances();
1716 // remove from old map now
1717 if(oldmap
) oldmap
->Remove(this, false);
1720 // new final coordinates
1724 float final_o
= orientation
;
1728 final_x
+= m_movementInfo
.t_x
;
1729 final_y
+= m_movementInfo
.t_y
;
1730 final_z
+= m_movementInfo
.t_z
;
1731 final_o
+= m_movementInfo
.t_o
;
1734 m_teleport_dest
= WorldLocation(mapid
, final_x
, final_y
, final_z
, final_o
);
1735 SetFallInformation(0, final_z
);
1736 // if the player is saved before worldportack (at logout for example)
1737 // this will be used instead of the current location in SaveToDB
1739 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP
);
1741 // move packet sent by client always after far teleport
1742 // SetPosition(final_x, final_y, final_z, final_o, true);
1745 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1753 void Player::AddToWorld()
1755 ///- Do not add/remove the player from the object storage
1756 ///- It will crash when updating the ObjectAccessor
1757 ///- The player should only be added when logging in
1760 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; i
++)
1763 m_items
[i
]->AddToWorld();
1767 void Player::RemoveFromWorld()
1772 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1774 UnsummonAllTotems();
1779 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; i
++)
1782 m_items
[i
]->RemoveFromWorld();
1785 ///- Do not add/remove the player from the object storage
1786 ///- It will crash when updating the ObjectAccessor
1787 ///- The player should only be removed when logging out
1788 Unit::RemoveFromWorld();
1791 void Player::RewardRage( uint32 damage
, uint32 weaponSpeedHitFactor
, bool attacker
)
1795 float rageconversion
= ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1799 addRage
= ((damage
/rageconversion
*7.5 + weaponSpeedHitFactor
)/2);
1801 // talent who gave more rage on attack
1802 addRage
*= 1.0f
+ GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT
) / 100.0f
;
1806 addRage
= damage
/rageconversion
*2.5;
1808 // Berserker Rage effect
1809 if(HasAura(18499,0))
1813 addRage
*= sWorld
.getRate(RATE_POWER_RAGE_INCOME
);
1815 ModifyPower(POWER_RAGE
, uint32(addRage
*10));
1818 void Player::RegenerateAll()
1820 if (m_regenTimer
!= 0)
1822 uint32 regenDelay
= 2000;
1824 // Not in combat or they have regeneration
1825 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) ||
1826 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
) || IsPolymorphed() )
1829 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN
))
1831 Regenerate(POWER_RAGE
);
1832 if(getClass() == CLASS_DEATH_KNIGHT
)
1833 Regenerate(POWER_RUNIC_POWER
);
1837 Regenerate( POWER_ENERGY
);
1839 Regenerate( POWER_MANA
);
1841 if(getClass() == CLASS_DEATH_KNIGHT
)
1842 Regenerate( POWER_RUNE
);
1844 m_regenTimer
= regenDelay
;
1847 void Player::Regenerate(Powers power
)
1849 uint32 curValue
= GetPower(power
);
1850 uint32 maxValue
= GetMaxPower(power
);
1852 float addvalue
= 0.0f
;
1858 bool recentCast
= IsUnderLastManaUseEffect();
1859 float ManaIncreaseRate
= sWorld
.getRate(RATE_POWER_MANA
);
1862 // Mangos Updates Mana in intervals of 2s, which is correct
1863 addvalue
= GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER
) * ManaIncreaseRate
* 2.00f
;
1867 addvalue
= GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER
) * ManaIncreaseRate
* 2.00f
;
1870 case POWER_RAGE
: // Regenerate rage
1872 float RageDecreaseRate
= sWorld
.getRate(RATE_POWER_RAGE_LOSS
);
1873 addvalue
= 30 * RageDecreaseRate
; // 3 rage by tick
1875 case POWER_ENERGY
: // Regenerate energy (rogue)
1878 case POWER_RUNIC_POWER
:
1880 float RunicPowerDecreaseRate
= sWorld
.getRate(RATE_POWER_RUNICPOWER_LOSS
);
1881 addvalue
= 30 * RunicPowerDecreaseRate
; // 3 RunicPower by tick
1885 for(uint32 i
= 0; i
< MAX_RUNES
; ++i
)
1886 if(uint8 cd
= GetRuneCooldown(i
)) // if we have cooldown, reduce it...
1887 SetRuneCooldown(i
, cd
- 1); // ... by 2 sec (because update is every 2 sec)
1890 case POWER_HAPPINESS
:
1894 // Mana regen calculated in Player::UpdateManaRegen()
1895 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1896 if(power
!= POWER_MANA
)
1898 AuraList
const& ModPowerRegenPCTAuras
= GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT
);
1899 for(AuraList::const_iterator i
= ModPowerRegenPCTAuras
.begin(); i
!= ModPowerRegenPCTAuras
.end(); ++i
)
1900 if ((*i
)->GetModifier()->m_miscvalue
== power
)
1901 addvalue
*= ((*i
)->GetModifier()->m_amount
+ 100) / 100.0f
;
1904 if (power
!= POWER_RAGE
&& power
!= POWER_RUNIC_POWER
)
1906 curValue
+= uint32(addvalue
);
1907 if (curValue
> maxValue
)
1908 curValue
= maxValue
;
1912 if(curValue
<= uint32(addvalue
))
1915 curValue
-= uint32(addvalue
);
1917 SetPower(power
, curValue
);
1920 void Player::RegenerateHealth()
1922 uint32 curValue
= GetHealth();
1923 uint32 maxValue
= GetMaxHealth();
1925 if (curValue
>= maxValue
) return;
1927 float HealthIncreaseRate
= sWorld
.getRate(RATE_HEALTH
);
1929 float addvalue
= 0.0f
;
1932 if ( IsPolymorphed() )
1933 addvalue
= GetMaxHealth()/3;
1934 // normal regen case (maybe partly in combat case)
1935 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) )
1937 addvalue
= OCTRegenHPPerSpirit()* HealthIncreaseRate
;
1940 AuraList
const& mModHealthRegenPct
= GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT
);
1941 for(AuraList::const_iterator i
= mModHealthRegenPct
.begin(); i
!= mModHealthRegenPct
.end(); ++i
)
1942 addvalue
*= (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
;
1944 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
))
1945 addvalue
*= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) / 100.0f
;
1951 // always regeneration bonus (including combat)
1952 addvalue
+= GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
);
1957 ModifyHealth(int32(addvalue
));
1960 bool Player::CanInteractWithNPCs(bool alive
) const
1962 if(alive
&& !isAlive())
1970 bool Player::IsUnderWater() const
1972 return IsInWater() &&
1973 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
1976 void Player::SetInWater(bool apply
)
1978 if(m_isInWater
==apply
)
1981 //define player in water by opcodes
1982 //move player's guid into HateOfflineList of those mobs
1983 //which can't swim and move guid back into ThreatList when
1985 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
1986 m_isInWater
= apply
;
1988 // remove auras that need water/land
1989 RemoveAurasWithInterruptFlags(apply
? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER
: AURA_INTERRUPT_FLAG_NOT_UNDERWATER
);
1991 getHostilRefManager().updateThreatTables();
1994 void Player::SetGameMaster(bool on
)
1998 m_ExtraFlags
|= PLAYER_EXTRA_GM_ON
;
2000 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
2002 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
2003 ResetContestedPvP();
2005 getHostilRefManager().setOnlineOfflineState(false);
2010 m_ExtraFlags
&= ~ PLAYER_EXTRA_GM_ON
;
2011 setFactionForRace(getRace());
2012 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
2014 // restore FFA PvP Server state
2015 if(sWorld
.IsFFAPvPRealm())
2016 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
2018 // restore FFA PvP area state, remove not allowed for GM mounts
2019 UpdateArea(m_areaUpdateId
);
2021 getHostilRefManager().setOnlineOfflineState(true);
2024 ObjectAccessor::UpdateVisibilityForPlayer(this);
2027 void Player::SetGMVisible(bool on
)
2031 m_ExtraFlags
&= ~PLAYER_EXTRA_GM_INVISIBLE
; //remove flag
2033 // Reapply stealth/invisibility if active or show if not any
2034 if(HasAuraType(SPELL_AURA_MOD_STEALTH
))
2035 SetVisibility(VISIBILITY_GROUP_STEALTH
);
2036 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY
))
2037 SetVisibility(VISIBILITY_GROUP_INVISIBILITY
);
2039 SetVisibility(VISIBILITY_ON
);
2043 m_ExtraFlags
|= PLAYER_EXTRA_GM_INVISIBLE
; //add flag
2045 SetAcceptWhispers(false);
2046 SetGameMaster(true);
2048 SetVisibility(VISIBILITY_OFF
);
2052 bool Player::IsGroupVisibleFor(Player
* p
) const
2054 switch(sWorld
.getConfig(CONFIG_GROUP_VISIBILITY
))
2056 default: return IsInSameGroupWith(p
);
2057 case 1: return IsInSameRaidWith(p
);
2058 case 2: return GetTeam()==p
->GetTeam();
2062 bool Player::IsInSameGroupWith(Player
const* p
) const
2064 return p
==this || GetGroup() != NULL
&&
2065 GetGroup() == p
->GetGroup() &&
2066 GetGroup()->SameSubGroup((Player
*)this, (Player
*)p
);
2069 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2070 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2071 void Player::UninviteFromGroup()
2073 Group
* group
= GetGroupInvite();
2077 group
->RemoveInvite(this);
2079 if(group
->GetMembersCount() <= 1) // group has just 1 member => disband
2081 if(group
->IsCreated())
2083 group
->Disband(true);
2084 objmgr
.RemoveGroup(group
);
2087 group
->RemoveAllInvites();
2093 void Player::RemoveFromGroup(Group
* group
, uint64 guid
)
2097 if (group
->RemoveMember(guid
, 0) <= 1)
2099 // group->Disband(); already disbanded in RemoveMember
2100 objmgr
.RemoveGroup(group
);
2102 // removemember sets the player's group pointer to NULL
2107 void Player::SendLogXPGain(uint32 GivenXP
, Unit
* victim
, uint32 RestXP
)
2109 WorldPacket
data(SMSG_LOG_XPGAIN
, 21);
2110 data
<< uint64(victim
? victim
->GetGUID() : 0); // guid
2111 data
<< uint32(GivenXP
+RestXP
); // given experience
2112 data
<< uint8(victim
? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2115 data
<< uint32(GivenXP
); // experience without rested bonus
2116 data
<< float(1); // 1 - none 0 - 100% group bonus output
2118 data
<< uint8(0); // new 2.4.0
2119 GetSession()->SendPacket(&data
);
2122 void Player::GiveXP(uint32 xp
, Unit
* victim
)
2130 uint32 level
= getLevel();
2132 // XP to money conversion processed in Player::RewardQuest
2133 if(level
>= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
2136 // handle SPELL_AURA_MOD_XP_PCT auras
2137 Unit::AuraList
const& ModXPPctAuras
= GetAurasByType(SPELL_AURA_MOD_XP_PCT
);
2138 for(Unit::AuraList::const_iterator i
= ModXPPctAuras
.begin();i
!= ModXPPctAuras
.end(); ++i
)
2139 xp
= uint32(xp
*(1.0f
+ (*i
)->GetModifier()->m_amount
/ 100.0f
));
2141 // XP resting bonus for kill
2142 uint32 rested_bonus_xp
= victim
? GetXPRestBonus(xp
) : 0;
2144 SendLogXPGain(xp
,victim
,rested_bonus_xp
);
2146 uint32 curXP
= GetUInt32Value(PLAYER_XP
);
2147 uint32 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2148 uint32 newXP
= curXP
+ xp
+ rested_bonus_xp
;
2150 while( newXP
>= nextLvlXP
&& level
< sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
2154 if ( level
< sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
2155 GiveLevel(level
+ 1);
2158 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2161 SetUInt32Value(PLAYER_XP
, newXP
);
2164 // Update player to next level
2165 // Current player experience not update (must be update by caller)
2166 void Player::GiveLevel(uint32 level
)
2168 if ( level
== getLevel() )
2171 PlayerLevelInfo info
;
2172 objmgr
.GetPlayerLevelInfo(getRace(),getClass(),level
,&info
);
2174 PlayerClassLevelInfo classInfo
;
2175 objmgr
.GetPlayerClassLevelInfo(getClass(),level
,&classInfo
);
2177 // send levelup info to client
2178 WorldPacket
data(SMSG_LEVELUP_INFO
, (4+4+MAX_POWERS
*4+MAX_STATS
*4));
2179 data
<< uint32(level
);
2180 data
<< uint32(int32(classInfo
.basehealth
) - int32(GetCreateHealth()));
2181 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2182 data
<< uint32(int32(classInfo
.basemana
) - int32(GetCreateMana()));
2190 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
) // Stats loop (0-4)
2191 data
<< uint32(int32(info
.stats
[i
]) - GetCreateStat(Stats(i
)));
2193 GetSession()->SendPacket(&data
);
2195 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, objmgr
.GetXPForLevel(level
));
2197 //update level, max level of skills
2198 if(getLevel()!= level
)
2199 m_Played_time
[1] = 0; // Level Played Time reset
2201 UpdateSkillsForLevel ();
2203 // save base values (bonuses already included in stored stats
2204 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2205 SetCreateStat(Stats(i
), info
.stats
[i
]);
2207 SetCreateHealth(classInfo
.basehealth
);
2208 SetCreateMana(classInfo
.basemana
);
2210 InitTalentForLevel();
2211 InitTaxiNodesForLevel();
2212 InitGlyphsForLevel();
2216 // set current level health and mana/energy to maximum after applying all mods.
2217 SetHealth(GetMaxHealth());
2218 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2219 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2220 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2221 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2222 SetPower(POWER_FOCUS
, 0);
2223 SetPower(POWER_HAPPINESS
, 0);
2225 // give level to summoned pet
2226 Pet
* pet
= GetPet();
2227 if(pet
&& pet
->getPetType()==SUMMON_PET
)
2228 pet
->GivePetLevel(level
);
2229 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL
);
2232 void Player::InitTalentForLevel()
2234 uint32 level
= getLevel();
2235 // talents base at level diff ( talents = level - 9 but some can be used already)
2238 // Remove all talent points
2239 if(m_usedTalentCount
> 0) // Free any used talents
2242 SetFreeTalentPoints(0);
2247 uint32 talentPointsForLevel
= CalculateTalentsPoints();
2249 // if used more that have then reset
2250 if(m_usedTalentCount
> talentPointsForLevel
)
2252 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR
)
2255 SetFreeTalentPoints(0);
2257 // else update amount of free points
2259 SetFreeTalentPoints(talentPointsForLevel
-m_usedTalentCount
);
2263 void Player::InitStatsForLevel(bool reapplyMods
)
2265 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2266 _RemoveAllStatBonuses();
2268 PlayerClassLevelInfo classInfo
;
2269 objmgr
.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo
);
2271 PlayerLevelInfo info
;
2272 objmgr
.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info
);
2274 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL
, sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) );
2275 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, objmgr
.GetXPForLevel(getLevel()));
2277 UpdateSkillsForLevel ();
2279 // set default cast time multiplier
2280 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
);
2282 // reset size before reapply auras
2283 SetFloatValue(OBJECT_FIELD_SCALE_X
,1.0f
);
2285 // save base values (bonuses already included in stored stats
2286 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2287 SetCreateStat(Stats(i
), info
.stats
[i
]);
2289 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2290 SetStat(Stats(i
), info
.stats
[i
]);
2292 SetCreateHealth(classInfo
.basehealth
);
2295 SetCreateMana(classInfo
.basemana
);
2297 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2301 //reset rating fields values
2302 for(uint16 index
= PLAYER_FIELD_COMBAT_RATING_1
; index
< PLAYER_FIELD_COMBAT_RATING_1
+ MAX_COMBAT_RATING
; ++index
)
2303 SetUInt32Value(index
, 0);
2305 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS
,0);
2306 for (int i
= 0; i
< 7; i
++)
2308 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG
+i
, 0);
2309 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS
+i
, 0);
2310 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT
+i
, 1.00f
);
2313 //reset attack power, damage and attack speed fields
2314 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
, 2000.0f
);
2315 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
+ 1, 2000.0f
); // offhand attack time
2316 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME
, 2000.0f
);
2318 SetFloatValue(UNIT_FIELD_MINDAMAGE
, 0.0f
);
2319 SetFloatValue(UNIT_FIELD_MAXDAMAGE
, 0.0f
);
2320 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
, 0.0f
);
2321 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
, 0.0f
);
2322 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
, 0.0f
);
2323 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
, 0.0f
);
2325 SetUInt32Value(UNIT_FIELD_ATTACK_POWER
, 0 );
2326 SetUInt32Value(UNIT_FIELD_ATTACK_POWER_MODS
, 0 );
2327 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER
,0.0f
);
2328 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER
, 0 );
2329 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS
,0 );
2330 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER
,0.0f
);
2332 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2333 SetFloatValue(PLAYER_CRIT_PERCENTAGE
,0.0f
);
2334 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE
,0.0f
);
2335 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE
,0.0f
);
2337 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2338 for (uint8 i
= 0; i
< 7; ++i
)
2339 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1
+i
, 0.0f
);
2341 SetFloatValue(PLAYER_PARRY_PERCENTAGE
, 0.0f
);
2342 SetFloatValue(PLAYER_BLOCK_PERCENTAGE
, 0.0f
);
2343 SetUInt32Value(PLAYER_SHIELD_BLOCK
, 0);
2346 SetFloatValue(PLAYER_DODGE_PERCENTAGE
, 0.0f
);
2348 // set armor (resistance 0) to original value (create_agility*2)
2349 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2350 SetResistanceBuffMods(SpellSchools(0), true, 0.0f
);
2351 SetResistanceBuffMods(SpellSchools(0), false, 0.0f
);
2352 // set other resistance to original value (0)
2353 for (int i
= 1; i
< MAX_SPELL_SCHOOL
; i
++)
2355 SetResistance(SpellSchools(i
), 0);
2356 SetResistanceBuffMods(SpellSchools(i
), true, 0.0f
);
2357 SetResistanceBuffMods(SpellSchools(i
), false, 0.0f
);
2360 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE
,0);
2361 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE
,0);
2362 for(int i
= 0; i
< MAX_SPELL_SCHOOL
; ++i
)
2364 SetFloatValue(UNIT_FIELD_POWER_COST_MODIFIER
+i
,0.0f
);
2365 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER
+i
,0.0f
);
2367 // Reset no reagent cost field
2368 for(int i
= 0; i
< 3; i
++)
2369 SetUInt32Value(PLAYER_NO_REAGENT_COST_1
+ i
, 0);
2370 // Init data for form but skip reapply item mods for form
2371 InitDataForForm(reapplyMods
);
2374 for (int i
= POWER_MANA
; i
< MAX_POWERS
; i
++)
2375 SetMaxPower(Powers(i
), uint32(GetCreatePowers(Powers(i
))));
2377 SetMaxHealth(classInfo
.basehealth
); // stamina bonus will applied later
2379 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2380 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID
, 0);
2382 // cleanup unit flags (will be re-applied if need at aura load).
2383 RemoveFlag( UNIT_FIELD_FLAGS
,
2384 UNIT_FLAG_NON_ATTACKABLE
| UNIT_FLAG_DISABLE_MOVE
| UNIT_FLAG_NOT_ATTACKABLE_1
|
2385 UNIT_FLAG_PET_IN_COMBAT
| UNIT_FLAG_SILENCED
| UNIT_FLAG_PACIFIED
|
2386 UNIT_FLAG_STUNNED
| UNIT_FLAG_IN_COMBAT
| UNIT_FLAG_DISARMED
|
2387 UNIT_FLAG_CONFUSED
| UNIT_FLAG_FLEEING
| UNIT_FLAG_NOT_SELECTABLE
|
2388 UNIT_FLAG_SKINNABLE
| UNIT_FLAG_MOUNT
| UNIT_FLAG_TAXI_FLIGHT
);
2389 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
); // must be set
2391 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2392 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
| PLAYER_FLAGS_DND
| PLAYER_FLAGS_GM
| PLAYER_FLAGS_GHOST
);
2394 SetByteValue(UNIT_FIELD_BYTES_1
, 2, 0x00); // one form stealth modified bytes
2395 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
| UNIT_BYTE2_FLAG_SANCTUARY
);
2397 // restore if need some important flags
2398 SetUInt32Value(PLAYER_FIELD_BYTES2
, 0 ); // flags empty by default
2400 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2401 _ApplyAllStatBonuses();
2403 // set current level health and mana/energy to maximum after applying all mods.
2404 SetHealth(GetMaxHealth());
2405 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2406 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2407 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2408 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2409 SetPower(POWER_FOCUS
, 0);
2410 SetPower(POWER_HAPPINESS
, 0);
2411 SetPower(POWER_RUNIC_POWER
, 0);
2414 void Player::SendInitialSpells()
2416 uint16 spellCount
= 0;
2418 WorldPacket
data(SMSG_INITIAL_SPELLS
, (1+2+4*m_spells
.size()+2+m_spellCooldowns
.size()*(2+2+2+4+4)));
2421 size_t countPos
= data
.wpos();
2422 data
<< uint16(spellCount
); // spell count placeholder
2424 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2426 if(itr
->second
->state
== PLAYERSPELL_REMOVED
)
2429 if(!itr
->second
->active
|| itr
->second
->disabled
)
2432 data
<< uint16(itr
->first
);
2433 data
<< uint16(0); // it's not slot id
2438 data
.put
<uint16
>(countPos
,spellCount
); // write real count value
2440 uint16 spellCooldowns
= m_spellCooldowns
.size();
2441 data
<< uint16(spellCooldowns
);
2442 for(SpellCooldowns::const_iterator itr
=m_spellCooldowns
.begin(); itr
!=m_spellCooldowns
.end(); ++itr
)
2444 SpellEntry
const *sEntry
= sSpellStore
.LookupEntry(itr
->first
);
2448 data
<< uint16(itr
->first
);
2450 time_t cooldown
= 0;
2451 time_t curTime
= time(NULL
);
2452 if(itr
->second
.end
> curTime
)
2453 cooldown
= (itr
->second
.end
-curTime
)*1000;
2455 data
<< uint16(itr
->second
.itemid
); // cast item id
2456 data
<< uint16(sEntry
->Category
); // spell category
2457 if(sEntry
->Category
) // may be wrong, but anyway better than nothing...
2459 data
<< uint32(0); // cooldown
2460 data
<< uint32(cooldown
); // category cooldown
2464 data
<< uint32(cooldown
); // cooldown
2465 data
<< uint32(0); // category cooldown
2469 GetSession()->SendPacket(&data
);
2471 sLog
.outDetail( "CHARACTER: Sent Initial Spells" );
2474 void Player::RemoveMail(uint32 id
)
2476 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
2478 if ((*itr
)->messageID
== id
)
2480 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2487 void Player::SendMailResult(uint32 mailId
, uint32 mailAction
, uint32 mailError
, uint32 equipError
, uint32 item_guid
, uint32 item_count
)
2489 WorldPacket
data(SMSG_SEND_MAIL_RESULT
, (4+4+4+(mailError
== MAIL_ERR_BAG_FULL
?4:(mailAction
== MAIL_ITEM_TAKEN
?4+4:0))));
2490 data
<< (uint32
) mailId
;
2491 data
<< (uint32
) mailAction
;
2492 data
<< (uint32
) mailError
;
2493 if ( mailError
== MAIL_ERR_BAG_FULL
)
2494 data
<< (uint32
) equipError
;
2495 else if( mailAction
== MAIL_ITEM_TAKEN
)
2497 data
<< (uint32
) item_guid
; // item guid low?
2498 data
<< (uint32
) item_count
; // item count?
2500 GetSession()->SendPacket(&data
);
2503 void Player::SendNewMail()
2505 // deliver undelivered mail
2506 WorldPacket
data(SMSG_RECEIVED_MAIL
, 4);
2508 GetSession()->SendPacket(&data
);
2511 void Player::UpdateNextMailTimeAndUnreads()
2513 // calculate next delivery time (min. from non-delivered mails
2514 // and recalculate unReadMail
2515 time_t cTime
= time(NULL
);
2516 m_nextMailDelivereTime
= 0;
2518 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
2520 if((*itr
)->deliver_time
> cTime
)
2522 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> (*itr
)->deliver_time
)
2523 m_nextMailDelivereTime
= (*itr
)->deliver_time
;
2525 else if(((*itr
)->checked
& MAIL_CHECK_MASK_READ
) == 0)
2530 void Player::AddNewMailDeliverTime(time_t deliver_time
)
2532 if(deliver_time
<= time(NULL
)) // ready now
2537 else // not ready and no have ready mails
2539 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> deliver_time
)
2540 m_nextMailDelivereTime
= deliver_time
;
2544 bool Player::addSpell(uint32 spell_id
, bool active
, bool learning
, bool disabled
)
2546 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
2549 // do character spell book cleanup (all characters)
2550 if(!IsInWorld() && !learning
) // spell load case
2552 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id
);
2553 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2556 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id
);
2561 if(!SpellMgr::IsSpellValid(spellInfo
,this,false))
2563 // do character spell book cleanup (all characters)
2564 if(!IsInWorld() && !learning
) // spell load case
2566 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id
);
2567 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2570 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id
);
2575 PlayerSpellState state
= learning
? PLAYERSPELL_NEW
: PLAYERSPELL_UNCHANGED
;
2577 bool disabled_case
= false;
2578 bool superceded_old
= false;
2580 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2581 if (itr
!= m_spells
.end())
2583 // update active state for known spell
2584 if(itr
->second
->active
!= active
&& itr
->second
->state
!= PLAYERSPELL_REMOVED
&& !itr
->second
->disabled
)
2586 itr
->second
->active
= active
;
2588 // !IsInWorld() && !learning == explicitly load from DB and then exist in it already and set correctly
2589 if(!IsInWorld() && !learning
)
2590 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2591 else if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2592 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2596 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
2597 data
<< uint16(spell_id
);
2598 GetSession()->SendPacket(&data
);
2600 return active
; // learn (show in spell book if active now)
2603 if(itr
->second
->disabled
!= disabled
&& itr
->second
->state
!= PLAYERSPELL_REMOVED
)
2605 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2606 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2607 itr
->second
->disabled
= disabled
;
2612 disabled_case
= true;
2614 else switch(itr
->second
->state
)
2616 case PLAYERSPELL_UNCHANGED
: // known saved spell
2618 case PLAYERSPELL_REMOVED
: // re-learning removed not saved spell
2621 m_spells
.erase(itr
);
2622 state
= PLAYERSPELL_CHANGED
;
2623 break; // need re-add
2625 default: // known not saved yet spell (new or modified)
2627 // can be in case spell loading but learned at some previous spell loading
2628 if(!IsInWorld() && !learning
)
2629 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2636 if(!disabled_case
) // skip new spell adding if spell already known (disabled spells case)
2638 // talent: unlearn all other talent ranks (high and low)
2639 if(TalentSpellPos
const* talentPos
= GetTalentSpellPos(spell_id
))
2641 if(TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry( talentPos
->talent_id
))
2643 for(int i
=0; i
<5; ++i
)
2645 // skip learning spell and no rank spell case
2646 uint32 rankSpellId
= talentInfo
->RankID
[i
];
2647 if(!rankSpellId
|| rankSpellId
==spell_id
)
2650 // skip unknown ranks
2651 if(!HasSpell(rankSpellId
))
2654 removeSpell(rankSpellId
);
2658 // non talent spell: learn low ranks (recursive call)
2659 else if(uint32 prev_spell
= spellmgr
.GetPrevSpellInChain(spell_id
))
2661 if(!IsInWorld()) // at spells loading, no output, but allow save
2662 addSpell(prev_spell
,active
,true,disabled
);
2663 else // at normal learning
2664 learnSpell(prev_spell
);
2667 PlayerSpell
*newspell
= new PlayerSpell
;
2668 newspell
->active
= active
;
2669 newspell
->state
= state
;
2670 newspell
->disabled
= disabled
;
2672 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2673 if(newspell
->active
&& !newspell
->disabled
&& !SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
2675 for( PlayerSpellMap::iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2677 if(itr
->second
->state
== PLAYERSPELL_REMOVED
) continue;
2678 SpellEntry
const *i_spellInfo
= sSpellStore
.LookupEntry(itr
->first
);
2679 if(!i_spellInfo
) continue;
2681 if( spellmgr
.IsRankSpellDueToSpell(spellInfo
,itr
->first
) )
2683 if(itr
->second
->active
)
2685 if(spellmgr
.IsHighRankOfSpell(spell_id
,itr
->first
))
2687 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2689 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2690 data
<< uint16(itr
->first
);
2691 data
<< uint16(spell_id
);
2692 GetSession()->SendPacket( &data
);
2695 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2696 itr
->second
->active
= false;
2697 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2698 superceded_old
= true; // new spell replace old in action bars and spell book.
2700 else if(spellmgr
.IsHighRankOfSpell(itr
->first
,spell_id
))
2702 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2704 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2705 data
<< uint16(spell_id
);
2706 data
<< uint16(itr
->first
);
2707 GetSession()->SendPacket( &data
);
2710 // mark new spell as disable (not learned yet for client and will not learned)
2711 newspell
->active
= false;
2712 if(newspell
->state
!= PLAYERSPELL_NEW
)
2713 newspell
->state
= PLAYERSPELL_CHANGED
;
2720 m_spells
[spell_id
] = newspell
;
2722 // return false if spell disabled
2723 if (newspell
->disabled
)
2727 uint32 talentCost
= GetTalentSpellCost(spell_id
);
2729 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2730 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2731 if( talentCost
> 0 && IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_LEARN_SPELL
) )
2733 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2734 CastSpell(this, spell_id
, true);
2736 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2737 else if (IsPassiveSpell(spell_id
))
2739 bool need_cast
= false;
2743 // some spells not have stance data expacted cast at form change or present
2744 case 5420: need_cast
= (m_form
== FORM_TREE
); break;
2745 case 5419: need_cast
= (m_form
== FORM_TRAVEL
); break;
2746 case 7376: need_cast
= (m_form
== FORM_DEFENSIVESTANCE
); break;
2747 case 7381: need_cast
= (m_form
== FORM_BERSERKERSTANCE
); break;
2748 case 21156: need_cast
= (m_form
== FORM_BATTLESTANCE
); break;
2749 case 21178: need_cast
= (m_form
== FORM_BEAR
|| m_form
== FORM_DIREBEAR
); break;
2750 case 33948: need_cast
= (m_form
== FORM_FLIGHT
); break;
2751 case 34764: need_cast
= (m_form
== FORM_FLIGHT
); break;
2752 case 40121: need_cast
= (m_form
== FORM_FLIGHT_EPIC
); break;
2753 case 40122: need_cast
= (m_form
== FORM_FLIGHT_EPIC
); break;
2754 // another spells have proper stance data
2755 default: need_cast
= !spellInfo
->Stances
|| m_form
!= 0 && (spellInfo
->Stances
& (1<<(m_form
-1))); break;
2757 //Check CasterAuraStates
2758 if (need_cast
&& (!spellInfo
->CasterAuraState
|| HasAuraState(AuraState(spellInfo
->CasterAuraState
))))
2759 CastSpell(this, spell_id
, true);
2761 else if( IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_SKILL_STEP
) )
2763 CastSpell(this, spell_id
, true);
2767 // update used talent points count
2768 m_usedTalentCount
+= talentCost
;
2770 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2771 if(uint32 freeProfs
= GetFreePrimaryProffesionPoints())
2773 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
2774 SetFreePrimaryProffesions(freeProfs
-1);
2777 // add dependent skills
2778 uint16 maxskill
= GetMaxSkillValueForLevel();
2780 SpellLearnSkillNode
const* spellLearnSkill
= spellmgr
.GetSpellLearnSkill(spell_id
);
2784 uint32 skill_value
= GetPureSkillValue(spellLearnSkill
->skill
);
2785 uint32 skill_max_value
= GetPureMaxSkillValue(spellLearnSkill
->skill
);
2787 if(skill_value
< spellLearnSkill
->value
)
2788 skill_value
= spellLearnSkill
->value
;
2790 uint32 new_skill_max_value
= spellLearnSkill
->maxvalue
== 0 ? maxskill
: spellLearnSkill
->maxvalue
;
2792 if(skill_max_value
< new_skill_max_value
)
2793 skill_max_value
= new_skill_max_value
;
2795 SetSkill(spellLearnSkill
->skill
,skill_value
,skill_max_value
);
2799 // not ranked skills
2800 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
2801 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
2803 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
2805 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
2809 if(HasSkill(pSkill
->id
))
2812 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
2813 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2814 pSkill
->id
==SKILL_LOCKPICKING
&& _spell_idx
->second
->max_value
==0 )
2816 switch(GetSkillRangeType(pSkill
,_spell_idx
->second
->racemask
!=0))
2818 case SKILL_RANGE_LANGUAGE
:
2819 SetSkill(pSkill
->id
, 300, 300 );
2821 case SKILL_RANGE_LEVEL
:
2822 SetSkill(pSkill
->id
, 1, GetMaxSkillValueForLevel() );
2824 case SKILL_RANGE_MONO
:
2825 SetSkill(pSkill
->id
, 1, 1 );
2834 // learn dependent spells
2835 SpellLearnSpellMap::const_iterator spell_begin
= spellmgr
.GetBeginSpellLearnSpell(spell_id
);
2836 SpellLearnSpellMap::const_iterator spell_end
= spellmgr
.GetEndSpellLearnSpell(spell_id
);
2838 for(SpellLearnSpellMap::const_iterator itr
= spell_begin
; itr
!= spell_end
; ++itr
)
2840 if(!itr
->second
.autoLearned
)
2842 if(!IsInWorld() || !itr
->second
.active
) // at spells loading, no output, but allow save
2843 addSpell(itr
->second
.spell
,itr
->second
.active
,true,false);
2844 else // at normal learning
2845 learnSpell(itr
->second
.spell
);
2851 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL
);
2852 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS
);
2855 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2856 return active
&& !disabled
&& !superceded_old
;
2859 void Player::learnSpell(uint32 spell_id
)
2861 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2863 bool disabled
= (itr
!= m_spells
.end()) ? itr
->second
->disabled
: false;
2864 bool active
= disabled
? itr
->second
->active
: true;
2866 bool learning
= addSpell(spell_id
,active
,true,false);
2868 // learn all disabled higher ranks (recursive)
2871 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
2872 for(SpellChainMapNext::const_iterator i
= nextMap
.lower_bound(spell_id
); i
!= nextMap
.upper_bound(spell_id
); ++i
)
2874 PlayerSpellMap::iterator iter
= m_spells
.find(i
->second
);
2875 if (iter
!= m_spells
.end() && iter
->second
->disabled
)
2876 learnSpell(i
->second
);
2880 // prevent duplicated entires in spell book, also not send if not in world (loading)
2881 if(!learning
|| !IsInWorld ())
2884 WorldPacket
data(SMSG_LEARNED_SPELL
, 4);
2885 data
<< uint32(spell_id
);
2886 GetSession()->SendPacket(&data
);
2889 void Player::removeSpell(uint32 spell_id
, bool disabled
)
2891 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2892 if (itr
== m_spells
.end())
2895 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| disabled
&& itr
->second
->disabled
)
2898 // unlearn non talent higher ranks (recursive)
2899 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
2900 for(SpellChainMapNext::const_iterator itr2
= nextMap
.lower_bound(spell_id
); itr2
!= nextMap
.upper_bound(spell_id
); ++itr2
)
2901 if(HasSpell(itr2
->second
) && !GetTalentSpellPos(itr2
->second
))
2902 removeSpell(itr2
->second
,disabled
);
2905 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
2906 data
<< uint16(spell_id
);
2907 GetSession()->SendPacket(&data
);
2911 itr
->second
->disabled
= disabled
;
2912 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2913 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2917 if(itr
->second
->state
== PLAYERSPELL_NEW
)
2920 m_spells
.erase(itr
);
2923 itr
->second
->state
= PLAYERSPELL_REMOVED
;
2926 RemoveAurasDueToSpell(spell_id
);
2929 if(PetAura
const* petSpell
= spellmgr
.GetPetAura(spell_id
))
2930 RemovePetAura(petSpell
);
2932 // free talent points
2933 uint32 talentCosts
= GetTalentSpellCost(spell_id
);
2936 if(talentCosts
< m_usedTalentCount
)
2937 m_usedTalentCount
-= talentCosts
;
2939 m_usedTalentCount
= 0;
2942 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
2943 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
2945 uint32 freeProfs
= GetFreePrimaryProffesionPoints()+1;
2946 if(freeProfs
<= sWorld
.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL
))
2947 SetFreePrimaryProffesions(freeProfs
);
2950 // remove dependent skill
2951 SpellLearnSkillNode
const* spellLearnSkill
= spellmgr
.GetSpellLearnSkill(spell_id
);
2954 uint32 prev_spell
= spellmgr
.GetPrevSpellInChain(spell_id
);
2955 if(!prev_spell
) // first rank, remove skill
2956 SetSkill(spellLearnSkill
->skill
,0,0);
2959 // search prev. skill setting by spell ranks chain
2960 SpellLearnSkillNode
const* prevSkill
= spellmgr
.GetSpellLearnSkill(prev_spell
);
2961 while(!prevSkill
&& prev_spell
)
2963 prev_spell
= spellmgr
.GetPrevSpellInChain(prev_spell
);
2964 prevSkill
= spellmgr
.GetSpellLearnSkill(spellmgr
.GetFirstSpellInChain(prev_spell
));
2967 if(!prevSkill
) // not found prev skill setting, remove skill
2968 SetSkill(spellLearnSkill
->skill
,0,0);
2969 else // set to prev. skill setting values
2971 uint32 skill_value
= GetPureSkillValue(prevSkill
->skill
);
2972 uint32 skill_max_value
= GetPureMaxSkillValue(prevSkill
->skill
);
2974 if(skill_value
> prevSkill
->value
)
2975 skill_value
= prevSkill
->value
;
2977 uint32 new_skill_max_value
= prevSkill
->maxvalue
== 0 ? GetMaxSkillValueForLevel() : prevSkill
->maxvalue
;
2979 if(skill_max_value
> new_skill_max_value
)
2980 skill_max_value
= new_skill_max_value
;
2982 SetSkill(prevSkill
->skill
,skill_value
,skill_max_value
);
2989 // not ranked skills
2990 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
2991 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
2993 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
2995 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
2999 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
3000 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3001 pSkill
->id
==SKILL_LOCKPICKING
&& _spell_idx
->second
->max_value
==0 )
3003 // not reset skills for professions and racial abilities
3004 if( (pSkill
->categoryId
==SKILL_CATEGORY_SECONDARY
|| pSkill
->categoryId
==SKILL_CATEGORY_PROFESSION
) &&
3005 (IsProfessionSkill(pSkill
->id
) || _spell_idx
->second
->racemask
!=0) )
3008 SetSkill(pSkill
->id
, 0, 0 );
3013 // remove dependent spells
3014 SpellLearnSpellMap::const_iterator spell_begin
= spellmgr
.GetBeginSpellLearnSpell(spell_id
);
3015 SpellLearnSpellMap::const_iterator spell_end
= spellmgr
.GetEndSpellLearnSpell(spell_id
);
3017 for(SpellLearnSpellMap::const_iterator itr2
= spell_begin
; itr2
!= spell_end
; ++itr2
)
3018 removeSpell(itr2
->second
.spell
, disabled
);
3020 // TODO: recast if need lesser ranks spell for passive with IsPassiveSpellStackableWithRanks
3023 void Player::RemoveArenaSpellCooldowns()
3025 // remove cooldowns on spells that has < 15 min CD
3026 SpellCooldowns::iterator itr
, next
;
3027 // iterate spell cooldowns
3028 for(itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); itr
= next
)
3032 SpellEntry
const * entry
= sSpellStore
.LookupEntry(itr
->first
);
3033 // check if spellentry is present and if the cooldown is less than 15 mins
3035 entry
->RecoveryTime
<= 15 * MINUTE
* 1000 &&
3036 entry
->CategoryRecoveryTime
<= 15 * MINUTE
* 1000 )
3039 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, (4+8));
3040 data
<< uint32(itr
->first
);
3042 GetSession()->SendPacket(&data
);
3044 m_spellCooldowns
.erase(itr
);
3049 void Player::RemoveAllSpellCooldown()
3051 if(!m_spellCooldowns
.empty())
3053 for(SpellCooldowns::const_iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); ++itr
)
3055 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, (4+8));
3056 data
<< uint32(itr
->first
);
3057 data
<< uint64(GetGUID());
3058 GetSession()->SendPacket(&data
);
3060 m_spellCooldowns
.clear();
3064 void Player::_LoadSpellCooldowns(QueryResult
*result
)
3066 m_spellCooldowns
.clear();
3068 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3072 time_t curTime
= time(NULL
);
3076 Field
*fields
= result
->Fetch();
3078 uint32 spell_id
= fields
[0].GetUInt32();
3079 uint32 item_id
= fields
[1].GetUInt32();
3080 time_t db_time
= (time_t)fields
[2].GetUInt64();
3082 if(!sSpellStore
.LookupEntry(spell_id
))
3084 sLog
.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id
);
3088 // skip outdated cooldown
3089 if(db_time
<= curTime
)
3092 AddSpellCooldown(spell_id
, item_id
, db_time
);
3094 sLog
.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id
, item_id
, uint32(db_time
-curTime
));
3096 while( result
->NextRow() );
3102 void Player::_SaveSpellCooldowns()
3104 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3106 time_t curTime
= time(NULL
);
3108 // remove outdated and save active
3109 for(SpellCooldowns::iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end();)
3111 if(itr
->second
.end
<= curTime
)
3112 m_spellCooldowns
.erase(itr
++);
3115 CharacterDatabase
.PExecute("INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ('%u', '%u', '%u', '" I64FMTD
"')", GetGUIDLow(), itr
->first
, itr
->second
.itemid
, uint64(itr
->second
.end
));
3121 uint32
Player::resetTalentsCost() const
3123 // The first time reset costs 1 gold
3124 if(m_resetTalentsCost
< 1*GOLD
)
3127 else if(m_resetTalentsCost
< 5*GOLD
)
3129 // After that it increases in increments of 5 gold
3130 else if(m_resetTalentsCost
< 10*GOLD
)
3134 uint32 months
= (sWorld
.GetGameTime() - m_resetTalentsTime
)/MONTH
;
3137 // This cost will be reduced by a rate of 5 gold per month
3138 int32 new_cost
= int32(m_resetTalentsCost
) - 5*GOLD
*months
;
3139 // to a minimum of 10 gold.
3140 return (new_cost
< 10*GOLD
? 10*GOLD
: new_cost
);
3144 // After that it increases in increments of 5 gold
3145 int32 new_cost
= m_resetTalentsCost
+ 5*GOLD
;
3146 // until it hits a cap of 50 gold.
3147 if(new_cost
> 50*GOLD
)
3154 bool Player::resetTalents(bool no_cost
)
3156 // not need after this call
3157 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS
))
3159 m_atLoginFlags
= m_atLoginFlags
& ~AT_LOGIN_RESET_TALENTS
;
3160 CharacterDatabase
.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS
), GetGUIDLow());
3163 uint32 talentPointsForLevel
= CalculateTalentsPoints();
3165 if (m_usedTalentCount
== 0)
3167 SetFreeTalentPoints(talentPointsForLevel
);
3175 cost
= resetTalentsCost();
3177 if (GetMoney() < cost
)
3179 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, 0, 0, 0);
3184 for (unsigned int i
= 0; i
< sTalentStore
.GetNumRows(); i
++)
3186 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry(i
);
3188 if (!talentInfo
) continue;
3190 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentInfo
->TalentTab
);
3195 // unlearn only talents for character class
3196 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3197 // to prevent unexpected lost normal learned spell skip another class talents
3198 if( (getClassMask() & talentTabInfo
->ClassMask
) == 0 )
3201 for (int j
= 0; j
< 5; j
++)
3203 for(PlayerSpellMap::iterator itr
= GetSpellMap().begin(); itr
!= GetSpellMap().end();)
3205 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->second
->disabled
)
3211 // remove learned spells (all ranks)
3212 uint32 itrFirstId
= spellmgr
.GetFirstSpellInChain(itr
->first
);
3214 // unlearn if first rank is talent or learned by talent
3215 if (itrFirstId
== talentInfo
->RankID
[j
] || spellmgr
.IsSpellLearnToSpell(talentInfo
->RankID
[j
],itrFirstId
))
3217 removeSpell(itr
->first
,!IsPassiveSpell(itr
->first
));
3218 itr
= GetSpellMap().begin();
3227 SetFreeTalentPoints(talentPointsForLevel
);
3231 ModifyMoney(-(int32
)cost
);
3233 m_resetTalentsCost
= cost
;
3234 m_resetTalentsTime
= time(NULL
);
3237 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3238 RemovePet(NULL
,PET_SAVE_NOT_IN_SLOT
, true);
3243 bool Player::_removeSpell(uint16 spell_id
)
3245 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
3246 if (itr
!= m_spells
.end())
3249 m_spells
.erase(itr
);
3255 Mail
* Player::GetMail(uint32 id
)
3257 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
3259 if ((*itr
)->messageID
== id
)
3267 void Player::_SetCreateBits(UpdateMask
*updateMask
, Player
*target
) const
3271 Object::_SetCreateBits(updateMask
, target
);
3275 for(uint16 index
= 0; index
< m_valuesCount
; index
++)
3277 if(GetUInt32Value(index
) != 0 && updateVisualBits
.GetBit(index
))
3278 updateMask
->SetBit(index
);
3283 void Player::_SetUpdateBits(UpdateMask
*updateMask
, Player
*target
) const
3287 Object::_SetUpdateBits(updateMask
, target
);
3291 Object::_SetUpdateBits(updateMask
, target
);
3292 *updateMask
&= updateVisualBits
;
3296 void Player::InitVisibleBits()
3298 updateVisualBits
.SetCount(PLAYER_END
);
3300 updateVisualBits
.SetBit(OBJECT_FIELD_GUID
);
3301 updateVisualBits
.SetBit(OBJECT_FIELD_TYPE
);
3302 updateVisualBits
.SetBit(OBJECT_FIELD_ENTRY
);
3303 updateVisualBits
.SetBit(OBJECT_FIELD_SCALE_X
);
3304 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 0);
3305 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 1);
3306 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 0);
3307 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 1);
3308 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 0);
3309 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 1);
3310 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 0);
3311 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 1);
3312 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 0);
3313 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 1);
3314 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_0
);
3315 updateVisualBits
.SetBit(UNIT_FIELD_HEALTH
);
3316 updateVisualBits
.SetBit(UNIT_FIELD_POWER1
);
3317 updateVisualBits
.SetBit(UNIT_FIELD_POWER2
);
3318 updateVisualBits
.SetBit(UNIT_FIELD_POWER3
);
3319 updateVisualBits
.SetBit(UNIT_FIELD_POWER4
);
3320 updateVisualBits
.SetBit(UNIT_FIELD_POWER5
);
3321 updateVisualBits
.SetBit(UNIT_FIELD_POWER6
);
3322 updateVisualBits
.SetBit(UNIT_FIELD_POWER7
);
3323 updateVisualBits
.SetBit(UNIT_FIELD_MAXHEALTH
);
3324 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER1
);
3325 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER2
);
3326 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER3
);
3327 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER4
);
3328 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER5
);
3329 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER6
);
3330 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER7
);
3331 updateVisualBits
.SetBit(UNIT_FIELD_LEVEL
);
3332 updateVisualBits
.SetBit(UNIT_FIELD_FACTIONTEMPLATE
);
3333 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 0);
3334 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 1);
3335 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 2);
3336 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS
);
3337 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS_2
);
3338 updateVisualBits
.SetBit(UNIT_FIELD_AURASTATE
);
3339 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 0);
3340 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 1);
3341 updateVisualBits
.SetBit(UNIT_FIELD_BOUNDINGRADIUS
);
3342 updateVisualBits
.SetBit(UNIT_FIELD_COMBATREACH
);
3343 updateVisualBits
.SetBit(UNIT_FIELD_DISPLAYID
);
3344 updateVisualBits
.SetBit(UNIT_FIELD_NATIVEDISPLAYID
);
3345 updateVisualBits
.SetBit(UNIT_FIELD_MOUNTDISPLAYID
);
3346 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_1
);
3347 updateVisualBits
.SetBit(UNIT_FIELD_PETNUMBER
);
3348 updateVisualBits
.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP
);
3349 updateVisualBits
.SetBit(UNIT_DYNAMIC_FLAGS
);
3350 updateVisualBits
.SetBit(UNIT_CHANNEL_SPELL
);
3351 updateVisualBits
.SetBit(UNIT_MOD_CAST_SPEED
);
3352 updateVisualBits
.SetBit(UNIT_FIELD_BASE_MANA
);
3353 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_2
);
3354 updateVisualBits
.SetBit(UNIT_FIELD_HOVERHEIGHT
);
3356 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 0);
3357 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 1);
3358 updateVisualBits
.SetBit(PLAYER_FLAGS
);
3359 updateVisualBits
.SetBit(PLAYER_GUILDID
);
3360 updateVisualBits
.SetBit(PLAYER_GUILDRANK
);
3361 updateVisualBits
.SetBit(PLAYER_BYTES
);
3362 updateVisualBits
.SetBit(PLAYER_BYTES_2
);
3363 updateVisualBits
.SetBit(PLAYER_BYTES_3
);
3364 updateVisualBits
.SetBit(PLAYER_DUEL_TEAM
);
3365 updateVisualBits
.SetBit(PLAYER_GUILD_TIMESTAMP
);
3367 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3368 for(uint16 i
= PLAYER_QUEST_LOG_1_1
; i
< PLAYER_QUEST_LOG_25_2
; i
+= 4)
3369 updateVisualBits
.SetBit(i
);
3371 // Players visible items are not inventory stuff
3372 for(uint16 i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
3374 uint32 offset
= i
* MAX_VISIBLE_ITEM_OFFSET
;
3377 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR
+ 0 + offset
);
3378 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR
+ 1 + offset
);
3381 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_0
+ 0 + offset
);
3383 // item enchantments
3384 for(uint8 j
= 0; j
< MAX_ENCHANTMENT_SLOT
; ++j
)
3385 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_0
+ 1 + j
+ offset
);
3387 // random properties
3388 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ offset
);
3389 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_SEED
+ offset
);
3390 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_PAD
+ offset
);
3393 updateVisualBits
.SetBit(PLAYER_CHOSEN_TITLE
);
3396 void Player::BuildCreateUpdateBlockForPlayer( UpdateData
*data
, Player
*target
) const
3398 for(int i
= 0; i
< EQUIPMENT_SLOT_END
; i
++)
3400 if(m_items
[i
] == NULL
)
3403 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3408 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
3410 if(m_items
[i
] == NULL
)
3413 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3415 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
3417 if(m_items
[i
] == NULL
)
3420 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3424 Unit::BuildCreateUpdateBlockForPlayer( data
, target
);
3427 void Player::DestroyForPlayer( Player
*target
) const
3429 Unit::DestroyForPlayer( target
);
3431 for(int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
3433 if(m_items
[i
] == NULL
)
3436 m_items
[i
]->DestroyForPlayer( target
);
3441 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
3443 if(m_items
[i
] == NULL
)
3446 m_items
[i
]->DestroyForPlayer( target
);
3448 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
3450 if(m_items
[i
] == NULL
)
3453 m_items
[i
]->DestroyForPlayer( target
);
3458 bool Player::HasSpell(uint32 spell
) const
3460 PlayerSpellMap::const_iterator itr
= m_spells
.find((uint16
)spell
);
3461 return (itr
!= m_spells
.end() && itr
->second
->state
!= PLAYERSPELL_REMOVED
&& !itr
->second
->disabled
);
3464 TrainerSpellState
Player::GetTrainerSpellState(TrainerSpell
const* trainer_spell
) const
3467 return TRAINER_SPELL_RED
;
3469 if (!trainer_spell
->learned_spell
)
3470 return TRAINER_SPELL_RED
;
3473 if(HasSpell(trainer_spell
->learned_spell
))
3474 return TRAINER_SPELL_GRAY
;
3476 // check race/class requirement
3477 if(!IsSpellFitByClassAndRace(trainer_spell
->learned_spell
))
3478 return TRAINER_SPELL_RED
;
3480 // check level requirement
3481 if(getLevel() < trainer_spell
->reqlevel
)
3482 return TRAINER_SPELL_RED
;
3484 if(SpellChainNode
const* spell_chain
= spellmgr
.GetSpellChainNode(trainer_spell
->learned_spell
))
3486 // check prev.rank requirement
3487 if(spell_chain
->prev
&& !HasSpell(spell_chain
->prev
))
3488 return TRAINER_SPELL_RED
;
3490 // check additional spell requirement
3491 if(spell_chain
->req
&& !HasSpell(spell_chain
->req
))
3492 return TRAINER_SPELL_RED
;
3495 // check skill requirement
3496 if(trainer_spell
->reqskill
&& GetBaseSkillValue(trainer_spell
->reqskill
) < trainer_spell
->reqskillvalue
)
3497 return TRAINER_SPELL_RED
;
3499 // exist, already checked at loading
3500 SpellEntry
const* spell
= sSpellStore
.LookupEntry(trainer_spell
->learned_spell
);
3502 // secondary prof. or not prof. spell
3503 uint32 skill
= spell
->EffectMiscValue
[1];
3505 if(spell
->Effect
[1] != SPELL_EFFECT_SKILL
|| !IsPrimaryProfessionSkill(skill
))
3506 return TRAINER_SPELL_GREEN
;
3508 // check primary prof. limit
3509 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell
->Id
) && GetFreePrimaryProffesionPoints() == 0)
3510 return TRAINER_SPELL_RED
;
3512 return TRAINER_SPELL_GREEN
;
3515 void Player::DeleteFromDB(uint64 playerguid
, uint32 accountId
, bool updateRealmChars
)
3517 uint32 guid
= GUID_LOPART(playerguid
);
3519 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3520 // bones will be deleted by corpse/bones deleting thread shortly
3521 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid
);
3523 // remove from guild
3524 uint32 guildId
= GetGuildIdFromDB(playerguid
);
3527 Guild
* guild
= objmgr
.GetGuildById(guildId
);
3529 guild
->DelMember(guid
);
3532 // remove from arena teams
3533 LeaveAllArenaTeams(playerguid
);
3535 // the player was uninvited already on logout so just remove from group
3536 QueryResult
*resultGroup
= CharacterDatabase
.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid
);
3539 uint64 leaderGuid
= MAKE_NEW_GUID((*resultGroup
)[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
3541 Group
* group
= objmgr
.GetGroupByLeader(leaderGuid
);
3544 RemoveFromGroup(group
, playerguid
);
3548 // remove signs from petitions (also remove petitions if owner);
3549 RemovePetitionsAndSigns(playerguid
, 10);
3551 // return back all mails with COD and Item 0 1 2 3 4 5 6
3552 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
);
3557 Field
*fields
= resultMail
->Fetch();
3559 uint32 mail_id
= fields
[0].GetUInt32();
3560 uint16 mailTemplateId
= fields
[1].GetUInt16();
3561 uint32 sender
= fields
[2].GetUInt32();
3562 std::string subject
= fields
[3].GetCppString();
3563 uint32 itemTextId
= fields
[4].GetUInt32();
3564 uint32 money
= fields
[5].GetUInt32();
3565 bool has_items
= fields
[6].GetBool();
3567 //we can return mail now
3568 //so firstly delete the old one
3569 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id
);
3574 // data needs to be at first place for Item::LoadFromDB
3575 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
);
3580 Field
*fields2
= resultItems
->Fetch();
3582 uint32 item_guidlow
= fields2
[1].GetUInt32();
3583 uint32 item_template
= fields2
[2].GetUInt32();
3585 ItemPrototype
const* itemProto
= objmgr
.GetItemPrototype(item_template
);
3588 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow
);
3592 Item
*pItem
= NewItemOrBag(itemProto
);
3593 if(!pItem
->LoadFromDB(item_guidlow
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
),resultItems
))
3595 pItem
->FSetState(ITEM_REMOVED
);
3596 pItem
->SaveToDB(); // it also deletes item object !
3600 mi
.AddItem(item_guidlow
, item_template
, pItem
);
3602 while (resultItems
->NextRow());
3608 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id
);
3610 uint32 pl_account
= objmgr
.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
3612 WorldSession::SendReturnToSender(MAIL_NORMAL
, pl_account
, guid
, sender
, subject
, itemTextId
, &mi
, money
, mailTemplateId
);
3614 while (resultMail
->NextRow());
3619 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3620 // Get guids of character's pets, will deleted in transaction
3621 QueryResult
*resultPets
= CharacterDatabase
.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid
);
3623 // NOW we can finally clear other DB data related to character
3624 CharacterDatabase
.BeginTransaction();
3629 Field
*fields3
= resultPets
->Fetch();
3630 uint32 petguidlow
= fields3
[0].GetUInt32();
3631 Pet::DeleteFromDB(petguidlow
);
3632 } while (resultPets
->NextRow());
3636 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",guid
);
3637 CharacterDatabase
.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid
);
3638 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid
);
3639 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid
);
3640 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid
);
3641 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid
);
3642 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid
);
3643 CharacterDatabase
.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid
);
3644 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid
);
3645 CharacterDatabase
.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid
);
3646 CharacterDatabase
.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid
);
3647 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid
);
3648 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid
);
3649 CharacterDatabase
.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid
);
3650 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid
);
3651 CharacterDatabase
.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid
,guid
);
3652 CharacterDatabase
.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid
);
3653 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid
);
3654 CharacterDatabase
.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid
);
3655 CharacterDatabase
.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid
);
3656 CharacterDatabase
.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid
);
3657 CharacterDatabase
.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid
);
3658 CharacterDatabase
.CommitTransaction();
3660 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3661 if(updateRealmChars
) sWorld
.UpdateRealmCharCount(accountId
);
3664 void Player::SetMovement(PlayerMovementType pType
)
3669 case MOVE_ROOT
: data
.Initialize(SMSG_FORCE_MOVE_ROOT
, GetPackGUID().size()+4); break;
3670 case MOVE_UNROOT
: data
.Initialize(SMSG_FORCE_MOVE_UNROOT
, GetPackGUID().size()+4); break;
3671 case MOVE_WATER_WALK
: data
.Initialize(SMSG_MOVE_WATER_WALK
, GetPackGUID().size()+4); break;
3672 case MOVE_LAND_WALK
: data
.Initialize(SMSG_MOVE_LAND_WALK
, GetPackGUID().size()+4); break;
3674 sLog
.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType
);
3677 data
.append(GetPackGUID());
3679 GetSession()->SendPacket( &data
);
3683 - a resurrectable corpse must not be loaded for the player (only bones)
3684 - the player must be in world
3686 void Player::BuildPlayerRepop()
3688 WorldPacket
data(SMSG_PRE_RESURRECT
, GetPackGUID().size());
3689 data
.append(GetPackGUID());
3690 GetSession()->SendPacket(&data
);
3692 if(getRace() == RACE_NIGHTELF
)
3693 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)
3694 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3696 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3697 // there must be SMSG.STOP_MIRROR_TIMER
3698 // there we must send 888 opcode
3700 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3703 sLog
.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3707 // create a corpse and place it at the player's location
3709 Corpse
*corpse
= GetCorpse();
3712 sLog
.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3715 GetMap()->Add(corpse
);
3717 // convert player body to ghost
3720 SetMovement(MOVE_WATER_WALK
);
3721 if(!GetSession()->isLogingOut())
3722 SetMovement(MOVE_UNROOT
);
3724 // BG - remove insignia related
3725 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_SKINNABLE
);
3727 SendCorpseReclaimDelay();
3729 // to prevent cheating
3730 corpse
->ResetGhostTime();
3732 StopMirrorTimers(); //disable timers(bars)
3734 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, (float)1.0); //see radius of death player?
3736 SetByteValue(UNIT_FIELD_BYTES_1
, 3, PLAYER_STATE_FLAG_ALWAYS_STAND
);
3739 void Player::SendDelayResponse(const uint32 ml_seconds
)
3741 //FIXME: is this delay time arg really need? 50msec by default in code
3742 WorldPacket
data( SMSG_QUERY_TIME_RESPONSE
, 4+4 );
3743 data
<< (uint32
)time(NULL
);
3745 GetSession()->SendPacket( &data
);
3748 void Player::ResurrectPlayer(float restore_percent
, bool applySickness
)
3750 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // remove spirit healer position
3755 GetSession()->SendPacket(&data
);
3757 // speed change, land walk
3759 // remove death flag + set aura
3760 SetByteValue(UNIT_FIELD_BYTES_1
, 3, 0x00);
3761 if(getRace() == RACE_NIGHTELF
)
3762 RemoveAurasDueToSpell(20584); // speed bonuses
3763 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3765 setDeathState(ALIVE
);
3767 SetMovement(MOVE_LAND_WALK
);
3768 SetMovement(MOVE_UNROOT
);
3772 // set health/powers (0- will be set in caller)
3773 if(restore_percent
>0.0f
)
3775 SetHealth(uint32(GetMaxHealth()*restore_percent
));
3776 SetPower(POWER_MANA
, uint32(GetMaxPower(POWER_MANA
)*restore_percent
));
3777 SetPower(POWER_RAGE
, 0);
3778 SetPower(POWER_ENERGY
, uint32(GetMaxPower(POWER_ENERGY
)*restore_percent
));
3781 // update visibility
3782 ObjectAccessor::UpdateVisibilityForPlayer(this);
3784 // some items limited to specific map
3785 DestroyZoneLimitedItem( true, GetZoneId());
3790 //Characters from level 1-10 are not affected by resurrection sickness.
3791 //Characters from level 11-19 will suffer from one minute of sickness
3792 //for each level they are above 10.
3793 //Characters level 20 and up suffer from ten minutes of sickness.
3794 int32 startLevel
= sWorld
.getConfig(CONFIG_DEATH_SICKNESS_LEVEL
);
3796 if(int32(getLevel()) >= startLevel
)
3798 // set resurrection sickness
3799 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,true);
3801 // not full duration
3802 if(int32(getLevel()) < startLevel
+9)
3804 int32 delta
= (int32(getLevel()) - startLevel
+ 1)*MINUTE
;
3806 for(int i
=0; i
< 3; ++i
)
3808 if(Aura
* Aur
= GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,i
))
3810 Aur
->SetAuraDuration(delta
*1000);
3811 Aur
->SendAuraUpdate(false);
3818 void Player::KillPlayer()
3820 SetMovement(MOVE_ROOT
);
3822 StopMirrorTimers(); //disable timers(bars)
3824 setDeathState(CORPSE
);
3825 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
3827 SetFlag(UNIT_DYNAMIC_FLAGS
, 0x00);
3828 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, !sMapStore
.LookupEntry(GetMapId())->Instanceable());
3830 // 6 minutes until repop at graveyard
3831 m_deathTimer
= 6*MINUTE
*1000;
3833 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
3835 // don't create corpse at this moment, player might be falling
3837 // update visibility
3838 ObjectAccessor::UpdateObjectVisibility(this);
3841 void Player::CreateCorpse()
3843 // prevent existence 2 corpse for player
3846 uint32 _uf
, _pb
, _pb2
, _cfb1
, _cfb2
;
3848 Corpse
*corpse
= new Corpse( (m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
) ? CORPSE_RESURRECTABLE_PVP
: CORPSE_RESURRECTABLE_PVE
);
3851 if(!corpse
->Create(objmgr
.GenerateLowGuid(HIGHGUID_CORPSE
), this, GetMapId(), GetPositionX(),
3852 GetPositionY(), GetPositionZ(), GetOrientation()))
3858 _uf
= GetUInt32Value(UNIT_FIELD_BYTES_0
);
3859 _pb
= GetUInt32Value(PLAYER_BYTES
);
3860 _pb2
= GetUInt32Value(PLAYER_BYTES_2
);
3862 uint8 race
= (uint8
)(_uf
);
3863 uint8 skin
= (uint8
)(_pb
);
3864 uint8 face
= (uint8
)(_pb
>> 8);
3865 uint8 hairstyle
= (uint8
)(_pb
>> 16);
3866 uint8 haircolor
= (uint8
)(_pb
>> 24);
3867 uint8 facialhair
= (uint8
)(_pb2
);
3869 _cfb1
= ((0x00) | (race
<< 8) | (getGender() << 16) | (skin
<< 24));
3870 _cfb2
= ((face
) | (hairstyle
<< 8) | (haircolor
<< 16) | (facialhair
<< 24));
3872 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_1
, _cfb1
);
3873 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_2
, _cfb2
);
3875 uint32 flags
= CORPSE_FLAG_UNK2
;
3876 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
3877 flags
|= CORPSE_FLAG_HIDE_HELM
;
3878 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
3879 flags
|= CORPSE_FLAG_HIDE_CLOAK
;
3880 if(InBattleGround())
3881 flags
|= CORPSE_FLAG_LOOTABLE
; // to be able to remove insignia
3882 corpse
->SetUInt32Value( CORPSE_FIELD_FLAGS
, flags
);
3884 corpse
->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID
, GetNativeDisplayId() );
3886 corpse
->SetUInt32Value( CORPSE_FIELD_GUILD
, GetGuildId() );
3889 uint16 iIventoryType
;
3891 for (int i
= 0; i
< EQUIPMENT_SLOT_END
; i
++)
3895 iDisplayID
= m_items
[i
]->GetProto()->DisplayInfoID
;
3896 iIventoryType
= (uint16
)m_items
[i
]->GetProto()->InventoryType
;
3898 _cfi
= (uint16(iDisplayID
)) | (iIventoryType
)<< 24;
3899 corpse
->SetUInt32Value(CORPSE_FIELD_ITEM
+ i
,_cfi
);
3903 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
3904 const MapEntry
*entry
= sMapStore
.LookupEntry(corpse
->GetMapId());
3906 if(entry
->map_type
!= MAP_BATTLEGROUND
)
3909 // register for player, but not show
3910 ObjectAccessor::Instance().AddCorpse(corpse
);
3913 void Player::SpawnCorpseBones()
3915 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
3916 SaveToDB(); // prevent loading as ghost without corpse
3919 Corpse
* Player::GetCorpse() const
3921 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
3924 void Player::DurabilityLossAll(double percent
, bool inventory
)
3926 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
3927 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3928 DurabilityLoss(pItem
,percent
);
3932 // bags not have durability
3933 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3935 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
3936 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3937 DurabilityLoss(pItem
,percent
);
3939 // keys not have durability
3940 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3942 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
3943 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3944 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
3945 if(Item
* pItem
= GetItemByPos( i
, j
))
3946 DurabilityLoss(pItem
,percent
);
3950 void Player::DurabilityLoss(Item
* item
, double percent
)
3955 uint32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
3960 uint32 pDurabilityLoss
= uint32(pMaxDurability
*percent
);
3962 if(pDurabilityLoss
< 1 )
3963 pDurabilityLoss
= 1;
3965 DurabilityPointsLoss(item
,pDurabilityLoss
);
3968 void Player::DurabilityPointsLossAll(int32 points
, bool inventory
)
3970 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
3971 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3972 DurabilityPointsLoss(pItem
,points
);
3976 // bags not have durability
3977 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3979 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
3980 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3981 DurabilityPointsLoss(pItem
,points
);
3983 // keys not have durability
3984 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3986 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
3987 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3988 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
3989 if(Item
* pItem
= GetItemByPos( i
, j
))
3990 DurabilityPointsLoss(pItem
,points
);
3994 void Player::DurabilityPointsLoss(Item
* item
, int32 points
)
3996 int32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
3997 int32 pOldDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
3998 int32 pNewDurability
= pOldDurability
- points
;
4000 if (pNewDurability
< 0)
4002 else if (pNewDurability
> pMaxDurability
)
4003 pNewDurability
= pMaxDurability
;
4005 if (pOldDurability
!= pNewDurability
)
4007 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4008 if ( pNewDurability
== 0 && pOldDurability
> 0 && item
->IsEquipped())
4009 _ApplyItemMods(item
,item
->GetSlot(), false);
4011 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, pNewDurability
);
4013 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4014 if ( pNewDurability
> 0 && pOldDurability
== 0 && item
->IsEquipped())
4015 _ApplyItemMods(item
,item
->GetSlot(), true);
4017 item
->SetState(ITEM_CHANGED
, this);
4021 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot
)
4023 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
))
4024 DurabilityPointsLoss(pItem
,1);
4027 uint32
Player::DurabilityRepairAll(bool cost
, float discountMod
, bool guildBank
)
4029 uint32 TotalCost
= 0;
4030 // equipped, backpack, bags itself
4031 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
4032 TotalCost
+= DurabilityRepair(( (INVENTORY_SLOT_BAG_0
<< 8) | i
),cost
,discountMod
, guildBank
);
4034 // bank, buyback and keys not repaired
4036 // items in inventory bags
4037 for(int j
= INVENTORY_SLOT_BAG_START
; j
< INVENTORY_SLOT_BAG_END
; j
++)
4038 for(int i
= 0; i
< MAX_BAG_SIZE
; i
++)
4039 TotalCost
+= DurabilityRepair(( (j
<< 8) | i
),cost
,discountMod
, guildBank
);
4043 uint32
Player::DurabilityRepair(uint16 pos
, bool cost
, float discountMod
, bool guildBank
)
4045 Item
* item
= GetItemByPos(pos
);
4047 uint32 TotalCost
= 0;
4051 uint32 maxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4055 uint32 curDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4059 uint32 LostDurability
= maxDurability
- curDurability
;
4060 if(LostDurability
>0)
4062 ItemPrototype
const *ditemProto
= item
->GetProto();
4064 DurabilityCostsEntry
const *dcost
= sDurabilityCostsStore
.LookupEntry(ditemProto
->ItemLevel
);
4067 sLog
.outError("ERROR: RepairDurability: Wrong item lvl %u", ditemProto
->ItemLevel
);
4071 uint32 dQualitymodEntryId
= (ditemProto
->Quality
+1)*2;
4072 DurabilityQualityEntry
const *dQualitymodEntry
= sDurabilityQualityStore
.LookupEntry(dQualitymodEntryId
);
4073 if(!dQualitymodEntry
)
4075 sLog
.outError("ERROR: RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId
);
4079 uint32 dmultiplier
= dcost
->multiplier
[ItemSubClassToDurabilityMultiplierId(ditemProto
->Class
,ditemProto
->SubClass
)];
4080 uint32 costs
= uint32(LostDurability
*dmultiplier
*double(dQualitymodEntry
->quality_mod
));
4082 costs
= uint32(costs
* discountMod
);
4084 if (costs
==0) //fix for ITEM_QUALITY_ARTIFACT
4089 if (GetGuildId()==0)
4091 DEBUG_LOG("You are not member of a guild");
4095 Guild
*pGuild
= objmgr
.GetGuildById(GetGuildId());
4099 if (!pGuild
->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR
))
4101 DEBUG_LOG("You do not have rights to withdraw for repairs");
4105 if (pGuild
->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs
)
4107 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4111 if (pGuild
->GetGuildBankMoney() < costs
)
4113 DEBUG_LOG("There is not enough money in bank");
4117 pGuild
->MemberMoneyWithdraw(costs
, GetGUIDLow());
4120 else if (GetMoney() < costs
)
4122 DEBUG_LOG("You do not have enough money");
4126 ModifyMoney( -int32(costs
) );
4130 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, maxDurability
);
4131 item
->SetState(ITEM_CHANGED
, this);
4133 // reapply mods for total broken and repaired item if equipped
4134 if(IsEquipmentPos(pos
) && !curDurability
)
4135 _ApplyItemMods(item
,pos
& 255, true);
4139 void Player::RepopAtGraveyard()
4141 // note: this can be called also when the player is alive
4142 // for example from WorldSession::HandleMovementOpcodes
4144 AreaTableEntry
const *zone
= GetAreaEntryByAreaID(GetAreaId());
4146 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4147 if(!isAlive() && zone
&& zone
->flags
& AREA_FLAG_NEED_FLY
|| GetTransport())
4149 ResurrectPlayer(0.5f
);
4153 WorldSafeLocsEntry
const *ClosestGrave
= NULL
;
4155 // Special handle for battleground maps
4156 BattleGround
*bg
= sBattleGroundMgr
.GetBattleGround(GetBattleGroundId());
4158 if(bg
&& (bg
->GetTypeID() == BATTLEGROUND_AB
|| bg
->GetTypeID() == BATTLEGROUND_EY
))
4159 ClosestGrave
= bg
->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetTeam());
4161 ClosestGrave
= objmgr
.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4163 // stop countdown until repop
4166 // if no grave found, stay at the current location
4167 // and don't show spirit healer location
4170 TeleportTo(ClosestGrave
->map_id
, ClosestGrave
->x
, ClosestGrave
->y
, ClosestGrave
->z
, GetOrientation());
4171 if(isDead()) // not send if alive, because it used in TeleportTo()
4173 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // show spirit healer position on minimap
4174 data
<< ClosestGrave
->map_id
;
4175 data
<< ClosestGrave
->x
;
4176 data
<< ClosestGrave
->y
;
4177 data
<< ClosestGrave
->z
;
4178 GetSession()->SendPacket(&data
);
4183 void Player::JoinedChannel(Channel
*c
)
4185 m_channels
.push_back(c
);
4188 void Player::LeftChannel(Channel
*c
)
4190 m_channels
.remove(c
);
4193 void Player::CleanupChannels()
4195 while(!m_channels
.empty())
4197 Channel
* ch
= *m_channels
.begin();
4198 m_channels
.erase(m_channels
.begin()); // remove from player's channel list
4199 ch
->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4200 if (ChannelMgr
* cMgr
= channelMgr(GetTeam()))
4201 cMgr
->LeftChannel(ch
->GetName()); // deleted channel if empty
4204 sLog
.outDebug("Player: channels cleaned up!");
4207 void Player::UpdateLocalChannels(uint32 newZone
)
4209 if(m_channels
.empty())
4212 AreaTableEntry
const* current_zone
= GetAreaEntryByAreaID(newZone
);
4216 ChannelMgr
* cMgr
= channelMgr(GetTeam());
4220 std::string current_zone_name
= current_zone
->area_name
[GetSession()->GetSessionDbcLocale()];
4222 for(JoinedChannelsList::iterator i
= m_channels
.begin(), next
; i
!= m_channels
.end(); i
= next
)
4226 // skip non built-in channels
4227 if(!(*i
)->IsConstant())
4230 ChatChannelsEntry
const* ch
= GetChannelEntryFor((*i
)->GetChannelId());
4234 if((ch
->flags
& 4) == 4) // global channel without zone name in pattern
4238 char new_channel_name_buf
[100];
4239 snprintf(new_channel_name_buf
,100,ch
->pattern
[m_session
->GetSessionDbcLocale()],current_zone_name
.c_str());
4240 Channel
* new_channel
= cMgr
->GetJoinChannel(new_channel_name_buf
,ch
->ChannelID
);
4242 if((*i
)!=new_channel
)
4244 new_channel
->Join(GetGUID(),""); // will output Changed Channel: N. Name
4246 // leave old channel
4247 (*i
)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4248 std::string name
= (*i
)->GetName(); // store name, (*i)erase in LeftChannel
4249 LeftChannel(*i
); // remove from player's channel list
4250 cMgr
->LeftChannel(name
); // delete if empty
4253 sLog
.outDebug("Player: channels cleaned up!");
4256 void Player::LeaveLFGChannel()
4258 for(JoinedChannelsList::iterator i
= m_channels
.begin(); i
!= m_channels
.end(); ++i
)
4262 (*i
)->Leave(GetGUID());
4268 void Player::UpdateDefense()
4270 uint32 defense_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_DEFENSE
);
4272 if(UpdateSkill(SKILL_DEFENSE
,defense_skill_gain
))
4274 // update dependent from defense skill part
4275 UpdateDefenseBonusesMod();
4279 void Player::HandleBaseModValue(BaseModGroup modGroup
, BaseModType modType
, float amount
, bool apply
)
4281 if(modGroup
>= BASEMOD_END
|| modType
>= MOD_END
)
4283 sLog
.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4292 m_auraBaseMod
[modGroup
][modType
] += apply
? amount
: -amount
;
4295 if(amount
<= -100.0f
)
4298 val
= (100.0f
+ amount
) / 100.0f
;
4299 m_auraBaseMod
[modGroup
][modType
] *= apply
? val
: (1.0f
/val
);
4303 if(!CanModifyStats())
4308 case CRIT_PERCENTAGE
: UpdateCritPercentage(BASE_ATTACK
); break;
4309 case RANGED_CRIT_PERCENTAGE
: UpdateCritPercentage(RANGED_ATTACK
); break;
4310 case OFFHAND_CRIT_PERCENTAGE
: UpdateCritPercentage(OFF_ATTACK
); break;
4311 case SHIELD_BLOCK_VALUE
: UpdateShieldBlockValue(); break;
4316 float Player::GetBaseModValue(BaseModGroup modGroup
, BaseModType modType
) const
4318 if(modGroup
>= BASEMOD_END
|| modType
> MOD_END
)
4320 sLog
.outError("ERROR: trial to access non existed BaseModGroup or wrong BaseModType!");
4324 if(modType
== PCT_MOD
&& m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4327 return m_auraBaseMod
[modGroup
][modType
];
4330 float Player::GetTotalBaseModValue(BaseModGroup modGroup
) const
4332 if(modGroup
>= BASEMOD_END
)
4334 sLog
.outError("ERROR: wrong BaseModGroup in GetTotalBaseModValue()!");
4338 if(m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4341 return m_auraBaseMod
[modGroup
][FLAT_MOD
] * m_auraBaseMod
[modGroup
][PCT_MOD
];
4344 uint32
Player::GetShieldBlockValue() const
4346 BaseModGroup modGroup
= SHIELD_BLOCK_VALUE
;
4348 float value
= GetTotalBaseModValue(modGroup
) + GetStat(STAT_STRENGTH
) * 0.5f
- 10;
4350 value
= (value
< 0) ? 0 : value
;
4352 return uint32(value
);
4355 float Player::GetMeleeCritFromAgility()
4357 uint32 level
= getLevel();
4358 uint32 pclass
= getClass();
4360 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4362 GtChanceToMeleeCritBaseEntry
const *critBase
= sGtChanceToMeleeCritBaseStore
.LookupEntry(pclass
-1);
4363 GtChanceToMeleeCritEntry
const *critRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4364 if (critBase
==NULL
|| critRatio
==NULL
)
4367 float crit
=critBase
->base
+ GetStat(STAT_AGILITY
)*critRatio
->ratio
;
4371 float Player::GetDodgeFromAgility()
4373 // Table for base dodge values
4374 float dodge_base
[MAX_CLASSES
] = {
4376 0.00652f
, // Paladin
4383 0.02011f
, // Warlock
4387 // Crit/agility to dodge/agility coefficient multipliers
4388 float crit_to_dodge
[MAX_CLASSES
] = {
4402 uint32 level
= getLevel();
4403 uint32 pclass
= getClass();
4405 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4407 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4408 GtChanceToMeleeCritEntry
const *dodgeRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4409 if (dodgeRatio
==NULL
|| pclass
> MAX_CLASSES
)
4412 float dodge
=dodge_base
[pclass
-1] + GetStat(STAT_AGILITY
) * dodgeRatio
->ratio
* crit_to_dodge
[pclass
-1];
4413 return dodge
*100.0f
;
4416 float Player::GetSpellCritFromIntellect()
4418 uint32 level
= getLevel();
4419 uint32 pclass
= getClass();
4421 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4423 GtChanceToSpellCritBaseEntry
const *critBase
= sGtChanceToSpellCritBaseStore
.LookupEntry(pclass
-1);
4424 GtChanceToSpellCritEntry
const *critRatio
= sGtChanceToSpellCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4425 if (critBase
==NULL
|| critRatio
==NULL
)
4428 float crit
=critBase
->base
+ GetStat(STAT_INTELLECT
)*critRatio
->ratio
;
4432 float Player::GetRatingCoefficient(CombatRating cr
) const
4434 uint32 level
= getLevel();
4436 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4438 GtCombatRatingsEntry
const *Rating
= sGtCombatRatingsStore
.LookupEntry(cr
*GT_MAX_LEVEL
+level
-1);
4440 return 1.0f
; // By default use minimum coefficient (not must be called)
4442 return Rating
->ratio
;
4445 float Player::GetRatingBonusValue(CombatRating cr
) const
4447 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
)) / GetRatingCoefficient(cr
);
4450 uint32
Player::GetMeleeCritDamageReduction(uint32 damage
) const
4452 float melee
= GetRatingBonusValue(CR_CRIT_TAKEN_MELEE
)*2.0f
;
4453 if (melee
>25.0f
) melee
= 25.0f
;
4454 return uint32 (melee
* damage
/100.0f
);
4457 uint32
Player::GetRangedCritDamageReduction(uint32 damage
) const
4459 float ranged
= GetRatingBonusValue(CR_CRIT_TAKEN_RANGED
)*2.0f
;
4460 if (ranged
>25.0f
) ranged
=25.0f
;
4461 return uint32 (ranged
* damage
/100.0f
);
4464 uint32
Player::GetSpellCritDamageReduction(uint32 damage
) const
4466 float spell
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
)*2.0f
;
4467 // In wow script resilience limited to 25%
4470 return uint32 (spell
* damage
/ 100.0f
);
4473 uint32
Player::GetDotDamageReduction(uint32 damage
) const
4475 float spellDot
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
);
4476 // Dot resilience not limited (limit it by 100%)
4477 if (spellDot
> 100.0f
)
4479 return uint32 (spellDot
* damage
/ 100.0f
);
4482 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType
) const
4487 return GetUInt32Value(PLAYER_EXPERTISE
) / 4.0f
;
4489 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE
) / 4.0f
;
4496 float Player::OCTRegenHPPerSpirit()
4498 uint32 level
= getLevel();
4499 uint32 pclass
= getClass();
4501 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4503 GtOCTRegenHPEntry
const *baseRatio
= sGtOCTRegenHPStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4504 GtRegenHPPerSptEntry
const *moreRatio
= sGtRegenHPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4505 if (baseRatio
==NULL
|| moreRatio
==NULL
)
4508 // Formula from PaperDollFrame script
4509 float spirit
= GetStat(STAT_SPIRIT
);
4510 float baseSpirit
= spirit
;
4511 if (baseSpirit
>50) baseSpirit
= 50;
4512 float moreSpirit
= spirit
- baseSpirit
;
4513 float regen
= baseSpirit
* baseRatio
->ratio
+ moreSpirit
* moreRatio
->ratio
;
4517 float Player::OCTRegenMPPerSpirit()
4519 uint32 level
= getLevel();
4520 uint32 pclass
= getClass();
4522 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4524 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4525 GtRegenMPPerSptEntry
const *moreRatio
= sGtRegenMPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4526 if (moreRatio
==NULL
)
4529 // Formula get from PaperDollFrame script
4530 float spirit
= GetStat(STAT_SPIRIT
);
4531 float regen
= spirit
* moreRatio
->ratio
;
4535 void Player::ApplyRatingMod(CombatRating cr
, int32 value
, bool apply
)
4537 m_baseRatingValue
[cr
]+=(apply
? value
: -value
);
4539 int32 amount
= uint32(m_baseRatingValue
[cr
]);
4540 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4541 // stat used stored in miscValueB for this aura
4542 AuraList
const& modRatingFromStat
= GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT
);
4543 for(AuraList::const_iterator i
= modRatingFromStat
.begin();i
!= modRatingFromStat
.end(); ++i
)
4544 if ((*i
)->GetMiscValue() & (1<<cr
))
4545 amount
+= int32(GetStat(Stats((*i
)->GetMiscBValue())) * (*i
)->GetModifier()->m_amount
/ 100.0f
);
4548 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
, uint32(amount
));
4550 float RatingCoeffecient
= GetRatingCoefficient(cr
);
4551 float RatingChange
= 0.0f
;
4553 bool affectStats
= CanModifyStats();
4557 case CR_WEAPON_SKILL
: // Implemented in Unit::RollMeleeOutcomeAgainst
4558 case CR_DEFENSE_SKILL
:
4559 UpdateDefenseBonusesMod();
4562 UpdateDodgePercentage();
4565 UpdateParryPercentage();
4568 UpdateBlockPercentage();
4571 UpdateMeleeHitChances();
4574 UpdateRangedHitChances();
4577 UpdateSpellHitChances();
4582 UpdateCritPercentage(BASE_ATTACK
);
4583 UpdateCritPercentage(OFF_ATTACK
);
4586 case CR_CRIT_RANGED
:
4588 UpdateCritPercentage(RANGED_ATTACK
);
4592 UpdateAllSpellCritChances();
4594 case CR_HIT_TAKEN_MELEE
: // Implemented in Unit::MeleeMissChanceCalc
4595 case CR_HIT_TAKEN_RANGED
:
4597 case CR_HIT_TAKEN_SPELL
: // Implemented in Unit::MagicSpellHitResult
4599 case CR_CRIT_TAKEN_MELEE
: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4600 case CR_CRIT_TAKEN_RANGED
:
4602 case CR_CRIT_TAKEN_SPELL
: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4604 case CR_HASTE_MELEE
:
4605 RatingChange
= value
/ RatingCoeffecient
;
4606 ApplyAttackTimePercentMod(BASE_ATTACK
,RatingChange
,apply
);
4607 ApplyAttackTimePercentMod(OFF_ATTACK
,RatingChange
,apply
);
4609 case CR_HASTE_RANGED
:
4610 RatingChange
= value
/ RatingCoeffecient
;
4611 ApplyAttackTimePercentMod(RANGED_ATTACK
, RatingChange
, apply
);
4613 case CR_HASTE_SPELL
:
4614 RatingChange
= value
/ RatingCoeffecient
;
4615 ApplyCastTimePercentMod(RatingChange
,apply
);
4617 case CR_WEAPON_SKILL_MAINHAND
: // Implemented in Unit::RollMeleeOutcomeAgainst
4618 case CR_WEAPON_SKILL_OFFHAND
:
4619 case CR_WEAPON_SKILL_RANGED
:
4624 UpdateExpertise(BASE_ATTACK
);
4625 UpdateExpertise(OFF_ATTACK
);
4631 void Player::SetRegularAttackTime()
4633 for(int i
= 0; i
< MAX_ATTACK
; ++i
)
4635 Item
*tmpitem
= GetWeaponForAttack(WeaponAttackType(i
));
4636 if(tmpitem
&& !tmpitem
->IsBroken())
4638 ItemPrototype
const *proto
= tmpitem
->GetProto();
4640 SetAttackTime(WeaponAttackType(i
), proto
->Delay
);
4642 SetAttackTime(WeaponAttackType(i
), BASE_ATTACK_TIME
);
4647 //skill+step, checking for max value
4648 bool Player::UpdateSkill(uint32 skill_id
, uint32 step
)
4654 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4655 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill_id
)
4658 if(i
>=PLAYER_MAX_SKILLS
)
4661 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4662 uint32 value
= SKILL_VALUE(data
);
4663 uint32 max
= SKILL_MAX(data
);
4665 if ((!max
) || (!value
) || (value
>= max
))
4668 if (value
*512 < max
*urand(0,512))
4670 uint32 new_value
= value
+step
;
4674 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,max
));
4675 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
);
4682 inline int SkillGainChance(uint32 SkillValue
, uint32 GrayLevel
, uint32 GreenLevel
, uint32 YellowLevel
)
4684 if ( SkillValue
>= GrayLevel
)
4685 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREY
)*10;
4686 if ( SkillValue
>= GreenLevel
)
4687 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREEN
)*10;
4688 if ( SkillValue
>= YellowLevel
)
4689 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_YELLOW
)*10;
4690 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_ORANGE
)*10;
4693 bool Player::UpdateCraftSkill(uint32 spellid
)
4695 sLog
.outDebug("UpdateCraftSkill spellid %d", spellid
);
4697 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spellid
);
4698 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spellid
);
4700 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
4702 if(_spell_idx
->second
->skillId
)
4704 uint32 SkillValue
= GetPureSkillValue(_spell_idx
->second
->skillId
);
4706 // Alchemy Discoveries here
4707 SpellEntry
const* spellEntry
= sSpellStore
.LookupEntry(spellid
);
4708 if(spellEntry
&& spellEntry
->Mechanic
==MECHANIC_DISCOVERY
)
4710 if(uint32 discoveredSpell
= GetSkillDiscoverySpell(_spell_idx
->second
->skillId
, spellid
, this))
4711 learnSpell(discoveredSpell
);
4714 uint32 craft_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_CRAFTING
);
4716 return UpdateSkillPro(_spell_idx
->second
->skillId
, SkillGainChance(SkillValue
,
4717 _spell_idx
->second
->max_value
,
4718 (_spell_idx
->second
->max_value
+ _spell_idx
->second
->min_value
)/2,
4719 _spell_idx
->second
->min_value
),
4726 bool Player::UpdateGatherSkill(uint32 SkillId
, uint32 SkillValue
, uint32 RedLevel
, uint32 Multiplicator
)
4728 sLog
.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId
, SkillValue
, RedLevel
);
4730 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
4732 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4735 case SKILL_HERBALISM
:
4736 case SKILL_LOCKPICKING
:
4737 case SKILL_JEWELCRAFTING
:
4738 case SKILL_INSCRIPTION
:
4739 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4740 case SKILL_SKINNING
:
4741 if( sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)==0)
4742 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4744 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)), gathering_skill_gain
);
4746 if (sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)==0)
4747 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4749 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)),gathering_skill_gain
);
4754 bool Player::UpdateFishingSkill()
4756 sLog
.outDebug("UpdateFishingSkill");
4758 uint32 SkillValue
= GetPureSkillValue(SKILL_FISHING
);
4760 int32 chance
= SkillValue
< 75 ? 100 : 2500/(SkillValue
-50);
4762 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
4764 return UpdateSkillPro(SKILL_FISHING
,chance
*10,gathering_skill_gain
);
4767 bool Player::UpdateSkillPro(uint16 SkillId
, int32 Chance
, uint32 step
)
4769 sLog
.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId
, Chance
/10.0);
4773 if(Chance
<= 0) // speedup in 0 chance case
4775 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
4780 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4781 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i
))) == SkillId
) break;
4782 if ( i
>= PLAYER_MAX_SKILLS
)
4785 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4786 uint16 SkillValue
= SKILL_VALUE(data
);
4787 uint16 MaxValue
= SKILL_MAX(data
);
4789 if ( !MaxValue
|| !SkillValue
|| SkillValue
>= MaxValue
)
4792 int32 Roll
= irand(1,1000);
4794 if ( Roll
<= Chance
)
4796 uint32 new_value
= SkillValue
+step
;
4797 if(new_value
> MaxValue
)
4798 new_value
= MaxValue
;
4800 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,MaxValue
));
4801 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
);
4802 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance
/10.0);
4806 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
4810 void Player::UpdateWeaponSkill (WeaponAttackType attType
)
4812 // no skill gain in pvp
4813 Unit
*pVictim
= getVictim();
4814 if(pVictim
&& pVictim
->GetTypeId() == TYPEID_PLAYER
)
4818 return; // always maximized SKILL_FERAL_COMBAT in fact
4820 if(m_form
== FORM_TREE
)
4821 return; // use weapon but not skill up
4823 uint32 weapon_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_WEAPON
);
4829 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
4832 UpdateSkill(SKILL_UNARMED
,weapon_skill_gain
);
4833 else if(tmpitem
->GetProto()->SubClass
!= ITEM_SUBCLASS_WEAPON_FISHING_POLE
)
4834 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
4840 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
4842 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
4846 UpdateAllCritPercentages();
4849 void Player::UpdateCombatSkills(Unit
*pVictim
, WeaponAttackType attType
, bool defence
)
4851 uint32 plevel
= getLevel(); // if defense than pVictim == attacker
4852 uint32 greylevel
= MaNGOS::XP::GetGrayLevel(plevel
);
4853 uint32 moblevel
= pVictim
->getLevelForTarget(this);
4854 if(moblevel
< greylevel
)
4857 if (moblevel
> plevel
+ 5)
4858 moblevel
= plevel
+ 5;
4860 uint32 lvldif
= moblevel
- greylevel
;
4864 uint32 skilldif
= 5 * plevel
- (defence
? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType
));
4868 float chance
= float(3 * lvldif
* skilldif
) / plevel
;
4871 if(getClass() == CLASS_WARRIOR
|| getClass() == CLASS_ROGUE
)
4872 chance
*= 0.1f
* GetStat(STAT_INTELLECT
);
4875 chance
= chance
< 1.0f
? 1.0f
: chance
; //minimum chance to increase skill is 1%
4877 if(roll_chance_f(chance
))
4882 UpdateWeaponSkill(attType
);
4888 void Player::ModifySkillBonus(uint32 skillid
,int32 val
, bool talent
)
4890 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4891 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skillid
)
4893 uint32 bonus_val
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
4894 int16 temp_bonus
= SKILL_TEMP_BONUS(bonus_val
);
4895 int16 perm_bonus
= SKILL_PERM_BONUS(bonus_val
);
4897 if(talent
) // permanent bonus stored in high part
4898 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
,perm_bonus
+val
));
4899 else // temporary/item bonus stored in low part
4900 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
+val
,perm_bonus
));
4905 void Player::UpdateSkillsForLevel()
4907 uint16 maxconfskill
= sWorld
.GetConfigMaxSkillValue();
4908 uint32 maxSkill
= GetMaxSkillValueForLevel();
4910 bool alwaysMaxSkill
= sWorld
.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL
);
4912 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4913 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
4915 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
4917 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(pskill
);
4921 if(GetSkillRangeType(pSkill
,false) != SKILL_RANGE_LEVEL
)
4924 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4925 uint32 max
= SKILL_MAX(data
);
4926 uint32 val
= SKILL_VALUE(data
);
4928 /// update only level dependent max skill values
4931 /// miximize skill always
4933 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(maxSkill
,maxSkill
));
4934 /// update max skill value if current max skill not maximized
4935 else if(max
!= maxconfskill
)
4936 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(val
,maxSkill
));
4941 void Player::UpdateSkillsToMaxSkillsForLevel()
4943 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4944 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
4946 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
4947 if( IsProfessionOrRidingSkill(pskill
))
4949 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4951 uint32 max
= SKILL_MAX(data
);
4954 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(max
,max
));
4956 if(pskill
== SKILL_DEFENSE
)
4957 UpdateDefenseBonusesMod();
4961 // This functions sets a skill line value (and adds if doesn't exist yet)
4962 // To "remove" a skill line, set it's values to zero
4963 void Player::SetSkill(uint32 id
, uint16 currVal
, uint16 maxVal
)
4969 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4970 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == id
) break;
4972 if(i
<PLAYER_MAX_SKILLS
) //has skill
4976 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
4977 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
);
4981 // clear skill fields
4982 SetUInt32Value(PLAYER_SKILL_INDEX(i
),0);
4983 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),0);
4984 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
4986 // remove spells that depend on this skill when removing the skill
4987 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(), next
= m_spells
.begin(); itr
!= m_spells
.end(); itr
= next
)
4990 if(itr
->second
->state
== PLAYERSPELL_REMOVED
)
4993 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(itr
->first
);
4994 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(itr
->first
);
4996 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
4998 if (_spell_idx
->second
->skillId
== id
)
5000 // this may remove more than one spell (dependents)
5001 removeSpell(itr
->first
);
5002 next
= m_spells
.begin();
5009 else if(currVal
) //add
5011 for (i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5012 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5014 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
5017 sLog
.outError("Skill not found in SkillLineStore: skill #%u", id
);
5020 // enable unlearn button for primary professions only
5021 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
5022 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
5024 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
5025 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
5026 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
);
5028 // apply skill bonuses
5029 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
5031 // temporary bonuses
5032 AuraList
const& mModSkill
= GetAurasByType(SPELL_AURA_MOD_SKILL
);
5033 for(AuraList::const_iterator i
= mModSkill
.begin(); i
!= mModSkill
.end(); ++i
)
5034 if ((*i
)->GetModifier()->m_miscvalue
== int32(id
))
5035 (*i
)->ApplyModifier(true);
5037 // permanent bonuses
5038 AuraList
const& mModSkillTalent
= GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT
);
5039 for(AuraList::const_iterator i
= mModSkillTalent
.begin(); i
!= mModSkillTalent
.end(); ++i
)
5040 if ((*i
)->GetModifier()->m_miscvalue
== int32(id
))
5041 (*i
)->ApplyModifier(true);
5043 // Learn all spells for skill
5044 learnSkillRewardedSpells(id
);
5050 bool Player::HasSkill(uint32 skill
) const
5052 if(!skill
)return false;
5053 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5055 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5063 uint16
Player::GetSkillValue(uint32 skill
) const
5068 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5070 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5072 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5074 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5075 result
+= SKILL_TEMP_BONUS(bonus
);
5076 result
+= SKILL_PERM_BONUS(bonus
);
5077 return result
< 0 ? 0 : result
;
5083 uint16
Player::GetMaxSkillValue(uint32 skill
) const
5086 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5088 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5090 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5092 int32 result
= int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5093 result
+= SKILL_TEMP_BONUS(bonus
);
5094 result
+= SKILL_PERM_BONUS(bonus
);
5095 return result
< 0 ? 0 : result
;
5101 uint16
Player::GetPureMaxSkillValue(uint32 skill
) const
5104 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5106 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5108 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5114 uint16
Player::GetBaseSkillValue(uint32 skill
) const
5117 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5119 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5121 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5122 result
+= SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5123 return result
< 0 ? 0 : result
;
5129 uint16
Player::GetPureSkillValue(uint32 skill
) const
5132 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5134 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5136 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5142 int16
Player::GetSkillPermBonusValue(uint32 skill
) const
5147 for (int i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
5149 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5151 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5158 int16
Player::GetSkillTempBonusValue(uint32 skill
) const
5163 for (int i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
5165 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5167 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5174 void Player::SendInitialActionButtons()
5176 sLog
.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5178 WorldPacket
data(SMSG_ACTION_BUTTONS
, (MAX_ACTION_BUTTONS
*4));
5179 for(int button
= 0; button
< MAX_ACTION_BUTTONS
; ++button
)
5181 ActionButtonList::const_iterator itr
= m_actionButtons
.find(button
);
5182 if(itr
!= m_actionButtons
.end() && itr
->second
.uState
!= ACTIONBUTTON_DELETED
)
5184 data
<< uint16(itr
->second
.action
);
5185 data
<< uint8(itr
->second
.misc
);
5186 data
<< uint8(itr
->second
.type
);
5194 GetSession()->SendPacket( &data
);
5195 sLog
.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5198 void Player::addActionButton(const uint8 button
, const uint16 action
, const uint8 type
, const uint8 misc
)
5200 if(button
>= MAX_ACTION_BUTTONS
)
5202 sLog
.outError( "Action %u not added into button %u for player %s: button must be < 132", action
, button
, GetName() );
5206 // check cheating with adding non-known spells to action bar
5207 if(type
==ACTION_BUTTON_SPELL
)
5209 if(!sSpellStore
.LookupEntry(action
))
5211 sLog
.outError( "Action %u not added into button %u for player %s: spell not exist", action
, button
, GetName() );
5215 if(!HasSpell(action
))
5217 sLog
.outError( "Action %u not added into button %u for player %s: player don't known this spell", action
, button
, GetName() );
5222 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5224 if (buttonItr
==m_actionButtons
.end())
5225 { // just add new button
5226 m_actionButtons
[button
] = ActionButton(action
,type
,misc
);
5229 { // change state of current button
5230 ActionButtonUpdateState uState
= buttonItr
->second
.uState
;
5231 buttonItr
->second
= ActionButton(action
,type
,misc
);
5232 if (uState
!= ACTIONBUTTON_NEW
) buttonItr
->second
.uState
= ACTIONBUTTON_CHANGED
;
5235 sLog
.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action
, button
);
5238 void Player::removeActionButton(uint8 button
)
5240 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5241 if (buttonItr
==m_actionButtons
.end())
5244 if(buttonItr
->second
.uState
==ACTIONBUTTON_NEW
)
5245 m_actionButtons
.erase(buttonItr
); // new and not saved
5247 buttonItr
->second
.uState
= ACTIONBUTTON_DELETED
; // saved, will deleted at next save
5249 sLog
.outDetail( "Action Button '%u' Removed from Player '%u'", button
, GetGUIDLow() );
5252 void Player::SetDontMove(bool dontMove
)
5254 m_dontMove
= dontMove
;
5257 bool Player::SetPosition(float x
, float y
, float z
, float orientation
, bool teleport
)
5259 // prevent crash when a bad coord is sent by the client
5260 if(!MaNGOS::IsValidMapCoord(x
,y
,z
,orientation
))
5262 sLog
.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x
,y
,z
,orientation
,teleport
,GetGUIDLow());
5268 const float old_x
= GetPositionX();
5269 const float old_y
= GetPositionY();
5270 const float old_z
= GetPositionZ();
5271 const float old_r
= GetOrientation();
5273 if( teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
|| old_r
!= orientation
)
5275 if (teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
)
5276 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE
| AURA_INTERRUPT_FLAG_TURNING
);
5278 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING
);
5280 // move and update visible state if need
5281 m
->PlayerRelocation(this, x
, y
, z
, orientation
);
5283 // reread after Map::Relocation
5290 if(GetGroup() && (old_x
!= x
|| old_y
!= y
))
5291 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION
);
5294 // code block for underwater state update
5295 UpdateUnderwaterState(m
, x
, y
, z
);
5297 CheckExploreSystem();
5302 void Player::SaveRecallPosition()
5304 m_recallMap
= GetMapId();
5305 m_recallX
= GetPositionX();
5306 m_recallY
= GetPositionY();
5307 m_recallZ
= GetPositionZ();
5308 m_recallO
= GetOrientation();
5311 void Player::SendMessageToSet(WorldPacket
*data
, bool self
)
5313 GetMap()->MessageBroadcast(this, data
, self
);
5316 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
)
5318 GetMap()->MessageDistBroadcast(this, data
, dist
, self
);
5321 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
, bool own_team_only
)
5323 GetMap()->MessageDistBroadcast(this, data
, dist
, self
,own_team_only
);
5326 void Player::SendDirectMessage(WorldPacket
*data
)
5328 GetSession()->SendPacket(data
);
5331 void Player::CheckExploreSystem()
5339 uint16 areaFlag
=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5340 if(areaFlag
==0xffff)
5342 int offset
= areaFlag
/ 32;
5346 sLog
.outError("ERROR: Wrong area flag %u in map data for (X: %f Y: %f) point to field PLAYER_EXPLORED_ZONES_1 + %u ( %u must be < 128 ).",areaFlag
,GetPositionX(),GetPositionY(),offset
,offset
);
5350 uint32 val
= (uint32
)(1 << (areaFlag
% 32));
5351 uint32 currFields
= GetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
);
5353 if( !(currFields
& val
) )
5355 SetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
, (uint32
)(currFields
| val
));
5357 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA
);
5359 AreaTableEntry
const *p
= GetAreaEntryByAreaFlagAndMap(areaFlag
,GetMapId());
5362 sLog
.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5364 else if(p
->area_level
> 0)
5366 uint32 area
= p
->ID
;
5367 if (getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
5369 SendExplorationExperience(area
,0);
5373 int32 diff
= int32(getLevel()) - p
->area_level
;
5377 XP
= uint32(objmgr
.GetBaseXP(getLevel()+5)*sWorld
.getRate(RATE_XP_EXPLORE
));
5381 int32 exploration_percent
= (100-((diff
-5)*5));
5382 if (exploration_percent
> 100)
5383 exploration_percent
= 100;
5384 else if (exploration_percent
< 0)
5385 exploration_percent
= 0;
5387 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*exploration_percent
/100*sWorld
.getRate(RATE_XP_EXPLORE
));
5391 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*sWorld
.getRate(RATE_XP_EXPLORE
));
5395 SendExplorationExperience(area
,XP
);
5397 sLog
.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area
);
5402 uint32
Player::TeamForRace(uint8 race
)
5404 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5407 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5411 switch(rEntry
->TeamID
)
5413 case 7: return ALLIANCE
;
5414 case 1: return HORDE
;
5417 sLog
.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race
),rEntry
->TeamID
);
5421 uint32
Player::getFactionForRace(uint8 race
)
5423 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5426 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5430 return rEntry
->FactionID
;
5433 void Player::setFactionForRace(uint8 race
)
5435 m_team
= TeamForRace(race
);
5436 setFaction( getFactionForRace(race
) );
5439 void Player::UpdateReputation() const
5441 sLog
.outDetail( "WORLD: Player::UpdateReputation" );
5443 for(FactionStateList::const_iterator itr
= m_factions
.begin(); itr
!= m_factions
.end(); ++itr
)
5445 SendFactionState(&(itr
->second
));
5449 void Player::SendFactionState(FactionState
const* faction
) const
5451 if(faction
->Flags
& FACTION_FLAG_VISIBLE
) //If faction is visible then update it
5453 WorldPacket
data(SMSG_SET_FACTION_STANDING
, (16)); // last check 2.4.0
5454 data
<< (float) 0; // unk 2.4.0
5455 data
<< (uint8
) 0; // wotlk 8634
5456 data
<< (uint32
) 1; // count
5458 data
<< (uint32
) faction
->ReputationListID
;
5459 data
<< (uint32
) faction
->Standing
;
5461 GetSession()->SendPacket(&data
);
5465 void Player::SendInitialReputations()
5467 WorldPacket
data(SMSG_INITIALIZE_FACTIONS
, (4+128*5));
5468 data
<< uint32 (0x00000080);
5472 for (FactionStateList::const_iterator itr
= m_factions
.begin(); itr
!= m_factions
.end(); ++itr
)
5474 // fill in absent fields
5475 for (; a
!= itr
->first
; a
++)
5477 data
<< uint8 (0x00);
5478 data
<< uint32 (0x00000000);
5481 // fill in encountered data
5482 data
<< uint8 (itr
->second
.Flags
);
5483 data
<< uint32 (itr
->second
.Standing
);
5488 // fill in absent fields
5489 for (; a
!= 128; a
++)
5491 data
<< uint8 (0x00);
5492 data
<< uint32 (0x00000000);
5495 GetSession()->SendPacket(&data
);
5498 FactionState
const* Player::GetFactionState( FactionEntry
const* factionEntry
) const
5500 FactionStateList::const_iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5501 if (itr
!= m_factions
.end())
5502 return &itr
->second
;
5507 void Player::SetFactionAtWar(FactionState
* faction
, bool atWar
)
5509 // not allow declare war to own faction
5510 if(atWar
&& (faction
->Flags
& FACTION_FLAG_PEACE_FORCED
) )
5514 if(((faction
->Flags
& FACTION_FLAG_AT_WAR
) != 0) == atWar
)
5518 faction
->Flags
|= FACTION_FLAG_AT_WAR
;
5520 faction
->Flags
&= ~FACTION_FLAG_AT_WAR
;
5522 faction
->Changed
= true;
5525 void Player::SetFactionInactive(FactionState
* faction
, bool inactive
)
5527 // always invisible or hidden faction can't be inactive
5528 if(inactive
&& ((faction
->Flags
& (FACTION_FLAG_INVISIBLE_FORCED
|FACTION_FLAG_HIDDEN
)) || !(faction
->Flags
& FACTION_FLAG_VISIBLE
) ) )
5532 if(((faction
->Flags
& FACTION_FLAG_INACTIVE
) != 0) == inactive
)
5536 faction
->Flags
|= FACTION_FLAG_INACTIVE
;
5538 faction
->Flags
&= ~FACTION_FLAG_INACTIVE
;
5540 faction
->Changed
= true;
5543 void Player::SetFactionVisibleForFactionTemplateId(uint32 FactionTemplateId
)
5545 FactionTemplateEntry
const*factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5547 if(!factionTemplateEntry
)
5550 SetFactionVisibleForFactionId(factionTemplateEntry
->faction
);
5553 void Player::SetFactionVisibleForFactionId(uint32 FactionId
)
5555 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(FactionId
);
5559 if(factionEntry
->reputationListID
< 0)
5562 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5563 if (itr
== m_factions
.end())
5566 SetFactionVisible(&itr
->second
);
5569 void Player::SetFactionVisible(FactionState
* faction
)
5571 // always invisible or hidden faction can't be make visible
5572 if(faction
->Flags
& (FACTION_FLAG_INVISIBLE_FORCED
|FACTION_FLAG_HIDDEN
))
5576 if(faction
->Flags
& FACTION_FLAG_VISIBLE
)
5579 faction
->Flags
|= FACTION_FLAG_VISIBLE
;
5580 faction
->Changed
= true;
5582 if(!m_session
->PlayerLoading())
5584 // make faction visible in reputation list at client
5585 WorldPacket
data(SMSG_SET_FACTION_VISIBLE
, 4);
5586 data
<< faction
->ReputationListID
;
5587 GetSession()->SendPacket(&data
);
5591 void Player::SetInitialFactions()
5593 for(unsigned int i
= 1; i
< sFactionStore
.GetNumRows(); i
++)
5595 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(i
);
5597 if( factionEntry
&& (factionEntry
->reputationListID
>= 0))
5599 FactionState newFaction
;
5600 newFaction
.ID
= factionEntry
->ID
;
5601 newFaction
.ReputationListID
= factionEntry
->reputationListID
;
5602 newFaction
.Standing
= 0;
5603 newFaction
.Flags
= GetDefaultReputationFlags(factionEntry
);
5604 newFaction
.Changed
= true;
5606 m_factions
[newFaction
.ReputationListID
] = newFaction
;
5611 uint32
Player::GetDefaultReputationFlags(const FactionEntry
*factionEntry
) const
5616 uint32 raceMask
= getRaceMask();
5617 uint32 classMask
= getClassMask();
5618 for (int i
=0; i
< 4; i
++)
5620 if( (factionEntry
->BaseRepRaceMask
[i
] & raceMask
) &&
5621 (factionEntry
->BaseRepClassMask
[i
]==0 ||
5622 (factionEntry
->BaseRepClassMask
[i
] & classMask
) ) )
5623 return factionEntry
->ReputationFlags
[i
];
5628 int32
Player::GetBaseReputation(const FactionEntry
*factionEntry
) const
5633 uint32 raceMask
= getRaceMask();
5634 uint32 classMask
= getClassMask();
5635 for (int i
=0; i
< 4; i
++)
5637 if( (factionEntry
->BaseRepRaceMask
[i
] & raceMask
) &&
5638 (factionEntry
->BaseRepClassMask
[i
]==0 ||
5639 (factionEntry
->BaseRepClassMask
[i
] & classMask
) ) )
5640 return factionEntry
->BaseRepValue
[i
];
5643 // in faction.dbc exist factions with (RepListId >=0, listed in character reputation list) with all BaseRepRaceMask[i]==0
5647 int32
Player::GetReputation(uint32 faction_id
) const
5649 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(faction_id
);
5653 sLog
.outError("Player::GetReputation: Can't get reputation of %s for unknown faction (faction template id) #%u.",GetName(), faction_id
);
5657 return GetReputation(factionEntry
);
5660 int32
Player::GetReputation(const FactionEntry
*factionEntry
) const
5662 // Faction without recorded reputation. Just ignore.
5666 FactionStateList::const_iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5667 if (itr
!= m_factions
.end())
5668 return GetBaseReputation(factionEntry
) + itr
->second
.Standing
;
5673 ReputationRank
Player::GetReputationRank(uint32 faction
) const
5675 FactionEntry
const*factionEntry
= sFactionStore
.LookupEntry(faction
);
5677 return MIN_REPUTATION_RANK
;
5679 return GetReputationRank(factionEntry
);
5682 ReputationRank
Player::ReputationToRank(int32 standing
) const
5684 int32 Limit
= Reputation_Cap
+ 1;
5685 for (int i
= MAX_REPUTATION_RANK
-1; i
>= MIN_REPUTATION_RANK
; --i
)
5687 Limit
-= ReputationRank_Length
[i
];
5688 if (standing
>= Limit
)
5689 return ReputationRank(i
);
5691 return MIN_REPUTATION_RANK
;
5694 ReputationRank
Player::GetReputationRank(const FactionEntry
*factionEntry
) const
5696 int32 Reputation
= GetReputation(factionEntry
);
5697 return ReputationToRank(Reputation
);
5700 ReputationRank
Player::GetBaseReputationRank(const FactionEntry
*factionEntry
) const
5702 int32 Reputation
= GetBaseReputation(factionEntry
);
5703 return ReputationToRank(Reputation
);
5706 bool Player::ModifyFactionReputation(uint32 FactionTemplateId
, int32 DeltaReputation
)
5708 FactionTemplateEntry
const* factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5710 if(!factionTemplateEntry
)
5712 sLog
.outError("Player::ModifyFactionReputation: Can't update reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId
);
5716 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(factionTemplateEntry
->faction
);
5718 // Faction without recorded reputation. Just ignore.
5722 return ModifyFactionReputation(factionEntry
, DeltaReputation
);
5725 bool Player::ModifyFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5727 SimpleFactionsList
const* flist
= GetFactionTeamList(factionEntry
->ID
);
5731 for (SimpleFactionsList::const_iterator itr
= flist
->begin();itr
!= flist
->end();++itr
)
5733 FactionEntry
const *factionEntryCalc
= sFactionStore
.LookupEntry(*itr
);
5734 if(factionEntryCalc
)
5735 res
= ModifyOneFactionReputation(factionEntryCalc
, standing
);
5740 return ModifyOneFactionReputation(factionEntry
, standing
);
5743 bool Player::ModifyOneFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5745 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5746 if (itr
!= m_factions
.end())
5748 int32 BaseRep
= GetBaseReputation(factionEntry
);
5749 int32 new_rep
= BaseRep
+ itr
->second
.Standing
+ standing
;
5751 if (new_rep
> Reputation_Cap
)
5752 new_rep
= Reputation_Cap
;
5754 if (new_rep
< Reputation_Bottom
)
5755 new_rep
= Reputation_Bottom
;
5757 if(ReputationToRank(new_rep
) <= REP_HOSTILE
)
5758 SetFactionAtWar(&itr
->second
,true);
5760 itr
->second
.Standing
= new_rep
- BaseRep
;
5761 itr
->second
.Changed
= true;
5763 SetFactionVisible(&itr
->second
);
5765 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
5767 if(uint32 questid
= GetQuestSlotQuestId(i
))
5769 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
5770 if( qInfo
&& qInfo
->GetRepObjectiveFaction() == factionEntry
->ID
)
5772 QuestStatusData
& q_status
= mQuestStatus
[questid
];
5773 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
5775 if(GetReputation(factionEntry
) >= qInfo
->GetRepObjectiveValue())
5776 if ( CanCompleteQuest( questid
) )
5777 CompleteQuest( questid
);
5779 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
5781 if(GetReputation(factionEntry
) < qInfo
->GetRepObjectiveValue())
5782 IncompleteQuest( questid
);
5787 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION
);
5788 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION
);
5789 SendFactionState(&(itr
->second
));
5796 bool Player::SetFactionReputation(uint32 FactionTemplateId
, int32 standing
)
5798 FactionTemplateEntry
const* factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5800 if(!factionTemplateEntry
)
5802 sLog
.outError("Player::SetFactionReputation: Can't set reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId
);
5806 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(factionTemplateEntry
->faction
);
5808 // Faction without recorded reputation. Just ignore.
5812 return SetFactionReputation(factionEntry
, standing
);
5815 bool Player::SetFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5817 SimpleFactionsList
const* flist
= GetFactionTeamList(factionEntry
->ID
);
5821 for (SimpleFactionsList::const_iterator itr
= flist
->begin();itr
!= flist
->end();++itr
)
5823 FactionEntry
const *factionEntryCalc
= sFactionStore
.LookupEntry(*itr
);
5824 if(factionEntryCalc
)
5825 res
= SetOneFactionReputation(factionEntryCalc
, standing
);
5830 return SetOneFactionReputation(factionEntry
, standing
);
5833 bool Player::SetOneFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5835 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5836 if (itr
!= m_factions
.end())
5838 if (standing
> Reputation_Cap
)
5839 standing
= Reputation_Cap
;
5841 if (standing
< Reputation_Bottom
)
5842 standing
= Reputation_Bottom
;
5844 int32 BaseRep
= GetBaseReputation(factionEntry
);
5845 itr
->second
.Standing
= standing
- BaseRep
;
5846 itr
->second
.Changed
= true;
5848 SetFactionVisible(&itr
->second
);
5850 if(ReputationToRank(standing
) <= REP_HOSTILE
)
5851 SetFactionAtWar(&itr
->second
,true);
5853 SendFactionState(&(itr
->second
));
5854 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION
);
5855 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION
);
5861 //Calculate total reputation percent player gain with quest/creature level
5862 int32
Player::CalculateReputationGain(uint32 creatureOrQuestLevel
, int32 rep
, bool for_quest
)
5864 // for grey creature kill received 20%, in other case 100.
5865 int32 percent
= (!for_quest
&& (creatureOrQuestLevel
<= MaNGOS::XP::GetGrayLevel(getLevel()))) ? 20 : 100;
5867 int32 repMod
= GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN
);
5869 percent
+= rep
> 0 ? repMod
: -repMod
;
5874 return int32(sWorld
.getRate(RATE_REPUTATION_GAIN
)*rep
*percent
/100);
5877 //Calculates how many reputation points player gains in victim's enemy factions
5878 void Player::RewardReputation(Unit
*pVictim
, float rate
)
5880 if(!pVictim
|| pVictim
->GetTypeId() == TYPEID_PLAYER
)
5883 ReputationOnKillEntry
const* Rep
= objmgr
.GetReputationOnKilEntry(((Creature
*)pVictim
)->GetCreatureInfo()->Entry
);
5888 if(Rep
->repfaction1
&& (!Rep
->team_dependent
|| GetTeam()==ALLIANCE
))
5890 int32 donerep1
= CalculateReputationGain(pVictim
->getLevel(),Rep
->repvalue1
,false);
5891 donerep1
= int32(donerep1
*rate
);
5892 FactionEntry
const *factionEntry1
= sFactionStore
.LookupEntry(Rep
->repfaction1
);
5893 uint32 current_reputation_rank1
= GetReputationRank(factionEntry1
);
5894 if(factionEntry1
&& current_reputation_rank1
<= Rep
->reputation_max_cap1
)
5895 ModifyFactionReputation(factionEntry1
, donerep1
);
5897 // Wiki: Team factions value divided by 2
5898 if(Rep
->is_teamaward1
)
5900 FactionEntry
const *team1_factionEntry
= sFactionStore
.LookupEntry(factionEntry1
->team
);
5901 if(team1_factionEntry
)
5902 ModifyFactionReputation(team1_factionEntry
, donerep1
/ 2);
5906 if(Rep
->repfaction2
&& (!Rep
->team_dependent
|| GetTeam()==HORDE
))
5908 int32 donerep2
= CalculateReputationGain(pVictim
->getLevel(),Rep
->repvalue2
,false);
5909 donerep2
= int32(donerep2
*rate
);
5910 FactionEntry
const *factionEntry2
= sFactionStore
.LookupEntry(Rep
->repfaction2
);
5911 uint32 current_reputation_rank2
= GetReputationRank(factionEntry2
);
5912 if(factionEntry2
&& current_reputation_rank2
<= Rep
->reputation_max_cap2
)
5913 ModifyFactionReputation(factionEntry2
, donerep2
);
5915 // Wiki: Team factions value divided by 2
5916 if(Rep
->is_teamaward2
)
5918 FactionEntry
const *team2_factionEntry
= sFactionStore
.LookupEntry(factionEntry2
->team
);
5919 if(team2_factionEntry
)
5920 ModifyFactionReputation(team2_factionEntry
, donerep2
/ 2);
5925 //Calculate how many reputation points player gain with the quest
5926 void Player::RewardReputation(Quest
const *pQuest
)
5928 // quest reputation reward/loss
5929 for(int i
= 0; i
< QUEST_REPUTATIONS_COUNT
; ++i
)
5931 if(pQuest
->RewRepFaction
[i
] && pQuest
->RewRepValue
[i
] )
5933 int32 rep
= CalculateReputationGain(pQuest
->GetQuestLevel(),pQuest
->RewRepValue
[i
],true);
5934 FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(pQuest
->RewRepFaction
[i
]);
5936 ModifyFactionReputation(factionEntry
, rep
);
5940 // TODO: implement reputation spillover
5943 void Player::UpdateArenaFields(void)
5945 /* arena calcs go here */
5948 void Player::UpdateHonorFields()
5950 /// called when rewarding honor and at each save
5951 uint64 now
= time(NULL
);
5952 uint64 today
= uint64(time(NULL
) / DAY
) * DAY
;
5954 if(m_lastHonorUpdateTime
< today
)
5956 uint64 yesterday
= today
- DAY
;
5958 uint16 kills_today
= PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS
));
5960 // update yesterday's contribution
5961 if(m_lastHonorUpdateTime
>= yesterday
)
5963 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
));
5965 // this is the first update today, reset today's contribution
5966 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, 0);
5967 SetUInt32Value(PLAYER_FIELD_KILLS
, MAKE_PAIR32(0,kills_today
));
5971 // no honor/kills yesterday or today, reset
5972 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0);
5973 SetUInt32Value(PLAYER_FIELD_KILLS
, 0);
5977 m_lastHonorUpdateTime
= now
;
5980 ///Calculate the amount of honor gained based on the victim
5981 ///and the size of the group for which the honor is divided
5982 ///An exact honor value can also be given (overriding the calcs)
5983 bool Player::RewardHonor(Unit
*uVictim
, uint32 groupsize
, float honor
)
5985 // do not reward honor in arenas, but enable onkill spellproc
5988 if(!uVictim
|| uVictim
== this || uVictim
->GetTypeId() != TYPEID_PLAYER
)
5991 if( GetBGTeam() == ((Player
*)uVictim
)->GetBGTeam() )
5997 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5998 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE
))
6001 uint64 victim_guid
= 0;
6002 uint32 victim_rank
= 0;
6004 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
6005 UpdateHonorFields();
6009 if(!uVictim
|| uVictim
== this || uVictim
->HasAuraType(SPELL_AURA_NO_PVP_CREDIT
))
6012 victim_guid
= uVictim
->GetGUID();
6014 if( uVictim
->GetTypeId() == TYPEID_PLAYER
)
6016 Player
*pVictim
= (Player
*)uVictim
;
6018 if( GetTeam() == pVictim
->GetTeam() && !sWorld
.IsFFAPvPRealm() )
6021 float f
= 1; //need for total kills (?? need more info)
6023 uint32 k_level
= getLevel();
6024 uint32 v_level
= pVictim
->getLevel();
6027 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
6029 // [1..14] Alliance honor titles and player name
6030 // [15..28] Horde honor titles and player name
6031 // [29..38] Other title and player name
6033 uint32 victim_title
= pVictim
->GetUInt32Value(PLAYER_CHOSEN_TITLE
);
6034 // Get Killer titles, CharTitlesEntry::bit_index
6036 // title[1..14] -> rank[5..18]
6037 // title[15..28] -> rank[5..18]
6038 // title[other] -> 0
6039 if (victim_title
== 0)
6040 victim_guid
= 0; // Don't show HK: <rank> message, only log.
6041 else if (victim_title
< 15)
6042 victim_rank
= victim_title
+ 4;
6043 else if (victim_title
< 29)
6044 victim_rank
= victim_title
- 14 + 4;
6046 victim_guid
= 0; // Don't show HK: <rank> message, only log.
6049 k_grey
= MaNGOS::XP::GetGrayLevel(k_level
);
6054 float diff_level
= (k_level
== k_grey
) ? 1 : ((float(v_level
) - float(k_grey
)) / (float(k_level
) - float(k_grey
)));
6056 int32 v_rank
=1; //need more info
6058 honor
= ((f
* diff_level
* (190 + v_rank
*10))/6);
6059 honor
*= ((float)k_level
) / 70.0f
; //factor of dependence on levels of the killer
6061 // count the number of playerkills in one day
6062 ApplyModUInt32Value(PLAYER_FIELD_KILLS
, 1, true);
6063 // and those in a lifetime
6064 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 1, true);
6068 Creature
*cVictim
= (Creature
*)uVictim
;
6070 if (!cVictim
->isRacialLeader())
6073 honor
= 100; // ??? need more info
6074 victim_rank
= 19; // HK: Leader
6078 if (uVictim
!= NULL
)
6080 honor
*= sWorld
.getRate(RATE_HONOR
);
6085 honor
*= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6088 // honor - for show honor points in log
6089 // victim_guid - for show victim name in log
6090 // victim_rank [1..4] HK: <dishonored rank>
6091 // victim_rank [5..19] HK: <alliance\horde rank>
6092 // victim_rank [0,20+] HK: <>
6093 WorldPacket
data(SMSG_PVP_CREDIT
,4+8+4);
6094 data
<< (uint32
) honor
;
6095 data
<< (uint64
) victim_guid
;
6096 data
<< (uint32
) victim_rank
;
6098 GetSession()->SendPacket(&data
);
6101 ModifyHonorPoints(int32(honor
));
6103 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, uint32(honor
), true);
6107 void Player::ModifyHonorPoints( int32 value
)
6111 if (GetHonorPoints() > sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
))
6112 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) + value
);
6114 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() > uint32(-value
) ? GetHonorPoints() + value
: 0);
6117 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() < sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) - value
? GetHonorPoints() + value
: sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
));
6120 void Player::ModifyArenaPoints( int32 value
)
6124 if (GetArenaPoints() > sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
))
6125 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) + value
);
6127 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() > uint32(-value
) ? GetArenaPoints() + value
: 0);
6130 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() < sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) - value
? GetArenaPoints() + value
: sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
));
6133 uint32
Player::GetGuildIdFromDB(uint64 guid
)
6135 QueryResult
* result
= CharacterDatabase
.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid
));
6139 uint32 id
= result
->Fetch()[0].GetUInt32();
6144 uint32
Player::GetRankFromDB(uint64 guid
)
6146 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid
) );
6149 uint32 v
= result
->Fetch()[0].GetUInt32();
6157 uint32
Player::GetArenaTeamIdFromDB(uint64 guid
, uint8 type
)
6159 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
);
6163 uint32 id
= (*result
)[0].GetUInt32();
6168 uint32
Player::GetZoneIdFromDB(uint64 guid
)
6170 uint32 guidLow
= GUID_LOPART(guid
);
6171 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow
);
6174 Field
* fields
= result
->Fetch();
6175 uint32 zone
= fields
[0].GetUInt32();
6180 // stored zone is zero, use generic and slow zone detection
6181 result
= CharacterDatabase
.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow
);
6184 fields
= result
->Fetch();
6185 uint32 map
= fields
[0].GetUInt32();
6186 float posx
= fields
[1].GetFloat();
6187 float posy
= fields
[2].GetFloat();
6188 float posz
= fields
[3].GetFloat();
6191 zone
= MapManager::Instance().GetZoneId(map
,posx
,posy
,posz
);
6193 CharacterDatabase
.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone
, guidLow
);
6199 void Player::UpdateArea(uint32 newArea
)
6201 // FFA_PVP flags are area and not zone id dependent
6202 // so apply them accordingly
6203 m_areaUpdateId
= newArea
;
6205 AreaTableEntry
const* area
= GetAreaEntryByAreaID(newArea
);
6207 if(area
&& (area
->flags
& AREA_FLAG_ARENA
))
6210 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6214 // remove ffa flag only if not ffapvp realm
6215 // removal in sanctuaries and capitals is handled in zone update
6216 if(HasByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
) && !sWorld
.IsFFAPvPRealm())
6217 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6220 UpdateAreaDependentAuras(newArea
);
6223 void Player::UpdateZone(uint32 newZone
)
6225 m_zoneUpdateId
= newZone
;
6226 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
6228 // zone changed, so area changed as well, update it
6229 UpdateArea(GetAreaId());
6231 AreaTableEntry
const* zone
= GetAreaEntryByAreaID(newZone
);
6235 if (sWorld
.getConfig(CONFIG_WEATHER
))
6237 Weather
*wth
= sWorld
.FindWeather(zone
->ID
);
6240 wth
->SendWeatherUpdateToPlayer(this);
6244 if(!sWorld
.AddWeather(zone
->ID
))
6246 // send fine weather packet to remove old zone's weather
6247 Weather::SendFineWeatherUpdateToPlayer(this);
6252 pvpInfo
.inHostileArea
=
6253 GetTeam() == ALLIANCE
&& zone
->team
== AREATEAM_HORDE
||
6254 GetTeam() == HORDE
&& zone
->team
== AREATEAM_ALLY
||
6255 sWorld
.IsPvPRealm() && zone
->team
== AREATEAM_NONE
||
6256 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6258 if(pvpInfo
.inHostileArea
) // in hostile area
6260 if(!IsPvP() || pvpInfo
.endTimer
!= 0)
6261 UpdatePvP(true, true);
6263 else // in friendly area
6265 if(IsPvP() && !HasFlag(PLAYER_FLAGS
,PLAYER_FLAGS_IN_PVP
) && pvpInfo
.endTimer
== 0)
6266 pvpInfo
.endTimer
= time(0); // start toggle-off
6269 if(zone
->flags
& AREA_FLAG_SANCTUARY
) // in sanctuary
6271 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_SANCTUARY
);
6272 if(sWorld
.IsFFAPvPRealm())
6273 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6277 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_SANCTUARY
);
6280 if(zone
->flags
& AREA_FLAG_CAPITAL
) // in capital city
6282 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6283 SetRestType(REST_TYPE_IN_CITY
);
6284 InnEnter(time(0),GetMapId(),0,0,0);
6286 if(sWorld
.IsFFAPvPRealm())
6287 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6289 else // anywhere else
6291 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6293 if(GetRestType()==REST_TYPE_IN_TAVERN
) // has been in tavern. Is still in?
6295 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6297 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6298 SetRestType(REST_TYPE_NO
);
6300 if(sWorld
.IsFFAPvPRealm())
6301 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6304 else // not in tavern (leave city then)
6306 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6307 SetRestType(REST_TYPE_NO
);
6309 // Set player to FFA PVP when not in rested environment.
6310 if(sWorld
.IsFFAPvPRealm())
6311 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6316 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6317 // if player resurrected at teleport this will be applied in resurrect code
6319 DestroyZoneLimitedItem( true, newZone
);
6321 // recent client version not send leave/join channel packets for built-in local channels
6322 UpdateLocalChannels( newZone
);
6326 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE
);
6328 UpdateZoneDependentAuras(newZone
);
6331 //If players are too far way of duel flag... then player loose the duel
6332 void Player::CheckDuelDistance(time_t currTime
)
6337 uint64 duelFlagGUID
= GetUInt64Value(PLAYER_DUEL_ARBITER
);
6338 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, duelFlagGUID
);
6342 if(duel
->outOfBound
== 0)
6344 if(!IsWithinDistInMap(obj
, 50))
6346 duel
->outOfBound
= currTime
;
6348 WorldPacket
data(SMSG_DUEL_OUTOFBOUNDS
, 0);
6349 GetSession()->SendPacket(&data
);
6354 if(IsWithinDistInMap(obj
, 40))
6356 duel
->outOfBound
= 0;
6358 WorldPacket
data(SMSG_DUEL_INBOUNDS
, 0);
6359 GetSession()->SendPacket(&data
);
6361 else if(currTime
>= (duel
->outOfBound
+10))
6363 DuelComplete(DUEL_FLED
);
6368 void Player::DuelComplete(DuelCompleteType type
)
6370 // duel not requested
6374 WorldPacket
data(SMSG_DUEL_COMPLETE
, (1));
6375 data
<< (uint8
)((type
!= DUEL_INTERUPTED
) ? 1 : 0);
6376 GetSession()->SendPacket(&data
);
6377 duel
->opponent
->GetSession()->SendPacket(&data
);
6379 if(type
!= DUEL_INTERUPTED
)
6381 data
.Initialize(SMSG_DUEL_WINNER
, (1+20)); // we guess size
6382 data
<< (uint8
)((type
==DUEL_WON
) ? 0 : 1); // 0 = just won; 1 = fled
6383 data
<< duel
->opponent
->GetName();
6385 SendMessageToSet(&data
,true);
6388 // cool-down duel spell
6389 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6396 GetSession()->SendPacket(&data);
6397 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6398 data<<duel->opponent->GetGUID();
6402 duel->opponent->GetSession()->SendPacket(&data);*/
6404 //Remove Duel Flag object
6405 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER
));
6407 duel
->initiator
->RemoveGameObject(obj
,true);
6410 std::vector
<uint32
> auras2remove
;
6411 AuraMap
const& vAuras
= duel
->opponent
->GetAuras();
6412 for (AuraMap::const_iterator i
= vAuras
.begin(); i
!= vAuras
.end(); ++i
)
6414 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6415 auras2remove
.push_back(i
->second
->GetId());
6418 for(size_t i
=0; i
<auras2remove
.size(); i
++)
6419 duel
->opponent
->RemoveAurasDueToSpell(auras2remove
[i
]);
6421 auras2remove
.clear();
6422 AuraMap
const& auras
= GetAuras();
6423 for (AuraMap::const_iterator i
= auras
.begin(); i
!= auras
.end(); ++i
)
6425 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == duel
->opponent
->GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6426 auras2remove
.push_back(i
->second
->GetId());
6428 for(size_t i
=0; i
<auras2remove
.size(); i
++)
6429 RemoveAurasDueToSpell(auras2remove
[i
]);
6431 // cleanup combo points
6432 if(GetComboTarget()==duel
->opponent
->GetGUID())
6434 else if(GetComboTarget()==duel
->opponent
->GetPetGUID())
6437 if(duel
->opponent
->GetComboTarget()==GetGUID())
6438 duel
->opponent
->ClearComboPoints();
6439 else if(duel
->opponent
->GetComboTarget()==GetPetGUID())
6440 duel
->opponent
->ClearComboPoints();
6443 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6444 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6445 duel
->opponent
->SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6446 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6448 delete duel
->opponent
->duel
;
6449 duel
->opponent
->duel
= NULL
;
6454 //---------------------------------------------------------//
6456 void Player::_ApplyItemMods(Item
*item
, uint8 slot
,bool apply
)
6458 if(slot
>= INVENTORY_SLOT_BAG_END
|| !item
)
6461 // not apply/remove mods for broken item
6462 if(item
->IsBroken())
6465 ItemPrototype
const *proto
= item
->GetProto();
6470 sLog
.outDetail("applying mods for item %u ",item
->GetGUIDLow());
6472 uint32 attacktype
= Player::GetAttackBySlot(slot
);
6473 if(attacktype
< MAX_ATTACK
)
6474 _ApplyWeaponDependentAuraMods(item
,WeaponAttackType(attacktype
),apply
);
6476 _ApplyItemBonuses(proto
,slot
,apply
);
6478 if( slot
==EQUIPMENT_SLOT_RANGED
)
6479 _ApplyAmmoBonuses();
6481 ApplyItemEquipSpell(item
,apply
);
6482 ApplyEnchantment(item
, apply
);
6484 if(proto
->Socket
[0].Color
) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6485 CorrectMetaGemEnchants(slot
, apply
);
6487 sLog
.outDebug("_ApplyItemMods complete.");
6490 void Player::_ApplyItemBonuses(ItemPrototype
const *proto
, uint8 slot
, bool apply
)
6492 if(slot
>= INVENTORY_SLOT_BAG_END
|| !proto
)
6495 for (int i
= 0; i
< 10; i
++)
6497 uint32 statType
= 0;
6500 if(proto
->ScalingStatDistribution
)
6502 if(ScalingStatDistributionEntry
const *ssd
= sScalingStatDistributionStore
.LookupEntry(proto
->ScalingStatDistribution
))
6504 statType
= ssd
->StatMod
[i
];
6506 if(uint32 modifier
= ssd
->Modifier
[i
])
6508 uint32 level
= ((getLevel() > ssd
->MaxLevel
) ? ssd
->MaxLevel
: getLevel());
6509 if(ScalingStatValuesEntry
const *ssv
= sScalingStatValuesStore
.LookupEntry(level
))
6511 uint32 multiplier
= ssv
->Multiplier
[proto
->GetScalingStatValuesColumn()];
6512 val
= (multiplier
* modifier
) / 10000;
6519 statType
= proto
->ItemStat
[i
].ItemStatType
;
6520 val
= proto
->ItemStat
[i
].ItemStatValue
;
6529 HandleStatModifier(UNIT_MOD_MANA
, BASE_VALUE
, float(val
), apply
);
6531 case ITEM_MOD_HEALTH
: // modify HP
6532 HandleStatModifier(UNIT_MOD_HEALTH
, BASE_VALUE
, float(val
), apply
);
6534 case ITEM_MOD_AGILITY
: // modify agility
6535 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, BASE_VALUE
, float(val
), apply
);
6536 ApplyStatBuffMod(STAT_AGILITY
, float(val
), apply
);
6538 case ITEM_MOD_STRENGTH
: //modify strength
6539 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, BASE_VALUE
, float(val
), apply
);
6540 ApplyStatBuffMod(STAT_STRENGTH
, float(val
), apply
);
6542 case ITEM_MOD_INTELLECT
: //modify intellect
6543 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, BASE_VALUE
, float(val
), apply
);
6544 ApplyStatBuffMod(STAT_INTELLECT
, float(val
), apply
);
6546 case ITEM_MOD_SPIRIT
: //modify spirit
6547 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, BASE_VALUE
, float(val
), apply
);
6548 ApplyStatBuffMod(STAT_SPIRIT
, float(val
), apply
);
6550 case ITEM_MOD_STAMINA
: //modify stamina
6551 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, BASE_VALUE
, float(val
), apply
);
6552 ApplyStatBuffMod(STAT_STAMINA
, float(val
), apply
);
6554 case ITEM_MOD_DEFENSE_SKILL_RATING
:
6555 ApplyRatingMod(CR_DEFENSE_SKILL
, int32(val
), apply
);
6557 case ITEM_MOD_DODGE_RATING
:
6558 ApplyRatingMod(CR_DODGE
, int32(val
), apply
);
6560 case ITEM_MOD_PARRY_RATING
:
6561 ApplyRatingMod(CR_PARRY
, int32(val
), apply
);
6563 case ITEM_MOD_BLOCK_RATING
:
6564 ApplyRatingMod(CR_BLOCK
, int32(val
), apply
);
6566 case ITEM_MOD_HIT_MELEE_RATING
:
6567 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6569 case ITEM_MOD_HIT_RANGED_RATING
:
6570 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6572 case ITEM_MOD_HIT_SPELL_RATING
:
6573 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6575 case ITEM_MOD_CRIT_MELEE_RATING
:
6576 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6578 case ITEM_MOD_CRIT_RANGED_RATING
:
6579 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6581 case ITEM_MOD_CRIT_SPELL_RATING
:
6582 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6584 case ITEM_MOD_HIT_TAKEN_MELEE_RATING
:
6585 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6587 case ITEM_MOD_HIT_TAKEN_RANGED_RATING
:
6588 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6590 case ITEM_MOD_HIT_TAKEN_SPELL_RATING
:
6591 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6593 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING
:
6594 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6596 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING
:
6597 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6599 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING
:
6600 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6602 case ITEM_MOD_HASTE_MELEE_RATING
:
6603 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6605 case ITEM_MOD_HASTE_RANGED_RATING
:
6606 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6608 case ITEM_MOD_HASTE_SPELL_RATING
:
6609 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6611 case ITEM_MOD_HIT_RATING
:
6612 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6613 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6614 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6616 case ITEM_MOD_CRIT_RATING
:
6617 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6618 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6619 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6621 case ITEM_MOD_HIT_TAKEN_RATING
:
6622 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6623 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6624 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6626 case ITEM_MOD_CRIT_TAKEN_RATING
:
6627 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6628 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6629 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6631 case ITEM_MOD_RESILIENCE_RATING
:
6632 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6633 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6634 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6636 case ITEM_MOD_HASTE_RATING
:
6637 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6638 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6639 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6641 case ITEM_MOD_EXPERTISE_RATING
:
6642 ApplyRatingMod(CR_EXPERTISE
, int32(val
), apply
);
6644 case ITEM_MOD_ATTACK_POWER
:
6645 HandleStatModifier(UNIT_MOD_ATTACK_POWER
, TOTAL_VALUE
, float(val
), apply
);
6647 case ITEM_MOD_RANGED_ATTACK_POWER
:
6648 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(val
), apply
);
6650 case ITEM_MOD_FERAL_ATTACK_POWER
:
6651 ApplyFeralAPBonus(int32(val
), apply
);
6653 case ITEM_MOD_SPELL_HEALING_DONE
:
6654 ApplySpellHealingBonus(int32(val
), apply
);
6656 case ITEM_MOD_SPELL_DAMAGE_DONE
:
6657 ApplySpellDamageBonus(int32(val
), apply
);
6659 case ITEM_MOD_MANA_REGENERATION
:
6660 ApplyManaRegenBonus(int32(val
), apply
);
6662 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
6663 ApplyRatingMod(CR_ARMOR_PENETRATION
, int32(val
), apply
);
6665 case ITEM_MOD_SPELL_POWER
:
6666 ApplySpellHealingBonus(int32(val
), apply
);
6667 ApplySpellDamageBonus(int32(val
), apply
);
6673 HandleStatModifier(UNIT_MOD_ARMOR
, BASE_VALUE
, float(proto
->Armor
), apply
);
6676 HandleBaseModValue(SHIELD_BLOCK_VALUE
, FLAT_MOD
, float(proto
->Block
), apply
);
6679 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY
, BASE_VALUE
, float(proto
->HolyRes
), apply
);
6682 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE
, BASE_VALUE
, float(proto
->FireRes
), apply
);
6684 if (proto
->NatureRes
)
6685 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE
, BASE_VALUE
, float(proto
->NatureRes
), apply
);
6687 if (proto
->FrostRes
)
6688 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST
, BASE_VALUE
, float(proto
->FrostRes
), apply
);
6690 if (proto
->ShadowRes
)
6691 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW
, BASE_VALUE
, float(proto
->ShadowRes
), apply
);
6693 if (proto
->ArcaneRes
)
6694 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE
, BASE_VALUE
, float(proto
->ArcaneRes
), apply
);
6696 WeaponAttackType attType
= BASE_ATTACK
;
6697 float damage
= 0.0f
;
6699 if( slot
== EQUIPMENT_SLOT_RANGED
&& (
6700 proto
->InventoryType
== INVTYPE_RANGED
|| proto
->InventoryType
== INVTYPE_THROWN
||
6701 proto
->InventoryType
== INVTYPE_RANGEDRIGHT
))
6703 attType
= RANGED_ATTACK
;
6705 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6707 attType
= OFF_ATTACK
;
6710 if (proto
->Damage
[0].DamageMin
> 0 )
6712 damage
= apply
? proto
->Damage
[0].DamageMin
: BASE_MINDAMAGE
;
6713 SetBaseWeaponDamage(attType
, MINDAMAGE
, damage
);
6714 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6717 if (proto
->Damage
[0].DamageMax
> 0 )
6719 damage
= apply
? proto
->Damage
[0].DamageMax
: BASE_MAXDAMAGE
;
6720 SetBaseWeaponDamage(attType
, MAXDAMAGE
, damage
);
6723 if(!IsUseEquipedWeapon(slot
==EQUIPMENT_SLOT_MAINHAND
))
6728 if(slot
== EQUIPMENT_SLOT_RANGED
)
6729 SetAttackTime(RANGED_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6730 else if(slot
==EQUIPMENT_SLOT_MAINHAND
)
6731 SetAttackTime(BASE_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6732 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6733 SetAttackTime(OFF_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6736 if(CanModifyStats() && (damage
|| proto
->Delay
))
6737 UpdateDamagePhysical(attType
);
6740 void Player::_ApplyWeaponDependentAuraMods(Item
*item
,WeaponAttackType attackType
,bool apply
)
6742 AuraList
const& auraCritList
= GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT
);
6743 for(AuraList::const_iterator itr
= auraCritList
.begin(); itr
!=auraCritList
.end();++itr
)
6744 _ApplyWeaponDependentAuraCritMod(item
,attackType
,*itr
,apply
);
6746 AuraList
const& auraDamageFlatList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE
);
6747 for(AuraList::const_iterator itr
= auraDamageFlatList
.begin(); itr
!=auraDamageFlatList
.end();++itr
)
6748 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6750 AuraList
const& auraDamagePCTList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
);
6751 for(AuraList::const_iterator itr
= auraDamagePCTList
.begin(); itr
!=auraDamagePCTList
.end();++itr
)
6752 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6755 void Player::_ApplyWeaponDependentAuraCritMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6757 // generic not weapon specific case processes in aura code
6758 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6761 BaseModGroup mod
= BASEMOD_END
;
6764 case BASE_ATTACK
: mod
= CRIT_PERCENTAGE
; break;
6765 case OFF_ATTACK
: mod
= OFFHAND_CRIT_PERCENTAGE
;break;
6766 case RANGED_ATTACK
: mod
= RANGED_CRIT_PERCENTAGE
; break;
6770 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6772 HandleBaseModValue(mod
, FLAT_MOD
, float (aura
->GetModifier()->m_amount
), apply
);
6776 void Player::_ApplyWeaponDependentAuraDamageMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6778 // ignore spell mods for not wands
6779 Modifier
const* modifier
= aura
->GetModifier();
6780 if((modifier
->m_miscvalue
& SPELL_SCHOOL_MASK_NORMAL
)==0 && (getClassMask() & CLASSMASK_WAND_USERS
)==0)
6783 // generic not weapon specific case processes in aura code
6784 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6787 UnitMods unitMod
= UNIT_MOD_END
;
6790 case BASE_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_MAINHAND
; break;
6791 case OFF_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_OFFHAND
; break;
6792 case RANGED_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_RANGED
; break;
6796 UnitModifierType unitModType
= TOTAL_VALUE
;
6797 switch(modifier
->m_auraname
)
6799 case SPELL_AURA_MOD_DAMAGE_DONE
: unitModType
= TOTAL_VALUE
; break;
6800 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
: unitModType
= TOTAL_PCT
; break;
6804 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6806 HandleStatModifier(unitMod
, unitModType
, float(modifier
->m_amount
),apply
);
6810 void Player::ApplyItemEquipSpell(Item
*item
, bool apply
, bool form_change
)
6815 ItemPrototype
const *proto
= item
->GetProto();
6819 for (int i
= 0; i
< 5; i
++)
6821 _Spell
const& spellData
= proto
->Spells
[i
];
6824 if(!spellData
.SpellId
)
6827 // wrong triggering type
6828 if(apply
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_EQUIP
)
6831 // check if it is valid spell
6832 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellData
.SpellId
);
6836 ApplyEquipSpell(spellproto
,item
,apply
,form_change
);
6840 void Player::ApplyEquipSpell(SpellEntry
const* spellInfo
, Item
* item
, bool apply
, bool form_change
)
6844 // Cannot be used in this stance/form
6845 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
)!=0)
6848 if(form_change
) // check aura active state from other form
6851 for (int k
=0; k
< 3; ++k
)
6853 spellEffectPair spair
= spellEffectPair(spellInfo
->Id
, k
);
6854 for (AuraMap::iterator iter
= m_Auras
.lower_bound(spair
); iter
!= m_Auras
.upper_bound(spair
); ++iter
)
6856 if(!item
|| iter
->second
->GetCastItemGUID() == item
->GetGUID())
6866 if(found
) // and skip re-cast already active aura at form change
6870 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item
? "item" : "itemset"), spellInfo
->Id
);
6872 CastSpell(this,spellInfo
,true,item
);
6876 if(form_change
) // check aura compatibility
6878 // Cannot be used in this stance/form
6879 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
)==0)
6880 return; // and remove only not compatible at form change
6884 RemoveAurasDueToItemSpell(item
,spellInfo
->Id
); // un-apply all spells , not only at-equipped
6886 RemoveAurasDueToSpell(spellInfo
->Id
); // un-apply spell (item set case)
6890 void Player::UpdateEquipSpellsAtFormChange()
6892 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6894 if(m_items
[i
] && !m_items
[i
]->IsBroken())
6896 ApplyItemEquipSpell(m_items
[i
],false,true); // remove spells that not fit to form
6897 ApplyItemEquipSpell(m_items
[i
],true,true); // add spells that fit form but not active
6901 // item set bonuses not dependent from item broken state
6902 for(size_t setindex
= 0; setindex
< ItemSetEff
.size(); ++setindex
)
6904 ItemSetEffect
* eff
= ItemSetEff
[setindex
];
6908 for(uint32 y
=0;y
<8; ++y
)
6910 SpellEntry
const* spellInfo
= eff
->spells
[y
];
6914 ApplyEquipSpell(spellInfo
,NULL
,false,true); // remove spells that not fit to form
6915 ApplyEquipSpell(spellInfo
,NULL
,true,true); // add spells that fit form but not active
6920 void Player::CastItemCombatSpell(Item
*item
,Unit
* Target
, WeaponAttackType attType
)
6922 if(!item
|| item
->IsBroken())
6925 ItemPrototype
const *proto
= item
->GetProto();
6929 if (!Target
|| Target
== this )
6932 for (int i
= 0; i
< 5; i
++)
6934 _Spell
const& spellData
= proto
->Spells
[i
];
6937 if(!spellData
.SpellId
)
6940 // wrong triggering type
6941 if(spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_CHANCE_ON_HIT
)
6944 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
6947 sLog
.outError("WORLD: unknown Item spellid %i", spellData
.SpellId
);
6951 // not allow proc extra attack spell at extra attack
6952 if( m_extraAttacks
&& IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_ADD_EXTRA_ATTACKS
) )
6955 float chance
= spellInfo
->procChance
;
6957 if(spellData
.SpellPPMRate
)
6959 uint32 WeaponSpeed
= GetAttackTime(attType
);
6960 chance
= GetPPMProcChance(WeaponSpeed
, spellData
.SpellPPMRate
);
6962 else if(chance
> 100.0f
)
6964 chance
= GetWeaponProcChance();
6967 if (roll_chance_f(chance
))
6968 CastSpell(Target
, spellInfo
->Id
, true, item
);
6971 // item combat enchantments
6972 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
6974 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
6975 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
6976 if(!pEnchant
) continue;
6977 for (int s
=0;s
<3;s
++)
6979 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
)
6982 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
6985 sLog
.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
6989 float chance
= pEnchant
->amount
[s
] != 0 ? float(pEnchant
->amount
[s
]) : GetWeaponProcChance();
6990 if (roll_chance_f(chance
))
6992 if(IsPositiveSpell(pEnchant
->spellid
[s
]))
6993 CastSpell(this, pEnchant
->spellid
[s
], true, item
);
6995 CastSpell(Target
, pEnchant
->spellid
[s
], true, item
);
7001 void Player::CastItemUseSpell(Item
*item
,SpellCastTargets
const& targets
,uint8 cast_count
, uint32 glyphIndex
)
7003 ItemPrototype
const* proto
= item
->GetProto();
7004 // special learning case
7005 if(proto
->Spells
[0].SpellId
==SPELL_ID_GENERIC_LEARN
|| proto
->Spells
[0].SpellId
==SPELL_ID_GENERIC_LEARN_PET
)
7007 uint32 learn_spell_id
= proto
->Spells
[0].SpellId
;
7008 uint32 learning_spell_id
= proto
->Spells
[1].SpellId
;
7010 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(learn_spell_id
);
7013 sLog
.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto
->ItemId
, learn_spell_id
);
7014 SendEquipError(EQUIP_ERR_NONE
,item
,NULL
);
7018 Spell
*spell
= new Spell(this, spellInfo
, false);
7019 spell
->m_CastItem
= item
;
7020 spell
->m_cast_count
= cast_count
; //set count of casts
7021 spell
->m_currentBasePoints
[0] = learning_spell_id
;
7022 spell
->prepare(&targets
);
7026 // use triggered flag only for items with many spell casts and for not first cast
7029 // item spells casted at use
7030 for(int i
= 0; i
< 5; ++i
)
7032 _Spell
const& spellData
= proto
->Spells
[i
];
7035 if(!spellData
.SpellId
)
7038 // wrong triggering type
7039 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_NO_DELAY_USE
)
7042 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
7045 sLog
.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto
->ItemId
, spellData
.SpellId
);
7049 Spell
*spell
= new Spell(this, spellInfo
, (count
> 0));
7050 spell
->m_CastItem
= item
;
7051 spell
->m_cast_count
= cast_count
; // set count of casts
7052 spell
->m_glyphIndex
= glyphIndex
; // glyph index
7053 spell
->prepare(&targets
);
7058 // Item enchantments spells casted at use
7059 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
7061 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
7062 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
7063 if(!pEnchant
) continue;
7064 for (int s
=0;s
<3;s
++)
7066 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL
)
7069 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
7072 sLog
.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
7076 Spell
*spell
= new Spell(this, spellInfo
, (count
> 0));
7077 spell
->m_CastItem
= item
;
7078 spell
->m_cast_count
= cast_count
; // set count of casts
7079 spell
->m_glyphIndex
= glyphIndex
; // glyph index
7080 spell
->prepare(&targets
);
7087 void Player::_RemoveAllItemMods()
7089 sLog
.outDebug("_RemoveAllItemMods start.");
7091 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
7095 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7099 // item set bonuses not dependent from item broken state
7101 RemoveItemsSetItem(this,proto
);
7103 if(m_items
[i
]->IsBroken())
7106 ApplyItemEquipSpell(m_items
[i
],false);
7107 ApplyEnchantment(m_items
[i
], false);
7111 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
7115 if(m_items
[i
]->IsBroken())
7117 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7121 uint32 attacktype
= Player::GetAttackBySlot(i
);
7122 if(attacktype
< MAX_ATTACK
)
7123 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),false);
7125 _ApplyItemBonuses(proto
,i
, false);
7127 if( i
== EQUIPMENT_SLOT_RANGED
)
7128 _ApplyAmmoBonuses();
7132 sLog
.outDebug("_RemoveAllItemMods complete.");
7135 void Player::_ApplyAllItemMods()
7137 sLog
.outDebug("_ApplyAllItemMods start.");
7139 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
7143 if(m_items
[i
]->IsBroken())
7146 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7150 uint32 attacktype
= Player::GetAttackBySlot(i
);
7151 if(attacktype
< MAX_ATTACK
)
7152 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),true);
7154 _ApplyItemBonuses(proto
,i
, true);
7156 if( i
== EQUIPMENT_SLOT_RANGED
)
7157 _ApplyAmmoBonuses();
7161 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
7165 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
7169 // item set bonuses not dependent from item broken state
7171 AddItemsSetItem(this,m_items
[i
]);
7173 if(m_items
[i
]->IsBroken())
7176 ApplyItemEquipSpell(m_items
[i
],true);
7177 ApplyEnchantment(m_items
[i
], true);
7181 sLog
.outDebug("_ApplyAllItemMods complete.");
7184 void Player::_ApplyAmmoBonuses()
7187 uint32 ammo_id
= GetUInt32Value(PLAYER_AMMO_ID
);
7191 float currentAmmoDPS
;
7193 ItemPrototype
const *ammo_proto
= objmgr
.GetItemPrototype( ammo_id
);
7194 if( !ammo_proto
|| ammo_proto
->Class
!=ITEM_CLASS_PROJECTILE
|| !CheckAmmoCompatibility(ammo_proto
))
7195 currentAmmoDPS
= 0.0f
;
7197 currentAmmoDPS
= ammo_proto
->Damage
[0].DamageMin
;
7199 if(currentAmmoDPS
== GetAmmoDPS())
7202 m_ammoDPS
= currentAmmoDPS
;
7204 if(CanModifyStats())
7205 UpdateDamagePhysical(RANGED_ATTACK
);
7208 bool Player::CheckAmmoCompatibility(const ItemPrototype
*ammo_proto
) const
7213 // check ranged weapon
7214 Item
*weapon
= GetWeaponForAttack( RANGED_ATTACK
);
7215 if(!weapon
|| weapon
->IsBroken() )
7218 ItemPrototype
const* weapon_proto
= weapon
->GetProto();
7219 if(!weapon_proto
|| weapon_proto
->Class
!=ITEM_CLASS_WEAPON
)
7222 // check ammo ws. weapon compatibility
7223 switch(weapon_proto
->SubClass
)
7225 case ITEM_SUBCLASS_WEAPON_BOW
:
7226 case ITEM_SUBCLASS_WEAPON_CROSSBOW
:
7227 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_ARROW
)
7230 case ITEM_SUBCLASS_WEAPON_GUN
:
7231 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_BULLET
)
7241 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7242 Called by remove insignia spell effect */
7243 void Player::RemovedInsignia(Player
* looterPlr
)
7245 if (!GetBattleGroundId())
7248 // If not released spirit, do it !
7249 if(m_deathTimer
> 0)
7256 Corpse
*corpse
= GetCorpse();
7260 // We have to convert player corpse to bones, not to be able to resurrect there
7261 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7262 Corpse
*bones
= ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7266 // Now we must make bones lootable, and send player loot
7267 bones
->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS
, CORPSE_DYNFLAG_LOOTABLE
);
7269 // We store the level of our player in the gold field
7270 // We retrieve this information at Player::SendLoot()
7271 bones
->loot
.gold
= getLevel();
7272 bones
->lootRecipient
= looterPlr
;
7273 looterPlr
->SendLoot(bones
->GetGUID(), LOOT_INSIGNIA
);
7282 void Player::SendLootRelease( uint64 guid
)
7284 WorldPacket
data( SMSG_LOOT_RELEASE_RESPONSE
, (8+1) );
7285 data
<< uint64(guid
) << uint8(1);
7286 SendDirectMessage( &data
);
7289 void Player::SendLoot(uint64 guid
, LootType loot_type
)
7292 PermissionTypes permission
= ALL_PERMISSION
;
7294 sLog
.outDebug("Player::SendLoot");
7295 if (IS_GAMEOBJECT_GUID(guid
))
7297 sLog
.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7299 ObjectAccessor::GetGameObject(*this, guid
);
7301 // not check distance for GO in case owned GO (fishing bobber case, for example)
7302 // And permit out of range GO with no owner in case fishing hole
7303 if (!go
|| (loot_type
!= LOOT_FISHINGHOLE
&& (loot_type
!= LOOT_FISHING
|| go
->GetOwnerGUID() != GetGUID()) && !go
->IsWithinDistInMap(this,INTERACTION_DISTANCE
)))
7305 SendLootRelease(guid
);
7311 if(go
->getLootState() == GO_READY
)
7313 uint32 lootid
= go
->GetLootId();
7317 sLog
.outDebug(" if(lootid)");
7319 loot
->FillLoot(lootid
, LootTemplates_Gameobject
, this);
7322 if(loot_type
== LOOT_FISHING
)
7323 go
->getFishLoot(loot
);
7325 go
->SetLootState(GO_ACTIVATED
);
7328 else if (IS_ITEM_GUID(guid
))
7330 Item
*item
= GetItemByGuid( guid
);
7334 SendLootRelease(guid
);
7338 if(loot_type
== LOOT_DISENCHANTING
)
7342 if(!item
->m_lootGenerated
)
7344 item
->m_lootGenerated
= true;
7346 loot
->FillLoot(item
->GetProto()->DisenchantID
, LootTemplates_Disenchant
, this);
7349 else if(loot_type
== LOOT_PROSPECTING
)
7353 if(!item
->m_lootGenerated
)
7355 item
->m_lootGenerated
= true;
7357 loot
->FillLoot(item
->GetEntry(), LootTemplates_Prospecting
, this);
7360 else if(loot_type
== LOOT_MILLING
)
7364 if(!item
->m_lootGenerated
)
7366 item
->m_lootGenerated
= true;
7368 loot
->FillLoot(item
->GetEntry(), LootTemplates_Milling
, this);
7375 if(!item
->m_lootGenerated
)
7377 item
->m_lootGenerated
= true;
7379 loot
->FillLoot(item
->GetEntry(), LootTemplates_Item
, this);
7381 loot
->generateMoneyLoot(item
->GetProto()->MinMoneyLoot
,item
->GetProto()->MaxMoneyLoot
);
7385 else if (IS_CORPSE_GUID(guid
)) // remove insignia
7387 Corpse
*bones
= ObjectAccessor::GetCorpse(*this, guid
);
7389 if (!bones
|| !((loot_type
== LOOT_CORPSE
) || (loot_type
== LOOT_INSIGNIA
)) || (bones
->GetType() != CORPSE_BONES
) )
7391 SendLootRelease(guid
);
7395 loot
= &bones
->loot
;
7397 if (!bones
->lootForBody
)
7399 bones
->lootForBody
= true;
7400 uint32 pLevel
= bones
->loot
.gold
;
7401 bones
->loot
.clear();
7402 // It may need a better formula
7403 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7404 bones
->loot
.gold
= (uint32
)( urand(50, 150) * 0.016f
* pow( ((float)pLevel
)/5.76f
, 2.5f
) * sWorld
.getRate(RATE_DROP_MONEY
) );
7407 if (bones
->lootRecipient
!= this)
7408 permission
= NONE_PERMISSION
;
7412 Creature
*creature
= ObjectAccessor::GetCreature(*this, guid
);
7414 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7415 if (!creature
|| creature
->isAlive()!=(loot_type
== LOOT_PICKPOCKETING
) || !creature
->IsWithinDistInMap(this,INTERACTION_DISTANCE
))
7417 SendLootRelease(guid
);
7421 if(loot_type
== LOOT_PICKPOCKETING
&& IsFriendlyTo(creature
))
7423 SendLootRelease(guid
);
7427 loot
= &creature
->loot
;
7429 if(loot_type
== LOOT_PICKPOCKETING
)
7431 if ( !creature
->lootForPickPocketed
)
7433 creature
->lootForPickPocketed
= true;
7436 if (uint32 lootid
= creature
->GetCreatureInfo()->pickpocketLootId
)
7437 loot
->FillLoot(lootid
, LootTemplates_Pickpocketing
, this);
7439 // Generate extra money for pick pocket loot
7440 const uint32 a
= urand(0, creature
->getLevel()/2);
7441 const uint32 b
= urand(0, getLevel()/2);
7442 loot
->gold
= uint32(10 * (a
+ b
) * sWorld
.getRate(RATE_DROP_MONEY
));
7447 // the player whose group may loot the corpse
7448 Player
*recipient
= creature
->GetLootRecipient();
7451 creature
->SetLootRecipient(this);
7455 if (creature
->lootForPickPocketed
)
7457 creature
->lootForPickPocketed
= false;
7461 if(!creature
->lootForBody
)
7463 creature
->lootForBody
= true;
7466 if (uint32 lootid
= creature
->GetCreatureInfo()->lootid
)
7467 loot
->FillLoot(lootid
, LootTemplates_Creature
, recipient
);
7469 loot
->generateMoneyLoot(creature
->GetCreatureInfo()->mingold
,creature
->GetCreatureInfo()->maxgold
);
7471 if(Group
* group
= recipient
->GetGroup())
7473 group
->UpdateLooterGuid(creature
,true);
7475 switch (group
->GetLootMethod())
7478 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7479 group
->GroupLoot(recipient
->GetGUID(), loot
, creature
);
7481 case NEED_BEFORE_GREED
:
7482 group
->NeedBeforeGreed(recipient
->GetGUID(), loot
, creature
);
7485 group
->MasterLoot(recipient
->GetGUID(), loot
, creature
);
7493 // possible only if creature->lootForBody && loot->empty() at spell cast check
7494 if (loot_type
== LOOT_SKINNING
)
7497 loot
->FillLoot(creature
->GetCreatureInfo()->SkinLootId
, LootTemplates_Skinning
, this);
7499 // set group rights only for loot_type != LOOT_SKINNING
7502 if(Group
* group
= GetGroup())
7504 if( group
== recipient
->GetGroup() )
7506 if(group
->GetLootMethod() == FREE_FOR_ALL
)
7507 permission
= ALL_PERMISSION
;
7508 else if(group
->GetLooterGuid() == GetGUID())
7510 if(group
->GetLootMethod() == MASTER_LOOT
)
7511 permission
= MASTER_PERMISSION
;
7513 permission
= ALL_PERMISSION
;
7516 permission
= GROUP_PERMISSION
;
7519 permission
= NONE_PERMISSION
;
7521 else if(recipient
== this)
7522 permission
= ALL_PERMISSION
;
7524 permission
= NONE_PERMISSION
;
7531 QuestItemList
*q_list
= 0;
7532 if (permission
!= NONE_PERMISSION
)
7534 QuestItemMap
const& lootPlayerQuestItems
= loot
->GetPlayerQuestItems();
7535 QuestItemMap::const_iterator itr
= lootPlayerQuestItems
.find(GetGUIDLow());
7536 if (itr
== lootPlayerQuestItems
.end())
7537 q_list
= loot
->FillQuestLoot(this);
7539 q_list
= itr
->second
;
7542 QuestItemList
*ffa_list
= 0;
7543 if (permission
!= NONE_PERMISSION
)
7545 QuestItemMap
const& lootPlayerFFAItems
= loot
->GetPlayerFFAItems();
7546 QuestItemMap::const_iterator itr
= lootPlayerFFAItems
.find(GetGUIDLow());
7547 if (itr
== lootPlayerFFAItems
.end())
7548 ffa_list
= loot
->FillFFALoot(this);
7550 ffa_list
= itr
->second
;
7553 QuestItemList
*conditional_list
= 0;
7554 if (permission
!= NONE_PERMISSION
)
7556 QuestItemMap
const& lootPlayerNonQuestNonFFAConditionalItems
= loot
->GetPlayerNonQuestNonFFAConditionalItems();
7557 QuestItemMap::const_iterator itr
= lootPlayerNonQuestNonFFAConditionalItems
.find(GetGUIDLow());
7558 if (itr
== lootPlayerNonQuestNonFFAConditionalItems
.end())
7559 conditional_list
= loot
->FillNonQuestNonFFAConditionalLoot(this);
7561 conditional_list
= itr
->second
;
7564 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING, LOOT_INSIGNIA and LOOT_MILLING unsupported by client, sending LOOT_SKINNING instead
7565 if(loot_type
== LOOT_PICKPOCKETING
|| loot_type
== LOOT_DISENCHANTING
|| loot_type
== LOOT_PROSPECTING
|| loot_type
== LOOT_INSIGNIA
|| loot_type
== LOOT_MILLING
)
7566 loot_type
= LOOT_SKINNING
;
7568 if(loot_type
== LOOT_FISHINGHOLE
)
7569 loot_type
= LOOT_FISHING
;
7571 WorldPacket
data(SMSG_LOOT_RESPONSE
, (9+50)); // we guess size
7573 data
<< uint64(guid
);
7574 data
<< uint8(loot_type
);
7575 data
<< LootView(*loot
, q_list
, ffa_list
, conditional_list
, this, permission
);
7577 SendDirectMessage(&data
);
7579 // add 'this' player as one of the players that are looting 'loot'
7580 if (permission
!= NONE_PERMISSION
)
7581 loot
->AddLooter(GetGUID());
7583 if ( loot_type
== LOOT_CORPSE
&& !IS_ITEM_GUID(guid
) )
7584 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_LOOTING
);
7587 void Player::SendNotifyLootMoneyRemoved()
7589 WorldPacket
data(SMSG_LOOT_CLEAR_MONEY
, 0);
7590 GetSession()->SendPacket( &data
);
7593 void Player::SendNotifyLootItemRemoved(uint8 lootSlot
)
7595 WorldPacket
data(SMSG_LOOT_REMOVED
, 1);
7596 data
<< uint8(lootSlot
);
7597 GetSession()->SendPacket( &data
);
7600 void Player::SendUpdateWorldState(uint32 Field
, uint32 Value
)
7602 WorldPacket
data(SMSG_UPDATE_WORLD_STATE
, 8);
7605 GetSession()->SendPacket(&data
);
7608 void Player::SendInitWorldStates()
7610 // data depends on zoneid/mapid...
7611 BattleGround
* bg
= GetBattleGround();
7612 uint16 NumberOfFields
= 0;
7613 uint32 mapid
= GetMapId();
7614 uint32 zoneid
= GetZoneId();
7615 uint32 areaid
= GetAreaId();
7616 sLog
.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid
, zoneid
);
7617 // may be exist better way to do this...
7640 NumberOfFields
= 41;
7643 NumberOfFields
= 15;
7646 NumberOfFields
= 83;
7649 NumberOfFields
= 16;
7653 NumberOfFields
= 40;
7656 NumberOfFields
= 27;
7659 NumberOfFields
= 39;
7662 NumberOfFields
= 38;
7665 NumberOfFields
= 37;
7670 NumberOfFields
= 11;
7673 NumberOfFields
= 11;
7676 NumberOfFields
= 12;
7680 WorldPacket
data(SMSG_INIT_WORLD_STATES
, (4+4+4+2+(NumberOfFields
*8)));
7681 data
<< uint32(mapid
); // mapid
7682 data
<< uint32(zoneid
); // zone id
7683 data
<< uint32(areaid
); // area id, new 2.1.0
7684 data
<< uint16(NumberOfFields
); // count of uint64 blocks
7685 data
<< uint32(0x8d8) << uint32(0x0); // 1
7686 data
<< uint32(0x8d7) << uint32(0x0); // 2
7687 data
<< uint32(0x8d6) << uint32(0x0); // 3
7688 data
<< uint32(0x8d5) << uint32(0x0); // 4
7689 data
<< uint32(0x8d4) << uint32(0x0); // 5
7690 data
<< uint32(0x8d3) << uint32(0x0); // 6
7691 // 7 1 - Arena season in progress, 0 - end of season
7692 data
<< uint32(0xC77) << uint32(sWorld
.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS
));
7693 // 8 Arena season id
7694 data
<< uint32(0xF3D) << uint32(sWorld
.getConfig(CONFIG_ARENA_SEASON_ID
));
7695 if(mapid
== 530) // Outland
7697 data
<< uint32(0x9bf) << uint32(0x0); // 7
7698 data
<< uint32(0x9bd) << uint32(0xF); // 8
7699 data
<< uint32(0x9bb) << uint32(0xF); // 9
7714 data
<< uint32(0x7ae) << uint32(0x1); // 7
7715 data
<< uint32(0x532) << uint32(0x1); // 8
7716 data
<< uint32(0x531) << uint32(0x0); // 9
7717 data
<< uint32(0x52e) << uint32(0x0); // 10
7718 data
<< uint32(0x571) << uint32(0x0); // 11
7719 data
<< uint32(0x570) << uint32(0x0); // 12
7720 data
<< uint32(0x567) << uint32(0x1); // 13
7721 data
<< uint32(0x566) << uint32(0x1); // 14
7722 data
<< uint32(0x550) << uint32(0x1); // 15
7723 data
<< uint32(0x544) << uint32(0x0); // 16
7724 data
<< uint32(0x536) << uint32(0x0); // 17
7725 data
<< uint32(0x535) << uint32(0x1); // 18
7726 data
<< uint32(0x518) << uint32(0x0); // 19
7727 data
<< uint32(0x517) << uint32(0x0); // 20
7728 data
<< uint32(0x574) << uint32(0x0); // 21
7729 data
<< uint32(0x573) << uint32(0x0); // 22
7730 data
<< uint32(0x572) << uint32(0x0); // 23
7731 data
<< uint32(0x56f) << uint32(0x0); // 24
7732 data
<< uint32(0x56e) << uint32(0x0); // 25
7733 data
<< uint32(0x56d) << uint32(0x0); // 26
7734 data
<< uint32(0x56c) << uint32(0x0); // 27
7735 data
<< uint32(0x56b) << uint32(0x0); // 28
7736 data
<< uint32(0x56a) << uint32(0x1); // 29
7737 data
<< uint32(0x569) << uint32(0x1); // 30
7738 data
<< uint32(0x568) << uint32(0x1); // 13
7739 data
<< uint32(0x565) << uint32(0x0); // 32
7740 data
<< uint32(0x564) << uint32(0x0); // 33
7741 data
<< uint32(0x563) << uint32(0x0); // 34
7742 data
<< uint32(0x562) << uint32(0x0); // 35
7743 data
<< uint32(0x561) << uint32(0x0); // 36
7744 data
<< uint32(0x560) << uint32(0x0); // 37
7745 data
<< uint32(0x55f) << uint32(0x0); // 38
7746 data
<< uint32(0x55e) << uint32(0x0); // 39
7747 data
<< uint32(0x55d) << uint32(0x0); // 40
7748 data
<< uint32(0x3c6) << uint32(0x4); // 41
7749 data
<< uint32(0x3c4) << uint32(0x6); // 42
7750 data
<< uint32(0x3c2) << uint32(0x4); // 43
7751 data
<< uint32(0x516) << uint32(0x1); // 44
7752 data
<< uint32(0x515) << uint32(0x0); // 45
7753 data
<< uint32(0x3b6) << uint32(0x6); // 46
7754 data
<< uint32(0x55c) << uint32(0x0); // 47
7755 data
<< uint32(0x55b) << uint32(0x0); // 48
7756 data
<< uint32(0x55a) << uint32(0x0); // 49
7757 data
<< uint32(0x559) << uint32(0x0); // 50
7758 data
<< uint32(0x558) << uint32(0x0); // 51
7759 data
<< uint32(0x557) << uint32(0x0); // 52
7760 data
<< uint32(0x556) << uint32(0x0); // 53
7761 data
<< uint32(0x555) << uint32(0x0); // 54
7762 data
<< uint32(0x554) << uint32(0x1); // 55
7763 data
<< uint32(0x553) << uint32(0x1); // 56
7764 data
<< uint32(0x552) << uint32(0x1); // 57
7765 data
<< uint32(0x551) << uint32(0x1); // 58
7766 data
<< uint32(0x54f) << uint32(0x0); // 59
7767 data
<< uint32(0x54e) << uint32(0x0); // 60
7768 data
<< uint32(0x54d) << uint32(0x1); // 61
7769 data
<< uint32(0x54c) << uint32(0x0); // 62
7770 data
<< uint32(0x54b) << uint32(0x0); // 63
7771 data
<< uint32(0x545) << uint32(0x0); // 64
7772 data
<< uint32(0x543) << uint32(0x1); // 65
7773 data
<< uint32(0x542) << uint32(0x0); // 66
7774 data
<< uint32(0x540) << uint32(0x0); // 67
7775 data
<< uint32(0x53f) << uint32(0x0); // 68
7776 data
<< uint32(0x53e) << uint32(0x0); // 69
7777 data
<< uint32(0x53d) << uint32(0x0); // 70
7778 data
<< uint32(0x53c) << uint32(0x0); // 71
7779 data
<< uint32(0x53b) << uint32(0x0); // 72
7780 data
<< uint32(0x53a) << uint32(0x1); // 73
7781 data
<< uint32(0x539) << uint32(0x0); // 74
7782 data
<< uint32(0x538) << uint32(0x0); // 75
7783 data
<< uint32(0x537) << uint32(0x0); // 76
7784 data
<< uint32(0x534) << uint32(0x0); // 77
7785 data
<< uint32(0x533) << uint32(0x0); // 78
7786 data
<< uint32(0x530) << uint32(0x0); // 79
7787 data
<< uint32(0x52f) << uint32(0x0); // 80
7788 data
<< uint32(0x52d) << uint32(0x1); // 81
7791 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_WS
)
7792 bg
->FillInitialWorldStates(data
);
7795 data
<< uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7796 data
<< uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7797 data
<< uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7798 data
<< uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7799 data
<< uint32(0x60b) << uint32(0x2); // 11 1547 unk
7800 data
<< uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7801 data
<< uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7802 data
<< uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7806 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_AB
)
7807 bg
->FillInitialWorldStates(data
);
7810 data
<< uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7811 data
<< uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7812 data
<< uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7813 data
<< uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7814 data
<< uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7815 data
<< uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7816 data
<< uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7817 data
<< uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7818 data
<< uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7819 data
<< uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7820 data
<< uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7821 data
<< uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7822 data
<< uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7823 data
<< uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7824 data
<< uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7825 data
<< uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7826 data
<< uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7827 data
<< uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7828 data
<< uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7829 data
<< uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7830 data
<< uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7831 data
<< uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7832 data
<< uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7833 data
<< uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7834 data
<< uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7835 data
<< uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7836 data
<< uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7837 data
<< uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7838 data
<< uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7839 data
<< uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7840 data
<< uint32(0x745) << uint32(0x2); // 37 1861 unk
7841 data
<< uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7845 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_EY
)
7846 bg
->FillInitialWorldStates(data
);
7849 data
<< uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7850 data
<< uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7851 data
<< uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7852 data
<< uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7853 data
<< uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7854 data
<< uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7855 data
<< uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7856 data
<< uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7857 data
<< uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7858 data
<< uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7859 data
<< uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7860 data
<< uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7861 data
<< uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7862 data
<< uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7863 data
<< uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7864 data
<< uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7865 data
<< uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7866 data
<< uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7867 data
<< uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7868 data
<< uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7869 data
<< uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7870 data
<< uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7871 data
<< uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7872 data
<< uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7873 data
<< uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7874 data
<< uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7875 data
<< uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7876 data
<< uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7877 data
<< uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7878 data
<< uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7879 data
<< uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7880 data
<< uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7881 // and some more ... unknown
7884 case 3483: // Hellfire Peninsula
7885 data
<< uint32(0x9ba) << uint32(0x1); // 10
7886 data
<< uint32(0x9b9) << uint32(0x1); // 11
7887 data
<< uint32(0x9b5) << uint32(0x0); // 12
7888 data
<< uint32(0x9b4) << uint32(0x1); // 13
7889 data
<< uint32(0x9b3) << uint32(0x0); // 14
7890 data
<< uint32(0x9b2) << uint32(0x0); // 15
7891 data
<< uint32(0x9b1) << uint32(0x1); // 16
7892 data
<< uint32(0x9b0) << uint32(0x0); // 17
7893 data
<< uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7894 data
<< uint32(0x9ac) << uint32(0x0); // 19
7895 data
<< uint32(0x9a8) << uint32(0x0); // 20
7896 data
<< uint32(0x9a7) << uint32(0x0); // 21
7897 data
<< uint32(0x9a6) << uint32(0x1); // 22
7899 case 3519: // Terokkar Forest
7900 data
<< uint32(0xa41) << uint32(0x0); // 10
7901 data
<< uint32(0xa40) << uint32(0x14); // 11
7902 data
<< uint32(0xa3f) << uint32(0x0); // 12
7903 data
<< uint32(0xa3e) << uint32(0x0); // 13
7904 data
<< uint32(0xa3d) << uint32(0x5); // 14
7905 data
<< uint32(0xa3c) << uint32(0x0); // 15
7906 data
<< uint32(0xa87) << uint32(0x0); // 16
7907 data
<< uint32(0xa86) << uint32(0x0); // 17
7908 data
<< uint32(0xa85) << uint32(0x0); // 18
7909 data
<< uint32(0xa84) << uint32(0x0); // 19
7910 data
<< uint32(0xa83) << uint32(0x0); // 20
7911 data
<< uint32(0xa82) << uint32(0x0); // 21
7912 data
<< uint32(0xa81) << uint32(0x0); // 22
7913 data
<< uint32(0xa80) << uint32(0x0); // 23
7914 data
<< uint32(0xa7e) << uint32(0x0); // 24
7915 data
<< uint32(0xa7d) << uint32(0x0); // 25
7916 data
<< uint32(0xa7c) << uint32(0x0); // 26
7917 data
<< uint32(0xa7b) << uint32(0x0); // 27
7918 data
<< uint32(0xa7a) << uint32(0x0); // 28
7919 data
<< uint32(0xa79) << uint32(0x0); // 29
7920 data
<< uint32(0x9d0) << uint32(0x5); // 30
7921 data
<< uint32(0x9ce) << uint32(0x0); // 31
7922 data
<< uint32(0x9cd) << uint32(0x0); // 32
7923 data
<< uint32(0x9cc) << uint32(0x0); // 33
7924 data
<< uint32(0xa88) << uint32(0x0); // 34
7925 data
<< uint32(0xad0) << uint32(0x0); // 35
7926 data
<< uint32(0xacf) << uint32(0x1); // 36
7928 case 3521: // Zangarmarsh
7929 data
<< uint32(0x9e1) << uint32(0x0); // 10
7930 data
<< uint32(0x9e0) << uint32(0x0); // 11
7931 data
<< uint32(0x9df) << uint32(0x0); // 12
7932 data
<< uint32(0xa5d) << uint32(0x1); // 13
7933 data
<< uint32(0xa5c) << uint32(0x0); // 14
7934 data
<< uint32(0xa5b) << uint32(0x1); // 15
7935 data
<< uint32(0xa5a) << uint32(0x0); // 16
7936 data
<< uint32(0xa59) << uint32(0x1); // 17
7937 data
<< uint32(0xa58) << uint32(0x0); // 18
7938 data
<< uint32(0xa57) << uint32(0x0); // 19
7939 data
<< uint32(0xa56) << uint32(0x0); // 20
7940 data
<< uint32(0xa55) << uint32(0x1); // 21
7941 data
<< uint32(0xa54) << uint32(0x0); // 22
7942 data
<< uint32(0x9e7) << uint32(0x0); // 23
7943 data
<< uint32(0x9e6) << uint32(0x0); // 24
7944 data
<< uint32(0x9e5) << uint32(0x0); // 25
7945 data
<< uint32(0xa00) << uint32(0x0); // 26
7946 data
<< uint32(0x9ff) << uint32(0x1); // 27
7947 data
<< uint32(0x9fe) << uint32(0x0); // 28
7948 data
<< uint32(0x9fd) << uint32(0x0); // 29
7949 data
<< uint32(0x9fc) << uint32(0x1); // 30
7950 data
<< uint32(0x9fb) << uint32(0x0); // 31
7951 data
<< uint32(0xa62) << uint32(0x0); // 32
7952 data
<< uint32(0xa61) << uint32(0x1); // 33
7953 data
<< uint32(0xa60) << uint32(0x1); // 34
7954 data
<< uint32(0xa5f) << uint32(0x0); // 35
7956 case 3698: // Nagrand Arena
7957 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_NA
)
7958 bg
->FillInitialWorldStates(data
);
7961 data
<< uint32(0xa0f) << uint32(0x0); // 7
7962 data
<< uint32(0xa10) << uint32(0x0); // 8
7963 data
<< uint32(0xa11) << uint32(0x0); // 9 show
7966 case 3702: // Blade's Edge Arena
7967 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_BE
)
7968 bg
->FillInitialWorldStates(data
);
7971 data
<< uint32(0x9f0) << uint32(0x0); // 7 gold
7972 data
<< uint32(0x9f1) << uint32(0x0); // 8 green
7973 data
<< uint32(0x9f3) << uint32(0x0); // 9 show
7976 case 3968: // Ruins of Lordaeron
7977 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_RL
)
7978 bg
->FillInitialWorldStates(data
);
7981 data
<< uint32(0xbb8) << uint32(0x0); // 7 gold
7982 data
<< uint32(0xbb9) << uint32(0x0); // 8 green
7983 data
<< uint32(0xbba) << uint32(0x0); // 9 show
7986 case 3703: // Shattrath City
7989 data
<< uint32(0x914) << uint32(0x0); // 7
7990 data
<< uint32(0x913) << uint32(0x0); // 8
7991 data
<< uint32(0x912) << uint32(0x0); // 9
7992 data
<< uint32(0x915) << uint32(0x0); // 10
7995 GetSession()->SendPacket(&data
);
7998 uint32
Player::GetXPRestBonus(uint32 xp
)
8000 uint32 rested_bonus
= (uint32
)GetRestBonus(); // xp for each rested bonus
8002 if(rested_bonus
> xp
) // max rested_bonus == xp or (r+x) = 200% xp
8005 SetRestBonus( GetRestBonus() - rested_bonus
);
8007 sLog
.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp
+rested_bonus
,rested_bonus
,GetRestBonus());
8008 return rested_bonus
;
8011 void Player::SetBindPoint(uint64 guid
)
8013 WorldPacket
data(SMSG_BINDER_CONFIRM
, 8);
8014 data
<< uint64(guid
);
8015 GetSession()->SendPacket( &data
);
8018 void Player::SendTalentWipeConfirm(uint64 guid
)
8020 WorldPacket
data(MSG_TALENT_WIPE_CONFIRM
, (8+4));
8021 data
<< uint64(guid
);
8022 data
<< uint32(resetTalentsCost());
8023 GetSession()->SendPacket( &data
);
8026 void Player::SendPetSkillWipeConfirm()
8028 Pet
* pet
= GetPet();
8031 WorldPacket
data(SMSG_PET_UNLEARN_CONFIRM
, (8+4));
8032 data
<< pet
->GetGUID();
8033 data
<< uint32(pet
->resetTalentsCost());
8034 GetSession()->SendPacket( &data
);
8037 /*********************************************************/
8038 /*** STORAGE SYSTEM ***/
8039 /*********************************************************/
8041 void Player::SetVirtualItemSlot( uint8 i
, Item
* item
)
8046 if(!item
->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT
))
8048 uint32 charges
= item
->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
);
8052 item
->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
,charges
-1);
8053 else if(charges
<= 1)
8055 ApplyEnchantment(item
,TEMP_ENCHANTMENT_SLOT
,false);
8056 item
->ClearEnchantment(TEMP_ENCHANTMENT_SLOT
);
8061 void Player::SetSheath( uint32 sheathed
)
8065 case SHEATH_STATE_UNARMED
: // no prepared weapon
8066 SetVirtualItemSlot(0,NULL
);
8067 SetVirtualItemSlot(1,NULL
);
8068 SetVirtualItemSlot(2,NULL
);
8070 case SHEATH_STATE_MELEE
: // prepared melee weapon
8072 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK
,true));
8073 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK
,true));
8074 SetVirtualItemSlot(2,NULL
);
8076 case SHEATH_STATE_RANGED
: // prepared ranged weapon
8077 SetVirtualItemSlot(0,NULL
);
8078 SetVirtualItemSlot(1,NULL
);
8079 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK
,true));
8082 SetVirtualItemSlot(0,NULL
);
8083 SetVirtualItemSlot(1,NULL
);
8084 SetVirtualItemSlot(2,NULL
);
8087 SetByteValue(UNIT_FIELD_BYTES_2
, 0, sheathed
); // this must visualize Sheath changing for other players...
8090 uint8
Player::FindEquipSlot( ItemPrototype
const* proto
, uint32 slot
, bool swap
) const
8092 uint8 pClass
= getClass();
8095 slots
[0] = NULL_SLOT
;
8096 slots
[1] = NULL_SLOT
;
8097 slots
[2] = NULL_SLOT
;
8098 slots
[3] = NULL_SLOT
;
8099 switch( proto
->InventoryType
)
8102 slots
[0] = EQUIPMENT_SLOT_HEAD
;
8105 slots
[0] = EQUIPMENT_SLOT_NECK
;
8107 case INVTYPE_SHOULDERS
:
8108 slots
[0] = EQUIPMENT_SLOT_SHOULDERS
;
8111 slots
[0] = EQUIPMENT_SLOT_BODY
;
8114 slots
[0] = EQUIPMENT_SLOT_CHEST
;
8117 slots
[0] = EQUIPMENT_SLOT_CHEST
;
8120 slots
[0] = EQUIPMENT_SLOT_WAIST
;
8123 slots
[0] = EQUIPMENT_SLOT_LEGS
;
8126 slots
[0] = EQUIPMENT_SLOT_FEET
;
8128 case INVTYPE_WRISTS
:
8129 slots
[0] = EQUIPMENT_SLOT_WRISTS
;
8132 slots
[0] = EQUIPMENT_SLOT_HANDS
;
8134 case INVTYPE_FINGER
:
8135 slots
[0] = EQUIPMENT_SLOT_FINGER1
;
8136 slots
[1] = EQUIPMENT_SLOT_FINGER2
;
8138 case INVTYPE_TRINKET
:
8139 slots
[0] = EQUIPMENT_SLOT_TRINKET1
;
8140 slots
[1] = EQUIPMENT_SLOT_TRINKET2
;
8143 slots
[0] = EQUIPMENT_SLOT_BACK
;
8145 case INVTYPE_WEAPON
:
8147 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8149 // suggest offhand slot only if know dual wielding
8150 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
8152 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
8155 case INVTYPE_SHIELD
:
8156 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8158 case INVTYPE_RANGED
:
8159 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8161 case INVTYPE_2HWEAPON
:
8162 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8163 if (CanDualWield() && CanTitanGrip())
8164 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
8166 case INVTYPE_TABARD
:
8167 slots
[0] = EQUIPMENT_SLOT_TABARD
;
8169 case INVTYPE_WEAPONMAINHAND
:
8170 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
8172 case INVTYPE_WEAPONOFFHAND
:
8173 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8175 case INVTYPE_HOLDABLE
:
8176 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
8178 case INVTYPE_THROWN
:
8179 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8181 case INVTYPE_RANGEDRIGHT
:
8182 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8185 slots
[0] = INVENTORY_SLOT_BAG_1
;
8186 slots
[1] = INVENTORY_SLOT_BAG_2
;
8187 slots
[2] = INVENTORY_SLOT_BAG_3
;
8188 slots
[3] = INVENTORY_SLOT_BAG_4
;
8192 switch(proto
->SubClass
)
8194 case ITEM_SUBCLASS_ARMOR_LIBRAM
:
8195 if (pClass
== CLASS_PALADIN
)
8196 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8198 case ITEM_SUBCLASS_ARMOR_IDOL
:
8199 if (pClass
== CLASS_DRUID
)
8200 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8202 case ITEM_SUBCLASS_ARMOR_TOTEM
:
8203 if (pClass
== CLASS_SHAMAN
)
8204 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8206 case ITEM_SUBCLASS_ARMOR_MISC
:
8207 if (pClass
== CLASS_WARLOCK
)
8208 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8210 case ITEM_SUBCLASS_ARMOR_SIGIL
:
8211 if (pClass
== CLASS_DEATH_KNIGHT
)
8212 slots
[0] = EQUIPMENT_SLOT_RANGED
;
8221 if( slot
!= NULL_SLOT
)
8223 if( swap
|| !GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
) )
8225 for (int i
= 0; i
< 4; i
++)
8227 if ( slots
[i
] == slot
)
8234 // search free slot at first
8235 for (int i
= 0; i
< 4; i
++)
8237 if ( slots
[i
] != NULL_SLOT
&& !GetItemByPos( INVENTORY_SLOT_BAG_0
, slots
[i
] ) )
8239 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
8240 if(slots
[i
]!=EQUIPMENT_SLOT_OFFHAND
|| !IsTwoHandUsed())
8245 // if not found free and can swap return first appropriate from used
8246 for (int i
= 0; i
< 4; i
++)
8248 if ( slots
[i
] != NULL_SLOT
&& swap
)
8257 uint8
Player::CanUnequipItems( uint32 item
, uint32 count
) const
8260 uint32 tempcount
= 0;
8262 uint8 res
= EQUIP_ERR_OK
;
8264 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8266 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8267 if( pItem
&& pItem
->GetEntry() == item
)
8269 uint8 ires
= CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
, false);
8270 if(ires
==EQUIP_ERR_OK
)
8272 tempcount
+= pItem
->GetCount();
8273 if( tempcount
>= count
)
8274 return EQUIP_ERR_OK
;
8280 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8282 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8283 if( pItem
&& pItem
->GetEntry() == item
)
8285 tempcount
+= pItem
->GetCount();
8286 if( tempcount
>= count
)
8287 return EQUIP_ERR_OK
;
8290 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8292 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8293 if( pItem
&& pItem
->GetEntry() == item
)
8295 tempcount
+= pItem
->GetCount();
8296 if( tempcount
>= count
)
8297 return EQUIP_ERR_OK
;
8301 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8303 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8306 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8308 pItem
= GetItemByPos( i
, j
);
8309 if( pItem
&& pItem
->GetEntry() == item
)
8311 tempcount
+= pItem
->GetCount();
8312 if( tempcount
>= count
)
8313 return EQUIP_ERR_OK
;
8319 // not found req. item count and have unequippable items
8323 uint32
Player::GetItemCount( uint32 item
, bool inBankAlso
, Item
* skipItem
) const
8326 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8328 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8329 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8330 count
+= pItem
->GetCount();
8332 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8334 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8335 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8336 count
+= pItem
->GetCount();
8338 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8340 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8342 count
+= pBag
->GetItemCount(item
,skipItem
);
8345 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8347 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8349 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8350 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8351 count
+= pItem
->GetGemCountWithID(item
);
8357 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8359 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8360 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8361 count
+= pItem
->GetCount();
8363 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8365 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8367 count
+= pBag
->GetItemCount(item
,skipItem
);
8370 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8372 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8374 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8375 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8376 count
+= pItem
->GetGemCountWithID(item
);
8384 Item
* Player::GetItemByGuid( uint64 guid
) const
8386 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8388 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8389 if( pItem
&& pItem
->GetGUID() == guid
)
8392 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8394 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8395 if( pItem
&& pItem
->GetGUID() == guid
)
8399 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8401 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8404 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8406 Item
* pItem
= pBag
->GetItemByPos( j
);
8407 if( pItem
&& pItem
->GetGUID() == guid
)
8412 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8414 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8417 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8419 Item
* pItem
= pBag
->GetItemByPos( j
);
8420 if( pItem
&& pItem
->GetGUID() == guid
)
8429 Item
* Player::GetItemByPos( uint16 pos
) const
8431 uint8 bag
= pos
>> 8;
8432 uint8 slot
= pos
& 255;
8433 return GetItemByPos( bag
, slot
);
8436 Item
* Player::GetItemByPos( uint8 bag
, uint8 slot
) const
8438 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< BANK_SLOT_BAG_END
|| slot
>= KEYRING_SLOT_START
&& slot
< QUESTBAG_SLOT_END
) )
8439 return m_items
[slot
];
8440 else if(bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
8441 || bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8443 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8445 return pBag
->GetItemByPos(slot
);
8450 Item
* Player::GetWeaponForAttack(WeaponAttackType attackType
, bool useable
) const
8455 case BASE_ATTACK
: slot
= EQUIPMENT_SLOT_MAINHAND
; break;
8456 case OFF_ATTACK
: slot
= EQUIPMENT_SLOT_OFFHAND
; break;
8457 case RANGED_ATTACK
: slot
= EQUIPMENT_SLOT_RANGED
; break;
8458 default: return NULL
;
8461 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, slot
);
8462 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_WEAPON
)
8468 if( item
->IsBroken() || !IsUseEquipedWeapon(attackType
==BASE_ATTACK
) )
8474 Item
* Player::GetShield(bool useable
) const
8476 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
8477 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_ARMOR
)
8483 if( item
->IsBroken())
8489 uint32
Player::GetAttackBySlot( uint8 slot
)
8493 case EQUIPMENT_SLOT_MAINHAND
: return BASE_ATTACK
;
8494 case EQUIPMENT_SLOT_OFFHAND
: return OFF_ATTACK
;
8495 case EQUIPMENT_SLOT_RANGED
: return RANGED_ATTACK
;
8496 default: return MAX_ATTACK
;
8500 bool Player::HasBankBagSlot( uint8 slot
) const
8502 uint32 maxslot
= GetByteValue(PLAYER_BYTES_2
, 2) + BANK_SLOT_BAG_START
;
8503 if( slot
< maxslot
)
8508 bool Player::IsInventoryPos( uint8 bag
, uint8 slot
)
8510 if( bag
== INVENTORY_SLOT_BAG_0
&& slot
== NULL_SLOT
)
8512 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
) )
8514 if( bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8516 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= KEYRING_SLOT_START
&& slot
< QUESTBAG_SLOT_END
) )
8521 bool Player::IsEquipmentPos( uint8 bag
, uint8 slot
)
8523 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< EQUIPMENT_SLOT_END
) )
8525 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8530 bool Player::IsBankPos( uint8 bag
, uint8 slot
)
8532 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
) )
8534 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8536 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8541 bool Player::IsBagPos( uint16 pos
)
8543 uint8 bag
= pos
>> 8;
8544 uint8 slot
= pos
& 255;
8545 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8547 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8552 bool Player::IsValidPos( uint8 bag
, uint8 slot
)
8558 if (bag
== INVENTORY_SLOT_BAG_0
)
8560 // any post selected
8561 if (slot
== NULL_SLOT
)
8565 if (slot
< EQUIPMENT_SLOT_END
)
8569 if (slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
)
8573 if (slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
)
8577 if (slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_END
)
8581 if (slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
)
8585 if (slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
8591 // bag content slots
8592 if (bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8594 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8598 // any post selected
8599 if (slot
== NULL_SLOT
)
8602 return slot
< pBag
->GetBagSize();
8605 // bank bag content slots
8606 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8608 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8612 // any post selected
8613 if (slot
== NULL_SLOT
)
8616 return slot
< pBag
->GetBagSize();
8624 bool Player::HasItemCount( uint32 item
, uint32 count
, bool inBankAlso
) const
8626 uint32 tempcount
= 0;
8627 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8629 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8630 if( pItem
&& pItem
->GetEntry() == item
)
8632 tempcount
+= pItem
->GetCount();
8633 if( tempcount
>= count
)
8637 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8639 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8640 if( pItem
&& pItem
->GetEntry() == item
)
8642 tempcount
+= pItem
->GetCount();
8643 if( tempcount
>= count
)
8647 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8649 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8651 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8653 Item
* pItem
= GetItemByPos( i
, j
);
8654 if( pItem
&& pItem
->GetEntry() == item
)
8656 tempcount
+= pItem
->GetCount();
8657 if( tempcount
>= count
)
8666 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8668 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8669 if( pItem
&& pItem
->GetEntry() == item
)
8671 tempcount
+= pItem
->GetCount();
8672 if( tempcount
>= count
)
8676 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8678 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8680 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8682 Item
* pItem
= GetItemByPos( i
, j
);
8683 if( pItem
&& pItem
->GetEntry() == item
)
8685 tempcount
+= pItem
->GetCount();
8686 if( tempcount
>= count
)
8697 Item
* Player::GetItemOrItemWithGemEquipped( uint32 item
) const
8700 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
8702 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8703 if( pItem
&& pItem
->GetEntry() == item
)
8707 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(item
);
8708 if (pProto
&& pProto
->GemProperties
)
8710 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
8712 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8713 if( pItem
&& pItem
->GetProto()->Socket
[0].Color
)
8715 if (pItem
->GetGemCountWithID(item
) > 0 )
8724 uint8
Player::_CanTakeMoreSimilarItems(uint32 entry
, uint32 count
, Item
* pItem
, uint32
* no_space_count
) const
8726 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
8730 *no_space_count
= count
;
8731 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8735 if(pProto
->MaxCount
<= 0)
8736 return EQUIP_ERR_OK
;
8738 uint32 curcount
= GetItemCount(pProto
->ItemId
,true,pItem
);
8740 if (curcount
+ count
> uint32(pProto
->MaxCount
))
8743 *no_space_count
= count
+curcount
- pProto
->MaxCount
;
8744 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8747 return EQUIP_ERR_OK
;
8750 bool Player::HasItemTotemCategory( uint32 TotemCategory
) const
8753 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8755 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8756 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8759 for(uint8 i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
8761 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8762 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8765 for(uint8 i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8767 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8769 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8771 pItem
= GetItemByPos( i
, j
);
8772 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8780 uint8
Player::_CanStoreItem_InSpecificSlot( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, ItemPrototype
const *pProto
, uint32
& count
, bool swap
, Item
* pSrcItem
) const
8782 Item
* pItem2
= GetItemByPos( bag
, slot
);
8784 // ignore move item (this slot will be empty at move)
8785 if(pItem2
==pSrcItem
)
8790 // empty specific slot - check item fit to slot
8791 if( !pItem2
|| swap
)
8793 if( bag
== INVENTORY_SLOT_BAG_0
)
8796 if(slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_START
+GetMaxKeyringSize() && !(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
))
8797 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8799 // vanitypet case (disabled until proper implement)
8800 if(slot
>= VANITYPET_SLOT_START
&& slot
< VANITYPET_SLOT_END
&& !(false /*pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS*/))
8801 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8803 // currencytoken case (disabled until proper implement)
8804 if(slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
&& !(false /*pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS*/))
8805 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8807 // guestbag case (disabled until proper implement)
8808 if(slot
>= QUESTBAG_SLOT_START
&& slot
< QUESTBAG_SLOT_END
&& !(false /*pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS*/))
8809 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8812 if(slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
|| slot
>= PLAYER_SLOT_END
)
8813 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8817 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8819 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8821 ItemPrototype
const* pBagProto
= pBag
->GetProto();
8823 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8825 if( !ItemCanGoIntoBag(pProto
,pBagProto
) )
8826 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8829 // non empty stack with space
8830 need_space
= pProto
->GetMaxStackSize();
8832 // non empty slot, check item type
8836 if(pItem2
->GetEntry() != pProto
->ItemId
)
8837 return EQUIP_ERR_ITEM_CANT_STACK
;
8840 if(pItem2
->GetCount() >= pProto
->GetMaxStackSize())
8841 return EQUIP_ERR_ITEM_CANT_STACK
;
8843 // free stack space or infinity
8844 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
8847 if(need_space
> count
)
8850 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | slot
, need_space
);
8851 if(!newPosition
.isContainedIn(dest
))
8853 dest
.push_back(newPosition
);
8854 count
-= need_space
;
8856 return EQUIP_ERR_OK
;
8859 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
8861 // skip specific bag already processed in first called _CanStoreItem_InBag
8863 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8865 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8867 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8869 ItemPrototype
const* pBagProto
= pBag
->GetProto();
8871 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8873 // specialized bag mode or non-specilized
8874 if( non_specialized
!= (pBagProto
->Class
== ITEM_CLASS_CONTAINER
&& pBagProto
->SubClass
== ITEM_SUBCLASS_CONTAINER
) )
8875 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8877 if( !ItemCanGoIntoBag(pProto
,pBagProto
) )
8878 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8880 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8882 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8886 Item
* pItem2
= GetItemByPos( bag
, j
);
8888 // ignore move item (this slot will be empty at move)
8889 if(pItem2
==pSrcItem
)
8892 // if merge skip empty, if !merge skip non-empty
8893 if((pItem2
!=NULL
)!=merge
)
8898 if(pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->GetMaxStackSize())
8900 uint32 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
8901 if(need_space
> count
)
8904 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
8905 if(!newPosition
.isContainedIn(dest
))
8907 dest
.push_back(newPosition
);
8908 count
-= need_space
;
8911 return EQUIP_ERR_OK
;
8917 uint32 need_space
= pProto
->GetMaxStackSize();
8918 if(need_space
> count
)
8921 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
8922 if(!newPosition
.isContainedIn(dest
))
8924 dest
.push_back(newPosition
);
8925 count
-= need_space
;
8928 return EQUIP_ERR_OK
;
8932 return EQUIP_ERR_OK
;
8935 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
8937 for(uint32 j
= slot_begin
; j
< slot_end
; j
++)
8939 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8940 if(INVENTORY_SLOT_BAG_0
==skip_bag
&& j
==skip_slot
)
8943 Item
* pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, j
);
8945 // ignore move item (this slot will be empty at move)
8946 if(pItem2
==pSrcItem
)
8949 // if merge skip empty, if !merge skip non-empty
8950 if((pItem2
!=NULL
)!=merge
)
8955 if(pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->GetMaxStackSize())
8957 uint32 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
8958 if(need_space
> count
)
8960 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
8961 if(!newPosition
.isContainedIn(dest
))
8963 dest
.push_back(newPosition
);
8964 count
-= need_space
;
8967 return EQUIP_ERR_OK
;
8973 uint32 need_space
= pProto
->GetMaxStackSize();
8974 if(need_space
> count
)
8977 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
8978 if(!newPosition
.isContainedIn(dest
))
8980 dest
.push_back(newPosition
);
8981 count
-= need_space
;
8984 return EQUIP_ERR_OK
;
8988 return EQUIP_ERR_OK
;
8991 uint8
Player::_CanStoreItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, uint32 entry
, uint32 count
, Item
*pItem
, bool swap
, uint32
* no_space_count
) const
8993 sLog
.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, entry
, count
);
8995 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
8999 *no_space_count
= count
;
9000 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
:EQUIP_ERR_ITEM_NOT_FOUND
;
9003 if(pItem
&& pItem
->IsBindedNotWith(GetGUID()))
9006 *no_space_count
= count
;
9007 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9010 // check count of items (skip for auto move for same player from bank)
9011 uint32 no_similar_count
= 0; // can't store this amount similar items
9012 uint8 res
= _CanTakeMoreSimilarItems(entry
,count
,pItem
,&no_similar_count
);
9013 if(res
!=EQUIP_ERR_OK
)
9015 if(count
==no_similar_count
)
9018 *no_space_count
= no_similar_count
;
9021 count
-= no_similar_count
;
9025 if( bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
9027 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
9028 if(res
!=EQUIP_ERR_OK
)
9031 *no_space_count
= count
+ no_similar_count
;
9037 if(no_similar_count
==0)
9038 return EQUIP_ERR_OK
;
9041 *no_space_count
= count
+ no_similar_count
;
9042 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9046 // not specific slot or have space for partly store only in specific slot
9049 if( bag
!= NULL_BAG
)
9051 // search stack in bag for merge to
9052 if( pProto
->Stackable
!= 1 )
9054 if( bag
== INVENTORY_SLOT_BAG_0
) // inventory
9056 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,QUESTBAG_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9057 if(res
!=EQUIP_ERR_OK
)
9060 *no_space_count
= count
+ no_similar_count
;
9066 if(no_similar_count
==0)
9067 return EQUIP_ERR_OK
;
9070 *no_space_count
= count
+ no_similar_count
;
9071 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9074 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9075 if(res
!=EQUIP_ERR_OK
)
9078 *no_space_count
= count
+ no_similar_count
;
9084 if(no_similar_count
==0)
9085 return EQUIP_ERR_OK
;
9088 *no_space_count
= count
+ no_similar_count
;
9089 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9092 else // equipped bag
9094 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
9095 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
9096 if(res
!=EQUIP_ERR_OK
)
9097 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
9099 if(res
!=EQUIP_ERR_OK
)
9102 *no_space_count
= count
+ no_similar_count
;
9108 if(no_similar_count
==0)
9109 return EQUIP_ERR_OK
;
9112 *no_space_count
= count
+ no_similar_count
;
9113 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9118 // search free slot in bag for place to
9119 if( bag
== INVENTORY_SLOT_BAG_0
) // inventory
9121 // search free slot - keyring case
9122 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9124 uint32 keyringSize
= GetMaxKeyringSize();
9125 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9126 if(res
!=EQUIP_ERR_OK
)
9129 *no_space_count
= count
+ no_similar_count
;
9135 if(no_similar_count
==0)
9136 return EQUIP_ERR_OK
;
9139 *no_space_count
= count
+ no_similar_count
;
9140 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9143 /* until proper implementation
9144 else if(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
9146 res = _CanStoreItem_InInventorySlots(VANITYPET_SLOT_START,VANITYPET_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9147 if(res!=EQUIP_ERR_OK)
9150 *no_space_count = count + no_similar_count;
9156 if(no_similar_count==0)
9157 return EQUIP_ERR_OK;
9160 *no_space_count = count + no_similar_count;
9161 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9165 /* until proper implementation
9166 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9168 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9169 if(res!=EQUIP_ERR_OK)
9172 *no_space_count = count + no_similar_count;
9178 if(no_similar_count==0)
9179 return EQUIP_ERR_OK;
9182 *no_space_count = count + no_similar_count;
9183 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9187 /* until proper implementation
9188 else if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9190 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9191 if(res!=EQUIP_ERR_OK)
9194 *no_space_count = count + no_similar_count;
9200 if(no_similar_count==0)
9201 return EQUIP_ERR_OK;
9204 *no_space_count = count + no_similar_count;
9205 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9210 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9211 if(res
!=EQUIP_ERR_OK
)
9214 *no_space_count
= count
+ no_similar_count
;
9220 if(no_similar_count
==0)
9221 return EQUIP_ERR_OK
;
9224 *no_space_count
= count
+ no_similar_count
;
9225 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9228 else // equipped bag
9230 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
9231 if(res
!=EQUIP_ERR_OK
)
9232 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
9234 if(res
!=EQUIP_ERR_OK
)
9237 *no_space_count
= count
+ no_similar_count
;
9243 if(no_similar_count
==0)
9244 return EQUIP_ERR_OK
;
9247 *no_space_count
= count
+ no_similar_count
;
9248 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9253 // not specific bag or have space for partly store only in specific bag
9255 // search stack for merge to
9256 if( pProto
->Stackable
!= 1 )
9258 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,QUESTBAG_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9259 if(res
!=EQUIP_ERR_OK
)
9262 *no_space_count
= count
+ no_similar_count
;
9268 if(no_similar_count
==0)
9269 return EQUIP_ERR_OK
;
9272 *no_space_count
= count
+ no_similar_count
;
9273 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9276 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9277 if(res
!=EQUIP_ERR_OK
)
9280 *no_space_count
= count
+ no_similar_count
;
9286 if(no_similar_count
==0)
9287 return EQUIP_ERR_OK
;
9290 *no_space_count
= count
+ no_similar_count
;
9291 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9294 if( pProto
->BagFamily
)
9296 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9298 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
9299 if(res
!=EQUIP_ERR_OK
)
9304 if(no_similar_count
==0)
9305 return EQUIP_ERR_OK
;
9308 *no_space_count
= count
+ no_similar_count
;
9309 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9314 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9316 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
9317 if(res
!=EQUIP_ERR_OK
)
9322 if(no_similar_count
==0)
9323 return EQUIP_ERR_OK
;
9326 *no_space_count
= count
+ no_similar_count
;
9327 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9332 // search free slot - special bag case
9333 if( pProto
->BagFamily
)
9335 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9337 uint32 keyringSize
= GetMaxKeyringSize();
9338 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9339 if(res
!=EQUIP_ERR_OK
)
9342 *no_space_count
= count
+ no_similar_count
;
9348 if(no_similar_count
==0)
9349 return EQUIP_ERR_OK
;
9352 *no_space_count
= count
+ no_similar_count
;
9353 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9356 /* until proper implementation
9357 else if(false pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
9359 res = _CanStoreItem_InInventorySlots(VANITYPET_SLOT_START,VANITYPET_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9360 if(res!=EQUIP_ERR_OK)
9363 *no_space_count = count + no_similar_count;
9369 if(no_similar_count==0)
9370 return EQUIP_ERR_OK;
9373 *no_space_count = count + no_similar_count;
9374 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9378 /* until proper implementation
9379 else if(false pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9381 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9382 if(res!=EQUIP_ERR_OK)
9385 *no_space_count = count + no_similar_count;
9391 if(no_similar_count==0)
9392 return EQUIP_ERR_OK;
9395 *no_space_count = count + no_similar_count;
9396 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9400 /* until proper implementation
9401 else if(false pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9403 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9404 if(res!=EQUIP_ERR_OK)
9407 *no_space_count = count + no_similar_count;
9413 if(no_similar_count==0)
9414 return EQUIP_ERR_OK;
9417 *no_space_count = count + no_similar_count;
9418 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9423 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9425 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
9426 if(res
!=EQUIP_ERR_OK
)
9431 if(no_similar_count
==0)
9432 return EQUIP_ERR_OK
;
9435 *no_space_count
= count
+ no_similar_count
;
9436 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9442 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9443 if(res
!=EQUIP_ERR_OK
)
9446 *no_space_count
= count
+ no_similar_count
;
9452 if(no_similar_count
==0)
9453 return EQUIP_ERR_OK
;
9456 *no_space_count
= count
+ no_similar_count
;
9457 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9460 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9462 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
9463 if(res
!=EQUIP_ERR_OK
)
9468 if(no_similar_count
==0)
9469 return EQUIP_ERR_OK
;
9472 *no_space_count
= count
+ no_similar_count
;
9473 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9478 *no_space_count
= count
+ no_similar_count
;
9480 return EQUIP_ERR_INVENTORY_FULL
;
9483 //////////////////////////////////////////////////////////////////////////
9484 uint8
Player::CanStoreItems( Item
**pItems
,int count
) const
9489 int inv_slot_items
[INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
];
9490 int inv_bags
[INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
][MAX_BAG_SIZE
];
9491 int inv_keys
[KEYRING_SLOT_END
-KEYRING_SLOT_START
];
9492 int inv_pets
[VANITYPET_SLOT_END
-VANITYPET_SLOT_START
];
9493 int inv_tokens
[CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
];
9494 int inv_quests
[QUESTBAG_SLOT_END
-QUESTBAG_SLOT_START
];
9496 memset(inv_slot_items
,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
));
9497 memset(inv_bags
,0,sizeof(int)*(INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
)*MAX_BAG_SIZE
);
9498 memset(inv_keys
,0,sizeof(int)*(KEYRING_SLOT_END
-KEYRING_SLOT_START
));
9499 memset(inv_pets
,0,sizeof(int)*(VANITYPET_SLOT_END
-VANITYPET_SLOT_START
));
9500 memset(inv_tokens
,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
));
9501 memset(inv_quests
,0,sizeof(int)*(QUESTBAG_SLOT_END
-QUESTBAG_SLOT_START
));
9503 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
9505 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9507 if (pItem2
&& !pItem2
->IsInTrade())
9509 inv_slot_items
[i
-INVENTORY_SLOT_ITEM_START
] = pItem2
->GetCount();
9513 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
9515 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9517 if (pItem2
&& !pItem2
->IsInTrade())
9519 inv_keys
[i
-KEYRING_SLOT_START
] = pItem2
->GetCount();
9523 for(int i
= VANITYPET_SLOT_START
; i
< VANITYPET_SLOT_END
; i
++)
9525 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9527 if (pItem2
&& !pItem2
->IsInTrade())
9529 inv_pets
[i
-VANITYPET_SLOT_START
] = pItem2
->GetCount();
9533 for(int i
= CURRENCYTOKEN_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; i
++)
9535 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9537 if (pItem2
&& !pItem2
->IsInTrade())
9539 inv_tokens
[i
-CURRENCYTOKEN_SLOT_START
] = pItem2
->GetCount();
9543 for(int i
= QUESTBAG_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
9545 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9547 if (pItem2
&& !pItem2
->IsInTrade())
9549 inv_quests
[i
-QUESTBAG_SLOT_START
] = pItem2
->GetCount();
9553 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9555 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
9557 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9559 pItem2
= GetItemByPos( i
, j
);
9560 if (pItem2
&& !pItem2
->IsInTrade())
9562 inv_bags
[i
-INVENTORY_SLOT_BAG_START
][j
] = pItem2
->GetCount();
9568 // check free space for all items
9569 for (int k
=0;k
<count
;k
++)
9571 Item
*pItem
= pItems
[k
];
9574 if (!pItem
) continue;
9576 sLog
.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k
+1, pItem
->GetEntry(), pItem
->GetCount());
9577 ItemPrototype
const *pProto
= pItem
->GetProto();
9581 return EQUIP_ERR_ITEM_NOT_FOUND
;
9584 if(pItem
->IsBindedNotWith(GetGUID()))
9585 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9588 ItemPrototype
const *pBagProto
;
9590 // item is 'one item only'
9591 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9592 if(res
!= EQUIP_ERR_OK
)
9595 // search stack for merge to
9596 if( pProto
->Stackable
!= 1 )
9598 bool b_found
= false;
9600 for(int t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_END
; t
++)
9602 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9603 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_keys
[t
-KEYRING_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9605 inv_keys
[t
-KEYRING_SLOT_START
] += pItem
->GetCount();
9610 if (b_found
) continue;
9612 for(int t
= VANITYPET_SLOT_START
; t
< VANITYPET_SLOT_END
; t
++)
9614 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9615 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_pets
[t
-VANITYPET_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9617 inv_pets
[t
-VANITYPET_SLOT_START
] += pItem
->GetCount();
9622 if (b_found
) continue;
9624 for(int t
= CURRENCYTOKEN_SLOT_START
; t
< CURRENCYTOKEN_SLOT_END
; t
++)
9626 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9627 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9629 inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] += pItem
->GetCount();
9634 if (b_found
) continue;
9636 for(int t
= QUESTBAG_SLOT_START
; t
< QUESTBAG_SLOT_END
; t
++)
9638 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9639 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_quests
[t
-QUESTBAG_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9641 inv_quests
[t
-QUESTBAG_SLOT_START
] += pItem
->GetCount();
9646 if (b_found
) continue;
9648 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; t
++)
9650 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9651 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9653 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] += pItem
->GetCount();
9658 if (b_found
) continue;
9660 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9662 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9665 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9667 pItem2
= GetItemByPos( t
, j
);
9668 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9670 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] += pItem
->GetCount();
9677 if (b_found
) continue;
9681 if( pProto
->BagFamily
)
9683 bool b_found
= false;
9684 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9686 uint32 keyringSize
= GetMaxKeyringSize();
9687 for(uint32 t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_START
+keyringSize
; ++t
)
9689 if( inv_keys
[t
-KEYRING_SLOT_START
] == 0 )
9691 inv_keys
[t
-KEYRING_SLOT_START
] = 1;
9698 if (b_found
) continue;
9700 /* until proper implementation
9701 if(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
9703 for(uint32 t = VANITYPET_SLOT_START; t < VANITYPET_SLOT_END; ++t)
9705 if( inv_pets[t-VANITYPET_SLOT_START] == 0 )
9707 inv_pets[t-VANITYPET_SLOT_START] = 1;
9714 if (b_found) continue;
9716 /* until proper implementation
9717 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9719 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9721 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9723 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9730 if (b_found) continue;
9732 /* until proper implementation
9733 if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9735 for(uint32 t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; ++t)
9737 if( inv_quests[t-QUESTBAG_SLOT_START] == 0 )
9739 inv_quests[t-QUESTBAG_SLOT_START] = 1;
9746 if (b_found) continue;
9749 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9751 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9754 pBagProto
= pBag
->GetProto();
9756 // not plain container check
9757 if( pBagProto
&& (pBagProto
->Class
!= ITEM_CLASS_CONTAINER
|| pBagProto
->SubClass
!= ITEM_SUBCLASS_CONTAINER
) &&
9758 ItemCanGoIntoBag(pProto
,pBagProto
) )
9760 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9762 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9764 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9772 if (b_found
) continue;
9776 bool b_found
= false;
9777 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; t
++)
9779 if( inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] == 0 )
9781 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] = 1;
9786 if (b_found
) continue;
9788 // search free slot in bags
9789 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9791 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9794 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9796 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9798 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9806 // no free slot found?
9808 return EQUIP_ERR_INVENTORY_FULL
;
9811 return EQUIP_ERR_OK
;
9814 //////////////////////////////////////////////////////////////////////////
9815 uint8
Player::CanEquipNewItem( uint8 slot
, uint16
&dest
, uint32 item
, bool swap
) const
9818 Item
*pItem
= Item::CreateItem( item
, 1, this );
9821 uint8 result
= CanEquipItem(slot
, dest
, pItem
, swap
);
9826 return EQUIP_ERR_ITEM_NOT_FOUND
;
9829 uint8
Player::CanEquipItem( uint8 slot
, uint16
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
9834 sLog
.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot
, pItem
->GetEntry(), pItem
->GetCount());
9835 ItemPrototype
const *pProto
= pItem
->GetProto();
9838 // May be here should be more stronger checks; STUNNED checked
9839 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9840 if (not_loading
&& hasUnitState(UNIT_STAT_STUNNED
))
9841 return EQUIP_ERR_YOU_ARE_STUNNED
;
9843 if(pItem
->IsBindedNotWith(GetGUID()))
9844 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9846 // check count of items (skip for auto move for same player from bank)
9847 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9848 if(res
!= EQUIP_ERR_OK
)
9851 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9853 // - in-progress arenas
9854 if( !pProto
->CanChangeEquipStateInCombat() )
9857 return EQUIP_ERR_NOT_IN_COMBAT
;
9859 if(BattleGround
* bg
= GetBattleGround())
9860 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
9861 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
9864 if(isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
!= 0)
9865 return EQUIP_ERR_CANT_DO_RIGHT_NOW
; // maybe exist better err
9867 if(IsNonMeleeSpellCasted(false))
9868 return EQUIP_ERR_CANT_DO_RIGHT_NOW
;
9870 uint8 eslot
= FindEquipSlot( pProto
, slot
, swap
);
9871 if( eslot
== NULL_SLOT
)
9872 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9874 uint8 msg
= CanUseItem( pItem
, not_loading
);
9875 if( msg
!= EQUIP_ERR_OK
)
9877 if( !swap
&& GetItemByPos( INVENTORY_SLOT_BAG_0
, eslot
) )
9878 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE
;
9880 // check unique-equipped on item
9881 if (pProto
->Flags
& ITEM_FLAGS_UNIQUE_EQUIPPED
)
9883 // there is an equip limit on this item
9884 Item
* tItem
= GetItemOrItemWithGemEquipped(pProto
->ItemId
);
9885 if (tItem
&& (!swap
|| tItem
->GetSlot() != eslot
) )
9886 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
9889 // check unique-equipped on gems
9890 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
9892 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
9895 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
9899 ItemPrototype
const* pGem
= objmgr
.GetItemPrototype(enchantEntry
->GemID
);
9900 if(pGem
&& (pGem
->Flags
& ITEM_FLAGS_UNIQUE_EQUIPPED
))
9902 Item
* tItem
= GetItemOrItemWithGemEquipped(enchantEntry
->GemID
);
9903 if(tItem
&& (!swap
|| tItem
->GetSlot() != eslot
))
9904 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
9908 // check unique-equipped special item classes
9909 if (pProto
->Class
== ITEM_CLASS_QUIVER
)
9911 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9913 if( Item
* pBag
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
) )
9915 if( ItemPrototype
const* pBagProto
= pBag
->GetProto() )
9917 if( pBagProto
->Class
==pProto
->Class
&& pBagProto
->SubClass
==pProto
->SubClass
&&
9918 (!swap
|| pBag
->GetSlot() != eslot
) )
9920 if(pBagProto
->SubClass
== ITEM_SUBCLASS_AMMO_POUCH
)
9921 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
;
9923 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER
;
9930 uint32 type
= pProto
->InventoryType
;
9932 if(eslot
== EQUIPMENT_SLOT_OFFHAND
)
9934 if (type
== INVTYPE_WEAPON
|| type
== INVTYPE_WEAPONOFFHAND
)
9937 return EQUIP_ERR_CANT_DUAL_WIELD
;
9939 else if (type
== INVTYPE_2HWEAPON
)
9941 if(!CanDualWield() || !CanTitanGrip())
9942 return EQUIP_ERR_CANT_DUAL_WIELD
;
9946 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED
;
9949 // equip two-hand weapon case (with possible unequip 2 items)
9950 if( type
== INVTYPE_2HWEAPON
)
9952 if (eslot
== EQUIPMENT_SLOT_OFFHAND
)
9954 if (!CanTitanGrip())
9955 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9957 else if (eslot
!= EQUIPMENT_SLOT_MAINHAND
)
9958 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9960 if (!CanTitanGrip())
9962 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9963 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
9964 ItemPosCountVec off_dest
;
9965 if( offItem
&& (!not_loading
||
9966 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0
) << 8 | EQUIPMENT_SLOT_OFFHAND
,false) != EQUIP_ERR_OK
||
9967 CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false ) != EQUIP_ERR_OK
) )
9968 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_INVENTORY_FULL
;
9971 dest
= ((INVENTORY_SLOT_BAG_0
<< 8) | eslot
);
9972 return EQUIP_ERR_OK
;
9976 return EQUIP_ERR_ITEM_NOT_FOUND
;
9978 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
;
9981 uint8
Player::CanUnequipItem( uint16 pos
, bool swap
) const
9983 // Applied only to equipped items and bank bags
9984 if(!IsEquipmentPos(pos
) && !IsBagPos(pos
))
9985 return EQUIP_ERR_OK
;
9987 Item
* pItem
= GetItemByPos(pos
);
9989 // Applied only to existed equipped item
9991 return EQUIP_ERR_OK
;
9993 sLog
.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos
, pItem
->GetEntry(), pItem
->GetCount());
9995 ItemPrototype
const *pProto
= pItem
->GetProto();
9997 return EQUIP_ERR_ITEM_NOT_FOUND
;
9999 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
10001 // - in-progress arenas
10002 if( !pProto
->CanChangeEquipStateInCombat() )
10005 return EQUIP_ERR_NOT_IN_COMBAT
;
10007 if(BattleGround
* bg
= GetBattleGround())
10008 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
10009 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
10012 if(!swap
&& pItem
->IsBag() && !((Bag
*)pItem
)->IsEmpty())
10013 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS
;
10015 return EQUIP_ERR_OK
;
10018 uint8
Player::CanBankItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
10021 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
10023 uint32 count
= pItem
->GetCount();
10025 sLog
.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), pItem
->GetCount());
10026 ItemPrototype
const *pProto
= pItem
->GetProto();
10028 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
10030 if( pItem
->IsBindedNotWith(GetGUID()) )
10031 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
10033 // check count of items (skip for auto move for same player from bank)
10034 uint8 res
= CanTakeMoreSimilarItems(pItem
);
10035 if(res
!= EQUIP_ERR_OK
)
10038 // in specific slot
10039 if( bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
10041 if( pProto
->InventoryType
== INVTYPE_BAG
)
10043 Bag
*pBag
= (Bag
*)pItem
;
10046 if( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
10048 if( !HasBankBagSlot( slot
) )
10049 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT
;
10050 if( uint8 cantuse
= CanUseItem( pItem
, not_loading
) != EQUIP_ERR_OK
)
10055 if( !pBag
->IsEmpty() )
10056 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
;
10062 if( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
10063 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
;
10066 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
10067 if(res
!=EQUIP_ERR_OK
)
10071 return EQUIP_ERR_OK
;
10074 // not specific slot or have space for partly store only in specific slot
10077 if( bag
!= NULL_BAG
)
10079 if( pProto
->InventoryType
== INVTYPE_BAG
)
10081 Bag
*pBag
= (Bag
*)pItem
;
10082 if( pBag
&& !pBag
->IsEmpty() )
10083 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
;
10086 // search stack in bag for merge to
10087 if( pProto
->Stackable
!= 1 )
10089 if( bag
== INVENTORY_SLOT_BAG_0
)
10091 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
10092 if(res
!=EQUIP_ERR_OK
)
10096 return EQUIP_ERR_OK
;
10100 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
10101 if(res
!=EQUIP_ERR_OK
)
10102 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
10104 if(res
!=EQUIP_ERR_OK
)
10108 return EQUIP_ERR_OK
;
10112 // search free slot in bag
10113 if( bag
== INVENTORY_SLOT_BAG_0
)
10115 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
10116 if(res
!=EQUIP_ERR_OK
)
10120 return EQUIP_ERR_OK
;
10124 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
10125 if(res
!=EQUIP_ERR_OK
)
10126 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
10128 if(res
!=EQUIP_ERR_OK
)
10132 return EQUIP_ERR_OK
;
10136 // not specific bag or have space for partly store only in specific bag
10138 // search stack for merge to
10139 if( pProto
->Stackable
!= 1 )
10142 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
10143 if(res
!=EQUIP_ERR_OK
)
10147 return EQUIP_ERR_OK
;
10150 if( pProto
->BagFamily
)
10152 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
10154 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
10155 if(res
!=EQUIP_ERR_OK
)
10159 return EQUIP_ERR_OK
;
10163 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
10165 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
10166 if(res
!=EQUIP_ERR_OK
)
10170 return EQUIP_ERR_OK
;
10174 // search free place in special bag
10175 if( pProto
->BagFamily
)
10177 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
10179 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
10180 if(res
!=EQUIP_ERR_OK
)
10184 return EQUIP_ERR_OK
;
10188 // search free space
10189 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
10190 if(res
!=EQUIP_ERR_OK
)
10194 return EQUIP_ERR_OK
;
10196 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
10198 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
10199 if(res
!=EQUIP_ERR_OK
)
10203 return EQUIP_ERR_OK
;
10205 return EQUIP_ERR_BANK_FULL
;
10208 uint8
Player::CanUseItem( Item
*pItem
, bool not_loading
) const
10212 sLog
.outDebug( "STORAGE: CanUseItem item = %u", pItem
->GetEntry());
10213 if( !isAlive() && not_loading
)
10214 return EQUIP_ERR_YOU_ARE_DEAD
;
10215 //if( isStunned() )
10216 // return EQUIP_ERR_YOU_ARE_STUNNED;
10217 ItemPrototype
const *pProto
= pItem
->GetProto();
10220 if( pItem
->IsBindedNotWith(GetGUID()) )
10221 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
10222 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
10223 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
10224 if( pItem
->GetSkill() != 0 )
10226 if( GetSkillValue( pItem
->GetSkill() ) == 0 )
10227 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10229 if( pProto
->RequiredSkill
!= 0 )
10231 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
10232 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10233 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10234 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
10236 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
10237 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10238 if( pProto
->RequiredReputationFaction
&& uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
10239 return EQUIP_ERR_CANT_EQUIP_REPUTATION
;
10240 if( getLevel() < pProto
->RequiredLevel
)
10241 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
10242 return EQUIP_ERR_OK
;
10245 return EQUIP_ERR_ITEM_NOT_FOUND
;
10248 bool Player::CanUseItem( ItemPrototype
const *pProto
)
10250 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10254 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
10256 if( pProto
->RequiredSkill
!= 0 )
10258 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
10260 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10263 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
10265 if( getLevel() < pProto
->RequiredLevel
)
10272 uint8
Player::CanUseAmmo( uint32 item
) const
10274 sLog
.outDebug( "STORAGE: CanUseAmmo item = %u", item
);
10276 return EQUIP_ERR_YOU_ARE_DEAD
;
10277 //if( isStunned() )
10278 // return EQUIP_ERR_YOU_ARE_STUNNED;
10279 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
10282 if( pProto
->InventoryType
!= INVTYPE_AMMO
)
10283 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE
;
10284 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
10285 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
10286 if( pProto
->RequiredSkill
!= 0 )
10288 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
10289 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10290 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
10291 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
10293 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
10294 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
10295 /*if( GetReputation() < pProto->RequiredReputation )
10296 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10298 if( getLevel() < pProto
->RequiredLevel
)
10299 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
10301 // Requires No Ammo
10302 if(GetDummyAura(46699))
10303 return EQUIP_ERR_BAG_FULL6
;
10305 return EQUIP_ERR_OK
;
10307 return EQUIP_ERR_ITEM_NOT_FOUND
;
10310 void Player::SetAmmo( uint32 item
)
10316 if( GetUInt32Value(PLAYER_AMMO_ID
) == item
)
10322 uint8 msg
= CanUseAmmo( item
);
10323 if( msg
!= EQUIP_ERR_OK
)
10325 SendEquipError( msg
, NULL
, NULL
);
10330 SetUInt32Value(PLAYER_AMMO_ID
, item
);
10332 _ApplyAmmoBonuses();
10335 void Player::RemoveAmmo()
10337 SetUInt32Value(PLAYER_AMMO_ID
, 0);
10341 if(CanModifyStats())
10342 UpdateDamagePhysical(RANGED_ATTACK
);
10345 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10346 Item
* Player::StoreNewItem( ItemPosCountVec
const& dest
, uint32 item
, bool update
,int32 randomPropertyId
)
10349 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); ++itr
)
10350 count
+= itr
->count
;
10352 Item
*pItem
= Item::CreateItem( item
, count
, this );
10355 ItemAddedQuestCheck( item
, count
);
10356 if(randomPropertyId
)
10357 pItem
->SetItemRandomProperties(randomPropertyId
);
10358 pItem
= StoreItem( dest
, pItem
, update
);
10363 Item
* Player::StoreItem( ItemPosCountVec
const& dest
, Item
* pItem
, bool update
)
10368 Item
* lastItem
= pItem
;
10370 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); )
10372 uint16 pos
= itr
->pos
;
10373 uint32 count
= itr
->count
;
10377 if(itr
== dest
.end())
10379 lastItem
= _StoreItem(pos
,pItem
,count
,false,update
);
10383 lastItem
= _StoreItem(pos
,pItem
,count
,true,update
);
10389 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10390 Item
* Player::_StoreItem( uint16 pos
, Item
*pItem
, uint32 count
, bool clone
, bool update
)
10395 uint8 bag
= pos
>> 8;
10396 uint8 slot
= pos
& 255;
10398 sLog
.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), count
);
10400 Item
*pItem2
= GetItemByPos( bag
, slot
);
10405 pItem
= pItem
->CloneItem(count
,this);
10407 pItem
->SetCount(count
);
10412 if( pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10413 pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10414 pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
) )
10415 pItem
->SetBinding( true );
10417 if( bag
== INVENTORY_SLOT_BAG_0
)
10419 m_items
[slot
] = pItem
;
10420 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), pItem
->GetGUID() );
10421 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10422 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10424 pItem
->SetSlot( slot
);
10425 pItem
->SetContainer( NULL
);
10427 if( IsInWorld() && update
)
10429 pItem
->AddToWorld();
10430 pItem
->SendUpdateToPlayer( this );
10433 pItem
->SetState(ITEM_CHANGED
, this);
10437 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
10440 pBag
->StoreItem( slot
, pItem
, update
);
10441 if( IsInWorld() && update
)
10443 pItem
->AddToWorld();
10444 pItem
->SendUpdateToPlayer( this );
10446 pItem
->SetState(ITEM_CHANGED
, this);
10447 pBag
->SetState(ITEM_CHANGED
, this);
10451 AddEnchantmentDurations(pItem
);
10452 AddItemDurations(pItem
);
10458 if( pItem2
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10459 pItem2
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10460 pItem2
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
) )
10461 pItem2
->SetBinding( true );
10463 pItem2
->SetCount( pItem2
->GetCount() + count
);
10464 if( IsInWorld() && update
)
10465 pItem2
->SendUpdateToPlayer( this );
10469 // delete item (it not in any slot currently)
10470 if( IsInWorld() && update
)
10472 pItem
->RemoveFromWorld();
10473 pItem
->DestroyForPlayer( this );
10476 RemoveEnchantmentDurations(pItem
);
10477 RemoveItemDurations(pItem
);
10479 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10480 pItem
->SetState(ITEM_REMOVED
, this);
10482 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10483 AddEnchantmentDurations(pItem2
);
10485 pItem2
->SetState(ITEM_CHANGED
, this);
10491 Item
* Player::EquipNewItem( uint16 pos
, uint32 item
, bool update
)
10493 Item
*pItem
= Item::CreateItem( item
, 1, this );
10496 ItemAddedQuestCheck( item
, 1 );
10497 Item
* retItem
= EquipItem( pos
, pItem
, update
);
10504 Item
* Player::EquipItem( uint16 pos
, Item
*pItem
, bool update
)
10508 AddEnchantmentDurations(pItem
);
10509 AddItemDurations(pItem
);
10511 uint8 bag
= pos
>> 8;
10512 uint8 slot
= pos
& 255;
10514 Item
*pItem2
= GetItemByPos( bag
, slot
);
10518 VisualizeItem( slot
, pItem
);
10522 ItemPrototype
const *pProto
= pItem
->GetProto();
10524 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10525 if(pProto
&& pProto
->ItemSet
)
10526 AddItemsSetItem(this,pItem
);
10528 _ApplyItemMods(pItem
, slot
, true);
10530 if(pProto
&& isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
== 0)
10532 uint32 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s
;
10534 if (getClass() == CLASS_ROGUE
)
10535 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s
;
10537 SpellEntry
const* spellProto
= sSpellStore
.LookupEntry(cooldownSpell
);
10540 sLog
.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell
);
10543 m_weaponChangeTimer
= spellProto
->StartRecoveryTime
;
10545 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+4);
10546 data
<< uint64(GetGUID());
10548 data
<< uint32(cooldownSpell
);
10550 GetSession()->SendPacket(&data
);
10555 if( IsInWorld() && update
)
10557 pItem
->AddToWorld();
10558 pItem
->SendUpdateToPlayer( this );
10561 ApplyEquipCooldown(pItem
);
10563 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
10564 UpdateExpertise(BASE_ATTACK
);
10565 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10566 UpdateExpertise(OFF_ATTACK
);
10570 pItem2
->SetCount( pItem2
->GetCount() + pItem
->GetCount() );
10571 if( IsInWorld() && update
)
10572 pItem2
->SendUpdateToPlayer( this );
10574 // delete item (it not in any slot currently)
10575 //pItem->DeleteFromDB();
10576 if( IsInWorld() && update
)
10578 pItem
->RemoveFromWorld();
10579 pItem
->DestroyForPlayer( this );
10582 RemoveEnchantmentDurations(pItem
);
10583 RemoveItemDurations(pItem
);
10585 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10586 pItem
->SetState(ITEM_REMOVED
, this);
10587 pItem2
->SetState(ITEM_CHANGED
, this);
10589 ApplyEquipCooldown(pItem2
);
10598 void Player::QuickEquipItem( uint16 pos
, Item
*pItem
)
10602 AddEnchantmentDurations(pItem
);
10603 AddItemDurations(pItem
);
10605 uint8 slot
= pos
& 255;
10606 VisualizeItem( slot
, pItem
);
10610 pItem
->AddToWorld();
10611 pItem
->SendUpdateToPlayer( this );
10616 void Player::SetVisibleItemSlot(uint8 slot
, Item
*pItem
)
10618 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10619 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10620 // entry // Size: 1
10621 // inspected enchantments // Size: 6
10623 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10624 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10629 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), pItem
->GetUInt64Value(ITEM_FIELD_CREATOR
));
10631 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
10632 SetUInt32Value(VisibleBase
+ 0, pItem
->GetEntry());
10634 for(int i
= 0; i
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++i
)
10635 SetUInt32Value(VisibleBase
+ 1 + i
, pItem
->GetEnchantmentId(EnchantmentSlot(i
)));
10637 // Use SetInt16Value to prevent set high part to FFFF for negative value
10638 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0, pItem
->GetItemRandomPropertyId());
10639 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), pItem
->GetItemSuffixFactor());
10643 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10645 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
10646 SetUInt32Value(VisibleBase
+ 0, 0);
10648 for(int i
= 0; i
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++i
)
10649 SetUInt32Value(VisibleBase
+ 1 + i
, 0);
10651 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 0 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10652 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10656 void Player::VisualizeItem( uint8 slot
, Item
*pItem
)
10661 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10662 if( pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
|| pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
|| pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
)
10663 pItem
->SetBinding( true );
10665 sLog
.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot
, pItem
->GetEntry());
10667 m_items
[slot
] = pItem
;
10668 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), pItem
->GetGUID() );
10669 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10670 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10671 pItem
->SetSlot( slot
);
10672 pItem
->SetContainer( NULL
);
10674 if( slot
< EQUIPMENT_SLOT_END
)
10675 SetVisibleItemSlot(slot
,pItem
);
10677 pItem
->SetState(ITEM_CHANGED
, this);
10680 void Player::RemoveItem( uint8 bag
, uint8 slot
, bool update
)
10682 // note: removeitem does not actually change the item
10683 // it only takes the item out of storage temporarily
10684 // note2: if removeitem is to be used for delinking
10685 // the item must be removed from the player's updatequeue
10687 Item
*pItem
= GetItemByPos( bag
, slot
);
10690 sLog
.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10692 RemoveEnchantmentDurations(pItem
);
10693 RemoveItemDurations(pItem
);
10695 if( bag
== INVENTORY_SLOT_BAG_0
)
10697 if ( slot
< INVENTORY_SLOT_BAG_END
)
10699 ItemPrototype
const *pProto
= pItem
->GetProto();
10700 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10702 if(pProto
&& pProto
->ItemSet
)
10703 RemoveItemsSetItem(this,pProto
);
10705 _ApplyItemMods(pItem
, slot
, false);
10707 // remove item dependent auras and casts (only weapon and armor slots)
10708 if(slot
< EQUIPMENT_SLOT_END
)
10709 RemoveItemDependentAurasAndCasts(pItem
);
10711 // remove held enchantments
10712 if ( slot
== EQUIPMENT_SLOT_MAINHAND
)
10714 if (pItem
->GetItemSuffixFactor())
10716 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3
);
10717 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4
);
10721 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0
);
10722 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1
);
10727 m_items
[slot
] = NULL
;
10728 SetUInt64Value((uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
*2)), 0);
10730 if ( slot
< EQUIPMENT_SLOT_END
)
10731 SetVisibleItemSlot(slot
,NULL
);
10735 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
10737 pBag
->RemoveItem(slot
, update
);
10739 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10740 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10741 pItem
->SetSlot( NULL_SLOT
);
10742 if( IsInWorld() && update
)
10743 pItem
->SendUpdateToPlayer( this );
10745 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
10746 UpdateExpertise(BASE_ATTACK
);
10747 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10748 UpdateExpertise(OFF_ATTACK
);
10752 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10753 void Player::MoveItemFromInventory(uint8 bag
, uint8 slot
, bool update
)
10755 if(Item
* it
= GetItemByPos(bag
,slot
))
10757 ItemRemovedQuestCheck(it
->GetEntry(),it
->GetCount());
10758 RemoveItem( bag
,slot
,update
);
10759 it
->RemoveFromUpdateQueueOf(this);
10760 if(it
->IsInWorld())
10762 it
->RemoveFromWorld();
10763 it
->DestroyForPlayer( this );
10768 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10769 void Player::MoveItemToInventory(ItemPosCountVec
const& dest
, Item
* pItem
, bool update
, bool in_characterInventoryDB
)
10771 // update quest counters
10772 ItemAddedQuestCheck(pItem
->GetEntry(),pItem
->GetCount());
10775 Item
* pLastItem
= StoreItem( dest
, pItem
, update
);
10777 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10778 if(pLastItem
==pItem
)
10780 // update owner for last item (this can be original item with wrong owner
10781 if(pLastItem
->GetOwnerGUID() != GetGUID())
10782 pLastItem
->SetOwnerGUID(GetGUID());
10784 // if this original item then it need create record in inventory
10785 // in case trade we already have item in other player inventory
10786 pLastItem
->SetState(in_characterInventoryDB
? ITEM_CHANGED
: ITEM_NEW
, this);
10790 void Player::DestroyItem( uint8 bag
, uint8 slot
, bool update
)
10792 Item
*pItem
= GetItemByPos( bag
, slot
);
10795 sLog
.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10797 // start from destroy contained items (only equipped bag can have its)
10798 if (pItem
->IsBag() && pItem
->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10800 for (int i
= 0; i
< MAX_BAG_SIZE
; i
++)
10801 DestroyItem(slot
,i
,update
);
10804 if(pItem
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_WRAPPED
))
10805 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem
->GetGUIDLow());
10807 RemoveEnchantmentDurations(pItem
);
10808 RemoveItemDurations(pItem
);
10810 ItemRemovedQuestCheck( pItem
->GetEntry(), pItem
->GetCount() );
10812 if( bag
== INVENTORY_SLOT_BAG_0
)
10814 SetUInt64Value((uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
*2)), 0);
10816 // equipment and equipped bags can have applied bonuses
10817 if ( slot
< INVENTORY_SLOT_BAG_END
)
10819 ItemPrototype
const *pProto
= pItem
->GetProto();
10821 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10822 if(pProto
&& pProto
->ItemSet
)
10823 RemoveItemsSetItem(this,pProto
);
10825 _ApplyItemMods(pItem
, slot
, false);
10828 if ( slot
< EQUIPMENT_SLOT_END
)
10830 // remove item dependent auras and casts (only weapon and armor slots)
10831 RemoveItemDependentAurasAndCasts(pItem
);
10833 // equipment visual show
10834 SetVisibleItemSlot(slot
,NULL
);
10837 m_items
[slot
] = NULL
;
10839 else if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
))
10840 pBag
->RemoveItem(slot
, update
);
10842 if( IsInWorld() && update
)
10844 pItem
->RemoveFromWorld();
10845 pItem
->DestroyForPlayer(this);
10848 //pItem->SetOwnerGUID(0);
10849 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10850 pItem
->SetSlot( NULL_SLOT
);
10851 pItem
->SetState(ITEM_REMOVED
, this);
10855 void Player::DestroyItemCount( uint32 item
, uint32 count
, bool update
, bool unequip_check
)
10857 sLog
.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item
, count
);
10859 ItemPrototype
const *pProto
;
10860 uint32 remcount
= 0;
10863 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
10865 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10866 if( pItem
&& pItem
->GetEntry() == item
)
10868 if( pItem
->GetCount() + remcount
<= count
)
10870 // all items in inventory can unequipped
10871 remcount
+= pItem
->GetCount();
10872 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10874 if(remcount
>=count
)
10879 pProto
= pItem
->GetProto();
10880 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10881 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10882 if( IsInWorld() & update
)
10883 pItem
->SendUpdateToPlayer( this );
10884 pItem
->SetState(ITEM_CHANGED
, this);
10889 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
10891 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10892 if( pItem
&& pItem
->GetEntry() == item
)
10894 if( pItem
->GetCount() + remcount
<= count
)
10896 // all keys can be unequipped
10897 remcount
+= pItem
->GetCount();
10898 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10900 if(remcount
>=count
)
10905 pProto
= pItem
->GetProto();
10906 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10907 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10908 if( IsInWorld() & update
)
10909 pItem
->SendUpdateToPlayer( this );
10910 pItem
->SetState(ITEM_CHANGED
, this);
10916 // in inventory bags
10917 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10919 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10921 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
10923 pItem
= pBag
->GetItemByPos(j
);
10924 if( pItem
&& pItem
->GetEntry() == item
)
10926 // all items in bags can be unequipped
10927 if( pItem
->GetCount() + remcount
<= count
)
10929 remcount
+= pItem
->GetCount();
10930 DestroyItem( i
, j
, update
);
10932 if(remcount
>=count
)
10937 pProto
= pItem
->GetProto();
10938 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10939 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10940 if( IsInWorld() && update
)
10941 pItem
->SendUpdateToPlayer( this );
10942 pItem
->SetState(ITEM_CHANGED
, this);
10950 // in equipment and bag list
10951 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10953 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10954 if( pItem
&& pItem
->GetEntry() == item
)
10956 if( pItem
->GetCount() + remcount
<= count
)
10958 if(!unequip_check
|| CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
,false) == EQUIP_ERR_OK
)
10960 remcount
+= pItem
->GetCount();
10961 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10963 if(remcount
>=count
)
10969 pProto
= pItem
->GetProto();
10970 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10971 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10972 if( IsInWorld() & update
)
10973 pItem
->SendUpdateToPlayer( this );
10974 pItem
->SetState(ITEM_CHANGED
, this);
10981 void Player::DestroyZoneLimitedItem( bool update
, uint32 new_zone
)
10983 sLog
.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone
);
10986 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
10988 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10989 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
10990 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10992 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
10994 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10995 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
10996 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10999 // in inventory bags
11000 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11002 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11005 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
11007 Item
* pItem
= pBag
->GetItemByPos(j
);
11008 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
11009 DestroyItem( i
, j
, update
);
11014 // in equipment and bag list
11015 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11017 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11018 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
11019 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11023 void Player::DestroyConjuredItems( bool update
)
11025 // used when entering arena
11026 // destroys all conjured items
11027 sLog
.outDebug( "STORAGE: DestroyConjuredItems" );
11030 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
11032 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11033 if( pItem
&& pItem
->GetProto() &&
11034 (pItem
->GetProto()->Class
== ITEM_CLASS_CONSUMABLE
) &&
11035 (pItem
->GetProto()->Flags
& ITEM_FLAGS_CONJURED
) )
11036 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11039 // in inventory bags
11040 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11042 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11045 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
11047 Item
* pItem
= pBag
->GetItemByPos(j
);
11048 if( pItem
&& pItem
->GetProto() &&
11049 (pItem
->GetProto()->Class
== ITEM_CLASS_CONSUMABLE
) &&
11050 (pItem
->GetProto()->Flags
& ITEM_FLAGS_CONJURED
) )
11051 DestroyItem( i
, j
, update
);
11056 // in equipment and bag list
11057 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11059 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11060 if( pItem
&& pItem
->GetProto() &&
11061 (pItem
->GetProto()->Class
== ITEM_CLASS_CONSUMABLE
) &&
11062 (pItem
->GetProto()->Flags
& ITEM_FLAGS_CONJURED
) )
11063 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
11067 void Player::DestroyItemCount( Item
* pItem
, uint32
&count
, bool update
)
11072 sLog
.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem
->GetGUIDLow(),pItem
->GetEntry(), count
);
11074 if( pItem
->GetCount() <= count
)
11076 count
-= pItem
->GetCount();
11078 DestroyItem( pItem
->GetBagSlot(),pItem
->GetSlot(), update
);
11082 ItemRemovedQuestCheck( pItem
->GetEntry(), count
);
11083 pItem
->SetCount( pItem
->GetCount() - count
);
11085 if( IsInWorld() & update
)
11086 pItem
->SendUpdateToPlayer( this );
11087 pItem
->SetState(ITEM_CHANGED
, this);
11091 void Player::SplitItem( uint16 src
, uint16 dst
, uint32 count
)
11093 uint8 srcbag
= src
>> 8;
11094 uint8 srcslot
= src
& 255;
11096 uint8 dstbag
= dst
>> 8;
11097 uint8 dstslot
= dst
& 255;
11099 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
11102 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
11106 // not let split all items (can be only at cheating)
11107 if(pSrcItem
->GetCount() == count
)
11109 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
11113 // not let split more existed items (can be only at cheating)
11114 if(pSrcItem
->GetCount() < count
)
11116 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT
, pSrcItem
, NULL
);
11120 if(pSrcItem
->m_lootGenerated
) // prevent split looting item (item
11122 //best error message found for attempting to split while looting
11123 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
11127 sLog
.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag
, dstslot
, pSrcItem
->GetEntry(), count
);
11128 Item
*pNewItem
= pSrcItem
->CloneItem( count
, this );
11131 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
11135 if( IsInventoryPos( dst
) )
11137 // change item amount before check (for unique max count check)
11138 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11140 ItemPosCountVec dest
;
11141 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pNewItem
, false );
11142 if( msg
!= EQUIP_ERR_OK
)
11145 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11146 SendEquipError( msg
, pSrcItem
, NULL
);
11151 pSrcItem
->SendUpdateToPlayer( this );
11152 pSrcItem
->SetState(ITEM_CHANGED
, this);
11153 StoreItem( dest
, pNewItem
, true);
11155 else if( IsBankPos ( dst
) )
11157 // change item amount before check (for unique max count check)
11158 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11160 ItemPosCountVec dest
;
11161 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pNewItem
, false );
11162 if( msg
!= EQUIP_ERR_OK
)
11165 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11166 SendEquipError( msg
, pSrcItem
, NULL
);
11171 pSrcItem
->SendUpdateToPlayer( this );
11172 pSrcItem
->SetState(ITEM_CHANGED
, this);
11173 BankItem( dest
, pNewItem
, true);
11175 else if( IsEquipmentPos ( dst
) )
11177 // change item amount before check (for unique max count check), provide space for splitted items
11178 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
11181 uint8 msg
= CanEquipItem( dstslot
, dest
, pNewItem
, false );
11182 if( msg
!= EQUIP_ERR_OK
)
11185 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
11186 SendEquipError( msg
, pSrcItem
, NULL
);
11191 pSrcItem
->SendUpdateToPlayer( this );
11192 pSrcItem
->SetState(ITEM_CHANGED
, this);
11193 EquipItem( dest
, pNewItem
, true);
11194 AutoUnequipOffhandIfNeed();
11198 void Player::SwapItem( uint16 src
, uint16 dst
)
11200 uint8 srcbag
= src
>> 8;
11201 uint8 srcslot
= src
& 255;
11203 uint8 dstbag
= dst
>> 8;
11204 uint8 dstslot
= dst
& 255;
11206 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
11207 Item
*pDstItem
= GetItemByPos( dstbag
, dstslot
);
11212 sLog
.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag
, dstslot
, pSrcItem
->GetEntry());
11216 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD
, pSrcItem
, pDstItem
);
11220 if(pSrcItem
->m_lootGenerated
) // prevent swap looting item
11222 //best error message found for attempting to swap while looting
11223 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pSrcItem
, NULL
);
11227 // check unequip potability for equipped items and bank bags
11228 if(IsEquipmentPos ( src
) || IsBagPos ( src
))
11230 // bags can be swapped with empty bag slots
11231 uint8 msg
= CanUnequipItem( src
, !IsBagPos ( src
) || IsBagPos ( dst
));
11232 if(msg
!= EQUIP_ERR_OK
)
11234 SendEquipError( msg
, pSrcItem
, pDstItem
);
11239 // prevent put equipped/bank bag in self
11240 if( IsBagPos ( src
) && srcslot
== dstbag
)
11242 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
11248 if( IsInventoryPos( dst
) )
11250 ItemPosCountVec dest
;
11251 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pSrcItem
, false );
11252 if( msg
!= EQUIP_ERR_OK
)
11254 SendEquipError( msg
, pSrcItem
, NULL
);
11258 RemoveItem(srcbag
, srcslot
, true);
11259 StoreItem( dest
, pSrcItem
, true);
11261 else if( IsBankPos ( dst
) )
11263 ItemPosCountVec dest
;
11264 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pSrcItem
, false);
11265 if( msg
!= EQUIP_ERR_OK
)
11267 SendEquipError( msg
, pSrcItem
, NULL
);
11271 RemoveItem(srcbag
, srcslot
, true);
11272 BankItem( dest
, pSrcItem
, true);
11274 else if( IsEquipmentPos ( dst
) )
11277 uint8 msg
= CanEquipItem( dstslot
, dest
, pSrcItem
, false );
11278 if( msg
!= EQUIP_ERR_OK
)
11280 SendEquipError( msg
, pSrcItem
, NULL
);
11284 RemoveItem(srcbag
, srcslot
, true);
11285 EquipItem( dest
, pSrcItem
, true);
11286 AutoUnequipOffhandIfNeed();
11289 else // if (!pDstItem)
11291 if(pDstItem
->m_lootGenerated
) // prevent swap looting item
11293 //best error message found for attempting to swap while looting
11294 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pDstItem
, NULL
);
11298 // check unequip potability for equipped items and bank bags
11299 if(IsEquipmentPos ( dst
) || IsBagPos ( dst
))
11301 // bags can be swapped with empty bag slots
11302 uint8 msg
= CanUnequipItem( dst
, !IsBagPos ( dst
) || IsBagPos ( src
) );
11303 if(msg
!= EQUIP_ERR_OK
)
11305 SendEquipError( msg
, pSrcItem
, pDstItem
);
11310 // attempt merge to / fill target item
11313 ItemPosCountVec sDest
;
11315 if( IsInventoryPos( dst
) )
11316 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
11317 else if( IsBankPos ( dst
) )
11318 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
11319 else if( IsEquipmentPos ( dst
) )
11320 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, false );
11324 // can be merge/fill
11325 if(msg
== EQUIP_ERR_OK
)
11327 if( pSrcItem
->GetCount() + pDstItem
->GetCount() <= pSrcItem
->GetProto()->GetMaxStackSize())
11329 RemoveItem(srcbag
, srcslot
, true);
11331 if( IsInventoryPos( dst
) )
11332 StoreItem( sDest
, pSrcItem
, true);
11333 else if( IsBankPos ( dst
) )
11334 BankItem( sDest
, pSrcItem
, true);
11335 else if( IsEquipmentPos ( dst
) )
11337 EquipItem( eDest
, pSrcItem
, true);
11338 AutoUnequipOffhandIfNeed();
11343 pSrcItem
->SetCount( pSrcItem
->GetCount() + pDstItem
->GetCount() - pSrcItem
->GetProto()->GetMaxStackSize());
11344 pDstItem
->SetCount( pSrcItem
->GetProto()->GetMaxStackSize());
11345 pSrcItem
->SetState(ITEM_CHANGED
, this);
11346 pDstItem
->SetState(ITEM_CHANGED
, this);
11349 pSrcItem
->SendUpdateToPlayer( this );
11350 pDstItem
->SendUpdateToPlayer( this );
11357 // impossible merge/fill, do real swap
11360 // check src->dest move possibility
11361 ItemPosCountVec sDest
;
11363 if( IsInventoryPos( dst
) )
11364 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
11365 else if( IsBankPos( dst
) )
11366 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
11367 else if( IsEquipmentPos( dst
) )
11369 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, true );
11370 if( msg
== EQUIP_ERR_OK
)
11371 msg
= CanUnequipItem( eDest
, true );
11374 if( msg
!= EQUIP_ERR_OK
)
11376 SendEquipError( msg
, pSrcItem
, pDstItem
);
11380 // check dest->src move possibility
11381 ItemPosCountVec sDest2
;
11383 if( IsInventoryPos( src
) )
11384 msg
= CanStoreItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11385 else if( IsBankPos( src
) )
11386 msg
= CanBankItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
11387 else if( IsEquipmentPos( src
) )
11389 msg
= CanEquipItem( srcslot
, eDest2
, pDstItem
, true);
11390 if( msg
== EQUIP_ERR_OK
)
11391 msg
= CanUnequipItem( eDest2
, true);
11394 if( msg
!= EQUIP_ERR_OK
)
11396 SendEquipError( msg
, pDstItem
, pSrcItem
);
11400 // now do moves, remove...
11401 RemoveItem(dstbag
, dstslot
, false);
11402 RemoveItem(srcbag
, srcslot
, false);
11405 if( IsInventoryPos( dst
) )
11406 StoreItem(sDest
, pSrcItem
, true);
11407 else if( IsBankPos( dst
) )
11408 BankItem(sDest
, pSrcItem
, true);
11409 else if( IsEquipmentPos( dst
) )
11410 EquipItem(eDest
, pSrcItem
, true);
11413 if( IsInventoryPos( src
) )
11414 StoreItem(sDest2
, pDstItem
, true);
11415 else if( IsBankPos( src
) )
11416 BankItem(sDest2
, pDstItem
, true);
11417 else if( IsEquipmentPos( src
) )
11418 EquipItem(eDest2
, pDstItem
, true);
11420 AutoUnequipOffhandIfNeed();
11424 void Player::AddItemToBuyBackSlot( Item
*pItem
)
11428 uint32 slot
= m_currentBuybackSlot
;
11429 // if current back slot non-empty search oldest or free
11432 uint32 oldest_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
);
11433 uint32 oldest_slot
= BUYBACK_SLOT_START
;
11435 for(uint32 i
= BUYBACK_SLOT_START
+1; i
< BUYBACK_SLOT_END
; ++i
)
11444 uint32 i_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ i
- BUYBACK_SLOT_START
);
11446 if(oldest_time
> i_time
)
11448 oldest_time
= i_time
;
11454 slot
= oldest_slot
;
11457 RemoveItemFromBuyBackSlot( slot
, true );
11458 sLog
.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem
->GetEntry(), slot
);
11460 m_items
[slot
] = pItem
;
11461 time_t base
= time(NULL
);
11462 uint32 etime
= uint32(base
- m_logintime
+ (30 * 3600));
11463 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11465 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ eslot
* 2, pItem
->GetGUID() );
11466 ItemPrototype
const *pProto
= pItem
->GetProto();
11468 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, pProto
->SellPrice
* pItem
->GetCount() );
11470 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11471 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, (uint32
)etime
);
11473 // move to next (for non filled list is move most optimized choice)
11474 if(m_currentBuybackSlot
< BUYBACK_SLOT_END
-1)
11475 ++m_currentBuybackSlot
;
11479 Item
* Player::GetItemFromBuyBackSlot( uint32 slot
)
11481 sLog
.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot
);
11482 if( slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11483 return m_items
[slot
];
11487 void Player::RemoveItemFromBuyBackSlot( uint32 slot
, bool del
)
11489 sLog
.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot
);
11490 if( slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11492 Item
*pItem
= m_items
[slot
];
11495 pItem
->RemoveFromWorld();
11496 if(del
) pItem
->SetState(ITEM_REMOVED
, this);
11499 m_items
[slot
] = NULL
;
11501 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11502 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ eslot
* 2, 0 );
11503 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11504 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, 0 );
11506 // if current backslot is filled set to now free slot
11507 if(m_items
[m_currentBuybackSlot
])
11508 m_currentBuybackSlot
= slot
;
11512 void Player::SendEquipError( uint8 msg
, Item
* pItem
, Item
*pItem2
)
11514 sLog
.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg
);
11515 WorldPacket
data( SMSG_INVENTORY_CHANGE_FAILURE
, (msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
? 22 : 18) );
11516 data
<< uint8(msg
);
11520 data
<< uint64(pItem
? pItem
->GetGUID() : 0);
11521 data
<< uint64(pItem2
? pItem2
->GetGUID() : 0);
11522 data
<< uint8(0); // not 0 there...
11524 if(msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
)
11529 if(ItemPrototype
const* proto
= pItem
->GetProto())
11530 level
= proto
->RequiredLevel
;
11532 data
<< uint32(level
); // new 2.4.0
11535 GetSession()->SendPacket(&data
);
11538 void Player::SendBuyError( uint8 msg
, Creature
* pCreature
, uint32 item
, uint32 param
)
11540 sLog
.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11541 WorldPacket
data( SMSG_BUY_FAILED
, (8+4+4+1) );
11542 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11543 data
<< uint32(item
);
11545 data
<< uint32(param
);
11546 data
<< uint8(msg
);
11547 GetSession()->SendPacket(&data
);
11550 void Player::SendSellError( uint8 msg
, Creature
* pCreature
, uint64 guid
, uint32 param
)
11552 sLog
.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11553 WorldPacket
data( SMSG_SELL_ITEM
,(8+8+(param
?4:0)+1)); // last check 2.0.10
11554 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11555 data
<< uint64(guid
);
11557 data
<< uint32(param
);
11558 data
<< uint8(msg
);
11559 GetSession()->SendPacket(&data
);
11562 void Player::ClearTrade()
11565 acceptTrade
= false;
11566 for(int i
= 0; i
< TRADE_SLOT_COUNT
; i
++)
11567 tradeItems
[i
] = NULL_SLOT
;
11570 void Player::TradeCancel(bool sendback
)
11574 // send yellow "Trade canceled" message to both traders
11578 ws
->SendCancelTrade();
11579 ws
= pTrader
->GetSession();
11580 if(!ws
->PlayerLogout())
11581 ws
->SendCancelTrade();
11585 pTrader
->ClearTrade();
11586 // prevent loss of reference
11587 pTrader
->pTrader
= NULL
;
11592 void Player::UpdateItemDuration(uint32 time
, bool realtimeonly
)
11594 if(m_itemDuration
.empty())
11597 sLog
.outDebug("Player::UpdateItemDuration(%u,%u)", time
,realtimeonly
);
11599 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); )
11602 ++itr
; // current element can be erased in UpdateDuration
11604 if (realtimeonly
&& item
->GetProto()->Duration
< 0 || !realtimeonly
)
11605 item
->UpdateDuration(this,time
);
11609 void Player::UpdateEnchantTime(uint32 time
)
11611 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11615 if(!itr
->item
->GetEnchantmentId(itr
->slot
))
11617 next
= m_enchantDuration
.erase(itr
);
11619 else if(itr
->leftduration
<= time
)
11621 ApplyEnchantment(itr
->item
,itr
->slot
,false,false);
11622 itr
->item
->ClearEnchantment(itr
->slot
);
11623 next
= m_enchantDuration
.erase(itr
);
11625 else if(itr
->leftduration
> time
)
11627 itr
->leftduration
-= time
;
11633 void Player::AddEnchantmentDurations(Item
*item
)
11635 for(int x
=0;x
<MAX_ENCHANTMENT_SLOT
;++x
)
11637 if(!item
->GetEnchantmentId(EnchantmentSlot(x
)))
11640 uint32 duration
= item
->GetEnchantmentDuration(EnchantmentSlot(x
));
11642 AddEnchantmentDuration(item
,EnchantmentSlot(x
),duration
);
11646 void Player::RemoveEnchantmentDurations(Item
*item
)
11648 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();)
11650 if(itr
->item
== item
)
11652 // save duration in item
11653 item
->SetEnchantmentDuration(EnchantmentSlot(itr
->slot
),itr
->leftduration
);
11654 itr
= m_enchantDuration
.erase(itr
);
11661 void Player::RemoveAllEnchantments(EnchantmentSlot slot
)
11663 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11664 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11667 if(itr
->slot
==slot
)
11669 if(itr
->item
&& itr
->item
->GetEnchantmentId(slot
))
11671 // remove from stats
11672 ApplyEnchantment(itr
->item
,slot
,false,false);
11674 itr
->item
->ClearEnchantment(slot
);
11676 // remove from update list
11677 next
= m_enchantDuration
.erase(itr
);
11683 // remove enchants from inventory items
11684 // NOTE: no need to remove these from stats, since these aren't equipped
11686 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
11688 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11689 if( pItem
&& pItem
->GetEnchantmentId(slot
) )
11690 pItem
->ClearEnchantment(slot
);
11693 // in inventory bags
11694 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11696 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11699 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
11701 Item
* pItem
= pBag
->GetItemByPos(j
);
11702 if( pItem
&& pItem
->GetEnchantmentId(slot
) )
11703 pItem
->ClearEnchantment(slot
);
11709 // duration == 0 will remove item enchant
11710 void Player::AddEnchantmentDuration(Item
*item
,EnchantmentSlot slot
,uint32 duration
)
11715 if(slot
>= MAX_ENCHANTMENT_SLOT
)
11718 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
11720 if(itr
->item
== item
&& itr
->slot
== slot
)
11722 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
11723 m_enchantDuration
.erase(itr
);
11727 if(item
&& duration
> 0 )
11729 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item
->GetGUID(),slot
,uint32(duration
/1000));
11730 m_enchantDuration
.push_back(EnchantDuration(item
,slot
,duration
));
11734 void Player::ApplyEnchantment(Item
*item
,bool apply
)
11736 for(uint32 slot
= 0; slot
< MAX_ENCHANTMENT_SLOT
; ++slot
)
11737 ApplyEnchantment(item
, EnchantmentSlot(slot
), apply
);
11740 void Player::ApplyEnchantment(Item
*item
,EnchantmentSlot slot
,bool apply
, bool apply_dur
, bool ignore_condition
)
11745 if(!item
->IsEquipped())
11748 if(slot
>= MAX_ENCHANTMENT_SLOT
)
11751 uint32 enchant_id
= item
->GetEnchantmentId(slot
);
11755 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
11759 if(!ignore_condition
&& pEnchant
->EnchantmentCondition
&& !((Player
*)this)->EnchantmentFitsRequirements(pEnchant
->EnchantmentCondition
, -1))
11762 for (int s
=0; s
<3; s
++)
11764 uint32 enchant_display_type
= pEnchant
->type
[s
];
11765 uint32 enchant_amount
= pEnchant
->amount
[s
];
11766 uint32 enchant_spell_id
= pEnchant
->spellid
[s
];
11768 switch(enchant_display_type
)
11770 case ITEM_ENCHANTMENT_TYPE_NONE
:
11772 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
:
11773 // processed in Player::CastItemCombatSpell
11775 case ITEM_ENCHANTMENT_TYPE_DAMAGE
:
11776 if (item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
11777 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11778 else if (item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
11779 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11780 else if (item
->GetSlot() == EQUIPMENT_SLOT_RANGED
)
11781 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11783 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL
:
11784 if(enchant_spell_id
)
11788 int32 basepoints
= 0;
11789 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11790 if (item
->GetItemRandomPropertyId())
11792 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11795 // Search enchant_amount
11796 for (int k
=0; k
<3; k
++)
11798 if(item_rand
->enchant_id
[k
] == enchant_id
)
11800 basepoints
= int32((item_rand
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11806 // Cast custom spell vs all equal basepoints getted from enchant_amount
11808 CastCustomSpell(this,enchant_spell_id
,&basepoints
,&basepoints
,&basepoints
,true,item
);
11810 CastSpell(this,enchant_spell_id
,true,item
);
11813 RemoveAurasDueToItemSpell(item
,enchant_spell_id
);
11816 case ITEM_ENCHANTMENT_TYPE_RESISTANCE
:
11817 if (!enchant_amount
)
11819 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11822 for (int k
=0; k
<3; k
++)
11824 if(item_rand
->enchant_id
[k
] == enchant_id
)
11826 enchant_amount
= uint32((item_rand
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11833 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START
+ enchant_spell_id
), TOTAL_VALUE
, float(enchant_amount
), apply
);
11835 case ITEM_ENCHANTMENT_TYPE_STAT
:
11837 if (!enchant_amount
)
11839 ItemRandomSuffixEntry
const *item_rand_suffix
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11840 if(item_rand_suffix
)
11842 for (int k
=0; k
<3; k
++)
11844 if(item_rand_suffix
->enchant_id
[k
] == enchant_id
)
11846 enchant_amount
= uint32((item_rand_suffix
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11853 sLog
.outDebug("Adding %u to stat nb %u",enchant_amount
,enchant_spell_id
);
11854 switch (enchant_spell_id
)
11856 case ITEM_MOD_AGILITY
:
11857 sLog
.outDebug("+ %u AGILITY",enchant_amount
);
11858 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11859 ApplyStatBuffMod(STAT_AGILITY
, enchant_amount
, apply
);
11861 case ITEM_MOD_STRENGTH
:
11862 sLog
.outDebug("+ %u STRENGTH",enchant_amount
);
11863 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11864 ApplyStatBuffMod(STAT_STRENGTH
, enchant_amount
, apply
);
11866 case ITEM_MOD_INTELLECT
:
11867 sLog
.outDebug("+ %u INTELLECT",enchant_amount
);
11868 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11869 ApplyStatBuffMod(STAT_INTELLECT
, enchant_amount
, apply
);
11871 case ITEM_MOD_SPIRIT
:
11872 sLog
.outDebug("+ %u SPIRIT",enchant_amount
);
11873 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11874 ApplyStatBuffMod(STAT_SPIRIT
, enchant_amount
, apply
);
11876 case ITEM_MOD_STAMINA
:
11877 sLog
.outDebug("+ %u STAMINA",enchant_amount
);
11878 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11879 ApplyStatBuffMod(STAT_STAMINA
, enchant_amount
, apply
);
11881 case ITEM_MOD_DEFENSE_SKILL_RATING
:
11882 ((Player
*)this)->ApplyRatingMod(CR_DEFENSE_SKILL
, enchant_amount
, apply
);
11883 sLog
.outDebug("+ %u DEFENCE", enchant_amount
);
11885 case ITEM_MOD_DODGE_RATING
:
11886 ((Player
*)this)->ApplyRatingMod(CR_DODGE
, enchant_amount
, apply
);
11887 sLog
.outDebug("+ %u DODGE", enchant_amount
);
11889 case ITEM_MOD_PARRY_RATING
:
11890 ((Player
*)this)->ApplyRatingMod(CR_PARRY
, enchant_amount
, apply
);
11891 sLog
.outDebug("+ %u PARRY", enchant_amount
);
11893 case ITEM_MOD_BLOCK_RATING
:
11894 ((Player
*)this)->ApplyRatingMod(CR_BLOCK
, enchant_amount
, apply
);
11895 sLog
.outDebug("+ %u SHIELD_BLOCK", enchant_amount
);
11897 case ITEM_MOD_HIT_MELEE_RATING
:
11898 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
11899 sLog
.outDebug("+ %u MELEE_HIT", enchant_amount
);
11901 case ITEM_MOD_HIT_RANGED_RATING
:
11902 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
11903 sLog
.outDebug("+ %u RANGED_HIT", enchant_amount
);
11905 case ITEM_MOD_HIT_SPELL_RATING
:
11906 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
11907 sLog
.outDebug("+ %u SPELL_HIT", enchant_amount
);
11909 case ITEM_MOD_CRIT_MELEE_RATING
:
11910 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
11911 sLog
.outDebug("+ %u MELEE_CRIT", enchant_amount
);
11913 case ITEM_MOD_CRIT_RANGED_RATING
:
11914 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
11915 sLog
.outDebug("+ %u RANGED_CRIT", enchant_amount
);
11917 case ITEM_MOD_CRIT_SPELL_RATING
:
11918 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
11919 sLog
.outDebug("+ %u SPELL_CRIT", enchant_amount
);
11921 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11923 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11924 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11926 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11927 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11929 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11930 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11932 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11933 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11935 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11936 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11938 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11939 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11941 // case ITEM_MOD_HASTE_MELEE_RATING:
11942 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11944 // case ITEM_MOD_HASTE_RANGED_RATING:
11945 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11947 case ITEM_MOD_HASTE_SPELL_RATING
:
11948 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
11950 case ITEM_MOD_HIT_RATING
:
11951 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
11952 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
11953 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
11954 sLog
.outDebug("+ %u HIT", enchant_amount
);
11956 case ITEM_MOD_CRIT_RATING
:
11957 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
11958 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
11959 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
11960 sLog
.outDebug("+ %u CRITICAL", enchant_amount
);
11962 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11963 // case ITEM_MOD_HIT_TAKEN_RATING:
11964 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11965 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11966 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11968 // case ITEM_MOD_CRIT_TAKEN_RATING:
11969 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11970 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11971 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11973 case ITEM_MOD_RESILIENCE_RATING
:
11974 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, enchant_amount
, apply
);
11975 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, enchant_amount
, apply
);
11976 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, enchant_amount
, apply
);
11977 sLog
.outDebug("+ %u RESILIENCE", enchant_amount
);
11979 case ITEM_MOD_HASTE_RATING
:
11980 ((Player
*)this)->ApplyRatingMod(CR_HASTE_MELEE
, enchant_amount
, apply
);
11981 ((Player
*)this)->ApplyRatingMod(CR_HASTE_RANGED
, enchant_amount
, apply
);
11982 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
11983 sLog
.outDebug("+ %u HASTE", enchant_amount
);
11985 case ITEM_MOD_EXPERTISE_RATING
:
11986 ((Player
*)this)->ApplyRatingMod(CR_EXPERTISE
, enchant_amount
, apply
);
11987 sLog
.outDebug("+ %u EXPERTISE", enchant_amount
);
11989 case ITEM_MOD_ATTACK_POWER
:
11990 HandleStatModifier(UNIT_MOD_ATTACK_POWER
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11991 sLog
.outDebug("+ %u ATTACK_POWER", enchant_amount
);
11993 case ITEM_MOD_RANGED_ATTACK_POWER
:
11994 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11995 sLog
.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount
);
11997 case ITEM_MOD_FERAL_ATTACK_POWER
:
11998 ((Player
*)this)->ApplyFeralAPBonus(enchant_amount
, apply
);
11999 sLog
.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount
);
12001 case ITEM_MOD_SPELL_HEALING_DONE
:
12002 ((Player
*)this)->ApplySpellHealingBonus(enchant_amount
, apply
);
12003 sLog
.outDebug("+ %u SPELL_HEALING_DONE", enchant_amount
);
12005 case ITEM_MOD_SPELL_DAMAGE_DONE
:
12006 ((Player
*)this)->ApplySpellDamageBonus(enchant_amount
, apply
);
12007 sLog
.outDebug("+ %u SPELL_DAMAGE_DONE", enchant_amount
);
12009 case ITEM_MOD_MANA_REGENERATION
:
12010 ((Player
*)this)->ApplyManaRegenBonus(enchant_amount
, apply
);
12011 sLog
.outDebug("+ %u MANA_REGENERATION", enchant_amount
);
12013 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
12014 ((Player
*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION
, enchant_amount
, apply
);
12015 sLog
.outDebug("+ %u ARMOR PENETRATION", enchant_amount
);
12017 case ITEM_MOD_SPELL_POWER
:
12018 ((Player
*)this)->ApplySpellHealingBonus(enchant_amount
, apply
);
12019 ((Player
*)this)->ApplySpellDamageBonus(enchant_amount
, apply
);
12020 sLog
.outDebug("+ %u SPELL_POWER", enchant_amount
);
12027 case ITEM_ENCHANTMENT_TYPE_TOTEM
: // Shaman Rockbiter Weapon
12029 if(getClass() == CLASS_SHAMAN
)
12031 float addValue
= 0.0f
;
12032 if(item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
12034 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/1000.0f
);
12035 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, addValue
, apply
);
12037 else if(item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
12039 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/1000.0f
);
12040 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, addValue
, apply
);
12045 case ITEM_ENCHANTMENT_TYPE_USE_SPELL
:
12046 // processed in Player::CastItemUseSpell
12049 sLog
.outError("Unknown item enchantment display type: %d",enchant_display_type
);
12051 } /*switch(enchant_display_type)*/
12054 // visualize enchantment at player and equipped items
12055 if(slot
< MAX_INSPECTED_ENCHANTMENT_SLOT
)
12057 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (item
->GetSlot() * MAX_VISIBLE_ITEM_OFFSET
);
12058 SetUInt32Value(VisibleBase
+ 1 + slot
, apply
? item
->GetEnchantmentId(slot
) : 0);
12066 uint32 duration
= item
->GetEnchantmentDuration(slot
);
12068 AddEnchantmentDuration(item
,slot
,duration
);
12072 // duration == 0 will remove EnchantDuration
12073 AddEnchantmentDuration(item
,slot
,0);
12078 void Player::SendEnchantmentDurations()
12080 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
12082 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr
->item
->GetGUID(),itr
->slot
,uint32(itr
->leftduration
)/1000);
12086 void Player::SendItemDurations()
12088 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end();++itr
)
12090 (*itr
)->SendTimeUpdate(this);
12094 void Player::SendNewItem(Item
*item
, uint32 count
, bool received
, bool created
, bool broadcast
)
12096 if(!item
) // prevent crash
12099 // last check 2.0.10
12100 WorldPacket
data( SMSG_ITEM_PUSH_RESULT
, (8+4+4+4+1+4+4+4+4+4) );
12101 data
<< GetGUID(); // player GUID
12102 data
<< uint32(received
); // 0=looted, 1=from npc
12103 data
<< uint32(created
); // 0=received, 1=created
12104 data
<< uint32(1); // always 0x01 (probably meant to be count of listed items)
12105 data
<< (uint8
)item
->GetBagSlot(); // bagslot
12106 // item slot, but when added to stack: 0xFFFFFFFF
12107 data
<< (uint32
) ((item
->GetCount()==count
) ? item
->GetSlot() : -1);
12108 data
<< uint32(item
->GetEntry()); // item id
12109 data
<< uint32(item
->GetItemSuffixFactor()); // SuffixFactor
12110 data
<< uint32(item
->GetItemRandomPropertyId()); // random item property id
12111 data
<< uint32(count
); // count of items
12112 data
<< GetItemCount(item
->GetEntry()); // count of items in inventory
12114 if (broadcast
&& GetGroup())
12115 GetGroup()->BroadcastPacket(&data
);
12117 GetSession()->SendPacket(&data
);
12120 /*********************************************************/
12121 /*** QUEST SYSTEM ***/
12122 /*********************************************************/
12124 void Player::PrepareQuestMenu( uint64 guid
)
12127 QuestRelations
* pObjectQR
;
12128 QuestRelations
* pObjectQIR
;
12129 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
12132 pObject
= (Object
*)pCreature
;
12133 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
12134 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
12138 GameObject
*pGameObject
= ObjectAccessor::GetGameObject(*this, guid
);
12141 pObject
= (Object
*)pGameObject
;
12142 pObjectQR
= &objmgr
.mGOQuestRelations
;
12143 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
12149 QuestMenu
&qm
= PlayerTalkClass
->GetQuestMenu();
12152 for(QuestRelations::const_iterator i
= pObjectQIR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQIR
->upper_bound(pObject
->GetEntry()); ++i
)
12154 uint32 quest_id
= i
->second
;
12155 QuestStatus status
= GetQuestStatus( quest_id
);
12156 if ( status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus( quest_id
) )
12157 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_REWARD_REP
);
12158 else if ( status
== QUEST_STATUS_INCOMPLETE
)
12159 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_INCOMPLETE
);
12160 else if (status
== QUEST_STATUS_AVAILABLE
)
12161 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_CHAT
);
12164 for(QuestRelations::const_iterator i
= pObjectQR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++i
)
12166 uint32 quest_id
= i
->second
;
12167 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
12168 if(!pQuest
) continue;
12170 QuestStatus status
= GetQuestStatus( quest_id
);
12172 if (pQuest
->IsAutoComplete() && CanTakeQuest(pQuest
, false))
12173 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_REWARD_REP
);
12174 else if ( status
== QUEST_STATUS_NONE
&& CanTakeQuest( pQuest
, false ) )
12175 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_AVAILABLE
);
12179 void Player::SendPreparedQuest( uint64 guid
)
12181 QuestMenu
& questMenu
= PlayerTalkClass
->GetQuestMenu();
12182 if( questMenu
.Empty() )
12185 QuestMenuItem
const& qmi0
= questMenu
.GetItem( 0 );
12187 uint32 status
= qmi0
.m_qIcon
;
12189 // single element case
12190 if ( questMenu
.MenuItemCount() == 1 )
12192 // Auto open -- maybe also should verify there is no greeting
12193 uint32 quest_id
= qmi0
.m_qId
;
12194 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
12197 if( status
== DIALOG_STATUS_REWARD_REP
&& !GetQuestRewardStatus( quest_id
) )
12198 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, CanRewardQuest(pQuest
,false), true );
12199 else if( status
== DIALOG_STATUS_INCOMPLETE
)
12200 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, false, true );
12201 // Send completable on repeatable quest if player don't have quest
12202 else if( pQuest
->IsRepeatable() && !pQuest
->IsDaily() )
12203 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, CanCompleteRepeatableQuest(pQuest
), true );
12205 PlayerTalkClass
->SendQuestGiverQuestDetails( pQuest
, guid
, true );
12208 // multiply entries
12214 std::string title
= "";
12215 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
12218 uint32 textid
= pCreature
->GetNpcTextId();
12219 GossipText
* gossiptext
= objmgr
.GetGossipText(textid
);
12222 qe
._Delay
= 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12223 qe
._Emote
= 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12228 qe
= gossiptext
->Options
[0].Emotes
[0];
12230 if(!gossiptext
->Options
[0].Text_0
.empty())
12232 title
= gossiptext
->Options
[0].Text_0
;
12234 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
12237 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
12240 if (nl
->Text_0
[0].size() > loc_idx
&& !nl
->Text_0
[0][loc_idx
].empty())
12241 title
= nl
->Text_0
[0][loc_idx
];
12247 title
= gossiptext
->Options
[0].Text_1
;
12249 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
12252 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
12255 if (nl
->Text_1
[0].size() > loc_idx
&& !nl
->Text_1
[0][loc_idx
].empty())
12256 title
= nl
->Text_1
[0][loc_idx
];
12262 PlayerTalkClass
->SendQuestGiverQuestList( qe
, title
, guid
);
12266 bool Player::IsActiveQuest( uint32 quest_id
) const
12268 QuestStatusMap::const_iterator itr
= mQuestStatus
.find(quest_id
);
12270 return itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
;
12273 Quest
const * Player::GetNextQuest( uint64 guid
, Quest
const *pQuest
)
12276 QuestRelations
* pObjectQR
;
12277 QuestRelations
* pObjectQIR
;
12279 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
12282 pObject
= (Object
*)pCreature
;
12283 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
12284 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
12288 GameObject
*pGameObject
= ObjectAccessor::GetGameObject(*this, guid
);
12291 pObject
= (Object
*)pGameObject
;
12292 pObjectQR
= &objmgr
.mGOQuestRelations
;
12293 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
12299 uint32 nextQuestID
= pQuest
->GetNextQuestInChain();
12300 for(QuestRelations::const_iterator itr
= pObjectQR
->lower_bound(pObject
->GetEntry()); itr
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++itr
)
12302 if (itr
->second
== nextQuestID
)
12303 return objmgr
.GetQuestTemplate(nextQuestID
);
12309 bool Player::CanSeeStartQuest( Quest
const *pQuest
)
12311 if( SatisfyQuestRace( pQuest
, false ) && SatisfyQuestSkillOrClass( pQuest
, false ) &&
12312 SatisfyQuestExclusiveGroup( pQuest
, false ) && SatisfyQuestReputation( pQuest
, false ) &&
12313 SatisfyQuestPreviousQuest( pQuest
, false ) && SatisfyQuestNextChain( pQuest
, false ) &&
12314 SatisfyQuestPrevChain( pQuest
, false ) && SatisfyQuestDay( pQuest
, false ) )
12316 return getLevel() + sWorld
.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF
) >= pQuest
->GetMinLevel();
12322 bool Player::CanTakeQuest( Quest
const *pQuest
, bool msg
)
12324 return SatisfyQuestStatus( pQuest
, msg
) && SatisfyQuestExclusiveGroup( pQuest
, msg
)
12325 && SatisfyQuestRace( pQuest
, msg
) && SatisfyQuestLevel( pQuest
, msg
)
12326 && SatisfyQuestSkillOrClass( pQuest
, msg
) && SatisfyQuestReputation( pQuest
, msg
)
12327 && SatisfyQuestPreviousQuest( pQuest
, msg
) && SatisfyQuestTimed( pQuest
, msg
)
12328 && SatisfyQuestNextChain( pQuest
, msg
) && SatisfyQuestPrevChain( pQuest
, msg
)
12329 && SatisfyQuestDay( pQuest
, msg
);
12332 bool Player::CanAddQuest( Quest
const *pQuest
, bool msg
)
12334 if( !SatisfyQuestLog( msg
) )
12337 uint32 srcitem
= pQuest
->GetSrcItemId();
12340 uint32 count
= pQuest
->GetSrcItemCount();
12341 ItemPosCountVec dest
;
12342 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
12344 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12345 if( msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
12347 else if( msg
!= EQUIP_ERR_OK
)
12349 SendEquipError( msg
, NULL
, NULL
);
12356 bool Player::CanCompleteQuest( uint32 quest_id
)
12360 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12361 if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
12362 return false; // not allow re-complete quest
12364 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12369 // auto complete quest
12370 if (qInfo
->IsAutoComplete() && CanTakeQuest(qInfo
, false))
12373 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
12376 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12378 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12380 if( qInfo
->ReqItemCount
[i
]!= 0 && q_status
.m_itemcount
[i
] < qInfo
->ReqItemCount
[i
] )
12385 if ( qInfo
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
12387 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12389 if( qInfo
->ReqCreatureOrGOId
[i
] == 0 )
12392 if( qInfo
->ReqCreatureOrGOCount
[i
] != 0 && q_status
.m_creatureOrGOcount
[i
] < qInfo
->ReqCreatureOrGOCount
[i
] )
12397 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT
) && !q_status
.m_explored
)
12400 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && q_status
.m_timer
== 0 )
12403 if ( qInfo
->GetRewOrReqMoney() < 0 )
12405 if ( GetMoney() < uint32(-qInfo
->GetRewOrReqMoney()) )
12409 uint32 repFacId
= qInfo
->GetRepObjectiveFaction();
12410 if ( repFacId
&& GetReputation(repFacId
) < qInfo
->GetRepObjectiveValue() )
12419 bool Player::CanCompleteRepeatableQuest( Quest
const *pQuest
)
12421 // Solve problem that player don't have the quest and try complete it.
12422 // if repeatable she must be able to complete event if player don't have it.
12423 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12424 if( !CanTakeQuest(pQuest
, false) )
12427 if (pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12428 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12429 if( pQuest
->ReqItemId
[i
] && pQuest
->ReqItemCount
[i
] && !HasItemCount(pQuest
->ReqItemId
[i
],pQuest
->ReqItemCount
[i
]) )
12432 if( !CanRewardQuest(pQuest
, false) )
12438 bool Player::CanRewardQuest( Quest
const *pQuest
, bool msg
)
12440 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12441 if(!pQuest
->IsAutoComplete() && GetQuestStatus(pQuest
->GetQuestId()) != QUEST_STATUS_COMPLETE
)
12444 // daily quest can't be rewarded (25 daily quest already completed)
12445 if(!SatisfyQuestDay(pQuest
,true))
12448 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12449 if(GetQuestRewardStatus(pQuest
->GetQuestId()))
12452 // prevent receive reward with quest items in bank
12453 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12455 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12457 if( pQuest
->ReqItemCount
[i
]!= 0 &&
12458 GetItemCount(pQuest
->ReqItemId
[i
]) < pQuest
->ReqItemCount
[i
] )
12461 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, NULL
, NULL
);
12467 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12468 if(pQuest
->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest
->GetRewOrReqMoney()) )
12474 bool Player::CanRewardQuest( Quest
const *pQuest
, uint32 reward
, bool msg
)
12476 // prevent receive reward with quest items in bank or for not completed quest
12477 if(!CanRewardQuest(pQuest
,msg
))
12480 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
12482 if( pQuest
->RewChoiceItemId
[reward
] )
12484 ItemPosCountVec dest
;
12485 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] );
12486 if( res
!= EQUIP_ERR_OK
)
12488 SendEquipError( res
, NULL
, NULL
);
12494 if ( pQuest
->GetRewItemsCount() > 0 )
12496 for (uint32 i
= 0; i
< pQuest
->GetRewItemsCount(); ++i
)
12498 if( pQuest
->RewItemId
[i
] )
12500 ItemPosCountVec dest
;
12501 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] );
12502 if( res
!= EQUIP_ERR_OK
)
12504 SendEquipError( res
, NULL
, NULL
);
12514 void Player::AddQuest( Quest
const *pQuest
, Object
*questGiver
)
12516 uint16 log_slot
= FindQuestSlot( 0 );
12517 assert(log_slot
< MAX_QUEST_LOG_SIZE
);
12519 uint32 quest_id
= pQuest
->GetQuestId();
12521 // if not exist then created with set uState==NEW and rewarded=false
12522 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
12523 if (questStatusData
.uState
!= QUEST_NEW
)
12524 questStatusData
.uState
= QUEST_CHANGED
;
12526 // check for repeatable quests status reset
12527 questStatusData
.m_status
= QUEST_STATUS_INCOMPLETE
;
12528 questStatusData
.m_explored
= false;
12530 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12532 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12533 questStatusData
.m_itemcount
[i
] = 0;
12536 if ( pQuest
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
12538 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12539 questStatusData
.m_creatureOrGOcount
[i
] = 0;
12542 GiveQuestSourceItem( pQuest
);
12543 AdjustQuestReqItemCount( pQuest
);
12545 if( pQuest
->GetRepObjectiveFaction() )
12546 SetFactionVisibleForFactionId(pQuest
->GetRepObjectiveFaction());
12549 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
12551 uint32 limittime
= pQuest
->GetLimitTime();
12553 // shared timed quest
12554 if(questGiver
&& questGiver
->GetTypeId()==TYPEID_PLAYER
)
12555 limittime
= ((Player
*)questGiver
)->getQuestStatusMap()[quest_id
].m_timer
/ 1000;
12557 AddTimedQuest( quest_id
);
12558 questStatusData
.m_timer
= limittime
* 1000;
12559 qtime
= static_cast<uint32
>(time(NULL
)) + limittime
;
12562 questStatusData
.m_timer
= 0;
12564 SetQuestSlot(log_slot
, quest_id
, qtime
);
12566 //starting initial quest script
12567 if(questGiver
&& pQuest
->GetQuestStartScript()!=0)
12568 sWorld
.ScriptsStart(sQuestStartScripts
, pQuest
->GetQuestStartScript(), questGiver
, this);
12570 UpdateForQuestsGO();
12573 void Player::CompleteQuest( uint32 quest_id
)
12577 SetQuestStatus( quest_id
, QUEST_STATUS_COMPLETE
);
12579 uint16 log_slot
= FindQuestSlot( quest_id
);
12580 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12581 SetQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
12583 if(Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
))
12585 if( qInfo
->HasFlag(QUEST_FLAGS_AUTO_REWARDED
) )
12586 RewardQuest(qInfo
,0,this,false);
12588 SendQuestComplete( quest_id
);
12593 void Player::IncompleteQuest( uint32 quest_id
)
12597 SetQuestStatus( quest_id
, QUEST_STATUS_INCOMPLETE
);
12599 uint16 log_slot
= FindQuestSlot( quest_id
);
12600 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12601 RemoveQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
12605 void Player::RewardQuest( Quest
const *pQuest
, uint32 reward
, Object
* questGiver
, bool announce
)
12607 uint32 quest_id
= pQuest
->GetQuestId();
12609 for (int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++ )
12611 if ( pQuest
->ReqItemId
[i
] )
12612 DestroyItemCount( pQuest
->ReqItemId
[i
], pQuest
->ReqItemCount
[i
], true);
12615 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12616 // SetTimedQuest( 0 );
12617 m_timedquests
.erase(pQuest
->GetQuestId());
12619 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
12621 if( pQuest
->RewChoiceItemId
[reward
] )
12623 ItemPosCountVec dest
;
12624 if( CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] ) == EQUIP_ERR_OK
)
12626 Item
* item
= StoreNewItem( dest
, pQuest
->RewChoiceItemId
[reward
], true);
12627 SendNewItem(item
, pQuest
->RewChoiceItemCount
[reward
], true, false);
12632 if ( pQuest
->GetRewItemsCount() > 0 )
12634 for (uint32 i
=0; i
< pQuest
->GetRewItemsCount(); ++i
)
12636 if( pQuest
->RewItemId
[i
] )
12638 ItemPosCountVec dest
;
12639 if( CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] ) == EQUIP_ERR_OK
)
12641 Item
* item
= StoreNewItem( dest
, pQuest
->RewItemId
[i
], true);
12642 SendNewItem(item
, pQuest
->RewItemCount
[i
], true, false);
12648 RewardReputation( pQuest
);
12650 if( pQuest
->GetRewSpellCast() > 0 )
12651 CastSpell( this, pQuest
->GetRewSpellCast(), true);
12652 else if( pQuest
->GetRewSpell() > 0)
12653 CastSpell( this, pQuest
->GetRewSpell(), true);
12655 uint16 log_slot
= FindQuestSlot( quest_id
);
12656 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12657 SetQuestSlot(log_slot
,0);
12659 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12661 // Not give XP in case already completed once repeatable quest
12662 uint32 XP
= q_status
.m_rewarded
? 0 : uint32(pQuest
->XPValue( this )*sWorld
.getRate(RATE_XP_QUEST
));
12664 if ( getLevel() < sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
12665 GiveXP( XP
, NULL
);
12667 ModifyMoney( int32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getRate(RATE_DROP_MONEY
)) );
12669 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12670 ModifyMoney( pQuest
->GetRewOrReqMoney() );
12673 if(pQuest
->GetRewHonorableKills())
12674 RewardHonor(NULL
, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorableKills()));
12677 if(pQuest
->GetCharTitleId())
12679 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
12680 SetTitle(titleEntry
);
12683 if(pQuest
->GetBonusTalents())
12685 m_questRewardTalentCount
+=pQuest
->GetBonusTalents();
12686 InitTalentForLevel();
12689 // Send reward mail
12690 if(pQuest
->GetRewMailTemplateId())
12692 MailMessageType mailType
;
12693 uint32 senderGuidOrEntry
;
12694 switch(questGiver
->GetTypeId())
12697 mailType
= MAIL_CREATURE
;
12698 senderGuidOrEntry
= questGiver
->GetEntry();
12700 case TYPEID_GAMEOBJECT
:
12701 mailType
= MAIL_GAMEOBJECT
;
12702 senderGuidOrEntry
= questGiver
->GetEntry();
12705 mailType
= MAIL_ITEM
;
12706 senderGuidOrEntry
= questGiver
->GetEntry();
12708 case TYPEID_PLAYER
:
12709 mailType
= MAIL_NORMAL
;
12710 senderGuidOrEntry
= questGiver
->GetGUIDLow();
12713 mailType
= MAIL_NORMAL
;
12714 senderGuidOrEntry
= GetGUIDLow();
12718 Loot questMailLoot
;
12720 questMailLoot
.FillLoot(pQuest
->GetQuestId(), LootTemplates_QuestMail
, this);
12723 MailItemsInfo mi
; // item list preparing
12725 for(size_t i
= 0; mi
.size() < MAX_MAIL_ITEMS
&& i
< questMailLoot
.items
.size(); ++i
)
12727 if(LootItem
* lootitem
= questMailLoot
.LootItemInSlot(i
,this))
12729 if(Item
* item
= Item::CreateItem(lootitem
->itemid
,lootitem
->count
,this))
12731 item
->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12732 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
12737 for(size_t i
= 0; mi
.size() < MAX_MAIL_ITEMS
&& i
< questMailLoot
.quest_items
.size(); ++i
)
12739 if(LootItem
* lootitem
= questMailLoot
.LootItemInSlot(i
+questMailLoot
.items
.size(),this))
12741 if(Item
* item
= Item::CreateItem(lootitem
->itemid
,lootitem
->count
,this))
12743 item
->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12744 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
12749 WorldSession::SendMailTo(this, mailType
, MAIL_STATIONERY_NORMAL
, senderGuidOrEntry
, GetGUIDLow(), "", 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
,pQuest
->GetRewMailDelaySecs(),pQuest
->GetRewMailTemplateId());
12752 if(pQuest
->IsDaily())
12754 SetDailyQuestStatus(quest_id
);
12755 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST
, 1);
12758 if ( !pQuest
->IsRepeatable() )
12759 SetQuestStatus(quest_id
, QUEST_STATUS_COMPLETE
);
12761 SetQuestStatus(quest_id
, QUEST_STATUS_NONE
);
12763 q_status
.m_rewarded
= true;
12766 SendQuestReward( pQuest
, XP
, questGiver
);
12768 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12769 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT
);
12770 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST
);
12773 void Player::FailQuest( uint32 quest_id
)
12777 IncompleteQuest( quest_id
);
12779 uint16 log_slot
= FindQuestSlot( quest_id
);
12780 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12782 SetQuestSlotTimer(log_slot
, 1 );
12783 SetQuestSlotState(log_slot
,QUEST_STATE_FAIL
);
12785 SendQuestFailed( quest_id
);
12789 void Player::FailTimedQuest( uint32 quest_id
)
12793 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12795 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12796 q_status
.m_timer
= 0;
12798 IncompleteQuest( quest_id
);
12800 uint16 log_slot
= FindQuestSlot( quest_id
);
12801 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12803 SetQuestSlotTimer(log_slot
, 1 );
12804 SetQuestSlotState(log_slot
,QUEST_STATE_FAIL
);
12806 SendQuestTimerFailed( quest_id
);
12810 bool Player::SatisfyQuestSkillOrClass( Quest
const* qInfo
, bool msg
)
12812 int32 zoneOrSort
= qInfo
->GetZoneOrSort();
12813 int32 skillOrClass
= qInfo
->GetSkillOrClass();
12815 // skip zone zoneOrSort and 0 case skillOrClass
12816 if( zoneOrSort
>= 0 && skillOrClass
== 0 )
12819 int32 questSort
= -zoneOrSort
;
12820 uint8 reqSortClass
= ClassByQuestSort(questSort
);
12822 // check class sort cases in zoneOrSort
12823 if( reqSortClass
!= 0 && getClass() != reqSortClass
)
12826 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12831 if( skillOrClass
< 0 )
12833 uint8 reqClass
= -int32(skillOrClass
);
12834 if(getClass() != reqClass
)
12837 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12842 else if( skillOrClass
> 0 )
12844 uint32 reqSkill
= skillOrClass
;
12845 if( GetSkillValue( reqSkill
) < qInfo
->GetRequiredSkillValue() )
12848 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12856 bool Player::SatisfyQuestLevel( Quest
const* qInfo
, bool msg
)
12858 if( getLevel() < qInfo
->GetMinLevel() )
12861 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12867 bool Player::SatisfyQuestLog( bool msg
)
12870 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE
)
12875 WorldPacket
data( SMSG_QUESTLOG_FULL
, 0 );
12876 GetSession()->SendPacket( &data
);
12877 sLog
.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12882 bool Player::SatisfyQuestPreviousQuest( Quest
const* qInfo
, bool msg
)
12884 // No previous quest (might be first quest in a series)
12885 if( qInfo
->prevQuests
.empty())
12888 for(Quest::PrevQuests::const_iterator iter
= qInfo
->prevQuests
.begin(); iter
!= qInfo
->prevQuests
.end(); ++iter
)
12890 uint32 prevId
= abs(*iter
);
12892 QuestStatusMap::iterator i_prevstatus
= mQuestStatus
.find( prevId
);
12893 Quest
const* qPrevInfo
= objmgr
.GetQuestTemplate(prevId
);
12895 if( qPrevInfo
&& i_prevstatus
!= mQuestStatus
.end() )
12897 // If any of the positive previous quests completed, return true
12898 if( *iter
> 0 && i_prevstatus
->second
.m_rewarded
)
12900 // skip one-from-all exclusive group
12901 if(qPrevInfo
->GetExclusiveGroup() >= 0)
12904 // each-from-all exclusive group ( < 0)
12905 // can be start if only all quests in prev quest exclusive group completed and rewarded
12906 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
12907 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
12909 assert(iter
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
12911 for(; iter
!= end
; ++iter
)
12913 uint32 exclude_Id
= iter
->second
;
12915 // skip checked quest id, only state of other quests in group is interesting
12916 if(exclude_Id
== prevId
)
12919 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12921 // alternative quest from group also must be completed and rewarded(reported)
12922 if( i_exstatus
== mQuestStatus
.end() || !i_exstatus
->second
.m_rewarded
)
12925 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12931 // If any of the negative previous quests active, return true
12932 if( *iter
< 0 && (i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
12933 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
))))
12935 // skip one-from-all exclusive group
12936 if(qPrevInfo
->GetExclusiveGroup() >= 0)
12939 // each-from-all exclusive group ( < 0)
12940 // can be start if only all quests in prev quest exclusive group active
12941 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
12942 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
12944 assert(iter
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
12946 for(; iter
!= end
; ++iter
)
12948 uint32 exclude_Id
= iter
->second
;
12950 // skip checked quest id, only state of other quests in group is interesting
12951 if(exclude_Id
== prevId
)
12954 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12956 // alternative quest from group also must be active
12957 if( i_exstatus
== mQuestStatus
.end() ||
12958 i_exstatus
->second
.m_status
!= QUEST_STATUS_INCOMPLETE
&&
12959 (i_prevstatus
->second
.m_status
!= QUEST_STATUS_COMPLETE
|| GetQuestRewardStatus(prevId
)) )
12962 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12971 // Has only positive prev. quests in non-rewarded state
12972 // and negative prev. quests in non-active state
12974 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12979 bool Player::SatisfyQuestRace( Quest
const* qInfo
, bool msg
)
12981 uint32 reqraces
= qInfo
->GetRequiredRaces();
12982 if ( reqraces
== 0 )
12984 if( (reqraces
& getRaceMask()) == 0 )
12987 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE
);
12993 bool Player::SatisfyQuestReputation( Quest
const* qInfo
, bool msg
)
12995 uint32 fIdMin
= qInfo
->GetRequiredMinRepFaction(); //Min required rep
12996 if(fIdMin
&& GetReputation(fIdMin
) < qInfo
->GetRequiredMinRepValue())
12999 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13003 uint32 fIdMax
= qInfo
->GetRequiredMaxRepFaction(); //Max required rep
13004 if(fIdMax
&& GetReputation(fIdMax
) >= qInfo
->GetRequiredMaxRepValue())
13007 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13014 bool Player::SatisfyQuestStatus( Quest
const* qInfo
, bool msg
)
13016 QuestStatusMap::iterator itr
= mQuestStatus
.find( qInfo
->GetQuestId() );
13017 if ( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
)
13020 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON
);
13026 bool Player::SatisfyQuestTimed( Quest
const* qInfo
, bool msg
)
13028 if ( (find(m_timedquests
.begin(), m_timedquests
.end(), qInfo
->GetQuestId()) != m_timedquests
.end()) && qInfo
->HasFlag(QUEST_MANGOS_FLAGS_TIMED
) )
13031 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED
);
13037 bool Player::SatisfyQuestExclusiveGroup( Quest
const* qInfo
, bool msg
)
13039 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
13040 if(qInfo
->GetExclusiveGroup() <= 0)
13043 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qInfo
->GetExclusiveGroup());
13044 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qInfo
->GetExclusiveGroup());
13046 assert(iter
!=end
); // always must be found if qInfo->ExclusiveGroup != 0
13048 for(; iter
!= end
; ++iter
)
13050 uint32 exclude_Id
= iter
->second
;
13052 // skip checked quest id, only state of other quests in group is interesting
13053 if(exclude_Id
== qInfo
->GetQuestId())
13056 // not allow have daily quest if daily quest from exclusive group already recently completed
13057 Quest
const* Nquest
= objmgr
.GetQuestTemplate(exclude_Id
);
13058 if( !SatisfyQuestDay(Nquest
, false) )
13061 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13065 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
13067 // alternative quest already started or completed
13068 if( i_exstatus
!= mQuestStatus
.end()
13069 && (i_exstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
|| i_exstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
13072 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13079 bool Player::SatisfyQuestNextChain( Quest
const* qInfo
, bool msg
)
13081 if(!qInfo
->GetNextQuestInChain())
13084 // next quest in chain already started or completed
13085 QuestStatusMap::iterator itr
= mQuestStatus
.find( qInfo
->GetNextQuestInChain() );
13086 if( itr
!= mQuestStatus
.end()
13087 && (itr
->second
.m_status
== QUEST_STATUS_COMPLETE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
13090 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13094 // check for all quests further up the chain
13095 // only necessary if there are quest chains with more than one quest that can be skipped
13096 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
13100 bool Player::SatisfyQuestPrevChain( Quest
const* qInfo
, bool msg
)
13102 // No previous quest in chain
13103 if( qInfo
->prevChainQuests
.empty())
13106 for(Quest::PrevChainQuests::const_iterator iter
= qInfo
->prevChainQuests
.begin(); iter
!= qInfo
->prevChainQuests
.end(); ++iter
)
13108 uint32 prevId
= *iter
;
13110 QuestStatusMap::iterator i_prevstatus
= mQuestStatus
.find( prevId
);
13112 if( i_prevstatus
!= mQuestStatus
.end() )
13114 // If any of the previous quests in chain active, return false
13115 if( i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
13116 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
)))
13119 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
13124 // check for all quests further down the chain
13125 // only necessary if there are quest chains with more than one quest that can be skipped
13126 //if( !SatisfyQuestPrevChain( prevId, msg ) )
13130 // No previous quest in chain active
13134 bool Player::SatisfyQuestDay( Quest
const* qInfo
, bool msg
)
13136 if(!qInfo
->IsDaily())
13139 bool have_slot
= false;
13140 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
13142 uint32 id
= GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
);
13143 if(qInfo
->GetQuestId()==id
)
13153 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING
);
13160 bool Player::GiveQuestSourceItem( Quest
const *pQuest
)
13162 uint32 srcitem
= pQuest
->GetSrcItemId();
13165 uint32 count
= pQuest
->GetSrcItemCount();
13169 ItemPosCountVec dest
;
13170 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
13171 if( msg
== EQUIP_ERR_OK
)
13173 Item
* item
= StoreNewItem(dest
, srcitem
, true);
13174 SendNewItem(item
, count
, true, false);
13177 // player already have max amount required item, just report success
13178 else if( msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
13181 SendEquipError( msg
, NULL
, NULL
);
13188 bool Player::TakeQuestSourceItem( uint32 quest_id
, bool msg
)
13190 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13193 uint32 srcitem
= qInfo
->GetSrcItemId();
13196 uint32 count
= qInfo
->GetSrcItemCount();
13200 // exist one case when destroy source quest item not possible:
13201 // non un-equippable item (equipped non-empty bag, for example)
13202 uint8 res
= CanUnequipItems(srcitem
,count
);
13203 if(res
!= EQUIP_ERR_OK
)
13206 SendEquipError( res
, NULL
, NULL
);
13210 DestroyItemCount(srcitem
, count
, true, true);
13216 bool Player::GetQuestRewardStatus( uint32 quest_id
) const
13218 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13221 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
13222 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13223 if( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
13224 && !qInfo
->IsRepeatable() )
13225 return itr
->second
.m_rewarded
;
13232 QuestStatus
Player::GetQuestStatus( uint32 quest_id
) const
13236 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13237 if( itr
!= mQuestStatus
.end() )
13238 return itr
->second
.m_status
;
13240 return QUEST_STATUS_NONE
;
13243 bool Player::CanShareQuest(uint32 quest_id
) const
13245 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13246 if( qInfo
&& qInfo
->HasFlag(QUEST_FLAGS_SHARABLE
) )
13248 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
13249 if( itr
!= mQuestStatus
.end() )
13250 return itr
->second
.m_status
== QUEST_STATUS_NONE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
;
13255 void Player::SetQuestStatus( uint32 quest_id
, QuestStatus status
)
13257 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13260 if( status
== QUEST_STATUS_NONE
|| status
== QUEST_STATUS_INCOMPLETE
|| status
== QUEST_STATUS_COMPLETE
)
13262 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
13263 m_timedquests
.erase(qInfo
->GetQuestId());
13266 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
13268 q_status
.m_status
= status
;
13269 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13272 UpdateForQuestsGO();
13275 // not used in MaNGOS, but used in scripting code
13276 uint32
Player::GetReqKillOrCastCurrentCount(uint32 quest_id
, int32 entry
)
13278 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13282 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13283 if ( qInfo
->ReqCreatureOrGOId
[j
] == entry
)
13284 return mQuestStatus
[quest_id
].m_creatureOrGOcount
[j
];
13289 void Player::AdjustQuestReqItemCount( Quest
const* pQuest
)
13291 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13293 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
13295 uint32 reqitemcount
= pQuest
->ReqItemCount
[i
];
13296 if( reqitemcount
!= 0 )
13298 uint32 quest_id
= pQuest
->GetQuestId();
13299 uint32 curitemcount
= GetItemCount(pQuest
->ReqItemId
[i
],true);
13301 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
13302 q_status
.m_itemcount
[i
] = std::min(curitemcount
, reqitemcount
);
13303 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13309 uint16
Player::FindQuestSlot( uint32 quest_id
) const
13311 for ( uint16 i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13312 if ( GetQuestSlotQuestId(i
) == quest_id
)
13315 return MAX_QUEST_LOG_SIZE
;
13318 void Player::AreaExploredOrEventHappens( uint32 questId
)
13322 uint16 log_slot
= FindQuestSlot( questId
);
13323 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13325 QuestStatusData
& q_status
= mQuestStatus
[questId
];
13327 if(!q_status
.m_explored
)
13329 q_status
.m_explored
= true;
13330 if (q_status
.uState
!= QUEST_NEW
)
13331 q_status
.uState
= QUEST_CHANGED
;
13334 if( CanCompleteQuest( questId
) )
13335 CompleteQuest( questId
);
13339 //not used in mangosd, function for external script library
13340 void Player::GroupEventHappens( uint32 questId
, WorldObject
const* pEventObject
)
13342 if( Group
*pGroup
= GetGroup() )
13344 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
13346 Player
*pGroupGuy
= itr
->getSource();
13348 // for any leave or dead (with not released body) group member at appropriate distance
13349 if( pGroupGuy
&& pGroupGuy
->IsAtGroupRewardDistance(pEventObject
) && !pGroupGuy
->GetCorpse() )
13350 pGroupGuy
->AreaExploredOrEventHappens(questId
);
13354 AreaExploredOrEventHappens(questId
);
13357 void Player::ItemAddedQuestCheck( uint32 entry
, uint32 count
)
13359 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13361 uint32 questid
= GetQuestSlotQuestId(i
);
13362 if ( questid
== 0 )
13365 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13367 if ( q_status
.m_status
!= QUEST_STATUS_INCOMPLETE
)
13370 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13371 if( !qInfo
|| !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13374 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13376 uint32 reqitem
= qInfo
->ReqItemId
[j
];
13377 if ( reqitem
== entry
)
13379 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
13380 uint32 curitemcount
= q_status
.m_itemcount
[j
];
13381 if ( curitemcount
< reqitemcount
)
13383 uint32 additemcount
= ( curitemcount
+ count
<= reqitemcount
? count
: reqitemcount
- curitemcount
);
13384 q_status
.m_itemcount
[j
] += additemcount
;
13385 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13387 SendQuestUpdateAddItem( qInfo
, j
, additemcount
);
13389 if ( CanCompleteQuest( questid
) )
13390 CompleteQuest( questid
);
13395 UpdateForQuestsGO();
13396 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM
, entry
);
13399 void Player::ItemRemovedQuestCheck( uint32 entry
, uint32 count
)
13401 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13403 uint32 questid
= GetQuestSlotQuestId(i
);
13406 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13409 if( !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13412 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13414 uint32 reqitem
= qInfo
->ReqItemId
[j
];
13415 if ( reqitem
== entry
)
13417 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13419 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
13420 uint32 curitemcount
;
13421 if( q_status
.m_status
!= QUEST_STATUS_COMPLETE
)
13422 curitemcount
= q_status
.m_itemcount
[j
];
13424 curitemcount
= GetItemCount(entry
,true);
13425 if ( curitemcount
< reqitemcount
+ count
)
13427 uint32 remitemcount
= ( curitemcount
<= reqitemcount
? count
: count
+ reqitemcount
- curitemcount
);
13428 q_status
.m_itemcount
[j
] = curitemcount
- remitemcount
;
13429 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13431 IncompleteQuest( questid
);
13437 UpdateForQuestsGO();
13440 void Player::KilledMonster( uint32 entry
, uint64 guid
)
13442 uint32 addkillcount
= 1;
13443 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE
, entry
, addkillcount
);
13444 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13446 uint32 questid
= GetQuestSlotQuestId(i
);
13450 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13453 // just if !ingroup || !noraidgroup || raidgroup
13454 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13455 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
&& (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo
->GetType() == QUEST_TYPE_RAID
))
13457 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
13459 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13461 // skip GO activate objective or none
13462 if(qInfo
->ReqCreatureOrGOId
[j
] <=0)
13465 // skip Cast at creature objective
13466 if(qInfo
->ReqSpell
[j
] !=0 )
13469 uint32 reqkill
= qInfo
->ReqCreatureOrGOId
[j
];
13471 if ( reqkill
== entry
)
13473 uint32 reqkillcount
= qInfo
->ReqCreatureOrGOCount
[j
];
13474 uint32 curkillcount
= q_status
.m_creatureOrGOcount
[j
];
13475 if ( curkillcount
< reqkillcount
)
13477 q_status
.m_creatureOrGOcount
[j
] = curkillcount
+ addkillcount
;
13478 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13480 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curkillcount
, addkillcount
);
13482 if ( CanCompleteQuest( questid
) )
13483 CompleteQuest( questid
);
13485 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13494 void Player::CastedCreatureOrGO( uint32 entry
, uint64 guid
, uint32 spell_id
)
13496 bool isCreature
= IS_CREATURE_GUID(guid
);
13498 uint32 addCastCount
= 1;
13499 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13501 uint32 questid
= GetQuestSlotQuestId(i
);
13505 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13509 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13511 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13513 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
13515 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13517 // skip kill creature objective (0) or wrong spell casts
13518 if(qInfo
->ReqSpell
[j
] != spell_id
)
13521 uint32 reqTarget
= 0;
13525 // creature activate objectives
13526 if(qInfo
->ReqCreatureOrGOId
[j
] > 0)
13527 // checked at quest_template loading
13528 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
13532 // GO activate objective
13533 if(qInfo
->ReqCreatureOrGOId
[j
] < 0)
13534 // checked at quest_template loading
13535 reqTarget
= - qInfo
->ReqCreatureOrGOId
[j
];
13538 // other not this creature/GO related objectives
13539 if( reqTarget
!= entry
)
13542 uint32 reqCastCount
= qInfo
->ReqCreatureOrGOCount
[j
];
13543 uint32 curCastCount
= q_status
.m_creatureOrGOcount
[j
];
13544 if ( curCastCount
< reqCastCount
)
13546 q_status
.m_creatureOrGOcount
[j
] = curCastCount
+ addCastCount
;
13547 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13549 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curCastCount
, addCastCount
);
13552 if ( CanCompleteQuest( questid
) )
13553 CompleteQuest( questid
);
13555 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13563 void Player::TalkedToCreature( uint32 entry
, uint64 guid
)
13565 uint32 addTalkCount
= 1;
13566 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13568 uint32 questid
= GetQuestSlotQuestId(i
);
13572 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13576 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13578 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13580 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
13582 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13584 // skip spell casts and Gameobject objectives
13585 if(qInfo
->ReqSpell
[j
] > 0 || qInfo
->ReqCreatureOrGOId
[j
] < 0)
13588 uint32 reqTarget
= 0;
13590 if(qInfo
->ReqCreatureOrGOId
[j
] > 0) // creature activate objectives
13591 // checked at quest_template loading
13592 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
13596 if ( reqTarget
== entry
)
13598 uint32 reqTalkCount
= qInfo
->ReqCreatureOrGOCount
[j
];
13599 uint32 curTalkCount
= q_status
.m_creatureOrGOcount
[j
];
13600 if ( curTalkCount
< reqTalkCount
)
13602 q_status
.m_creatureOrGOcount
[j
] = curTalkCount
+ addTalkCount
;
13603 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13605 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curTalkCount
, addTalkCount
);
13607 if ( CanCompleteQuest( questid
) )
13608 CompleteQuest( questid
);
13610 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13619 void Player::MoneyChanged( uint32 count
)
13621 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13623 uint32 questid
= GetQuestSlotQuestId(i
);
13627 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13628 if( qInfo
&& qInfo
->GetRewOrReqMoney() < 0 )
13630 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13632 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13634 if(int32(count
) >= -qInfo
->GetRewOrReqMoney())
13636 if ( CanCompleteQuest( questid
) )
13637 CompleteQuest( questid
);
13640 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
13642 if(int32(count
) < -qInfo
->GetRewOrReqMoney())
13643 IncompleteQuest( questid
);
13649 bool Player::HasQuestForItem( uint32 itemid
) const
13651 for( QuestStatusMap::const_iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
13653 QuestStatusData
const& q_status
= i
->second
;
13655 if (q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13657 Quest
const* qinfo
= objmgr
.GetQuestTemplate(i
->first
);
13661 // hide quest if player is in raid-group and quest is no raid quest
13662 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
13665 // There should be no mixed ReqItem/ReqSource drop
13666 // This part for ReqItem drop
13667 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13669 if(itemid
== qinfo
->ReqItemId
[j
] && q_status
.m_itemcount
[j
] < qinfo
->ReqItemCount
[j
] )
13672 // This part - for ReqSource
13673 for (int j
= 0; j
< QUEST_SOURCE_ITEM_IDS_COUNT
; j
++)
13675 // examined item is a source item
13676 if (qinfo
->ReqSourceId
[j
] == itemid
&& qinfo
->ReqSourceRef
[j
] > 0 && qinfo
->ReqSourceRef
[j
] <= QUEST_OBJECTIVES_COUNT
)
13678 uint32 idx
= qinfo
->ReqSourceRef
[j
]-1;
13680 // total count of created ReqItems and SourceItems is less than ReqItemCount
13681 if(qinfo
->ReqItemId
[idx
] != 0 &&
13682 q_status
.m_itemcount
[idx
] * qinfo
->ReqSourceCount
[j
] + GetItemCount(itemid
,true) < qinfo
->ReqItemCount
[idx
] * qinfo
->ReqSourceCount
[j
])
13685 // total count of casted ReqCreatureOrGOs and SourceItems is less than ReqCreatureOrGOCount
13686 if (qinfo
->ReqCreatureOrGOId
[idx
] != 0)
13688 if(q_status
.m_creatureOrGOcount
[idx
] * qinfo
->ReqSourceCount
[j
] + GetItemCount(itemid
,true) < qinfo
->ReqCreatureOrGOCount
[idx
] * qinfo
->ReqSourceCount
[j
])
13691 // spell with SPELL_EFFECT_QUEST_COMPLETE or SPELL_EFFECT_SEND_EVENT (with script) case
13692 else if(qinfo
->ReqSpell
[idx
] != 0)
13694 // not casted and need more reagents/item for use.
13695 if(!q_status
.m_explored
&& GetItemCount(itemid
,true) < qinfo
->ReqSourceCount
[j
])
13705 void Player::SendQuestComplete( uint32 quest_id
)
13709 WorldPacket
data( SMSG_QUESTUPDATE_COMPLETE
, 4 );
13710 data
<< uint32(quest_id
);
13711 GetSession()->SendPacket( &data
);
13712 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id
);
13716 void Player::SendQuestReward( Quest
const *pQuest
, uint32 XP
, Object
* questGiver
)
13718 uint32 questid
= pQuest
->GetQuestId();
13719 sLog
.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid
);
13720 WorldPacket
data( SMSG_QUESTGIVER_QUEST_COMPLETE
, (4+4+4+4+4) );
13721 data
<< uint32(questid
);
13723 if ( getLevel() < sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
13725 data
<< uint32(XP
);
13726 data
<< uint32(pQuest
->GetRewOrReqMoney());
13731 data
<< uint32(pQuest
->GetRewOrReqMoney() + int32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getRate(RATE_DROP_MONEY
)));
13734 data
<< uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorableKills()));
13735 data
<< uint32(pQuest
->GetBonusTalents()); // bonus talents
13736 GetSession()->SendPacket( &data
);
13738 if (pQuest
->GetQuestCompleteScript() != 0)
13739 sWorld
.ScriptsStart(sQuestEndScripts
, pQuest
->GetQuestCompleteScript(), questGiver
, this);
13742 void Player::SendQuestFailed( uint32 quest_id
)
13746 WorldPacket
data( SMSG_QUESTGIVER_QUEST_FAILED
, 4+4 );
13748 data
<< uint32(0); // failed reason (4 for inventory is full)
13749 GetSession()->SendPacket( &data
);
13750 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13754 void Player::SendQuestTimerFailed( uint32 quest_id
)
13758 WorldPacket
data( SMSG_QUESTUPDATE_FAILEDTIMER
, 4 );
13760 GetSession()->SendPacket( &data
);
13761 sLog
.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13765 void Player::SendCanTakeQuestResponse( uint32 msg
)
13767 WorldPacket
data( SMSG_QUESTGIVER_QUEST_INVALID
, 4 );
13768 data
<< uint32(msg
);
13769 GetSession()->SendPacket( &data
);
13770 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13773 void Player::SendPushToPartyResponse( Player
*pPlayer
, uint32 msg
)
13777 WorldPacket
data( MSG_QUEST_PUSH_RESULT
, (8+1) );
13778 data
<< uint64(pPlayer
->GetGUID());
13779 data
<< uint8(msg
); // valid values: 0-8
13780 GetSession()->SendPacket( &data
);
13781 sLog
.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13785 void Player::SendQuestUpdateAddItem( Quest
const* pQuest
, uint32 item_idx
, uint32 count
)
13787 WorldPacket
data( SMSG_QUESTUPDATE_ADD_ITEM
, 0 );
13788 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13789 //data << pQuest->ReqItemId[item_idx];
13791 GetSession()->SendPacket( &data
);
13794 void Player::SendQuestUpdateAddCreatureOrGo( Quest
const* pQuest
, uint64 guid
, uint32 creatureOrGO_idx
, uint32 old_count
, uint32 add_count
)
13796 assert(old_count
+ add_count
< 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13798 int32 entry
= pQuest
->ReqCreatureOrGOId
[ creatureOrGO_idx
];
13800 // client expected gameobject template id in form (id|0x80000000)
13801 entry
= (-entry
) | 0x80000000;
13803 WorldPacket
data( SMSG_QUESTUPDATE_ADD_KILL
, (4*4+8) );
13804 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13805 data
<< uint32(pQuest
->GetQuestId());
13806 data
<< uint32(entry
);
13807 data
<< uint32(old_count
+ add_count
);
13808 data
<< uint32(pQuest
->ReqCreatureOrGOCount
[ creatureOrGO_idx
]);
13809 data
<< uint64(guid
);
13810 GetSession()->SendPacket(&data
);
13812 uint16 log_slot
= FindQuestSlot( pQuest
->GetQuestId() );
13813 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13814 SetQuestSlotCounter(log_slot
,creatureOrGO_idx
,GetQuestSlotCounter(log_slot
,creatureOrGO_idx
)+add_count
);
13817 /*********************************************************/
13818 /*** LOAD SYSTEM ***/
13819 /*********************************************************/
13821 bool Player::MinimalLoadFromDB( QueryResult
*result
, uint32 guid
)
13823 bool delete_result
= true;
13826 // 0 1 2 3 4 5 6 7 8 9
13827 result
= CharacterDatabase
.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid
);
13828 if(!result
) return false;
13830 else delete_result
= false;
13832 Field
*fields
= result
->Fetch();
13834 if(!LoadValues( fields
[1].GetString()))
13836 sLog
.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid
));
13837 if(delete_result
) delete result
;
13841 // overwrite possible wrong/corrupted guid
13842 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
13844 m_name
= fields
[2].GetCppString();
13846 Relocate(fields
[3].GetFloat(),fields
[4].GetFloat(),fields
[5].GetFloat());
13847 SetMapId(fields
[6].GetUInt32());
13848 // the instance id is not needed at character enum
13850 m_Played_time
[0] = fields
[7].GetUInt32();
13851 m_Played_time
[1] = fields
[8].GetUInt32();
13853 m_atLoginFlags
= fields
[9].GetUInt32();
13855 // I don't see these used anywhere ..
13858 _LoadBoundInstances();*/
13860 if (delete_result
) delete result
;
13862 for (int i
= 0; i
< PLAYER_SLOTS_COUNT
; i
++)
13865 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
13866 m_deathState
= DEAD
;
13871 void Player::_LoadDeclinedNames(QueryResult
* result
)
13877 delete m_declinedname
;
13879 m_declinedname
= new DeclinedName
;
13880 Field
*fields
= result
->Fetch();
13881 for(int i
= 0; i
< MAX_DECLINED_NAME_CASES
; ++i
)
13882 m_declinedname
->name
[i
] = fields
[i
].GetCppString();
13887 void Player::_LoadArenaTeamInfo(QueryResult
*result
)
13889 // arenateamid, played_week, played_season, personal_rating
13890 memset((void*)&m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
], 0, sizeof(uint32
)*18);
13896 Field
*fields
= result
->Fetch();
13898 uint32 arenateamid
= fields
[0].GetUInt32();
13899 uint32 played_week
= fields
[1].GetUInt32();
13900 uint32 played_season
= fields
[2].GetUInt32();
13901 uint32 personal_rating
= fields
[3].GetUInt32();
13903 ArenaTeam
* aTeam
= objmgr
.GetArenaTeamById(arenateamid
);
13906 sLog
.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid
, played_week
, played_season
, personal_rating
);
13909 uint8 arenaSlot
= aTeam
->GetSlot();
13911 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6] = arenateamid
; // TeamID
13912 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 1] = ((aTeam
->GetCaptain() == GetGUID()) ? (uint32
)0 : (uint32
)1); // Captain 0, member 1
13913 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 2] = played_week
; // Played Week
13914 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 3] = played_season
; // Played Season
13915 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 4] = 0; // Unk
13916 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 5] = personal_rating
; // Personal Rating
13918 }while (result
->NextRow());
13922 bool Player::LoadPositionFromDB(uint32
& mapid
, float& x
,float& y
,float& z
,float& o
, bool& in_flight
, uint64 guid
)
13924 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid
));
13928 Field
*fields
= result
->Fetch();
13930 x
= fields
[0].GetFloat();
13931 y
= fields
[1].GetFloat();
13932 z
= fields
[2].GetFloat();
13933 o
= fields
[3].GetFloat();
13934 mapid
= fields
[4].GetUInt32();
13935 in_flight
= !fields
[5].GetCppString().empty();
13941 bool Player::LoadValuesArrayFromDB(Tokens
& data
, uint64 guid
)
13943 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid
));
13947 Field
*fields
= result
->Fetch();
13949 data
= StrSplit(fields
[0].GetCppString(), " ");
13956 uint32
Player::GetUInt32ValueFromArray(Tokens
const& data
, uint16 index
)
13958 if(index
>= data
.size())
13961 return (uint32
)atoi(data
[index
].c_str());
13964 float Player::GetFloatValueFromArray(Tokens
const& data
, uint16 index
)
13967 uint32 temp
= Player::GetUInt32ValueFromArray(data
,index
);
13968 memcpy(&result
, &temp
, sizeof(result
));
13973 uint32
Player::GetUInt32ValueFromDB(uint16 index
, uint64 guid
)
13976 if(!LoadValuesArrayFromDB(data
,guid
))
13979 return GetUInt32ValueFromArray(data
,index
);
13982 float Player::GetFloatValueFromDB(uint16 index
, uint64 guid
)
13985 uint32 temp
= Player::GetUInt32ValueFromDB(index
, guid
);
13986 memcpy(&result
, &temp
, sizeof(result
));
13991 bool Player::LoadFromDB( uint32 guid
, SqlQueryHolder
*holder
)
13993 //// 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
13994 //QueryResult *result = CharacterDatabase.PQuery("SELECT guid, account, data, name, race, class, position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, dungeon_difficulty, arena_pending_points FROM characters WHERE guid = '%u'", guid);
13995 QueryResult
*result
= holder
->GetResult(PLAYER_LOGIN_QUERY_LOADFROM
);
13999 sLog
.outError("ERROR: Player (GUID: %u) not found in table `characters`, can't load. ",guid
);
14003 Field
*fields
= result
->Fetch();
14005 uint32 dbAccountId
= fields
[1].GetUInt32();
14007 // check if the character's account in the db and the logged in account match.
14008 // player should be able to load/delete character only with correct account!
14009 if( dbAccountId
!= GetSession()->GetAccountId() )
14011 sLog
.outError("ERROR: Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid
,GetSession()->GetAccountId(),dbAccountId
);
14016 Object::_Create( guid
, 0, HIGHGUID_PLAYER
);
14018 m_name
= fields
[3].GetCppString();
14020 // check name limitations
14021 if(!ObjectMgr::IsValidName(m_name
) || GetSession()->GetSecurity() == SEC_PLAYER
&& objmgr
.IsReservedName(m_name
))
14024 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME
),guid
);
14028 if(!LoadValues( fields
[2].GetString()))
14030 sLog
.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid
));
14035 // overwrite possible wrong/corrupted guid
14036 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
14038 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
14039 for(uint8 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
14041 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), 0 );
14042 SetVisibleItemSlot(slot
,NULL
);
14046 delete m_items
[slot
];
14047 m_items
[slot
] = NULL
;
14051 // update money limits
14052 if(GetMoney() > MAX_MONEY_AMOUNT
)
14053 SetMoney(MAX_MONEY_AMOUNT
);
14055 sLog
.outDebug("Load Basic value of player %s is: ", m_name
.c_str());
14058 m_race
= fields
[4].GetUInt8();
14059 //Need to call it to initialize m_team (m_team can be calculated from m_race)
14060 //Other way is to saves m_team into characters table.
14061 setFactionForRace(m_race
);
14064 m_class
= fields
[5].GetUInt8();
14066 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(m_race
, m_class
);
14069 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
14074 InitPrimaryProffesions(); // to max set before any spell loaded
14076 uint32 transGUID
= fields
[24].GetUInt32();
14077 Relocate(fields
[6].GetFloat(),fields
[7].GetFloat(),fields
[8].GetFloat(),fields
[10].GetFloat());
14078 SetMapId(fields
[9].GetUInt32());
14079 SetDifficulty(fields
[32].GetUInt32()); // may be changed in _LoadGroup
14081 _LoadGroup(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP
));
14083 _LoadArenaTeamInfo(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO
));
14085 uint32 arena_currency
= GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
) + fields
[33].GetUInt32();
14086 if (arena_currency
> sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
))
14087 arena_currency
= sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
);
14089 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, arena_currency
);
14091 // check arena teams integrity
14092 for(uint32 arena_slot
= 0; arena_slot
< MAX_ARENA_SLOT
; ++arena_slot
)
14094 uint32 arena_team_id
= GetArenaTeamId(arena_slot
);
14098 if(ArenaTeam
* at
= objmgr
.GetArenaTeamById(arena_team_id
))
14099 if(at
->HaveMember(GetGUID()))
14102 // arena team not exist or not member, cleanup fields
14103 for(int j
=0; j
< 6; ++j
)
14104 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arena_slot
* 6 + j
, 0);
14107 _LoadBoundInstances(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES
));
14109 if(!IsPositionValid())
14111 sLog
.outError("ERROR: Player (guidlow %d) have invalid coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",guid
,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
14113 SetMapId(info
->mapId
);
14114 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
,0.0f
);
14118 m_movementInfo
.t_x
= 0.0f
;
14119 m_movementInfo
.t_y
= 0.0f
;
14120 m_movementInfo
.t_z
= 0.0f
;
14121 m_movementInfo
.t_o
= 0.0f
;
14124 // load the player's map here if it's not already loaded
14125 Map
*map
= GetMap();
14126 // since the player may not be bound to the map yet, make sure subsequent
14127 // getmap calls won't create new maps
14128 SetInstanceId(map
->GetInstanceId());
14130 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14131 if(GetInstanceId() && !sInstanceSaveManager
.GetInstanceSave(GetInstanceId()))
14133 AreaTrigger
const* at
= objmgr
.GetMapEntranceTrigger(GetMapId());
14135 Relocate(at
->target_X
, at
->target_Y
, at
->target_Z
, at
->target_Orientation
);
14137 sLog
.outError("Player %s(GUID: %u) logged in to a reset instance (map: %u) and there is no aretrigger leading to this map. Thus he can't be ported back to the entrance. This _might_ be an exploit attempt.", GetName(), GetGUIDLow(), GetMapId());
14140 SaveRecallPosition();
14142 if (transGUID
!= 0)
14144 m_movementInfo
.t_x
= fields
[20].GetFloat();
14145 m_movementInfo
.t_y
= fields
[21].GetFloat();
14146 m_movementInfo
.t_z
= fields
[22].GetFloat();
14147 m_movementInfo
.t_o
= fields
[23].GetFloat();
14149 if( !MaNGOS::IsValidMapCoord(
14150 GetPositionX()+m_movementInfo
.t_x
,GetPositionY()+m_movementInfo
.t_y
,
14151 GetPositionZ()+m_movementInfo
.t_z
,GetOrientation()+m_movementInfo
.t_o
) ||
14152 // transport size limited
14153 m_movementInfo
.t_x
> 50 || m_movementInfo
.t_y
> 50 || m_movementInfo
.t_z
> 50 )
14155 sLog
.outError("ERROR: Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
14156 guid
,GetPositionX()+m_movementInfo
.t_x
,GetPositionY()+m_movementInfo
.t_y
,
14157 GetPositionZ()+m_movementInfo
.t_z
,GetOrientation()+m_movementInfo
.t_o
);
14159 SetMapId(info
->mapId
);
14160 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
,0.0f
);
14162 m_movementInfo
.t_x
= 0.0f
;
14163 m_movementInfo
.t_y
= 0.0f
;
14164 m_movementInfo
.t_z
= 0.0f
;
14165 m_movementInfo
.t_o
= 0.0f
;
14171 if (transGUID
!= 0)
14173 for (MapManager::TransportSet::iterator iter
= MapManager::Instance().m_Transports
.begin(); iter
!= MapManager::Instance().m_Transports
.end(); ++iter
)
14175 if( (*iter
)->GetGUIDLow() == transGUID
)
14177 m_transport
= *iter
;
14178 m_transport
->AddPassenger(this);
14179 SetMapId(m_transport
->GetMapId());
14186 sLog
.outError("ERROR: Player (guidlow %d) have invalid transport guid (%u). Teleport to default race/class locations.",
14189 SetMapId(info
->mapId
);
14190 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
,0.0f
);
14192 m_movementInfo
.t_x
= 0.0f
;
14193 m_movementInfo
.t_y
= 0.0f
;
14194 m_movementInfo
.t_z
= 0.0f
;
14195 m_movementInfo
.t_o
= 0.0f
;
14201 time_t now
= time(NULL
);
14202 time_t logoutTime
= time_t(fields
[16].GetUInt64());
14204 // since last logout (in seconds)
14205 uint64 time_diff
= uint64(now
- logoutTime
);
14207 // set value, including drunk invisibility detection
14208 // calculate sobering. after 15 minutes logged out, the player will be sober again
14210 if(time_diff
> 15*MINUTE
)
14213 soberFactor
= 1-time_diff
/(15.0f
*MINUTE
);
14214 uint16 newDrunkenValue
= uint16(soberFactor
*(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFE));
14215 SetDrunkValue(newDrunkenValue
);
14217 m_rest_bonus
= fields
[15].GetFloat();
14218 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14219 float bubble0
= 0.031;
14220 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14221 float bubble1
= 0.125;
14223 if((int32
)fields
[16].GetUInt32() > 0)
14225 float bubble
= fields
[17].GetUInt32() > 0
14226 ? bubble1
*sWorld
.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY
)
14227 : bubble0
*sWorld
.getRate(RATE_REST_OFFLINE_IN_WILDERNESS
);
14229 SetRestBonus(GetRestBonus()+ time_diff
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
14232 m_cinematic
= fields
[12].GetUInt32();
14233 m_Played_time
[0]= fields
[13].GetUInt32();
14234 m_Played_time
[1]= fields
[14].GetUInt32();
14236 m_resetTalentsCost
= fields
[18].GetUInt32();
14237 m_resetTalentsTime
= time_t(fields
[19].GetUInt64());
14239 // reserve some flags
14240 uint32 old_safe_flags
= GetUInt32Value(PLAYER_FLAGS
) & ( PLAYER_FLAGS_HIDE_CLOAK
| PLAYER_FLAGS_HIDE_HELM
);
14242 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
) )
14243 SetUInt32Value(PLAYER_FLAGS
, 0 | old_safe_flags
);
14245 m_taxi
.LoadTaxiMask( fields
[11].GetString() ); // must be before InitTaxiNodesForLevel
14247 uint32 extraflags
= fields
[25].GetUInt32();
14249 m_stableSlots
= fields
[26].GetUInt32();
14250 if(m_stableSlots
> 4)
14252 sLog
.outError("Player can have not more 4 stable slots, but have in DB %u",uint32(m_stableSlots
));
14256 m_atLoginFlags
= fields
[27].GetUInt32();
14259 // Update Honor kills data
14260 m_lastHonorUpdateTime
= logoutTime
;
14261 UpdateHonorFields();
14263 m_deathExpireTime
= (time_t)fields
[30].GetUInt64();
14264 if(m_deathExpireTime
> now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
)
14265 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
-1;
14267 std::string taxi_nodes
= fields
[31].GetCppString();
14271 // clear channel spell data (if saved at channel spell casting)
14272 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT
, 0);
14273 SetUInt32Value(UNIT_CHANNEL_SPELL
,0);
14275 // clear charm/summon related fields
14282 // reset some aura modifiers before aura apply
14283 SetFarSightGUID(0);
14284 SetUInt32Value(PLAYER_TRACK_CREATURES
, 0 );
14285 SetUInt32Value(PLAYER_TRACK_RESOURCES
, 0 );
14287 // reset skill modifiers and set correct unlearn flags
14288 for (uint32 i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
14290 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
14292 // set correct unlearn bit
14293 uint32 id
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
14296 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
14297 if(!pSkill
) continue;
14299 // enable unlearn button for primary professions only
14300 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
14301 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
14303 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
14306 // make sure the unit is considered out of combat for proper loading
14309 // make sure the unit is considered not in duel for proper loading
14310 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
14311 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
14313 // remember loaded power/health values to restore after stats initialization and modifier applying
14314 uint32 savedHealth
= GetHealth();
14315 uint32 savedPower
[MAX_POWERS
];
14316 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
14317 savedPower
[i
] = GetPower(Powers(i
));
14319 // reset stats before loading any modifiers
14320 InitStatsForLevel();
14321 InitTaxiNodesForLevel();
14322 InitGlyphsForLevel();
14325 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14327 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14330 _LoadAuras(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS
), time_diff
);
14333 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14334 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
14335 m_deathState
= DEAD
;
14337 _LoadSpells(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS
));
14339 // after spell load, learn rewarded spell if need also
14340 _LoadQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS
));
14341 _LoadDailyQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS
));
14343 // after spell and quest load
14344 InitTalentForLevel();
14345 learnSkillRewardedSpells();
14346 learnDefaultSpells();
14348 _LoadTutorials(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS
));
14350 // must be before inventory (some items required reputation check)
14351 _LoadReputation(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION
));
14353 _LoadInventory(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY
), time_diff
);
14355 // update items with duration and realtime
14356 UpdateItemDuration(time_diff
, true);
14358 _LoadActions(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS
));
14360 // unread mails and next delivery time, actual mails not loaded
14361 _LoadMailInit(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT
), holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE
));
14363 m_social
= sSocialMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST
), GetGUIDLow());
14365 if(!_LoadHomeBind(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND
)))
14368 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14369 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14370 if(uint32 curTitle
= GetUInt32Value(PLAYER_CHOSEN_TITLE
))
14372 if(!HasTitle(curTitle
))
14373 SetUInt32Value(PLAYER_CHOSEN_TITLE
,0);
14376 // Not finish taxi flight path
14377 if(!m_taxi
.LoadTaxiDestinationsFromString(taxi_nodes
,GetTeam()))
14379 // problems with taxi path loading
14380 TaxiNodesEntry
const* nodeEntry
= NULL
;
14381 if(uint32 node_id
= m_taxi
.GetTaxiSource())
14382 nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
14384 if(!nodeEntry
) // don't know taxi start node, to homebind
14386 sLog
.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14387 SetMapId(m_homebindMapId
);
14388 Relocate( m_homebindX
, m_homebindY
, m_homebindZ
,0.0f
);
14389 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14391 else // have start node, to it
14393 sLog
.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14394 SetMapId(nodeEntry
->map_id
);
14395 Relocate(nodeEntry
->x
, nodeEntry
->y
, nodeEntry
->z
,0.0f
);
14396 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14398 m_taxi
.ClearTaxiDestinations();
14400 else if(uint32 node_id
= m_taxi
.GetTaxiSource())
14402 // save source node as recall coord to prevent recall and fall from sky
14403 TaxiNodesEntry
const* nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
14404 assert(nodeEntry
); // checked in m_taxi.LoadTaxiDestinationsFromString
14405 m_recallMap
= nodeEntry
->map_id
;
14406 m_recallX
= nodeEntry
->x
;
14407 m_recallY
= nodeEntry
->y
;
14408 m_recallZ
= nodeEntry
->z
;
14410 // flight will started later
14413 // has to be called after last Relocate() in Player::LoadFromDB
14414 SetFallInformation(0, GetPositionZ());
14416 _LoadSpellCooldowns(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS
));
14418 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14419 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14421 RemoveAllAurasOnDeath();
14423 //apply all stat bonuses from items and auras
14424 SetCanModifyStats(true);
14427 // restore remembered power/health values (but not more max values)
14428 SetHealth(savedHealth
> GetMaxHealth() ? GetMaxHealth() : savedHealth
);
14429 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
14430 SetPower(Powers(i
),savedPower
[i
] > GetMaxPower(Powers(i
)) ? GetMaxPower(Powers(i
)) : savedPower
[i
]);
14432 sLog
.outDebug("The value of player %s after load item and aura is: ", m_name
.c_str());
14436 if(GetSession()->GetSecurity() > SEC_PLAYER
)
14438 switch(sWorld
.getConfig(CONFIG_GM_LOGIN_STATE
))
14441 case 0: break; // disable
14442 case 1: SetGameMaster(true); break; // enable
14443 case 2: // save state
14444 if(extraflags
& PLAYER_EXTRA_GM_ON
)
14445 SetGameMaster(true);
14449 switch(sWorld
.getConfig(CONFIG_GM_ACCEPT_TICKETS
))
14452 case 0: break; // disable
14453 case 1: SetAcceptTicket(true); break; // enable
14454 case 2: // save state
14455 if(extraflags
& PLAYER_EXTRA_GM_ACCEPT_TICKETS
)
14456 SetAcceptTicket(true);
14460 switch(sWorld
.getConfig(CONFIG_GM_CHAT
))
14463 case 0: break; // disable
14464 case 1: SetGMChat(true); break; // enable
14465 case 2: // save state
14466 if(extraflags
& PLAYER_EXTRA_GM_CHAT
)
14471 switch(sWorld
.getConfig(CONFIG_GM_WISPERING_TO
))
14474 case 0: break; // disable
14475 case 1: SetAcceptWhispers(true); break; // enable
14476 case 2: // save state
14477 if(extraflags
& PLAYER_EXTRA_ACCEPT_WHISPERS
)
14478 SetAcceptWhispers(true);
14483 _LoadDeclinedNames(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES
));
14485 m_achievementMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS
), holder
->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS
));
14486 m_achievementMgr
.CheckAllAchievementCriteria();
14490 bool Player::isAllowedToLoot(Creature
* creature
)
14492 if(Player
* recipient
= creature
->GetLootRecipient())
14494 if (recipient
== this)
14496 if( Group
* otherGroup
= recipient
->GetGroup())
14498 Group
* thisGroup
= GetGroup();
14501 return thisGroup
== otherGroup
;
14506 // prevent other players from looting if the recipient got disconnected
14507 return !creature
->hasLootRecipient();
14510 void Player::_LoadActions(QueryResult
*result
)
14512 m_actionButtons
.clear();
14514 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14520 Field
*fields
= result
->Fetch();
14522 uint8 button
= fields
[0].GetUInt8();
14524 addActionButton(button
, fields
[1].GetUInt16(), fields
[2].GetUInt8(), fields
[3].GetUInt8());
14526 m_actionButtons
[button
].uState
= ACTIONBUTTON_UNCHANGED
;
14528 while( result
->NextRow() );
14534 void Player::_LoadAuras(QueryResult
*result
, uint32 timediff
)
14537 for (int i
= 0; i
< TOTAL_AURAS
; i
++)
14538 m_modAuras
[i
].clear();
14540 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14546 Field
*fields
= result
->Fetch();
14547 uint64 caster_guid
= fields
[0].GetUInt64();
14548 uint32 spellid
= fields
[1].GetUInt32();
14549 uint32 effindex
= fields
[2].GetUInt32();
14550 uint32 stackcount
= fields
[3].GetUInt32();
14551 int32 damage
= (int32
)fields
[4].GetUInt32();
14552 int32 maxduration
= (int32
)fields
[5].GetUInt32();
14553 int32 remaintime
= (int32
)fields
[6].GetUInt32();
14554 int32 remaincharges
= (int32
)fields
[7].GetUInt32();
14556 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellid
);
14559 sLog
.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid
,effindex
);
14565 sLog
.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid
,effindex
);
14569 // negative effects should continue counting down after logout
14570 if (remaintime
!= -1 && !IsPositiveEffect(spellid
, effindex
))
14572 if(remaintime
<= int32(timediff
))
14575 remaintime
-= timediff
;
14578 // prevent wrong values of remaincharges
14579 if(spellproto
->procCharges
)
14581 if(remaincharges
<= 0 || remaincharges
> spellproto
->procCharges
)
14582 remaincharges
= spellproto
->procCharges
;
14587 //do not load single target auras (unless they were cast by the player)
14588 if (caster_guid
!= GetGUID() && IsSingleTargetSpell(spellproto
))
14591 for(uint32 i
=0; i
<stackcount
; i
++)
14593 Aura
* aura
= CreateAura(spellproto
, effindex
, NULL
, this, NULL
);
14595 damage
= aura
->GetModifier()->m_amount
;
14596 aura
->SetLoadedState(caster_guid
,damage
,maxduration
,remaintime
,remaincharges
);
14598 sLog
.outDetail("Added aura spellid %u, effect %u", spellproto
->Id
, effindex
);
14601 while( result
->NextRow() );
14606 if(m_class
== CLASS_WARRIOR
)
14607 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
14610 void Player::_LoadGlyphAuras()
14612 for (uint8 i
= 0; i
<= MAX_GLYPH_SLOT_INDEX
; ++i
)
14614 if (uint32 glyph
= GetGlyph(i
))
14616 if (GlyphPropertiesEntry
const *gp
= sGlyphPropertiesStore
.LookupEntry(glyph
))
14618 if (GlyphSlotEntry
const *gs
= sGlyphSlotStore
.LookupEntry(GetGlyphSlot(i
)))
14620 if(gp
->TypeFlags
== gs
->TypeFlags
)
14622 CastSpell(this, gp
->SpellId
, true);
14626 sLog
.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name
.c_str(), gp
->TypeFlags
, gs
->TypeFlags
);
14629 sLog
.outError("Player %s has not existing glyph slot entry %u on index %u", m_name
.c_str(), GetGlyphSlot(i
), i
);
14632 sLog
.outError("Player %s has not existing glyph entry %u on index %u", m_name
.c_str(), glyph
, i
);
14634 // On any error remove glyph
14640 void Player::LoadCorpse()
14644 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14648 if(Corpse
*corpse
= GetCorpse())
14650 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, corpse
&& !sMapStore
.LookupEntry(corpse
->GetMapId())->Instanceable() );
14654 //Prevent Dead Player login without corpse
14655 ResurrectPlayer(0.5f
);
14660 void Player::_LoadInventory(QueryResult
*result
, uint32 timediff
)
14662 //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());
14663 std::map
<uint64
, Bag
*> bagMap
; // fast guid lookup for bags
14664 //NOTE: the "order by `bag`" is important because it makes sure
14665 //the bagMap is filled before items in the bags are loaded
14666 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14667 //expected to be equipped before offhand items (TODO: fixme)
14669 uint32 zone
= GetZoneId();
14673 std::list
<Item
*> problematicItems
;
14675 // prevent items from being added to the queue when stored
14676 m_itemUpdateQueueBlocked
= true;
14679 Field
*fields
= result
->Fetch();
14680 uint32 bag_guid
= fields
[1].GetUInt32();
14681 uint8 slot
= fields
[2].GetUInt8();
14682 uint32 item_guid
= fields
[3].GetUInt32();
14683 uint32 item_id
= fields
[4].GetUInt32();
14685 ItemPrototype
const * proto
= objmgr
.GetItemPrototype(item_id
);
14689 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14690 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid
);
14691 sLog
.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id
);
14695 Item
*item
= NewItemOrBag(proto
);
14697 if(!item
->LoadFromDB(item_guid
, GetGUID(), result
))
14699 sLog
.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id
);
14700 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14701 item
->FSetState(ITEM_REMOVED
);
14702 item
->SaveToDB(); // it also deletes item object !
14706 // not allow have in alive state item limited to another map/zone
14707 if(isAlive() && item
->IsLimitedToAnotherMapOrZone(GetMapId(),zone
) )
14709 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14710 item
->FSetState(ITEM_REMOVED
);
14711 item
->SaveToDB(); // it also deletes item object !
14715 // "Conjured items disappear if you are logged out for more than 15 minutes"
14716 if ((timediff
> 15*60) && (item
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_CONJURED
)))
14718 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14719 item
->FSetState(ITEM_REMOVED
);
14720 item
->SaveToDB(); // it also deletes item object !
14724 bool success
= true;
14728 // the item is not in a bag
14729 item
->SetContainer( NULL
);
14730 item
->SetSlot(slot
);
14732 if( IsInventoryPos( INVENTORY_SLOT_BAG_0
, slot
) )
14734 ItemPosCountVec dest
;
14735 if( CanStoreItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false ) == EQUIP_ERR_OK
)
14736 item
= StoreItem(dest
, item
, true);
14740 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0
, slot
) )
14743 if( CanEquipItem( slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
14744 QuickEquipItem(dest
, item
);
14748 else if( IsBankPos( INVENTORY_SLOT_BAG_0
, slot
) )
14750 ItemPosCountVec dest
;
14751 if( CanBankItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
14752 item
= BankItem(dest
, item
, true);
14759 // store bags that may contain items in them
14760 if(item
->IsBag() && IsBagPos(item
->GetPos()))
14761 bagMap
[item_guid
] = (Bag
*)item
;
14766 item
->SetSlot(NULL_SLOT
);
14767 // the item is in a bag, find the bag
14768 std::map
<uint64
, Bag
*>::iterator itr
= bagMap
.find(bag_guid
);
14769 if(itr
!= bagMap
.end())
14770 itr
->second
->StoreItem(slot
, item
, true );
14775 // item's state may have changed after stored
14777 item
->SetState(ITEM_UNCHANGED
, this);
14780 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
);
14781 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14782 problematicItems
.push_back(item
);
14784 } while (result
->NextRow());
14787 m_itemUpdateQueueBlocked
= false;
14789 // send by mail problematic items
14790 while(!problematicItems
.empty())
14793 MailItemsInfo mi
; // item list preparing
14795 for(int i
= 0; !problematicItems
.empty() && i
< MAX_MAIL_ITEMS
; ++i
)
14797 Item
* item
= problematicItems
.front();
14798 problematicItems
.pop_front();
14800 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
14803 std::string subject
= GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM
);
14805 WorldSession::SendMailTo(this, MAIL_NORMAL
, MAIL_STATIONERY_GM
, GetGUIDLow(), GetGUIDLow(), subject
, 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
);
14809 _ApplyAllItemMods();
14812 // load mailed item which should receive current player
14813 void Player::_LoadMailedItems(Mail
*mail
)
14815 // data needs to be at first place for Item::LoadFromDB
14816 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
);
14822 Field
*fields
= result
->Fetch();
14823 uint32 item_guid_low
= fields
[1].GetUInt32();
14824 uint32 item_template
= fields
[2].GetUInt32();
14826 mail
->AddItem(item_guid_low
, item_template
);
14828 ItemPrototype
const *proto
= objmgr
.GetItemPrototype(item_template
);
14832 sLog
.outError( "Player %u have unknown item_template (ProtoType) in mailed items(GUID: %u template: %u) in mail (%u), deleted.", GetGUIDLow(), item_guid_low
, item_template
,mail
->messageID
);
14833 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
14834 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low
);
14838 Item
*item
= NewItemOrBag(proto
);
14840 if(!item
->LoadFromDB(item_guid_low
, 0, result
))
14842 sLog
.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail
->messageID
, item_guid_low
);
14843 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
14844 item
->FSetState(ITEM_REMOVED
);
14845 item
->SaveToDB(); // it also deletes item object !
14850 } while (result
->NextRow());
14855 void Player::_LoadMailInit(QueryResult
*resultUnread
, QueryResult
*resultDelivery
)
14857 //set a count of unread mails
14858 //QueryResult *resultMails = CharacterDatabase.PQuery("SELECT COUNT(id) FROM mail WHERE receiver = '%u' AND (checked & 1)=0 AND deliver_time <= '" I64FMTD "'", GUID_LOPART(playerGuid),(uint64)cTime);
14861 Field
*fieldMail
= resultUnread
->Fetch();
14862 unReadMails
= fieldMail
[0].GetUInt8();
14863 delete resultUnread
;
14866 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14867 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14868 if (resultDelivery
)
14870 Field
*fieldMail
= resultDelivery
->Fetch();
14871 m_nextMailDelivereTime
= (time_t)fieldMail
[0].GetUInt64();
14872 delete resultDelivery
;
14876 void Player::_LoadMail()
14879 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14880 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());
14885 Field
*fields
= result
->Fetch();
14886 Mail
*m
= new Mail
;
14887 m
->messageID
= fields
[0].GetUInt32();
14888 m
->messageType
= fields
[1].GetUInt8();
14889 m
->sender
= fields
[2].GetUInt32();
14890 m
->receiver
= fields
[3].GetUInt32();
14891 m
->subject
= fields
[4].GetCppString();
14892 m
->itemTextId
= fields
[5].GetUInt32();
14893 bool has_items
= fields
[6].GetBool();
14894 m
->expire_time
= (time_t)fields
[7].GetUInt64();
14895 m
->deliver_time
= (time_t)fields
[8].GetUInt64();
14896 m
->money
= fields
[9].GetUInt32();
14897 m
->COD
= fields
[10].GetUInt32();
14898 m
->checked
= fields
[11].GetUInt32();
14899 m
->stationery
= fields
[12].GetUInt8();
14900 m
->mailTemplateId
= fields
[13].GetInt16();
14902 if(m
->mailTemplateId
&& !sMailTemplateStore
.LookupEntry(m
->mailTemplateId
))
14904 sLog
.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m
->messageID
, m
->mailTemplateId
);
14905 m
->mailTemplateId
= 0;
14908 m
->state
= MAIL_STATE_UNCHANGED
;
14911 _LoadMailedItems(m
);
14913 m_mail
.push_back(m
);
14914 } while( result
->NextRow() );
14917 m_mailsLoaded
= true;
14920 void Player::LoadPet()
14922 //fixme: the pet should still be loaded if the player is not in world
14923 // just not added to the map
14926 Pet
*pet
= new Pet
;
14927 if(!pet
->LoadPetFromDB(this,0,0,true))
14932 void Player::_LoadQuestStatus(QueryResult
*result
)
14934 mQuestStatus
.clear();
14938 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14939 //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());
14945 Field
*fields
= result
->Fetch();
14947 uint32 quest_id
= fields
[0].GetUInt32();
14948 // used to be new, no delete?
14949 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
14953 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
14955 uint32 qstatus
= fields
[1].GetUInt32();
14956 if(qstatus
< MAX_QUEST_STATUS
)
14957 questStatusData
.m_status
= QuestStatus(qstatus
);
14960 questStatusData
.m_status
= QUEST_STATUS_NONE
;
14961 sLog
.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id
,qstatus
);
14964 questStatusData
.m_rewarded
= ( fields
[2].GetUInt8() > 0 );
14965 questStatusData
.m_explored
= ( fields
[3].GetUInt8() > 0 );
14967 time_t quest_time
= time_t(fields
[4].GetUInt64());
14969 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && !GetQuestRewardStatus(quest_id
) && questStatusData
.m_status
!= QUEST_STATUS_NONE
)
14971 AddTimedQuest( quest_id
);
14973 if (quest_time
<= sWorld
.GetGameTime())
14974 questStatusData
.m_timer
= 1;
14976 questStatusData
.m_timer
= (quest_time
- sWorld
.GetGameTime()) * 1000;
14981 questStatusData
.m_creatureOrGOcount
[0] = fields
[5].GetUInt32();
14982 questStatusData
.m_creatureOrGOcount
[1] = fields
[6].GetUInt32();
14983 questStatusData
.m_creatureOrGOcount
[2] = fields
[7].GetUInt32();
14984 questStatusData
.m_creatureOrGOcount
[3] = fields
[8].GetUInt32();
14985 questStatusData
.m_itemcount
[0] = fields
[9].GetUInt32();
14986 questStatusData
.m_itemcount
[1] = fields
[10].GetUInt32();
14987 questStatusData
.m_itemcount
[2] = fields
[11].GetUInt32();
14988 questStatusData
.m_itemcount
[3] = fields
[12].GetUInt32();
14990 questStatusData
.uState
= QUEST_UNCHANGED
;
14992 // add to quest log
14993 if( slot
< MAX_QUEST_LOG_SIZE
&&
14994 ( questStatusData
.m_status
==QUEST_STATUS_INCOMPLETE
||
14995 questStatusData
.m_status
==QUEST_STATUS_COMPLETE
&&
14996 (!questStatusData
.m_rewarded
|| pQuest
->IsDaily()) ) )
14998 SetQuestSlot(slot
,quest_id
,quest_time
);
15000 if(questStatusData
.m_status
== QUEST_STATUS_COMPLETE
)
15001 SetQuestSlotState(slot
,QUEST_STATE_COMPLETE
);
15003 for(uint8 idx
= 0; idx
< QUEST_OBJECTIVES_COUNT
; ++idx
)
15004 if(questStatusData
.m_creatureOrGOcount
[idx
])
15005 SetQuestSlotCounter(slot
,idx
,questStatusData
.m_creatureOrGOcount
[idx
]);
15010 if(questStatusData
.m_rewarded
)
15012 // learn rewarded spell if unknown
15013 learnQuestRewardedSpells(pQuest
);
15015 // set rewarded title if any
15016 if(pQuest
->GetCharTitleId())
15018 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
15019 SetTitle(titleEntry
);
15022 if(pQuest
->GetBonusTalents())
15023 m_questRewardTalentCount
+=pQuest
->GetBonusTalents();
15026 sLog
.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData
.m_status
, quest_id
, GetGUIDLow());
15029 while( result
->NextRow() );
15034 // clear quest log tail
15035 for ( uint16 i
= slot
; i
< MAX_QUEST_LOG_SIZE
; ++i
)
15039 void Player::_LoadDailyQuestStatus(QueryResult
*result
)
15041 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
15042 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
15044 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
15048 uint32 quest_daily_idx
= 0;
15052 if(quest_daily_idx
>= PLAYER_MAX_DAILY_QUESTS
) // max amount with exist data in query
15054 sLog
.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
15058 Field
*fields
= result
->Fetch();
15060 uint32 quest_id
= fields
[0].GetUInt32();
15062 // save _any_ from daily quest times (it must be after last reset anyway)
15063 m_lastDailyQuestTime
= (time_t)fields
[1].GetUInt64();
15065 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
15069 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
15072 sLog
.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id
, GetGUIDLow());
15074 while( result
->NextRow() );
15079 m_DailyQuestChanged
= false;
15082 void Player::_LoadReputation(QueryResult
*result
)
15084 m_factions
.clear();
15086 // Set initial reputations (so everything is nifty before DB data load)
15087 SetInitialFactions();
15089 //QueryResult *result = CharacterDatabase.PQuery("SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'",GetGUIDLow());
15095 Field
*fields
= result
->Fetch();
15097 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(fields
[0].GetUInt32());
15098 if( factionEntry
&& (factionEntry
->reputationListID
>= 0))
15100 FactionState
* faction
= &m_factions
[factionEntry
->reputationListID
];
15102 // update standing to current
15103 faction
->Standing
= int32(fields
[1].GetUInt32());
15105 uint32 dbFactionFlags
= fields
[2].GetUInt32();
15107 if( dbFactionFlags
& FACTION_FLAG_VISIBLE
)
15108 SetFactionVisible(faction
); // have internal checks for forced invisibility
15110 if( dbFactionFlags
& FACTION_FLAG_INACTIVE
)
15111 SetFactionInactive(faction
,true); // have internal checks for visibility requirement
15113 if( dbFactionFlags
& FACTION_FLAG_AT_WAR
) // DB at war
15114 SetFactionAtWar(faction
,true); // have internal checks for FACTION_FLAG_PEACE_FORCED
15115 else // DB not at war
15117 // allow remove if visible (and then not FACTION_FLAG_INVISIBLE_FORCED or FACTION_FLAG_HIDDEN)
15118 if( faction
->Flags
& FACTION_FLAG_VISIBLE
)
15119 SetFactionAtWar(faction
,false); // have internal checks for FACTION_FLAG_PEACE_FORCED
15122 // set atWar for hostile
15123 if(GetReputationRank(factionEntry
) <= REP_HOSTILE
)
15124 SetFactionAtWar(faction
,true);
15126 // reset changed flag if values similar to saved in DB
15127 if(faction
->Flags
==dbFactionFlags
)
15128 faction
->Changed
= false;
15131 while( result
->NextRow() );
15137 void Player::_LoadSpells(QueryResult
*result
)
15139 for (PlayerSpellMap::iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
15140 delete itr
->second
;
15143 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
15149 Field
*fields
= result
->Fetch();
15151 addSpell(fields
[0].GetUInt16(), fields
[1].GetBool(), false, fields
[2].GetBool());
15153 while( result
->NextRow() );
15159 void Player::_LoadTutorials(QueryResult
*result
)
15161 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
15167 Field
*fields
= result
->Fetch();
15169 for (int iI
=0; iI
<8; iI
++)
15170 m_Tutorials
[iI
] = fields
[iI
].GetUInt32();
15172 while( result
->NextRow() );
15177 m_TutorialsChanged
= false;
15180 void Player::_LoadGroup(QueryResult
*result
)
15182 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
15185 uint64 leaderGuid
= MAKE_NEW_GUID((*result
)[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
15187 Group
* group
= objmgr
.GetGroupByLeader(leaderGuid
);
15190 uint8 subgroup
= group
->GetMemberGroup(GetGUID());
15191 SetGroup(group
, subgroup
);
15192 if(getLevel() >= LEVELREQUIREMENT_HEROIC
)
15194 // the group leader may change the instance difficulty while the player is offline
15195 SetDifficulty(group
->GetDifficulty());
15201 void Player::_LoadBoundInstances(QueryResult
*result
)
15203 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15204 m_boundInstances
[i
].clear();
15206 Group
*group
= GetGroup();
15208 //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));
15213 Field
*fields
= result
->Fetch();
15214 bool perm
= fields
[1].GetBool();
15215 uint32 mapId
= fields
[2].GetUInt32();
15216 uint32 instanceId
= fields
[0].GetUInt32();
15217 uint8 difficulty
= fields
[3].GetUInt8();
15218 time_t resetTime
= (time_t)fields
[4].GetUInt64();
15219 // the resettime for normal instances is only saved when the InstanceSave is unloaded
15220 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
15221 // and in that case it is not used
15225 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
);
15226 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
15230 // since non permanent binds are always solo bind, they can always be reset
15231 InstanceSave
*save
= sInstanceSaveManager
.AddInstanceSave(mapId
, instanceId
, difficulty
, resetTime
, !perm
, true);
15232 if(save
) BindToInstance(save
, perm
, true);
15233 } while(result
->NextRow());
15238 InstancePlayerBind
* Player::GetBoundInstance(uint32 mapid
, uint8 difficulty
)
15240 // some instances only have one difficulty
15241 const MapEntry
* entry
= sMapStore
.LookupEntry(mapid
);
15242 if(!entry
|| !entry
->SupportsHeroicMode()) difficulty
= DIFFICULTY_NORMAL
;
15244 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
15245 if(itr
!= m_boundInstances
[difficulty
].end())
15246 return &itr
->second
;
15251 void Player::UnbindInstance(uint32 mapid
, uint8 difficulty
, bool unload
)
15253 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
15254 UnbindInstance(itr
, difficulty
, unload
);
15257 void Player::UnbindInstance(BoundInstancesMap::iterator
&itr
, uint8 difficulty
, bool unload
)
15259 if(itr
!= m_boundInstances
[difficulty
].end())
15261 if(!unload
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr
->second
.save
->GetInstanceId());
15262 itr
->second
.save
->RemovePlayer(this); // save can become invalid
15263 m_boundInstances
[difficulty
].erase(itr
++);
15267 InstancePlayerBind
* Player::BindToInstance(InstanceSave
*save
, bool permanent
, bool load
)
15271 InstancePlayerBind
& bind
= m_boundInstances
[save
->GetDifficulty()][save
->GetMapId()];
15274 // update the save when the group kills a boss
15275 if(permanent
!= bind
.perm
|| save
!= bind
.save
)
15276 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());
15279 if(!load
) CharacterDatabase
.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save
->GetInstanceId(), permanent
);
15281 if(bind
.save
!= save
)
15283 if(bind
.save
) bind
.save
->RemovePlayer(this);
15284 save
->AddPlayer(this);
15287 if(permanent
) save
->SetCanReset(false);
15290 bind
.perm
= permanent
;
15291 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());
15298 void Player::SendRaidInfo()
15300 uint32 counter
= 0;
15302 WorldPacket
data(SMSG_RAID_INSTANCE_INFO
, 4);
15304 size_t p_counter
= data
.wpos();
15305 data
<< uint32(counter
); // placeholder
15307 for(int i
= 0; i
< TOTAL_DIFFICULTIES
; ++i
)
15309 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15311 if(itr
->second
.perm
)
15313 InstanceSave
*save
= itr
->second
.save
;
15314 data
<< uint32(save
->GetMapId());
15315 data
<< uint32(save
->GetResetTime() - time(NULL
));
15316 data
<< uint32(save
->GetInstanceId());
15317 data
<< uint32(save
->GetDifficulty());
15322 data
.put
<uint32
>(p_counter
,counter
);
15323 GetSession()->SendPacket(&data
);
15327 - called on every successful teleportation to a map
15329 void Player::SendSavedInstances()
15331 bool hasBeenSaved
= false;
15334 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15336 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15338 if(itr
->second
.perm
) // only permanent binds are sent
15340 hasBeenSaved
= true;
15346 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15347 data
.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP
);
15348 data
<< uint32(hasBeenSaved
);
15349 GetSession()->SendPacket(&data
);
15354 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15356 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15358 if(itr
->second
.perm
)
15360 data
.Initialize(SMSG_UPDATE_LAST_INSTANCE
);
15361 data
<< uint32(itr
->second
.save
->GetMapId());
15362 GetSession()->SendPacket(&data
);
15368 /// convert the player's binds to the group
15369 void Player::ConvertInstancesToGroup(Player
*player
, Group
*group
, uint64 player_guid
)
15371 bool has_binds
= false;
15372 bool has_solo
= false;
15374 if(player
) { player_guid
= player
->GetGUID(); if(!group
) group
= player
->GetGroup(); }
15375 assert(player_guid
);
15377 // copy all binds to the group, when changing leader it's assumed the character
15378 // will not have any solo binds
15382 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15384 for (BoundInstancesMap::iterator itr
= player
->m_boundInstances
[i
].begin(); itr
!= player
->m_boundInstances
[i
].end();)
15387 if(group
) group
->BindToInstance(itr
->second
.save
, itr
->second
.perm
, true);
15388 // permanent binds are not removed
15389 if(!itr
->second
.perm
)
15391 player
->UnbindInstance(itr
, i
, true); // increments itr
15400 // if the player's not online we don't know what binds it has
15401 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
));
15402 // the following should not get executed when changing leaders
15403 if(!player
|| has_solo
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid
));
15406 bool Player::_LoadHomeBind(QueryResult
*result
)
15409 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15412 Field
*fields
= result
->Fetch();
15413 m_homebindMapId
= fields
[0].GetUInt32();
15414 m_homebindZoneId
= fields
[1].GetUInt16();
15415 m_homebindX
= fields
[2].GetFloat();
15416 m_homebindY
= fields
[3].GetFloat();
15417 m_homebindZ
= fields
[4].GetFloat();
15420 // accept saved data only for valid position (and non instanceable)
15421 if( MapManager::IsValidMapCoord(m_homebindMapId
,m_homebindX
,m_homebindY
,m_homebindZ
) &&
15422 !sMapStore
.LookupEntry(m_homebindMapId
)->Instanceable() )
15427 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15432 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(), getClass());
15433 if(!info
) return false;
15435 m_homebindMapId
= info
->mapId
;
15436 m_homebindZoneId
= info
->zoneId
;
15437 m_homebindX
= info
->positionX
;
15438 m_homebindY
= info
->positionY
;
15439 m_homebindZ
= info
->positionZ
;
15441 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
);
15444 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",
15445 m_homebindMapId
, m_homebindZoneId
, m_homebindX
, m_homebindY
, m_homebindZ
);
15450 /*********************************************************/
15451 /*** SAVE SYSTEM ***/
15452 /*********************************************************/
15454 void Player::SaveToDB()
15456 // delay auto save at any saves (manual, in code, or autosave)
15457 m_nextSave
= sWorld
.getConfig(CONFIG_INTERVAL_SAVE
);
15459 // first save/honor gain after midnight will also update the player's honor fields
15460 UpdateHonorFields();
15462 // players aren't saved on battleground maps
15463 uint32 mapid
= IsBeingTeleported() ? GetTeleportDest().mapid
: GetMapId();
15464 const MapEntry
* me
= sMapStore
.LookupEntry(mapid
);
15465 if(!me
|| me
->IsBattleGroundOrArena())
15468 int is_save_resting
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
) ? 1 : 0;
15469 //save, far from tavern/city
15470 //save, but in tavern/city
15471 sLog
.outDebug("The value of player %s at save: ", m_name
.c_str());
15474 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15475 uint32 tmp_bytes
= GetUInt32Value(UNIT_FIELD_BYTES_1
);
15476 uint32 tmp_bytes2
= GetUInt32Value(UNIT_FIELD_BYTES_2
);
15477 uint32 tmp_flags
= GetUInt32Value(UNIT_FIELD_FLAGS
);
15478 uint32 tmp_pflags
= GetUInt32Value(PLAYER_FLAGS
);
15479 uint32 tmp_displayid
= GetDisplayId();
15481 // Set player sit state to standing on save, also stealth and shifted form
15482 SetByteValue(UNIT_FIELD_BYTES_1
, 0, 0); // stand state
15483 SetByteValue(UNIT_FIELD_BYTES_2
, 3, 0); // shapeshift
15484 SetByteValue(UNIT_FIELD_BYTES_1
, 3, 0); // stand flags?
15485 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_STUNNED
);
15486 SetDisplayId(GetNativeDisplayId());
15488 bool inworld
= IsInWorld();
15490 CharacterDatabase
.BeginTransaction();
15492 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15494 std::string sql_name
= m_name
;
15495 CharacterDatabase
.escape_string(sql_name
);
15497 std::ostringstream ss
;
15498 ss
<< "INSERT INTO characters (guid,account,name,race,class,"
15499 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15500 "taximask, online, cinematic, "
15501 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15502 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15503 "death_expire_time, taxi_path, arena_pending_points) VALUES ("
15504 << GetGUIDLow() << ", "
15505 << GetSession()->GetAccountId() << ", '"
15506 << sql_name
<< "', "
15508 << m_class
<< ", ";
15510 bool save_to_dest
= false;
15511 if(IsBeingTeleported())
15513 // don't save to battlegrounds or arenas
15514 const MapEntry
*entry
= sMapStore
.LookupEntry(GetTeleportDest().mapid
);
15515 if(entry
&& entry
->map_type
!= MAP_BATTLEGROUND
&& entry
->map_type
!= MAP_ARENA
)
15516 save_to_dest
= true;
15521 ss
<< GetMapId() << ", "
15522 << (uint32
)GetDifficulty() << ", "
15523 << finiteAlways(GetPositionX()) << ", "
15524 << finiteAlways(GetPositionY()) << ", "
15525 << finiteAlways(GetPositionZ()) << ", "
15526 << finiteAlways(GetOrientation()) << ", '";
15530 ss
<< GetTeleportDest().mapid
<< ", "
15531 << (uint32
)GetDifficulty() << ", "
15532 << finiteAlways(GetTeleportDest().x
) << ", "
15533 << finiteAlways(GetTeleportDest().y
) << ", "
15534 << finiteAlways(GetTeleportDest().z
) << ", "
15535 << finiteAlways(GetTeleportDest().o
) << ", '";
15539 for( i
= 0; i
< m_valuesCount
; i
++ )
15541 ss
<< GetUInt32Value(i
) << " ";
15546 ss
<< m_taxi
; // string with TaxiMaskSize numbers
15549 ss
<< (inworld
? 1 : 0);
15555 ss
<< m_Played_time
[0];
15557 ss
<< m_Played_time
[1];
15560 ss
<< finiteAlways(m_rest_bonus
);
15562 ss
<< (uint64
)time(NULL
);
15564 ss
<< is_save_resting
;
15566 ss
<< m_resetTalentsCost
;
15568 ss
<< (uint64
)m_resetTalentsTime
;
15571 ss
<< finiteAlways(m_movementInfo
.t_x
);
15573 ss
<< finiteAlways(m_movementInfo
.t_y
);
15575 ss
<< finiteAlways(m_movementInfo
.t_z
);
15577 ss
<< finiteAlways(m_movementInfo
.t_o
);
15580 ss
<< m_transport
->GetGUIDLow();
15585 ss
<< m_ExtraFlags
;
15588 ss
<< uint32(m_stableSlots
); // to prevent save uint8 as char
15591 ss
<< uint32(m_atLoginFlags
);
15597 ss
<< (uint64
)m_deathExpireTime
;
15600 ss
<< m_taxi
.SaveTaxiDestinationsToString();
15603 CharacterDatabase
.Execute( ss
.str().c_str() );
15605 if(m_mailsUpdated
) //save mails only when needed
15609 _SaveQuestStatus();
15610 _SaveDailyQuestStatus();
15613 _SaveSpellCooldowns();
15618 CharacterDatabase
.CommitTransaction();
15620 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15621 SetDisplayId(tmp_displayid
);
15622 SetUInt32Value(UNIT_FIELD_BYTES_1
, tmp_bytes
);
15623 SetUInt32Value(UNIT_FIELD_BYTES_2
, tmp_bytes2
);
15624 SetUInt32Value(UNIT_FIELD_FLAGS
, tmp_flags
);
15625 SetUInt32Value(PLAYER_FLAGS
, tmp_pflags
);
15627 // save pet (hunter pet level and experience and all type pets health/mana).
15628 if(Pet
* pet
= GetPet())
15629 pet
->SavePetToDB(PET_SAVE_AS_CURRENT
);
15630 m_achievementMgr
.SaveToDB();
15633 // fast save function for item/money cheating preventing - save only inventory and money state
15634 void Player::SaveInventoryAndGoldToDB()
15637 //money is in data field
15638 SaveDataFieldToDB();
15641 void Player::_SaveActions()
15643 for(ActionButtonList::iterator itr
= m_actionButtons
.begin(); itr
!= m_actionButtons
.end(); )
15645 switch (itr
->second
.uState
)
15647 case ACTIONBUTTON_NEW
:
15648 CharacterDatabase
.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15649 GetGUIDLow(), (uint32
)itr
->first
, (uint32
)itr
->second
.action
, (uint32
)itr
->second
.type
, (uint32
)itr
->second
.misc
);
15650 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
15653 case ACTIONBUTTON_CHANGED
:
15654 CharacterDatabase
.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15655 (uint32
)itr
->second
.action
, (uint32
)itr
->second
.type
, (uint32
)itr
->second
.misc
, GetGUIDLow(), (uint32
)itr
->first
);
15656 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
15659 case ACTIONBUTTON_DELETED
:
15660 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32
)itr
->first
);
15661 m_actionButtons
.erase(itr
++);
15670 void Player::_SaveAuras()
15672 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15674 AuraMap
const& auras
= GetAuras();
15679 spellEffectPair lastEffectPair
= auras
.begin()->first
;
15680 uint32 stackCounter
= 1;
15682 for(AuraMap::const_iterator itr
= auras
.begin(); ; ++itr
)
15684 if(itr
== auras
.end() || lastEffectPair
!= itr
->first
)
15686 AuraMap::const_iterator itr2
= itr
;
15687 // save previous spellEffectPair to db
15689 SpellEntry
const *spellInfo
= itr2
->second
->GetSpellProto();
15691 //skip all auras from spells that are passive or need a shapeshift
15692 if (!(itr2
->second
->IsPassive() || itr2
->second
->IsRemovedOnShapeLost()))
15694 //do not save single target auras (unless they were cast by the player)
15695 if (!(itr2
->second
->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo
)))
15698 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15699 for (i
= 0; i
< 3; i
++)
15700 if (spellInfo
->EffectApplyAuraName
[i
] == SPELL_AURA_MOD_SHAPESHIFT
||
15701 spellInfo
->EffectApplyAuraName
[i
] == SPELL_AURA_MOD_STEALTH
)
15706 CharacterDatabase
.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15707 "VALUES ('%u', '" I64FMTD
"' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15708 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()));
15713 if(itr
== auras
.end())
15717 if (lastEffectPair
== itr
->first
)
15721 lastEffectPair
= itr
->first
;
15727 void Player::_SaveInventory()
15729 // force items in buyback slots to new state
15730 // and remove those that aren't already
15731 for (uint8 i
= BUYBACK_SLOT_START
; i
< BUYBACK_SLOT_END
; i
++)
15733 Item
*item
= m_items
[i
];
15734 if (!item
|| item
->GetState() == ITEM_NEW
) continue;
15735 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
15736 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item
->GetGUIDLow());
15737 m_items
[i
]->FSetState(ITEM_NEW
);
15740 // update enchantment durations
15741 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
15743 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
15747 if (m_itemUpdateQueue
.empty()) return;
15749 // do not save if the update queue is corrupt
15750 bool error
= false;
15751 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); i
++)
15753 Item
*item
= m_itemUpdateQueue
[i
];
15754 if(!item
|| item
->GetState() == ITEM_REMOVED
) continue;
15755 Item
*test
= GetItemByPos( item
->GetBagSlot(), item
->GetSlot());
15759 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());
15762 else if (test
!= item
)
15764 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());
15771 sLog
.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15772 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED
);
15776 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); i
++)
15778 Item
*item
= m_itemUpdateQueue
[i
];
15779 if(!item
) continue;
15781 Bag
*container
= item
->GetContainer();
15782 uint32 bag_guid
= container
? container
->GetGUIDLow() : 0;
15784 switch(item
->GetState())
15787 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());
15790 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());
15793 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
15795 case ITEM_UNCHANGED
:
15799 item
->SaveToDB(); // item have unchanged inventory record and can be save standalone
15801 m_itemUpdateQueue
.clear();
15804 void Player::_SaveMail()
15806 if (!m_mailsLoaded
)
15809 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
15812 if (m
->state
== MAIL_STATE_CHANGED
)
15814 CharacterDatabase
.PExecute("UPDATE mail SET itemTextId = '%u',has_items = '%u',expire_time = '" I64FMTD
"', deliver_time = '" I64FMTD
"',money = '%u',cod = '%u',checked = '%u' WHERE id = '%u'",
15815 m
->itemTextId
, m
->HasItems() ? 1 : 0, (uint64
)m
->expire_time
, (uint64
)m
->deliver_time
, m
->money
, m
->COD
, m
->checked
, m
->messageID
);
15816 if(m
->removedItems
.size())
15818 for(std::vector
<uint32
>::iterator itr2
= m
->removedItems
.begin(); itr2
!= m
->removedItems
.end(); ++itr2
)
15819 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2
);
15820 m
->removedItems
.clear();
15822 m
->state
= MAIL_STATE_UNCHANGED
;
15824 else if (m
->state
== MAIL_STATE_DELETED
)
15827 for(std::vector
<MailItemInfo
>::iterator itr2
= m
->items
.begin(); itr2
!= m
->items
.end(); ++itr2
)
15828 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2
->item_guid
);
15830 CharacterDatabase
.PExecute("DELETE FROM item_text WHERE id = '%u'", m
->itemTextId
);
15831 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", m
->messageID
);
15832 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m
->messageID
);
15836 //deallocate deleted mails...
15837 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); )
15839 if ((*itr
)->state
== MAIL_STATE_DELETED
)
15844 itr
= m_mail
.begin();
15850 m_mailsUpdated
= false;
15853 void Player::_SaveQuestStatus()
15855 // we don't need transactions here.
15856 for( QuestStatusMap::iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
15858 switch (i
->second
.uState
)
15861 CharacterDatabase
.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15862 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD
"', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15863 GetGUIDLow(), i
->first
, i
->second
.m_status
, i
->second
.m_rewarded
, i
->second
.m_explored
, uint64(i
->second
.m_timer
/ 1000 + 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]);
15865 case QUEST_CHANGED
:
15866 CharacterDatabase
.PExecute("UPDATE character_queststatus SET status = '%u',rewarded = '%u',explored = '%u',timer = '" I64FMTD
"',mobcount1 = '%u',mobcount2 = '%u',mobcount3 = '%u',mobcount4 = '%u',itemcount1 = '%u',itemcount2 = '%u',itemcount3 = '%u',itemcount4 = '%u' WHERE guid = '%u' AND quest = '%u' ",
15867 i
->second
.m_status
, i
->second
.m_rewarded
, i
->second
.m_explored
, uint64(i
->second
.m_timer
/ 1000 + 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
);
15869 case QUEST_UNCHANGED
:
15872 i
->second
.uState
= QUEST_UNCHANGED
;
15876 void Player::_SaveDailyQuestStatus()
15878 if(!m_DailyQuestChanged
)
15881 m_DailyQuestChanged
= false;
15883 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15885 // we don't need transactions here.
15886 CharacterDatabase
.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15887 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
15888 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
15889 CharacterDatabase
.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD
"')",
15890 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
),uint64(m_lastDailyQuestTime
));
15893 void Player::_SaveReputation()
15895 for(FactionStateList::iterator itr
= m_factions
.begin(); itr
!= m_factions
.end(); ++itr
)
15897 if (itr
->second
.Changed
)
15899 CharacterDatabase
.PExecute("DELETE FROM character_reputation WHERE guid = '%u' AND faction='%u'", GetGUIDLow(), itr
->second
.ID
);
15900 CharacterDatabase
.PExecute("INSERT INTO character_reputation (guid,faction,standing,flags) VALUES ('%u', '%u', '%i', '%u')", GetGUIDLow(), itr
->second
.ID
, itr
->second
.Standing
, itr
->second
.Flags
);
15901 itr
->second
.Changed
= false;
15906 void Player::_SaveSpells()
15908 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(), next
= m_spells
.begin(); itr
!= m_spells
.end(); itr
= next
)
15911 if (itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->second
->state
== PLAYERSPELL_CHANGED
)
15912 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr
->first
);
15913 if (itr
->second
->state
== PLAYERSPELL_NEW
|| itr
->second
->state
== PLAYERSPELL_CHANGED
)
15914 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);
15916 if (itr
->second
->state
== PLAYERSPELL_REMOVED
)
15917 _removeSpell(itr
->first
);
15919 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
15923 void Player::_SaveTutorials()
15925 if(!m_TutorialsChanged
)
15929 // it's better than rebuilding indexes multiple times
15930 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID
);
15933 Rows
= result
->Fetch()[0].GetUInt32();
15939 CharacterDatabase
.PExecute("UPDATE character_tutorial SET tut0='%u', tut1='%u', tut2='%u', tut3='%u', tut4='%u', tut5='%u', tut6='%u', tut7='%u' WHERE account = '%u' AND realmid = '%u'",
15940 m_Tutorials
[0], m_Tutorials
[1], m_Tutorials
[2], m_Tutorials
[3], m_Tutorials
[4], m_Tutorials
[5], m_Tutorials
[6], m_Tutorials
[7], GetSession()->GetAccountId(), realmID
);
15944 CharacterDatabase
.PExecute("INSERT INTO character_tutorial (account,realmid,tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7) VALUES ('%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')", GetSession()->GetAccountId(), realmID
, m_Tutorials
[0], m_Tutorials
[1], m_Tutorials
[2], m_Tutorials
[3], m_Tutorials
[4], m_Tutorials
[5], m_Tutorials
[6], m_Tutorials
[7]);
15947 m_TutorialsChanged
= false;
15950 void Player::outDebugValues() const
15952 if(!sLog
.IsOutDebug()) // optimize disabled debug output
15955 sLog
.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA
));
15956 sLog
.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY
), GetStat(STAT_STRENGTH
));
15957 sLog
.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT
), GetStat(STAT_SPIRIT
));
15958 sLog
.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA
), GetStat(STAT_SPIRIT
));
15959 sLog
.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE
));
15960 sLog
.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY
), GetResistance(SPELL_SCHOOL_FIRE
));
15961 sLog
.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE
), GetResistance(SPELL_SCHOOL_FROST
));
15962 sLog
.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW
), GetResistance(SPELL_SCHOOL_ARCANE
));
15963 sLog
.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE
), GetFloatValue(UNIT_FIELD_MAXDAMAGE
));
15964 sLog
.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
));
15965 sLog
.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
));
15966 sLog
.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK
), GetAttackTime(RANGED_ATTACK
));
15969 /*********************************************************/
15970 /*** FLOOD FILTER SYSTEM ***/
15971 /*********************************************************/
15973 void Player::UpdateSpeakTime()
15975 // ignore chat spam protection for GMs in any mode
15976 if(GetSession()->GetSecurity() > SEC_PLAYER
)
15979 time_t current
= time (NULL
);
15980 if(m_speakTime
> current
)
15982 uint32 max_count
= sWorld
.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT
);
15987 if(m_speakCount
>= max_count
)
15989 // prevent overwrite mute time, if message send just before mutes set, for example.
15990 time_t new_mute
= current
+ sWorld
.getConfig(CONFIG_CHATFLOOD_MUTE_TIME
);
15991 if(GetSession()->m_muteTime
< new_mute
)
15992 GetSession()->m_muteTime
= new_mute
;
16000 m_speakTime
= current
+ sWorld
.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY
);
16003 bool Player::CanSpeak() const
16005 return GetSession()->m_muteTime
<= time (NULL
);
16008 /*********************************************************/
16009 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
16010 /*********************************************************/
16012 void Player::SendAttackSwingNotInRange()
16014 WorldPacket
data(SMSG_ATTACKSWING_NOTINRANGE
, 0);
16015 GetSession()->SendPacket( &data
);
16018 void Player::SavePositionInDB(uint32 mapid
, float x
,float y
,float z
,float o
,uint32 zone
,uint64 guid
)
16020 std::ostringstream ss
;
16021 ss
<< "UPDATE characters SET position_x='"<<x
<<"',position_y='"<<y
16022 << "',position_z='"<<z
<<"',orientation='"<<o
<<"',map='"<<mapid
16023 << "',zone='"<<zone
<<"',trans_x='0',trans_y='0',trans_z='0',"
16024 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
16025 sLog
.outDebug(ss
.str().c_str());
16026 CharacterDatabase
.Execute(ss
.str().c_str());
16029 void Player::SaveDataFieldToDB()
16031 std::ostringstream ss
;
16032 ss
<<"UPDATE characters SET data='";
16034 for(uint16 i
= 0; i
< m_valuesCount
; i
++ )
16036 ss
<< GetUInt32Value(i
) << " ";
16038 ss
<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
16040 CharacterDatabase
.Execute(ss
.str().c_str());
16043 bool Player::SaveValuesArrayInDB(Tokens
const& tokens
, uint64 guid
)
16045 std::ostringstream ss2
;
16046 ss2
<<"UPDATE characters SET data='";
16048 for (Tokens::const_iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
, ++i
)
16050 ss2
<<tokens
[i
]<<" ";
16052 ss2
<<"' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
16054 return CharacterDatabase
.Execute(ss2
.str().c_str());
16057 void Player::SetUInt32ValueInArray(Tokens
& tokens
,uint16 index
, uint32 value
)
16060 snprintf(buf
,11,"%u",value
);
16062 if(index
>= tokens
.size())
16065 tokens
[index
] = buf
;
16068 void Player::SetUInt32ValueInDB(uint16 index
, uint32 value
, uint64 guid
)
16071 if(!LoadValuesArrayFromDB(tokens
,guid
))
16074 if(index
>= tokens
.size())
16078 snprintf(buf
,11,"%u",value
);
16079 tokens
[index
] = buf
;
16081 SaveValuesArrayInDB(tokens
,guid
);
16084 void Player::SetFloatValueInDB(uint16 index
, float value
, uint64 guid
)
16087 memcpy(&temp
, &value
, sizeof(value
));
16088 Player::SetUInt32ValueInDB(index
, temp
, guid
);
16091 void Player::Customize(uint64 guid
, uint8 gender
, uint8 skin
, uint8 face
, uint8 hairStyle
, uint8 hairColor
, uint8 facialHair
)
16094 if(!LoadValuesArrayFromDB(tokens
, guid
))
16097 uint32 unit_bytes0
= GetUInt32ValueFromArray(tokens
, UNIT_FIELD_BYTES_0
);
16098 uint8 race
= unit_bytes0
& 0xFF;
16099 uint8 class_
= (unit_bytes0
>> 8) & 0xFF;
16101 PlayerInfo
const* info
= objmgr
.GetPlayerInfo(race
, class_
);
16105 unit_bytes0
&= ~(0xFF << 16);
16106 unit_bytes0
|= (gender
<< 16);
16107 SetUInt32ValueInArray(tokens
, UNIT_FIELD_BYTES_0
, unit_bytes0
);
16109 SetUInt32ValueInArray(tokens
, UNIT_FIELD_DISPLAYID
, gender
? info
->displayId_f
: info
->displayId_m
);
16110 SetUInt32ValueInArray(tokens
, UNIT_FIELD_NATIVEDISPLAYID
, gender
? info
->displayId_f
: info
->displayId_m
);
16112 SetUInt32ValueInArray(tokens
, PLAYER_BYTES
, (skin
| (face
<< 8) | (hairStyle
<< 16) | (hairColor
<< 24)));
16114 uint32 player_bytes2
= GetUInt32ValueFromArray(tokens
, PLAYER_BYTES_2
);
16115 player_bytes2
&= ~0xFF;
16116 player_bytes2
|= facialHair
;
16117 SetUInt32ValueInArray(tokens
, PLAYER_BYTES_2
, player_bytes2
);
16119 uint32 player_bytes3
= GetUInt32ValueFromArray(tokens
, PLAYER_BYTES_3
);
16120 player_bytes3
&= ~0xFF;
16121 player_bytes3
|= gender
;
16122 SetUInt32ValueInArray(tokens
, PLAYER_BYTES_3
, player_bytes3
);
16124 SaveValuesArrayInDB(tokens
, guid
);
16127 void Player::SendAttackSwingNotStanding()
16129 WorldPacket
data(SMSG_ATTACKSWING_NOTSTANDING
, 0);
16130 GetSession()->SendPacket( &data
);
16133 void Player::SendAttackSwingDeadTarget()
16135 WorldPacket
data(SMSG_ATTACKSWING_DEADTARGET
, 0);
16136 GetSession()->SendPacket( &data
);
16139 void Player::SendAttackSwingCantAttack()
16141 WorldPacket
data(SMSG_ATTACKSWING_CANT_ATTACK
, 0);
16142 GetSession()->SendPacket( &data
);
16145 void Player::SendAttackSwingCancelAttack()
16147 WorldPacket
data(SMSG_CANCEL_COMBAT
, 0);
16148 GetSession()->SendPacket( &data
);
16151 void Player::SendAttackSwingBadFacingAttack()
16153 WorldPacket
data(SMSG_ATTACKSWING_BADFACING
, 0);
16154 GetSession()->SendPacket( &data
);
16157 void Player::SendAutoRepeatCancel()
16159 WorldPacket
data(SMSG_CANCEL_AUTO_REPEAT
, GetPackGUID().size());
16160 data
.append(GetPackGUID()); // may be it's target guid
16161 GetSession()->SendPacket( &data
);
16164 void Player::PlaySound(uint32 Sound
, bool OnlySelf
)
16166 WorldPacket
data(SMSG_PLAY_SOUND
, 4);
16169 GetSession()->SendPacket( &data
);
16171 SendMessageToSet( &data
, true );
16174 void Player::SendExplorationExperience(uint32 Area
, uint32 Experience
)
16176 WorldPacket
data( SMSG_EXPLORATION_EXPERIENCE
, 8 );
16178 data
<< Experience
;
16179 GetSession()->SendPacket(&data
);
16182 void Player::SendDungeonDifficulty(bool IsInGroup
)
16184 uint8 val
= 0x00000001;
16185 WorldPacket
data(MSG_SET_DUNGEON_DIFFICULTY
, 12);
16186 data
<< (uint32
)GetDifficulty();
16187 data
<< uint32(val
);
16188 data
<< uint32(IsInGroup
);
16189 GetSession()->SendPacket(&data
);
16192 void Player::SendResetFailedNotify(uint32 mapid
)
16194 WorldPacket
data(SMSG_RESET_FAILED_NOTIFY
, 4);
16195 data
<< uint32(mapid
);
16196 GetSession()->SendPacket(&data
);
16199 /// Reset all solo instances and optionally send a message on success for each
16200 void Player::ResetInstances(uint8 method
)
16202 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
16204 // we assume that when the difficulty changes, all instances that can be reset will be
16205 uint8 dif
= GetDifficulty();
16207 for (BoundInstancesMap::iterator itr
= m_boundInstances
[dif
].begin(); itr
!= m_boundInstances
[dif
].end();)
16209 InstanceSave
*p
= itr
->second
.save
;
16210 const MapEntry
*entry
= sMapStore
.LookupEntry(itr
->first
);
16211 if(!entry
|| !p
->CanReset())
16217 if(method
== INSTANCE_RESET_ALL
)
16219 // the "reset all instances" method can only reset normal maps
16220 if(dif
== DIFFICULTY_HEROIC
|| entry
->map_type
== MAP_RAID
)
16227 // if the map is loaded, reset it
16228 Map
*map
= MapManager::Instance().FindMap(p
->GetMapId(), p
->GetInstanceId());
16229 if(map
&& map
->IsDungeon())
16230 ((InstanceMap
*)map
)->Reset(method
);
16232 // since this is a solo instance there should not be any players inside
16233 if(method
== INSTANCE_RESET_ALL
|| method
== INSTANCE_RESET_CHANGE_DIFFICULTY
)
16234 SendResetInstanceSuccess(p
->GetMapId());
16237 m_boundInstances
[dif
].erase(itr
++);
16239 // the following should remove the instance save from the manager and delete it as well
16240 p
->RemovePlayer(this);
16244 void Player::SendResetInstanceSuccess(uint32 MapId
)
16246 WorldPacket
data(SMSG_INSTANCE_RESET
, 4);
16248 GetSession()->SendPacket(&data
);
16251 void Player::SendResetInstanceFailed(uint32 reason
, uint32 MapId
)
16253 // TODO: find what other fail reasons there are besides players in the instance
16254 WorldPacket
data(SMSG_INSTANCE_RESET_FAILED
, 4);
16257 GetSession()->SendPacket(&data
);
16260 /*********************************************************/
16261 /*** Update timers ***/
16262 /*********************************************************/
16264 ///checks the 15 afk reports per 5 minutes limit
16265 void Player::UpdateAfkReport(time_t currTime
)
16267 if(m_bgAfkReportedTimer
<= currTime
)
16269 m_bgAfkReportedCount
= 0;
16270 m_bgAfkReportedTimer
= currTime
+5*MINUTE
;
16274 void Player::UpdateContestedPvP(uint32 diff
)
16276 if(!m_contestedPvPTimer
||isInCombat())
16278 if(m_contestedPvPTimer
<= diff
)
16280 ResetContestedPvP();
16283 m_contestedPvPTimer
-= diff
;
16286 void Player::UpdatePvPFlag(time_t currTime
)
16290 if(pvpInfo
.endTimer
== 0 || currTime
< (pvpInfo
.endTimer
+ 300))
16296 void Player::UpdateDuelFlag(time_t currTime
)
16298 if(!duel
|| duel
->startTimer
== 0 ||currTime
< duel
->startTimer
+ 3)
16301 SetUInt32Value(PLAYER_DUEL_TEAM
, 1);
16302 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 2);
16304 duel
->startTimer
= 0;
16305 duel
->startTime
= currTime
;
16306 duel
->opponent
->duel
->startTimer
= 0;
16307 duel
->opponent
->duel
->startTime
= currTime
;
16310 void Player::RemovePet(Pet
* pet
, PetSaveMode mode
, bool returnreagent
)
16315 if(returnreagent
&& (pet
|| m_temporaryUnsummonedPetNumber
))
16317 //returning of reagents only for players, so best done here
16318 uint32 spellId
= pet
? pet
->GetUInt32Value(UNIT_CREATED_BY_SPELL
) : m_oldpetspell
;
16319 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellId
);
16323 for(uint32 i
= 0; i
< 7; ++i
)
16325 if(spellInfo
->Reagent
[i
] > 0)
16327 ItemPosCountVec dest
; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16328 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, spellInfo
->Reagent
[i
], spellInfo
->ReagentCount
[i
] );
16329 if( msg
== EQUIP_ERR_OK
)
16331 Item
* item
= StoreNewItem( dest
, spellInfo
->Reagent
[i
], true);
16333 SendNewItem(item
,spellInfo
->ReagentCount
[i
],true,false);
16338 m_temporaryUnsummonedPetNumber
= 0;
16341 if(!pet
|| pet
->GetOwnerGUID()!=GetGUID())
16344 // only if current pet in slot
16345 switch(pet
->getPetType())
16351 m_guardianPets
.erase(pet
->GetGUID());
16354 if(GetPetGUID() == pet
->GetGUID())
16363 switch(pet
->GetEntry())
16365 //warlock pets except imp are removed(?) when logging out
16370 mode
= PET_SAVE_NOT_IN_SLOT
;
16375 pet
->SavePetToDB(mode
);
16377 pet
->CleanupsBeforeDelete();
16378 pet
->AddObjectToRemoveList();
16379 pet
->m_removed
= true;
16381 if(pet
->isControlled())
16383 WorldPacket
data(SMSG_PET_SPELLS
, 8);
16386 GetSession()->SendPacket(&data
);
16389 SetGroupUpdateFlag(GROUP_UPDATE_PET
);
16393 void Player::RemoveMiniPet()
16395 if(Pet
* pet
= GetMiniPet())
16397 pet
->Remove(PET_SAVE_AS_DELETED
);
16402 Pet
* Player::GetMiniPet()
16406 return ObjectAccessor::GetPet(m_miniPet
);
16409 void Player::RemoveGuardians()
16411 while(!m_guardianPets
.empty())
16413 uint64 guid
= *m_guardianPets
.begin();
16414 if(Pet
* pet
= ObjectAccessor::GetPet(guid
))
16415 pet
->Remove(PET_SAVE_AS_DELETED
);
16417 m_guardianPets
.erase(guid
);
16421 bool Player::HasGuardianWithEntry(uint32 entry
)
16423 // pet guid middle part is entry (and creature also)
16424 // and in guardian list must be guardians with same entry _always_
16425 for(GuardianPetList::const_iterator itr
= m_guardianPets
.begin(); itr
!= m_guardianPets
.end(); ++itr
)
16426 if(GUID_ENPART(*itr
)==entry
)
16432 void Player::Uncharm()
16434 Unit
* charm
= GetCharm();
16438 charm
->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM
);
16439 charm
->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS
);
16442 void Player::BuildPlayerChat(WorldPacket
*data
, uint8 msgtype
, const std::string
& text
, uint32 language
) const
16444 *data
<< (uint8
)msgtype
;
16445 *data
<< (uint32
)language
;
16446 *data
<< (uint64
)GetGUID();
16447 *data
<< (uint32
)language
; //language 2.1.0 ?
16448 *data
<< (uint64
)GetGUID();
16449 *data
<< (uint32
)(text
.length()+1);
16451 *data
<< (uint8
)chatTag();
16454 void Player::Say(const std::string
& text
, const uint32 language
)
16456 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16457 BuildPlayerChat(&data
, CHAT_MSG_SAY
, text
, language
);
16458 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_SAY
),true);
16461 void Player::Yell(const std::string
& text
, const uint32 language
)
16463 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16464 BuildPlayerChat(&data
, CHAT_MSG_YELL
, text
, language
);
16465 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_YELL
),true);
16468 void Player::TextEmote(const std::string
& text
)
16470 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16471 BuildPlayerChat(&data
, CHAT_MSG_EMOTE
, text
, LANG_UNIVERSAL
);
16472 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE
),true, !sWorld
.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT
) );
16475 void Player::Whisper(const std::string
& text
, uint32 language
,uint64 receiver
)
16477 if (language
!= LANG_ADDON
) // if not addon data
16478 language
= LANG_UNIVERSAL
; // whispers should always be readable
16480 Player
*rPlayer
= objmgr
.GetPlayer(receiver
);
16482 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16483 if(!rPlayer
->isDND() || isGameMaster())
16485 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16486 BuildPlayerChat(&data
, CHAT_MSG_WHISPER
, text
, language
);
16487 rPlayer
->GetSession()->SendPacket(&data
);
16489 data
.Initialize(SMSG_MESSAGECHAT
, 200);
16490 rPlayer
->BuildPlayerChat(&data
, CHAT_MSG_REPLY
, text
, language
);
16491 GetSession()->SendPacket(&data
);
16495 // announce to player that player he is whispering to is dnd and cannot receive his message
16496 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND
, rPlayer
->GetName(), rPlayer
->dndMsg
.c_str());
16499 if(!isAcceptWhispers())
16501 SetAcceptWhispers(true);
16502 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON
);
16505 // announce to player that player he is whispering to is afk
16506 if(rPlayer
->isAFK())
16507 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK
, rPlayer
->GetName(), rPlayer
->afkMsg
.c_str());
16509 // if player whisper someone, auto turn of dnd to be able to receive an answer
16510 if(isDND() && !rPlayer
->isGameMaster())
16514 void Player::PetSpellInitialize()
16516 Pet
* pet
= GetPet();
16521 sLog
.outDebug("Pet Spells Groups");
16523 CharmInfo
*charmInfo
= pet
->GetCharmInfo();
16525 WorldPacket
data(SMSG_PET_SPELLS
, 8+4+4+4+10*4);
16526 data
<< uint64(pet
->GetGUID());
16527 data
<< uint32(pet
->GetCreatureInfo()->family
); // creature family (required for pet talents)
16529 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState()) << uint16(0);
16532 for(uint32 i
= 0; i
< 10; i
++)
16534 data
<< uint32(charmInfo
->GetActionBarEntry(i
)->Raw
);
16537 size_t spellsCountPos
= data
.wpos();
16541 data
<< uint8(addlist
); // placeholder
16543 if(pet
->isControlled() && ((pet
->getPetType() == HUNTER_PET
) || ((pet
->GetCreatureInfo()->type
== CREATURE_TYPE_DEMON
) && (getClass() == CLASS_WARLOCK
))))
16546 for (PetSpellMap::iterator itr
= pet
->m_spells
.begin(); itr
!= pet
->m_spells
.end(); ++itr
)
16548 if(itr
->second
->state
== PETSPELL_REMOVED
)
16551 data
<< uint16(itr
->first
);
16552 data
<< uint16(itr
->second
->active
); // pet spell active state isn't boolean
16557 data
.put
<uint8
>(spellsCountPos
, addlist
);
16559 uint8 cooldownsCount
= pet
->m_CreatureSpellCooldowns
.size() + pet
->m_CreatureCategoryCooldowns
.size();
16560 data
<< uint8(cooldownsCount
);
16562 time_t curTime
= time(NULL
);
16564 for(CreatureSpellCooldowns::const_iterator itr
= pet
->m_CreatureSpellCooldowns
.begin(); itr
!= pet
->m_CreatureSpellCooldowns
.end(); ++itr
)
16566 time_t cooldown
= 0;
16568 if(itr
->second
> curTime
)
16569 cooldown
= (itr
->second
- curTime
) * 1000;
16571 data
<< uint16(itr
->first
); // spellid
16572 data
<< uint16(0); // spell category?
16573 data
<< uint32(itr
->second
); // cooldown
16574 data
<< uint32(0); // category cooldown
16577 for(CreatureSpellCooldowns::const_iterator itr
= pet
->m_CreatureCategoryCooldowns
.begin(); itr
!= pet
->m_CreatureCategoryCooldowns
.end(); ++itr
)
16579 time_t cooldown
= 0;
16581 if(itr
->second
> curTime
)
16582 cooldown
= (itr
->second
- curTime
) * 1000;
16584 data
<< uint16(itr
->first
); // spellid
16585 data
<< uint16(0); // spell category?
16586 data
<< uint32(0); // cooldown
16587 data
<< uint32(itr
->second
); // category cooldown
16590 GetSession()->SendPacket(&data
);
16593 void Player::PossessSpellInitialize()
16595 Unit
* charm
= GetCharm();
16600 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
16604 sLog
.outError("Player::PossessSpellInitialize(): charm ("I64FMTD
") has no charminfo!", charm
->GetGUID());
16609 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);// first line + actionbar + spellcount + spells + last adds
16612 data
<< uint64(charm
->GetGUID());
16613 data
<< uint32(0x00000000);
16615 data
<< uint8(0) << uint8(0) << uint16(0);
16617 for(uint32 i
= 0; i
< 10; i
++) //40
16619 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
16622 data
<< uint8(addlist
); //1
16625 data
<< uint8(count
); // cooldowns count
16627 GetSession()->SendPacket(&data
);
16630 void Player::CharmSpellInitialize()
16632 Unit
* charm
= GetCharm();
16637 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
16640 sLog
.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD
") has no charminfo!", charm
->GetGUID());
16646 if(charm
->GetTypeId() != TYPEID_PLAYER
)
16648 CreatureInfo
const *cinfo
= ((Creature
*)charm
)->GetCreatureInfo();
16650 if(cinfo
&& cinfo
->type
== CREATURE_TYPE_DEMON
&& getClass() == CLASS_WARLOCK
)
16652 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
16654 if(charmInfo
->GetCharmSpell(i
)->spellId
)
16660 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);// first line + actionbar + spellcount + spells + last adds
16662 data
<< uint64(charm
->GetGUID());
16663 data
<< uint32(0x00000000);
16665 if(charm
->GetTypeId() != TYPEID_PLAYER
)
16666 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState());
16668 data
<< uint8(0) << uint8(0);
16671 for(uint32 i
= 0; i
< 10; i
++) //40
16673 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
16676 data
<< uint8(addlist
); //1
16680 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
16682 CharmSpellEntry
*cspell
= charmInfo
->GetCharmSpell(i
);
16683 if(cspell
->spellId
)
16685 data
<< uint16(cspell
->spellId
);
16686 data
<< uint16(cspell
->active
);
16692 data
<< uint8(count
); // cooldowns count
16694 GetSession()->SendPacket(&data
);
16697 bool Player::IsAffectedBySpellmod(SpellEntry
const *spellInfo
, SpellModifier
*mod
, Spell
const* spell
)
16699 if (!mod
|| !spellInfo
)
16702 if(mod
->charges
== -1 && mod
->lastAffected
) // marked as expired but locked until spell casting finish
16704 // prevent apply to any spell except spell that trigger expire
16707 if(mod
->lastAffected
!= spell
)
16710 else if(mod
->lastAffected
!= FindCurrentSpellBySpellId(spellInfo
->Id
))
16714 return spellmgr
.IsAffectedByMod(spellInfo
, mod
);
16717 void Player::AddSpellMod(SpellModifier
* mod
, bool apply
)
16719 uint16 Opcode
= (mod
->type
== SPELLMOD_FLAT
) ? SMSG_SET_FLAT_SPELL_MODIFIER
: SMSG_SET_PCT_SPELL_MODIFIER
;
16721 for(int eff
=0;eff
<96;++eff
)
16725 if (eff
<64) _mask
= uint64(1) << (eff
- 0);
16726 else _mask2
= uint64(1) << (eff
-64);
16727 if ( mod
->mask
& _mask
|| mod
->mask2
& _mask2
)
16730 for (SpellModList::iterator itr
= m_spellMods
[mod
->op
].begin(); itr
!= m_spellMods
[mod
->op
].end(); ++itr
)
16732 if ((*itr
)->type
== mod
->type
&& ((*itr
)->mask
& _mask
|| (*itr
)->mask2
& _mask2
))
16733 val
+= (*itr
)->value
;
16735 val
+= apply
? mod
->value
: -(mod
->value
);
16736 WorldPacket
data(Opcode
, (1+1+4));
16737 data
<< uint8(eff
);
16738 data
<< uint8(mod
->op
);
16739 data
<< int32(val
);
16740 SendDirectMessage(&data
);
16745 m_spellMods
[mod
->op
].push_back(mod
);
16748 if (mod
->charges
== -1)
16749 --m_SpellModRemoveCount
;
16750 m_spellMods
[mod
->op
].remove(mod
);
16755 void Player::RemoveSpellMods(Spell
const* spell
)
16757 if(!spell
|| (m_SpellModRemoveCount
== 0))
16760 for(int i
=0;i
<MAX_SPELLMOD
;++i
)
16762 for (SpellModList::iterator itr
= m_spellMods
[i
].begin(); itr
!= m_spellMods
[i
].end();)
16764 SpellModifier
*mod
= *itr
;
16767 if (mod
&& mod
->charges
== -1 && (mod
->lastAffected
== spell
|| mod
->lastAffected
==NULL
))
16769 RemoveAurasDueToSpell(mod
->spellId
);
16770 if (m_spellMods
[i
].empty())
16773 itr
= m_spellMods
[i
].begin();
16779 // send Proficiency
16780 void Player::SendProficiency(uint8 pr1
, uint32 pr2
)
16782 WorldPacket
data(SMSG_SET_PROFICIENCY
, 8);
16783 data
<< pr1
<< pr2
;
16784 GetSession()->SendPacket (&data
);
16787 void Player::RemovePetitionsAndSigns(uint64 guid
, uint32 type
)
16789 QueryResult
*result
= NULL
;
16791 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
16793 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16796 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.
16797 { // and SendPetitionQueryOpcode reads data from the DB
16798 Field
*fields
= result
->Fetch();
16799 uint64 ownerguid
= MAKE_NEW_GUID(fields
[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
16800 uint64 petitionguid
= MAKE_NEW_GUID(fields
[1].GetUInt32(), 0, HIGHGUID_ITEM
);
16802 // send update if charter owner in game
16803 Player
* owner
= objmgr
.GetPlayer(ownerguid
);
16805 owner
->GetSession()->SendPetitionQueryOpcode(petitionguid
);
16807 } while ( result
->NextRow() );
16812 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
16814 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16817 CharacterDatabase
.BeginTransaction();
16820 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid
));
16821 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid
));
16825 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16826 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16828 CharacterDatabase
.CommitTransaction();
16831 void Player::LeaveAllArenaTeams(uint64 guid
)
16833 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
));
16839 Field
*fields
= result
->Fetch();
16840 uint32 at_id
= fields
[0].GetUInt32();
16843 ArenaTeam
* at
= objmgr
.GetArenaTeamById(at_id
);
16845 at
->DelMember(guid
);
16847 } while (result
->NextRow());
16852 void Player::SetRestBonus (float rest_bonus_new
)
16854 // Prevent resting on max level
16855 if(getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
16856 rest_bonus_new
= 0;
16858 if(rest_bonus_new
< 0)
16859 rest_bonus_new
= 0;
16861 float rest_bonus_max
= (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)*1.5/2;
16863 if(rest_bonus_new
> rest_bonus_max
)
16864 m_rest_bonus
= rest_bonus_max
;
16866 m_rest_bonus
= rest_bonus_new
;
16868 // update data for client
16869 if(m_rest_bonus
>10)
16870 SetByteValue(PLAYER_BYTES_2
, 3, 0x01); // Set Reststate = Rested
16871 else if(m_rest_bonus
<=1)
16872 SetByteValue(PLAYER_BYTES_2
, 3, 0x02); // Set Reststate = Normal
16875 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE
, uint32(m_rest_bonus
));
16878 void Player::HandleStealthedUnitsDetection()
16880 std::list
<Unit
*> stealthedUnits
;
16882 CellPair
p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16884 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
16885 cell
.SetNoCreate();
16887 MaNGOS::AnyStealthedCheck u_check
;
16888 MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
> searcher(stealthedUnits
, u_check
);
16890 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, WorldTypeMapContainer
> world_unit_searcher(searcher
);
16891 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, GridTypeMapContainer
> grid_unit_searcher(searcher
);
16893 CellLock
<GridReadGuard
> cell_lock(cell
, p
);
16894 cell_lock
->Visit(cell_lock
, world_unit_searcher
, *GetMap());
16895 cell_lock
->Visit(cell_lock
, grid_unit_searcher
, *GetMap());
16897 for (std::list
<Unit
*>::iterator i
= stealthedUnits
.begin(); i
!= stealthedUnits
.end();)
16901 i
= stealthedUnits
.erase(i
);
16905 if ((*i
)->isVisibleForOrDetect(this,true))
16908 (*i
)->SendUpdateToPlayer(this);
16909 m_clientGUIDs
.insert((*i
)->GetGUID());
16911 #ifdef MANGOS_DEBUG
16912 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
16913 sLog
.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i
)->GetGUIDLow(),(*i
)->GetTypeId(),GetGUIDLow(),GetDistance(*i
));
16916 // target aura duration for caster show only if target exist at caster client
16917 // send data at target visibility change (adding to client)
16918 if((*i
)!=this && (*i
)->isType(TYPEMASK_UNIT
))
16919 SendAurasForTarget(*i
);
16921 i
= stealthedUnits
.erase(i
);
16929 bool Player::ActivateTaxiPathTo(std::vector
<uint32
> const& nodes
, uint32 mount_id
, Creature
* npc
)
16931 if(nodes
.size() < 2)
16934 // not let cheating with start flight mounted
16937 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16938 data
<< uint32(ERR_TAXIPLAYERALREADYMOUNTED
);
16939 GetSession()->SendPacket(&data
);
16943 if( m_ShapeShiftFormSpellId
&& m_form
!= FORM_BATTLESTANCE
&& m_form
!= FORM_BERSERKERSTANCE
&& m_form
!= FORM_DEFENSIVESTANCE
&& m_form
!= FORM_SHADOW
)
16945 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16946 data
<< uint32(ERR_TAXIPLAYERSHAPESHIFTED
);
16947 GetSession()->SendPacket(&data
);
16951 // 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
16952 if(GetSession()->isLogingOut() ||
16953 (!m_currentSpells
[CURRENT_GENERIC_SPELL
] ||
16954 m_currentSpells
[CURRENT_GENERIC_SPELL
]->m_spellInfo
->Effect
[0] != SPELL_EFFECT_SEND_TAXI
)&&
16955 IsNonMeleeSpellCasted(false) ||
16958 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16959 data
<< uint32(ERR_TAXIPLAYERBUSY
);
16960 GetSession()->SendPacket(&data
);
16964 if(HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_DISABLE_MOVE
))
16967 uint32 sourcenode
= nodes
[0];
16969 // starting node too far away (cheat?)
16970 TaxiNodesEntry
const* node
= sTaxiNodesStore
.LookupEntry(sourcenode
);
16971 if( !node
|| node
->map_id
!= GetMapId() ||
16972 (node
->x
- GetPositionX())*(node
->x
- GetPositionX())+
16973 (node
->y
- GetPositionY())*(node
->y
- GetPositionY())+
16974 (node
->z
- GetPositionZ())*(node
->z
- GetPositionZ()) >
16975 (2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
) )
16977 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16978 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
16979 GetSession()->SendPacket(&data
);
16983 // Prepare to flight start now
16985 // stop combat at start taxi flight if any
16988 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16991 // clean not finished taxi path if any
16992 m_taxi
.ClearTaxiDestinations();
16994 // 0 element current node
16995 m_taxi
.AddTaxiDestination(sourcenode
);
16997 // fill destinations path tail
16998 uint32 sourcepath
= 0;
16999 uint32 totalcost
= 0;
17001 uint32 prevnode
= sourcenode
;
17002 uint32 lastnode
= 0;
17004 for(uint32 i
= 1; i
< nodes
.size(); ++i
)
17008 lastnode
= nodes
[i
];
17009 objmgr
.GetTaxiPath(prevnode
, lastnode
, path
, cost
);
17013 m_taxi
.ClearTaxiDestinations();
17019 if(prevnode
== sourcenode
)
17022 m_taxi
.AddTaxiDestination(lastnode
);
17024 prevnode
= lastnode
;
17027 if(!mount_id
) // if not provide then attempt use default.
17028 mount_id
= objmgr
.GetTaxiMount(sourcenode
, GetTeam());
17030 if (mount_id
== 0 || sourcepath
== 0)
17032 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17033 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
17034 GetSession()->SendPacket(&data
);
17035 m_taxi
.ClearTaxiDestinations();
17039 uint32 money
= GetMoney();
17043 totalcost
= (uint32
)ceil(totalcost
*GetReputationPriceDiscount(npc
));
17046 if(money
< totalcost
)
17048 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17049 data
<< uint32(ERR_TAXINOTENOUGHMONEY
);
17050 GetSession()->SendPacket(&data
);
17051 m_taxi
.ClearTaxiDestinations();
17055 //Checks and preparations done, DO FLIGHT
17056 ModifyMoney(-(int32
)totalcost
);
17058 // prevent stealth flight
17059 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH
);
17061 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
17062 data
<< uint32(ERR_TAXIOK
);
17063 GetSession()->SendPacket(&data
);
17065 sLog
.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
17067 GetSession()->SendDoFlight(mount_id
, sourcepath
);
17072 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask
, uint32 unTimeMs
)
17074 // last check 2.0.10
17075 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+m_spells
.size()*8);
17077 data
<< uint8(0x0); // flags (0x1, 0x2)
17078 time_t curTime
= time(NULL
);
17079 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
17081 if (itr
->second
->state
== PLAYERSPELL_REMOVED
)
17083 uint32 unSpellId
= itr
->first
;
17084 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(unSpellId
);
17091 // Not send cooldown for this spells
17092 if (spellInfo
->Attributes
& SPELL_ATTR_DISABLED_WHILE_ACTIVE
)
17095 if((idSchoolMask
& GetSpellSchoolMask(spellInfo
)) && GetSpellCooldownDelay(unSpellId
) < unTimeMs
)
17098 data
<< unTimeMs
; // in m.secs
17099 AddSpellCooldown(unSpellId
, 0, curTime
+ unTimeMs
/1000);
17102 GetSession()->SendPacket(&data
);
17105 void Player::InitDataForForm(bool reapplyMods
)
17107 SpellShapeshiftEntry
const* ssEntry
= sSpellShapeshiftStore
.LookupEntry(m_form
);
17108 if(ssEntry
&& ssEntry
->attackSpeed
)
17110 SetAttackTime(BASE_ATTACK
,ssEntry
->attackSpeed
);
17111 SetAttackTime(OFF_ATTACK
,ssEntry
->attackSpeed
);
17112 SetAttackTime(RANGED_ATTACK
, BASE_ATTACK_TIME
);
17115 SetRegularAttackTime();
17121 if(getPowerType()!=POWER_ENERGY
)
17122 setPowerType(POWER_ENERGY
);
17126 case FORM_DIREBEAR
:
17128 if(getPowerType()!=POWER_RAGE
)
17129 setPowerType(POWER_RAGE
);
17132 default: // 0, for example
17134 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(getClass());
17135 if(cEntry
&& cEntry
->powerType
< MAX_POWERS
&& uint32(getPowerType()) != cEntry
->powerType
)
17136 setPowerType(Powers(cEntry
->powerType
));
17141 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
17143 UpdateEquipSpellsAtFormChange();
17145 UpdateAttackPowerAndDamage();
17146 UpdateAttackPowerAndDamage(true);
17149 // Return true is the bought item has a max count to force refresh of window by caller
17150 bool Player::BuyItemFromVendor(uint64 vendorguid
, uint32 item
, uint8 count
, uint64 bagguid
, uint8 slot
)
17152 // cheating attempt
17153 if(count
< 1) count
= 1;
17158 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
17161 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, NULL
, item
, 0);
17165 Creature
*pCreature
= ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid
,UNIT_NPC_FLAG_VENDOR
);
17168 sLog
.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid
)) );
17169 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR
, NULL
, item
, 0);
17173 VendorItemData
const* vItems
= pCreature
->GetVendorItems();
17174 if(!vItems
|| vItems
->Empty())
17176 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
17180 size_t vendor_slot
= vItems
->FindItemSlot(item
);
17181 if(vendor_slot
>= vItems
->GetItemCount())
17183 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
17187 VendorItem
const* crItem
= vItems
->m_items
[vendor_slot
];
17189 // check current item amount if it limited
17190 if( crItem
->maxcount
!= 0 )
17192 if(pCreature
->GetVendorItemCurrentCount(crItem
) < pProto
->BuyCount
* count
)
17194 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD
, pCreature
, item
, 0);
17199 if( uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
17201 SendBuyError( BUY_ERR_REPUTATION_REQUIRE
, pCreature
, item
, 0);
17205 if(crItem
->ExtendedCost
)
17207 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
17210 sLog
.outError("Item %u have wrong ExtendedCost field value %u", pProto
->ItemId
, crItem
->ExtendedCost
);
17214 // honor points price
17215 if(GetHonorPoints() < (iece
->reqhonorpoints
* count
))
17217 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS
, NULL
, NULL
);
17221 // arena points price
17222 if(GetArenaPoints() < (iece
->reqarenapoints
* count
))
17224 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS
, NULL
, NULL
);
17229 for (uint8 i
= 0; i
< 5; ++i
)
17231 if(iece
->reqitem
[i
] && !HasItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
)))
17233 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS
, NULL
, NULL
);
17238 // check for personal arena rating requirement
17239 if( GetMaxPersonalArenaRatingRequirement() < iece
->reqpersonalarenarating
)
17241 // probably not the proper equip err
17242 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK
,NULL
,NULL
);
17247 uint32 price
= pProto
->BuyPrice
* count
;
17249 // reputation discount
17250 price
= uint32(floor(price
* GetReputationPriceDiscount(pCreature
)));
17252 if( GetMoney() < price
)
17254 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, pCreature
, item
, 0);
17258 uint8 bag
= 0; // init for case invalid bagGUID
17260 if (bagguid
!= NULL_BAG
&& slot
!= NULL_SLOT
)
17263 if( bagguid
== GetGUID() )
17265 bag
= INVENTORY_SLOT_BAG_0
;
17269 for (int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
;i
++)
17271 pBag
= (Bag
*)GetItemByPos(INVENTORY_SLOT_BAG_0
,i
);
17274 if( bagguid
== pBag
->GetGUID() )
17284 if( IsInventoryPos( bag
, slot
) || (bagguid
== NULL_BAG
&& slot
== NULL_SLOT
) )
17286 ItemPosCountVec dest
;
17287 uint8 msg
= CanStoreNewItem( bag
, slot
, dest
, item
, pProto
->BuyCount
* count
);
17288 if( msg
!= EQUIP_ERR_OK
)
17290 SendEquipError( msg
, NULL
, NULL
);
17294 ModifyMoney( -(int32
)price
);
17295 if(crItem
->ExtendedCost
) // case for new honor system
17297 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
17298 if(iece
->reqhonorpoints
)
17299 ModifyHonorPoints( - int32(iece
->reqhonorpoints
* count
));
17300 if(iece
->reqarenapoints
)
17301 ModifyArenaPoints( - int32(iece
->reqarenapoints
* count
));
17302 for (uint8 i
= 0; i
< 5; ++i
)
17304 if(iece
->reqitem
[i
])
17305 DestroyItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
), true);
17309 if(Item
*it
= StoreNewItem( dest
, item
, true ))
17311 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
17313 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
17314 data
<< pCreature
->GetGUID();
17315 data
<< (uint32
)(vendor_slot
+1); // numbered from 1 at client
17316 data
<< (uint32
)(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
17317 data
<< (uint32
)count
;
17318 GetSession()->SendPacket(&data
);
17320 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
17323 else if( IsEquipmentPos( bag
, slot
) )
17325 if(pProto
->BuyCount
* count
!= 1)
17327 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
, NULL
, NULL
);
17332 uint8 msg
= CanEquipNewItem( slot
, dest
, item
, false );
17333 if( msg
!= EQUIP_ERR_OK
)
17335 SendEquipError( msg
, NULL
, NULL
);
17339 ModifyMoney( -(int32
)price
);
17340 if(crItem
->ExtendedCost
) // case for new honor system
17342 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
17343 if(iece
->reqhonorpoints
)
17344 ModifyHonorPoints( - int32(iece
->reqhonorpoints
));
17345 if(iece
->reqarenapoints
)
17346 ModifyArenaPoints( - int32(iece
->reqarenapoints
));
17347 for (uint8 i
= 0; i
< 5; ++i
)
17349 if(iece
->reqitem
[i
])
17350 DestroyItemCount(iece
->reqitem
[i
], iece
->reqitemcount
[i
], true);
17354 if(Item
*it
= EquipNewItem( dest
, item
, true ))
17356 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
17358 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
17359 data
<< pCreature
->GetGUID();
17360 data
<< (uint32
)(vendor_slot
+1); // numbered from 1 at client
17361 data
<< (uint32
)(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
17362 data
<< (uint32
)count
;
17363 GetSession()->SendPacket(&data
);
17365 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
17367 AutoUnequipOffhandIfNeed();
17372 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
, NULL
, NULL
);
17376 return crItem
->maxcount
!=0;
17379 uint32
Player::GetMaxPersonalArenaRatingRequirement()
17381 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17382 // the personal rating of the arena team must match the required limit as well
17383 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17384 uint32 max_personal_rating
= 0;
17385 for(int i
= 0; i
< MAX_ARENA_SLOT
; ++i
)
17387 if(ArenaTeam
* at
= objmgr
.GetArenaTeamById(GetArenaTeamId(i
)))
17389 uint32 p_rating
= GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ (i
* 6) + 5);
17390 uint32 t_rating
= at
->GetRating();
17391 p_rating
= p_rating
<t_rating
? p_rating
: t_rating
;
17392 if(max_personal_rating
< p_rating
)
17393 max_personal_rating
= p_rating
;
17396 return max_personal_rating
;
17399 void Player::UpdateHomebindTime(uint32 time
)
17401 // GMs never get homebind timer online
17402 if (m_InstanceValid
|| isGameMaster())
17404 if(m_HomebindTimer
) // instance valid, but timer not reset
17407 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
17410 GetSession()->SendPacket(&data
);
17412 // instance is valid, reset homebind timer
17413 m_HomebindTimer
= 0;
17415 else if (m_HomebindTimer
> 0)
17417 if (time
>= m_HomebindTimer
)
17419 // teleport to homebind location
17420 TeleportTo(m_homebindMapId
, m_homebindX
, m_homebindY
, m_homebindZ
, GetOrientation());
17423 m_HomebindTimer
-= time
;
17427 // instance is invalid, start homebind timer
17428 m_HomebindTimer
= 60000;
17429 // send message to player
17430 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
17431 data
<< m_HomebindTimer
;
17433 GetSession()->SendPacket(&data
);
17434 sLog
.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17438 void Player::UpdatePvP(bool state
, bool ovrride
)
17440 if(!state
|| ovrride
)
17443 if(Pet
* pet
= GetPet())
17444 pet
->SetPvP(state
);
17445 if(Unit
* charmed
= GetCharm())
17446 charmed
->SetPvP(state
);
17448 pvpInfo
.endTimer
= 0;
17452 if(pvpInfo
.endTimer
!= 0)
17453 pvpInfo
.endTimer
= time(NULL
);
17458 if(Pet
* pet
= GetPet())
17459 pet
->SetPvP(state
);
17460 if(Unit
* charmed
= GetCharm())
17461 charmed
->SetPvP(state
);
17466 void Player::AddSpellCooldown(uint32 spellid
, uint32 itemid
, time_t end_time
)
17470 sc
.itemid
= itemid
;
17471 m_spellCooldowns
[spellid
] = sc
;
17474 void Player::SendCooldownEvent(SpellEntry
const *spellInfo
)
17476 if ( !(spellInfo
->Attributes
& SPELL_ATTR_DISABLED_WHILE_ACTIVE
) )
17479 // Get spell cooldown
17480 int32 cooldown
= GetSpellRecoveryTime(spellInfo
);
17482 ApplySpellMod(spellInfo
->Id
, SPELLMOD_COOLDOWN
, cooldown
);
17486 AddSpellCooldown(spellInfo
->Id
, 0, time(NULL
) + cooldown
/ 1000);
17488 WorldPacket
data(SMSG_COOLDOWN_EVENT
, (4+8));
17489 data
<< spellInfo
->Id
;
17491 SendDirectMessage(&data
);
17493 //slot to be excluded while counting
17494 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition
, int8 slot
)
17496 if(!enchantmentcondition
)
17499 SpellItemEnchantmentConditionEntry
const *Condition
= sSpellItemEnchantmentConditionStore
.LookupEntry(enchantmentcondition
);
17504 uint8 curcount
[4] = {0, 0, 0, 0};
17506 //counting current equipped gem colors
17507 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
17511 Item
*pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
17512 if(pItem2
&& pItem2
->GetProto()->Socket
[0].Color
)
17514 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17516 uint32 enchant_id
= pItem2
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17520 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17524 uint32 gemid
= enchantEntry
->GemID
;
17528 ItemPrototype
const* gemProto
= sItemStorage
.LookupEntry
<ItemPrototype
>(gemid
);
17532 GemPropertiesEntry
const* gemProperty
= sGemPropertiesStore
.LookupEntry(gemProto
->GemProperties
);
17536 uint8 GemColor
= gemProperty
->color
;
17538 for(uint8 b
= 0, tmpcolormask
= 1; b
< 4; b
++, tmpcolormask
<<= 1)
17540 if(tmpcolormask
& GemColor
)
17547 bool activate
= true;
17549 for(int i
= 0; i
< 5; i
++)
17551 if(!Condition
->Color
[i
])
17554 uint32 _cur_gem
= curcount
[Condition
->Color
[i
] - 1];
17556 // if have <CompareColor> use them as count, else use <value> from Condition
17557 uint32 _cmp_gem
= Condition
->CompareColor
[i
] ? curcount
[Condition
->CompareColor
[i
] - 1]: Condition
->Value
[i
];
17559 switch(Condition
->Comparator
[i
])
17561 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17562 activate
&= (_cur_gem
< _cmp_gem
) ? true : false;
17564 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17565 activate
&= (_cur_gem
> _cmp_gem
) ? true : false;
17567 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17568 activate
&= (_cur_gem
>= _cmp_gem
) ? true : false;
17573 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");
17578 void Player::CorrectMetaGemEnchants(uint8 exceptslot
, bool apply
)
17580 //cycle all equipped items
17581 for(uint32 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
17583 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17584 if(slot
== exceptslot
)
17587 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
17589 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
)
17592 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17594 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17598 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17602 uint32 condition
= enchantEntry
->EnchantmentCondition
;
17605 //was enchant active with/without item?
17606 bool wasactive
= EnchantmentFitsRequirements(condition
, apply
? exceptslot
: -1);
17607 //should it now be?
17608 if(wasactive
^ EnchantmentFitsRequirements(condition
, apply
? -1 : exceptslot
))
17610 // ignore item gem conditions
17611 //if state changed, (dis)apply enchant
17612 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
),!wasactive
,true,true);
17619 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17620 void Player::ToggleMetaGemsActive(uint8 exceptslot
, bool apply
)
17622 //cycle all equipped items
17623 for(int slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
17625 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17626 if(slot
== exceptslot
)
17629 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
17631 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
) //if item has no sockets or no item is equipped go to next item
17634 //cycle all (gem)enchants
17635 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17637 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17638 if(!enchant_id
) //if no enchant go to next enchant(slot)
17641 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17645 //only metagems to be (de)activated, so only enchants with condition
17646 uint32 condition
= enchantEntry
->EnchantmentCondition
;
17648 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
), apply
);
17653 void Player::LeaveBattleground(bool teleportToEntryPoint
)
17655 if(BattleGround
*bg
= GetBattleGround())
17657 bool need_debuf
= bg
->isBattleGround() && (bg
->GetStatus() == STATUS_IN_PROGRESS
) && sWorld
.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER
);
17659 bg
->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint
, true);
17661 // call after remove to be sure that player resurrected for correct cast
17663 CastSpell(this, 26013, true); // Deserter
17667 bool Player::CanJoinToBattleground() const
17669 // check Deserter debuff
17670 if(GetDummyAura(26013))
17676 bool Player::CanReportAfkDueToLimit()
17678 // a player can complain about 15 people per 5 minutes
17679 if(m_bgAfkReportedCount
>= 15)
17681 ++m_bgAfkReportedCount
;
17685 ///This player has been blamed to be inactive in a battleground
17686 void Player::ReportedAfkBy(Player
* reporter
)
17688 BattleGround
*bg
= GetBattleGround();
17689 if(!bg
|| bg
!= reporter
->GetBattleGround() || GetTeam() != reporter
->GetTeam())
17692 // check if player has 'Idle' or 'Inactive' debuff
17693 if(m_bgAfkReporter
.find(reporter
->GetGUIDLow())==m_bgAfkReporter
.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter
->CanReportAfkDueToLimit())
17695 m_bgAfkReporter
.insert(reporter
->GetGUIDLow());
17696 // 3 players have to complain to apply debuff
17697 if(m_bgAfkReporter
.size() >= 3)
17699 // cast 'Idle' spell
17700 CastSpell(this, 43680, true);
17701 m_bgAfkReporter
.clear();
17706 bool Player::IsVisibleInGridForPlayer( Player
* pl
) const
17708 // gamemaster in GM mode see all, including ghosts
17709 if(pl
->isGameMaster() && GetSession()->GetSecurity() <= pl
->GetSession()->GetSecurity())
17712 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17713 if (InBattleGround())
17715 if (!(isAlive() || m_deathTimer
> 0) && !IsFriendlyTo(pl
) )
17720 // Live player see live player or dead player with not realized corpse
17721 if(pl
->isAlive() || pl
->m_deathTimer
> 0)
17723 return isAlive() || m_deathTimer
> 0;
17726 // Ghost see other friendly ghosts, that's for sure
17727 if(!(isAlive() || m_deathTimer
> 0) && IsFriendlyTo(pl
))
17730 // Dead player see live players near own corpse
17733 Corpse
*corpse
= pl
->GetCorpse();
17736 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17737 if(corpse
->IsWithinDistInMap(this,(20+25)*sWorld
.getRate(RATE_CREATURE_AGGRO
)))
17742 // and not see any other
17746 bool Player::IsVisibleGloballyFor( Player
* u
) const
17751 // Always can see self
17755 // Visible units, always are visible for all players
17756 if (GetVisibility() == VISIBILITY_ON
)
17759 // GMs are visible for higher gms (or players are visible for gms)
17760 if (u
->GetSession()->GetSecurity() > SEC_PLAYER
)
17761 return GetSession()->GetSecurity() <= u
->GetSession()->GetSecurity();
17763 // non faction visibility non-breakable for non-GMs
17764 if (GetVisibility() == VISIBILITY_OFF
)
17767 // non-gm stealth/invisibility not hide from global player lists
17771 void Player::UpdateVisibilityOf(WorldObject
* target
)
17773 if(HaveAtClient(target
))
17775 if(!target
->isVisibleForInState(this,true))
17777 target
->DestroyForPlayer(this);
17778 m_clientGUIDs
.erase(target
->GetGUID());
17780 #ifdef MANGOS_DEBUG
17781 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17782 sLog
.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
17788 if(target
->isVisibleForInState(this,false))
17790 target
->SendUpdateToPlayer(this);
17791 if(target
->GetTypeId()!=TYPEID_GAMEOBJECT
||!((GameObject
*)target
)->IsTransport())
17792 m_clientGUIDs
.insert(target
->GetGUID());
17794 #ifdef MANGOS_DEBUG
17795 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17796 sLog
.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
17799 // target aura duration for caster show only if target exist at caster client
17800 // send data at target visibility change (adding to client)
17801 if(target
!=this && target
->isType(TYPEMASK_UNIT
))
17802 SendAurasForTarget((Unit
*)target
);
17804 if(target
->GetTypeId()==TYPEID_UNIT
&& ((Creature
*)target
)->isAlive())
17805 ((Creature
*)target
)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17811 inline void UpdateVisibilityOf_helper(std::set
<uint64
>& s64
, T
* target
)
17813 s64
.insert(target
->GetGUID());
17817 inline void UpdateVisibilityOf_helper(std::set
<uint64
>& s64
, GameObject
* target
)
17819 if(!target
->IsTransport())
17820 s64
.insert(target
->GetGUID());
17824 void Player::UpdateVisibilityOf(T
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
)
17826 if(HaveAtClient(target
))
17828 if(!target
->isVisibleForInState(this,true))
17830 target
->BuildOutOfRangeUpdateBlock(&data
);
17831 m_clientGUIDs
.erase(target
->GetGUID());
17833 #ifdef MANGOS_DEBUG
17834 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17835 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
));
17841 if(target
->isVisibleForInState(this,false))
17843 visibleNow
.insert(target
);
17844 target
->BuildUpdate(data_updates
);
17845 target
->BuildCreateUpdateBlockForPlayer(&data
, this);
17846 UpdateVisibilityOf_helper(m_clientGUIDs
,target
);
17848 #ifdef MANGOS_DEBUG
17849 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17850 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
));
17856 template void Player::UpdateVisibilityOf(Player
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17857 template void Player::UpdateVisibilityOf(Creature
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17858 template void Player::UpdateVisibilityOf(Corpse
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17859 template void Player::UpdateVisibilityOf(GameObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17860 template void Player::UpdateVisibilityOf(DynamicObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17862 void Player::InitPrimaryProffesions()
17864 SetFreePrimaryProffesions(sWorld
.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL
));
17867 void Player::SendComboPoints()
17869 Unit
*combotarget
= ObjectAccessor::GetUnit(*this, m_comboTarget
);
17872 WorldPacket
data(SMSG_UPDATE_COMBO_POINTS
, combotarget
->GetPackGUID().size()+1);
17873 data
.append(combotarget
->GetPackGUID());
17874 data
<< uint8(m_comboPoints
);
17875 GetSession()->SendPacket(&data
);
17879 void Player::AddComboPoints(Unit
* target
, int8 count
)
17884 // without combo points lost (duration checked in aura)
17885 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
17887 if(target
->GetGUID() == m_comboTarget
)
17889 m_comboPoints
+= count
;
17894 if(Unit
* target
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
17895 target
->RemoveComboPointHolder(GetGUIDLow());
17897 m_comboTarget
= target
->GetGUID();
17898 m_comboPoints
= count
;
17900 target
->AddComboPointHolder(GetGUIDLow());
17903 if (m_comboPoints
> 5) m_comboPoints
= 5;
17904 if (m_comboPoints
< 0) m_comboPoints
= 0;
17909 void Player::ClearComboPoints()
17914 // without combopoints lost (duration checked in aura)
17915 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
17921 if(Unit
* target
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
17922 target
->RemoveComboPointHolder(GetGUIDLow());
17927 void Player::SetGroup(Group
*group
, int8 subgroup
)
17929 if(group
== NULL
) m_group
.unlink();
17932 // never use SetGroup without a subgroup unless you specify NULL for group
17933 assert(subgroup
>= 0);
17934 m_group
.link(group
, this);
17935 m_group
.setSubGroup((uint8
)subgroup
);
17939 void Player::SendInitialPacketsBeforeAddToMap()
17941 WorldPacket
data(SMSG_SET_REST_START_OBSOLETE
, 4);
17942 data
<< uint32(0); // unknown, may be rest state time or experience
17943 GetSession()->SendPacket(&data
);
17946 data
.Initialize(SMSG_BINDPOINTUPDATE
, 5*4);
17947 data
<< m_homebindX
<< m_homebindY
<< m_homebindZ
;
17948 data
<< (uint32
) m_homebindMapId
;
17949 data
<< (uint32
) m_homebindZoneId
;
17950 GetSession()->SendPacket(&data
);
17952 // SMSG_SET_PROFICIENCY
17953 // SMSG_UPDATE_AURA_DURATION
17956 data
.Initialize(SMSG_TUTORIAL_FLAGS
, 8*4);
17957 for (int i
= 0; i
< 8; ++i
)
17958 data
<< uint32( GetTutorialInt(i
) );
17959 GetSession()->SendPacket(&data
);
17961 SendInitialSpells();
17963 data
.Initialize(SMSG_SEND_UNLEARN_SPELLS
, 4);
17964 data
<< uint32(0); // count, for(count) uint32;
17965 GetSession()->SendPacket(&data
);
17967 SendInitialActionButtons();
17968 SendInitialReputations();
17969 m_achievementMgr
.SendAllAchievementData();
17970 UpdateZone(GetZoneId());
17971 SendInitWorldStates();
17973 // SMSG_SET_AURA_SINGLE
17975 data
.Initialize(SMSG_LOGIN_SETTIMESPEED
, 8);
17976 data
<< uint32(secsToTimeBitFields(sWorld
.GetGameTime()));
17977 data
<< (float)0.01666667f
; // game speed
17978 GetSession()->SendPacket( &data
);
17980 data
.Initialize(SMSG_TIME_SYNC_REQ
, 4); // new 2.0.x, enable movement
17981 data
<< uint32(0x00000000); // on blizz it increments periodically
17982 GetSession()->SendPacket(&data
);
17984 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17985 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
) || isInFlight())
17986 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2
);
17991 void Player::SendInitialPacketsAfterAddToMap()
17993 WorldPacket
data(SMSG_TIME_SYNC_REQ
, 4); // new 2.0.x, enable movement
17994 data
<< uint32(0x00000000); // on blizz it increments periodically
17995 GetSession()->SendPacket(&data
);
17997 CastSpell(this, 836, true); // LOGINEFFECT
17999 // set some aura effects that send packet to player client after add player to map
18000 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
18001 // same auras state lost at far teleport, send it one more time in this case also
18002 static const AuraType auratypes
[] =
18004 SPELL_AURA_MOD_FEAR
, SPELL_AURA_TRANSFORM
, SPELL_AURA_WATER_WALK
,
18005 SPELL_AURA_FEATHER_FALL
, SPELL_AURA_HOVER
, SPELL_AURA_SAFE_FALL
,
18006 SPELL_AURA_FLY
, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
, SPELL_AURA_NONE
18008 for(AuraType
const* itr
= &auratypes
[0]; itr
&& itr
[0] != SPELL_AURA_NONE
; ++itr
)
18010 Unit::AuraList
const& auraList
= GetAurasByType(*itr
);
18011 if(!auraList
.empty())
18012 auraList
.front()->ApplyModifier(true,true);
18015 if(HasAuraType(SPELL_AURA_MOD_STUN
))
18016 SetMovement(MOVE_ROOT
);
18018 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
18019 if(HasAuraType(SPELL_AURA_MOD_ROOT
))
18021 WorldPacket
data(SMSG_FORCE_MOVE_ROOT
, 10);
18022 data
.append(GetPackGUID());
18024 SendMessageToSet(&data
,true);
18027 SendAurasForTarget(this);
18028 SendEnchantmentDurations(); // must be after add to map
18029 SendItemDurations(); // must be after add to map
18032 void Player::SendUpdateToOutOfRangeGroupMembers()
18034 if (m_groupUpdateMask
== GROUP_UPDATE_FLAG_NONE
)
18036 if(Group
* group
= GetGroup())
18037 group
->UpdatePlayerOutOfRange(this);
18039 m_groupUpdateMask
= GROUP_UPDATE_FLAG_NONE
;
18040 m_auraUpdateMask
= 0;
18041 if(Pet
*pet
= GetPet())
18042 pet
->ResetAuraUpdateMask();
18045 void Player::SendTransferAborted(uint32 mapid
, uint8 reason
, uint8 arg
)
18047 WorldPacket
data(SMSG_TRANSFER_ABORTED
, 4+2);
18048 data
<< uint32(mapid
);
18049 data
<< uint8(reason
); // transfer abort reason
18052 case TRANSFER_ABORT_INSUF_EXPAN_LVL
:
18053 case TRANSFER_ABORT_DIFFICULTY
:
18054 case TRANSFER_ABORT_UNIQUE_MESSAGE
:
18055 data
<< uint8(arg
);
18058 GetSession()->SendPacket(&data
);
18061 void Player::SendInstanceResetWarning(uint32 mapid
, uint32 time
)
18063 // type of warning, based on the time remaining until reset
18066 type
= RAID_INSTANCE_WELCOME
;
18067 else if(time
> 900 && time
<= 3600)
18068 type
= RAID_INSTANCE_WARNING_HOURS
;
18069 else if(time
> 300 && time
<= 900)
18070 type
= RAID_INSTANCE_WARNING_MIN
;
18072 type
= RAID_INSTANCE_WARNING_MIN_SOON
;
18073 WorldPacket
data(SMSG_RAID_INSTANCE_MESSAGE
, 4+4+4);
18074 data
<< uint32(type
);
18075 data
<< uint32(mapid
);
18076 data
<< uint32(time
);
18077 GetSession()->SendPacket(&data
);
18080 void Player::ApplyEquipCooldown( Item
* pItem
)
18082 for(int i
= 0; i
<5; ++i
)
18084 _Spell
const& spellData
= pItem
->GetProto()->Spells
[i
];
18087 if( !spellData
.SpellId
)
18090 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
18091 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
)
18094 AddSpellCooldown(spellData
.SpellId
, pItem
->GetEntry(), time(NULL
) + 30);
18096 WorldPacket
data(SMSG_ITEM_COOLDOWN
, 12);
18097 data
<< pItem
->GetGUID();
18098 data
<< uint32(spellData
.SpellId
);
18099 GetSession()->SendPacket(&data
);
18103 void Player::resetSpells()
18105 // not need after this call
18106 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS
))
18108 m_atLoginFlags
= m_atLoginFlags
& ~AT_LOGIN_RESET_SPELLS
;
18109 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS
), GetGUIDLow());
18112 // make full copy of map (spells removed and marked as deleted at another spell remove
18113 // and we can't use original map for safe iterative with visit each spell at loop end
18114 PlayerSpellMap smap
= GetSpellMap();
18116 for(PlayerSpellMap::const_iterator iter
= smap
.begin();iter
!= smap
.end(); ++iter
)
18117 removeSpell(iter
->first
); // only iter->first can be accessed, object by iter->second can be deleted already
18119 learnDefaultSpells();
18120 learnQuestRewardedSpells();
18123 void Player::learnDefaultSpells()
18125 // learn default race/class spells
18126 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(),getClass());
18127 for (PlayerCreateInfoSpells::const_iterator itr
= info
->spell
.begin(); itr
!=info
->spell
.end(); ++itr
)
18129 uint32 tspell
= *itr
;
18130 sLog
.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell
);
18131 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
18132 addSpell(tspell
,true,true,false);
18133 else // but send in normal spell in game learn case
18134 learnSpell(tspell
);
18138 void Player::learnQuestRewardedSpells(Quest
const* quest
)
18140 uint32 spell_id
= quest
->GetRewSpellCast();
18142 // skip quests without rewarded spell
18146 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
18150 // check learned spells state
18151 bool found
= false;
18152 for(int i
=0; i
< 3; ++i
)
18154 if(spellInfo
->Effect
[i
] == SPELL_EFFECT_LEARN_SPELL
&& !HasSpell(spellInfo
->EffectTriggerSpell
[i
]))
18161 // skip quests with not teaching spell or already known spell
18165 // prevent learn non first rank unknown profession and second specialization for same profession)
18166 uint32 learned_0
= spellInfo
->EffectTriggerSpell
[0];
18167 if( spellmgr
.GetSpellRank(learned_0
) > 1 && !HasSpell(learned_0
) )
18169 // not have first rank learned (unlearned prof?)
18170 uint32 first_spell
= spellmgr
.GetFirstSpellInChain(learned_0
);
18171 if( !HasSpell(first_spell
) )
18174 SpellEntry
const *learnedInfo
= sSpellStore
.LookupEntry(learned_0
);
18179 if(learnedInfo
->Effect
[0]==SPELL_EFFECT_TRADE_SKILL
&& learnedInfo
->Effect
[1]==0)
18181 // search other specialization for same prof
18182 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
18184 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->first
==learned_0
)
18187 SpellEntry
const *itrInfo
= sSpellStore
.LookupEntry(itr
->first
);
18191 // compare only specializations
18192 if(itrInfo
->Effect
[0]!=SPELL_EFFECT_TRADE_SKILL
|| itrInfo
->Effect
[1]!=0)
18195 // compare same chain spells
18196 if(spellmgr
.GetFirstSpellInChain(itr
->first
) != first_spell
)
18199 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18200 if(!spellmgr
.IsHighRankOfSpell(learned_0
,itr
->first
))
18206 CastSpell( this, spell_id
, true);
18209 void Player::learnQuestRewardedSpells()
18211 // learn spells received from quest completing
18212 for(QuestStatusMap::const_iterator itr
= mQuestStatus
.begin(); itr
!= mQuestStatus
.end(); ++itr
)
18214 // skip no rewarded quests
18215 if(!itr
->second
.m_rewarded
)
18218 Quest
const* quest
= objmgr
.GetQuestTemplate(itr
->first
);
18222 learnQuestRewardedSpells(quest
);
18226 void Player::learnSkillRewardedSpells(uint32 skill_id
)
18228 uint32 raceMask
= getRaceMask();
18229 uint32 classMask
= getClassMask();
18230 for (uint32 j
=0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
18232 SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
);
18233 if (!pAbility
|| pAbility
->skillId
!=skill_id
|| pAbility
->learnOnGetSkill
!= ABILITY_LEARNED_ON_GET_PROFESSION_SKILL
)
18235 // Check race if set
18236 if (pAbility
->racemask
&& !(pAbility
->racemask
& raceMask
))
18238 // Check class if set
18239 if (pAbility
->classmask
&& !(pAbility
->classmask
& classMask
))
18242 if (sSpellStore
.LookupEntry(pAbility
->spellId
))
18244 // Ok need learn spell
18245 learnSpell(pAbility
->spellId
);
18250 void Player::learnSkillRewardedSpells()
18252 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
18254 if(!GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
18257 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
18259 learnSkillRewardedSpells(pskill
);
18263 void Player::SendAurasForTarget(Unit
*target
)
18265 if(target
->GetVisibleAuras()->empty()) // speedup things
18268 WorldPacket
data(SMSG_AURA_UPDATE_ALL
);
18269 data
.append(target
->GetPackGUID());
18271 Unit::VisibleAuraMap
const *visibleAuras
= target
->GetVisibleAuras();
18272 for(Unit::VisibleAuraMap::const_iterator itr
= visibleAuras
->begin(); itr
!= visibleAuras
->end(); ++itr
)
18274 for(uint32 j
= 0; j
< 3; ++j
)
18276 if(Aura
*aura
= target
->GetAura(itr
->second
, j
))
18278 data
<< uint8(aura
->GetAuraSlot());
18279 data
<< uint32(aura
->GetId());
18283 uint8 auraFlags
= aura
->GetAuraFlags();
18285 data
<< uint8(auraFlags
);
18287 data
<< uint8(aura
->GetAuraLevel());
18289 data
<< uint8(aura
->GetAuraCharges());
18291 if(!(auraFlags
& AFLAG_NOT_CASTER
))
18293 data
<< uint8(0); // packed GUID of someone (caster?)
18296 if(auraFlags
& AFLAG_DURATION
) // include aura duration
18298 data
<< uint32(aura
->GetAuraMaxDuration());
18299 data
<< uint32(aura
->GetAuraDuration());
18307 GetSession()->SendPacket(&data
);
18310 void Player::SetDailyQuestStatus( uint32 quest_id
)
18312 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
18314 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
18316 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
18317 m_lastDailyQuestTime
= time(NULL
); // last daily quest time
18318 m_DailyQuestChanged
= true;
18324 void Player::ResetDailyQuestStatus()
18326 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
18327 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
18329 // DB data deleted in caller
18330 m_DailyQuestChanged
= false;
18331 m_lastDailyQuestTime
= 0;
18334 BattleGround
* Player::GetBattleGround() const
18336 if(GetBattleGroundId()==0)
18339 return sBattleGroundMgr
.GetBattleGround(GetBattleGroundId());
18342 bool Player::InArena() const
18344 BattleGround
*bg
= GetBattleGround();
18345 if(!bg
|| !bg
->isArena())
18351 bool Player::GetBGAccessByLevel(uint32 bgTypeId
) const
18353 // get a template bg instead of running one
18354 BattleGround
*bg
= sBattleGroundMgr
.GetBattleGroundTemplate(bgTypeId
);
18358 if(getLevel() < bg
->GetMinLevel() || getLevel() > bg
->GetMaxLevel())
18364 uint32
Player::GetMinLevelForBattleGroundQueueId(uint32 queue_id
)
18372 return 10*(queue_id
+1);
18375 uint32
Player::GetMaxLevelForBattleGroundQueueId(uint32 queue_id
)
18378 return 255; // hardcoded max level
18380 return 10*(queue_id
+2)-1;
18383 uint32
Player::GetBattleGroundQueueIdFromLevel() const
18385 uint32 level
= getLevel();
18388 else if (level
> 79)
18391 return level
/10 - 1; // 20..29 -> 1, 30-39 -> 2, ...
18393 assert(bgTypeId < MAX_BATTLEGROUND_TYPES);
18394 BattleGround *bg = sBattleGroundMgr.GetBattleGroundTemplate(bgTypeId);
18396 return (getLevel() - bg->GetMinLevel()) / 10;*/
18399 float Player::GetReputationPriceDiscount( Creature
const* pCreature
) const
18401 FactionTemplateEntry
const* vendor_faction
= pCreature
->getFactionTemplateEntry();
18402 if(!vendor_faction
)
18405 ReputationRank rank
= GetReputationRank(vendor_faction
->faction
);
18406 if(rank
<= REP_NEUTRAL
)
18409 return 1.0f
- 0.05f
* (rank
- REP_NEUTRAL
);
18412 bool Player::IsSpellFitByClassAndRace( uint32 spell_id
) const
18414 uint32 racemask
= getRaceMask();
18415 uint32 classmask
= getClassMask();
18417 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
18418 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
18422 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
18424 // skip wrong race skills
18425 if( _spell_idx
->second
->racemask
&& (_spell_idx
->second
->racemask
& racemask
) == 0)
18428 // skip wrong class skills
18429 if( _spell_idx
->second
->classmask
&& (_spell_idx
->second
->classmask
& classmask
) == 0)
18438 bool Player::HasQuestForGO(int32 GOId
)
18440 for( QuestStatusMap::iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
18442 QuestStatusData qs
=i
->second
;
18443 if (qs
.m_status
== QUEST_STATUS_INCOMPLETE
)
18445 Quest
const* qinfo
= objmgr
.GetQuestTemplate(i
->first
);
18449 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
18452 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
18454 if (qinfo
->ReqCreatureOrGOId
[j
]>=0) //skip non GO case
18457 if((-1)*GOId
== qinfo
->ReqCreatureOrGOId
[j
] && qs
.m_creatureOrGOcount
[j
] < qinfo
->ReqCreatureOrGOCount
[j
])
18465 void Player::UpdateForQuestsGO()
18467 if(m_clientGUIDs
.empty())
18471 WorldPacket packet
;
18472 for(ClientGUIDs::iterator itr
=m_clientGUIDs
.begin(); itr
!=m_clientGUIDs
.end(); ++itr
)
18474 if(IS_GAMEOBJECT_GUID(*itr
))
18476 GameObject
*obj
= HashMapHolder
<GameObject
>::Find(*itr
);
18478 obj
->BuildValuesUpdateBlockForPlayer(&udata
,this);
18481 udata
.BuildPacket(&packet
);
18482 GetSession()->SendPacket(&packet
);
18485 void Player::SummonIfPossible(bool agree
)
18489 m_summon_expire
= 0;
18493 // expire and auto declined
18494 if(m_summon_expire
< time(NULL
))
18497 // stop taxi flight at summon
18500 GetMotionMaster()->MovementExpired();
18501 m_taxi
.ClearTaxiDestinations();
18504 // drop flag at summon
18505 if(BattleGround
*bg
= GetBattleGround())
18506 bg
->EventPlayerDroppedFlag(this);
18508 m_summon_expire
= 0;
18510 TeleportTo(m_summon_mapid
, m_summon_x
, m_summon_y
, m_summon_z
,GetOrientation());
18513 void Player::RemoveItemDurations( Item
*item
)
18515 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); ++itr
)
18519 m_itemDuration
.erase(itr
);
18525 void Player::AddItemDurations( Item
*item
)
18527 if(item
->GetUInt32Value(ITEM_FIELD_DURATION
))
18529 m_itemDuration
.push_back(item
);
18530 item
->SendTimeUpdate(this);
18534 void Player::AutoUnequipOffhandIfNeed()
18536 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
18540 // need unequip for 2h-weapon without TitanGrip
18541 if (!IsTwoHandUsed())
18544 ItemPosCountVec off_dest
;
18545 uint8 off_msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false );
18546 if( off_msg
== EQUIP_ERR_OK
)
18548 RemoveItem(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
, true);
18549 StoreItem( off_dest
, offItem
, true );
18553 sLog
.outError("Player::EquipItem: Can's store offhand item at 2hand item equip for player (GUID: %u).",GetGUIDLow());
18557 bool Player::HasItemFitToSpellReqirements(SpellEntry
const* spellInfo
, Item
const* ignoreItem
)
18559 if(spellInfo
->EquippedItemClass
< 0)
18562 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18563 // for optimize check 2 used cases only
18564 switch(spellInfo
->EquippedItemClass
)
18566 case ITEM_CLASS_WEAPON
:
18568 for(int i
= EQUIPMENT_SLOT_MAINHAND
; i
< EQUIPMENT_SLOT_TABARD
; ++i
)
18569 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
18570 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18574 case ITEM_CLASS_ARMOR
:
18576 // tabard not have dependent spells
18577 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_MAINHAND
; ++i
)
18578 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
18579 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18582 // shields can be equipped to offhand slot
18583 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
))
18584 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18587 // ranged slot can have some armor subclasses
18588 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_RANGED
))
18589 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18595 sLog
.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo
->EquippedItemClass
);
18602 bool Player::CanNoReagentCast(SpellEntry
const* spellInfo
) const
18604 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18605 if (spellInfo
->AttributesEx5
& SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
&&
18606 HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PREPARATION
))
18609 // Check no reagent use mask
18610 uint64 noReagentMask_0_1
= GetUInt64Value(PLAYER_NO_REAGENT_COST_1
);
18611 uint32 noReagentMask_2
= GetUInt64Value(PLAYER_NO_REAGENT_COST_1
+2);
18612 if (spellInfo
->SpellFamilyFlags
& noReagentMask_0_1
||
18613 spellInfo
->SpellFamilyFlags2
& noReagentMask_2
)
18619 void Player::RemoveItemDependentAurasAndCasts( Item
* pItem
)
18621 AuraMap
& auras
= GetAuras();
18622 for(AuraMap::iterator itr
= auras
.begin(); itr
!= auras
.end(); )
18624 Aura
* aura
= itr
->second
;
18626 // skip passive (passive item dependent spells work in another way) and not self applied auras
18627 SpellEntry
const* spellInfo
= aura
->GetSpellProto();
18628 if(aura
->IsPassive() || aura
->GetCasterGUID()!=GetGUID())
18634 // skip if not item dependent or have alternative item
18635 if(HasItemFitToSpellReqirements(spellInfo
,pItem
))
18641 // no alt item, remove aura, restart check
18642 RemoveAurasDueToSpell(aura
->GetId());
18643 itr
= auras
.begin();
18646 // currently casted spells can be dependent from item
18647 for (uint32 i
= 0; i
< CURRENT_MAX_SPELL
; i
++)
18649 if( m_currentSpells
[i
] && m_currentSpells
[i
]->getState()!=SPELL_STATE_DELAYED
&&
18650 !HasItemFitToSpellReqirements(m_currentSpells
[i
]->m_spellInfo
,pItem
) )
18655 uint32
Player::GetResurrectionSpellId()
18657 // search priceless resurrection possibilities
18659 uint32 spell_id
= 0;
18660 AuraList
const& dummyAuras
= GetAurasByType(SPELL_AURA_DUMMY
);
18661 for(AuraList::const_iterator itr
= dummyAuras
.begin(); itr
!= dummyAuras
.end(); ++itr
)
18663 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18664 if( prio
< 2 && (*itr
)->GetSpellProto()->SpellVisual
[0] == 99 && (*itr
)->GetSpellProto()->SpellIconID
== 92 )
18666 switch((*itr
)->GetId())
18668 case 20707: spell_id
= 3026; break; // rank 1
18669 case 20762: spell_id
= 20758; break; // rank 2
18670 case 20763: spell_id
= 20759; break; // rank 3
18671 case 20764: spell_id
= 20760; break; // rank 4
18672 case 20765: spell_id
= 20761; break; // rank 5
18673 case 27239: spell_id
= 27240; break; // rank 6
18675 sLog
.outError("Unhandled spell %%u: S.Resurrection",(*itr
)->GetId());
18681 // Twisting Nether // prio: 2 (max)
18682 else if((*itr
)->GetId()==23701 && roll_chance_i(10))
18689 // Reincarnation (passive spell) // prio: 1
18690 if(prio
< 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18696 // Used in triggers for check "Only to targets that grant experience or honor" req
18697 bool Player::isHonorOrXPTarget(Unit
* pVictim
)
18699 uint32 v_level
= pVictim
->getLevel();
18700 uint32 k_grey
= MaNGOS::XP::GetGrayLevel(getLevel());
18702 // Victim level less gray level
18703 if(v_level
<=k_grey
)
18706 if(pVictim
->GetTypeId() == TYPEID_UNIT
)
18708 if (((Creature
*)pVictim
)->isTotem() ||
18709 ((Creature
*)pVictim
)->isPet() ||
18710 ((Creature
*)pVictim
)->GetCreatureInfo()->flags_extra
& CREATURE_FLAG_EXTRA_NO_XP_AT_KILL
)
18716 bool Player::RewardPlayerAndGroupAtKill(Unit
* pVictim
)
18718 bool PvP
= pVictim
->isCharmedOwnedByPlayerOrPlayer();
18720 // prepare data for near group iteration (PvP and !PvP cases)
18722 bool honored_kill
= false;
18724 if(Group
*pGroup
= GetGroup())
18727 uint32 sum_level
= 0;
18728 Player
* member_with_max_level
= NULL
;
18729 Player
* not_gray_member_with_max_level
= NULL
;
18731 pGroup
->GetDataForXPAtKill(pVictim
,count
,sum_level
,member_with_max_level
,not_gray_member_with_max_level
);
18733 if(member_with_max_level
)
18735 /// not get Xp in PvP or no not gray players in group
18736 xp
= (PvP
|| !not_gray_member_with_max_level
) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level
, pVictim
);
18738 /// skip in check PvP case (for speed, not used)
18739 bool is_raid
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsRaid() && pGroup
->isRaidGroup();
18740 bool is_dungeon
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsDungeon();
18741 float group_rate
= MaNGOS::XP::xp_in_group_rate(count
,is_raid
);
18743 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
18745 Player
* pGroupGuy
= itr
->getSource();
18749 if(!pGroupGuy
->IsAtGroupRewardDistance(pVictim
))
18750 continue; // member (alive or dead) or his corpse at req. distance
18752 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18753 if(pGroupGuy
->isAlive() && pGroupGuy
->RewardHonor(pVictim
,count
) && pGroupGuy
==this)
18754 honored_kill
= true;
18756 // xp and reputation only in !PvP case
18759 float rate
= group_rate
* float(pGroupGuy
->getLevel()) / sum_level
;
18761 // if is in dungeon then all receive full reputation at kill
18762 // rewarded any alive/dead/near_corpse group member
18763 pGroupGuy
->RewardReputation(pVictim
,is_dungeon
? 1.0f
: rate
);
18765 // XP updated only for alive group member
18766 if(pGroupGuy
->isAlive() && not_gray_member_with_max_level
&&
18767 pGroupGuy
->getLevel() <= not_gray_member_with_max_level
->getLevel())
18769 uint32 itr_xp
= (member_with_max_level
== not_gray_member_with_max_level
) ? uint32(xp
*rate
) : uint32((xp
*rate
/2)+1);
18771 pGroupGuy
->GiveXP(itr_xp
, pVictim
);
18772 if(Pet
* pet
= pGroupGuy
->GetPet())
18773 pet
->GivePetXP(itr_xp
/2);
18776 // quest objectives updated only for alive group member or dead but with not released body
18777 if(pGroupGuy
->isAlive()|| !pGroupGuy
->GetCorpse())
18779 // normal creature (not pet/etc) can be only in !PvP case
18780 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
18781 pGroupGuy
->KilledMonster(pVictim
->GetEntry(), pVictim
->GetGUID());
18787 else // if (!pGroup)
18789 xp
= PvP
? 0 : MaNGOS::XP::Gain(this, pVictim
);
18791 // honor can be in PvP and !PvP (racial leader) cases
18792 if(RewardHonor(pVictim
,1))
18793 honored_kill
= true;
18795 // xp and reputation only in !PvP case
18798 RewardReputation(pVictim
,1);
18799 GiveXP(xp
, pVictim
);
18801 if(Pet
* pet
= GetPet())
18802 pet
->GivePetXP(xp
);
18804 // normal creature (not pet/etc) can be only in !PvP case
18805 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
18806 KilledMonster(pVictim
->GetEntry(),pVictim
->GetGUID());
18809 return xp
|| honored_kill
;
18812 bool Player::IsAtGroupRewardDistance(WorldObject
const* pRewardSource
) const
18814 if(pRewardSource
->GetDistance(this) <= sWorld
.getConfig(CONFIG_GROUP_XP_DISTANCE
))
18820 Corpse
* corpse
= GetCorpse();
18824 return pRewardSource
->GetDistance(corpse
) <= sWorld
.getConfig(CONFIG_GROUP_XP_DISTANCE
);
18827 uint32
Player::GetBaseWeaponSkillValue (WeaponAttackType attType
) const
18829 Item
* item
= GetWeaponForAttack(attType
,true);
18831 // unarmed only with base attack
18832 if(attType
!= BASE_ATTACK
&& !item
)
18835 // weapon skill or (unarmed for base attack)
18836 uint32 skill
= item
? item
->GetSkill() : SKILL_UNARMED
;
18837 return GetBaseSkillValue(skill
);
18840 void Player::ResurectUsingRequestData()
18842 /// Teleport before resurrecting, otherwise the player might get attacked from creatures near his corpse
18843 TeleportTo(m_resurrectMap
, m_resurrectX
, m_resurrectY
, m_resurrectZ
, GetOrientation());
18845 ResurrectPlayer(0.0f
,false);
18847 if(GetMaxHealth() > m_resurrectHealth
)
18848 SetHealth( m_resurrectHealth
);
18850 SetHealth( GetMaxHealth() );
18852 if(GetMaxPower(POWER_MANA
) > m_resurrectMana
)
18853 SetPower(POWER_MANA
, m_resurrectMana
);
18855 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
) );
18857 SetPower(POWER_RAGE
, 0 );
18859 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
) );
18861 SpawnCorpseBones();
18864 void Player::SetClientControl(Unit
* target
, uint8 allowMove
)
18866 WorldPacket
data(SMSG_CLIENT_CONTROL_UPDATE
, target
->GetPackGUID().size()+1);
18867 data
.append(target
->GetPackGUID());
18868 data
<< uint8(allowMove
);
18869 GetSession()->SendPacket(&data
);
18872 void Player::UpdateZoneDependentAuras( uint32 newZone
)
18874 // remove new continent flight forms
18875 uint32 v_map
= GetVirtualMapForMapAndZone(GetMapId(), newZone
);
18876 if( !isGameMaster() && v_map
!= 530 && v_map
!= 571)
18878 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
);
18879 RemoveSpellsCausingAura(SPELL_AURA_FLY
);
18882 // Some spells applied at enter into zone (with subzones)
18884 // NOTE: these are removed by RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
18885 if ( newZone
== 2367 ) // Old Hillsbrad Foothills
18887 uint32 spellid
= 0;
18889 if( GetTeam() == HORDE
)
18890 spellid
= getGender() == GENDER_FEMALE
? 35481 : 35480;
18891 // and some alliance races
18892 else if( getRace() == RACE_NIGHTELF
|| getRace() == RACE_DRAENEI
)
18893 spellid
= getGender() == GENDER_FEMALE
? 35483 : 35482;
18895 if(spellid
&& !HasAura(spellid
,0) )
18896 CastSpell(this,spellid
,true);
18900 void Player::UpdateAreaDependentAuras( uint32 newArea
)
18902 // remove auras from spells with area limitations
18903 for(AuraMap::iterator iter
= m_Auras
.begin(); iter
!= m_Auras
.end();)
18905 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18906 if(GetSpellAllowedInLocationError(iter
->second
->GetSpellProto(),GetMapId(),m_zoneUpdateId
,newArea
)!=0)
18912 // some auras applied at subzone enter
18915 // Dragonmaw Illusion
18916 case 3759: // Netherwing Ledge
18917 case 3939: // Dragonmaw Fortress
18918 case 3966: // Dragonmaw Base Camp
18919 if( GetDummyAura(40214) )
18921 if( !HasAura(40216,0) )
18922 CastSpell(this,40216,true);
18923 if( !HasAura(42016,0) )
18924 CastSpell(this,42016,true);
18927 // Dominion Over Acherus
18928 case 4281: // Acherus: The Ebon Hold
18929 case 4342: // Acherus: The Ebon Hold
18930 if( HasSpell(51721) )
18931 if( !HasAura(51721,0) )
18932 CastSpell(this,51721,true);
18937 uint32
Player::GetCorpseReclaimDelay(bool pvp
) const
18939 if( pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18940 !pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18942 return copseReclaimDelay
[0];
18945 time_t now
= time(NULL
);
18946 // 0..2 full period
18947 uint32 count
= (now
< m_deathExpireTime
) ? (m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
: 0;
18948 return copseReclaimDelay
[count
];
18951 void Player::UpdateCorpseReclaimDelay()
18953 bool pvp
= m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
;
18955 if( pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18956 !pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18959 time_t now
= time(NULL
);
18960 if(now
< m_deathExpireTime
)
18962 // full and partly periods 1..3
18963 uint32 count
= (m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
+1;
18964 if(count
< MAX_DEATH_COUNT
)
18965 m_deathExpireTime
= now
+(count
+1)*DEATH_EXPIRE_STEP
;
18967 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
;
18970 m_deathExpireTime
= now
+DEATH_EXPIRE_STEP
;
18973 void Player::SendCorpseReclaimDelay(bool load
)
18975 Corpse
* corpse
= GetCorpse();
18982 if(corpse
->GetGhostTime() > m_deathExpireTime
)
18985 bool pvp
= corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
;
18988 if( pvp
&& sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18989 !pvp
&& sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18991 count
= (m_deathExpireTime
-corpse
->GetGhostTime())/DEATH_EXPIRE_STEP
;
18992 if(count
>=MAX_DEATH_COUNT
)
18993 count
= MAX_DEATH_COUNT
-1;
18998 time_t expected_time
= corpse
->GetGhostTime()+copseReclaimDelay
[count
];
19000 time_t now
= time(NULL
);
19001 if(now
>= expected_time
)
19004 delay
= expected_time
-now
;
19007 delay
= GetCorpseReclaimDelay(corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
);
19009 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
19010 WorldPacket
data(SMSG_CORPSE_RECLAIM_DELAY
, 4);
19011 data
<< uint32(delay
*1000);
19012 GetSession()->SendPacket( &data
);
19015 Player
* Player::GetNextRandomRaidMember(float radius
)
19017 Group
*pGroup
= GetGroup();
19021 std::vector
<Player
*> nearMembers
;
19022 nearMembers
.reserve(pGroup
->GetMembersCount());
19024 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
19026 Player
* Target
= itr
->getSource();
19028 // IsHostileTo check duel and controlled by enemy
19029 if( Target
&& Target
!= this && IsWithinDistInMap(Target
, radius
) &&
19030 !Target
->HasInvisibilityAura() && !IsHostileTo(Target
) )
19031 nearMembers
.push_back(Target
);
19034 if (nearMembers
.empty())
19037 uint32 randTarget
= urand(0,nearMembers
.size()-1);
19038 return nearMembers
[randTarget
];
19041 PartyResult
Player::CanUninviteFromGroup() const
19043 const Group
* grp
= GetGroup();
19045 return PARTY_RESULT_YOU_NOT_IN_GROUP
;
19047 if(!grp
->IsLeader(GetGUID()) && !grp
->IsAssistant(GetGUID()))
19048 return PARTY_RESULT_YOU_NOT_LEADER
;
19050 if(InBattleGround())
19051 return PARTY_RESULT_INVITE_RESTRICTED
;
19053 return PARTY_RESULT_OK
;
19056 void Player::UpdateUnderwaterState( Map
* m
, float x
, float y
, float z
)
19058 float water_z
= m
->GetWaterLevel(x
,y
);
19059 float terrain_z
= m
->GetHeight(x
,y
,z
, false); // use .map base surface height
19060 uint8 flag1
= m
->GetTerrainType(x
,y
);
19062 //!Underwater check, not in water if underground or above water level - take UC royal quater for example
19063 if (terrain_z
<= INVALID_HEIGHT
|| z
< (terrain_z
-2) || z
> (water_z
- 2) )
19064 m_isunderwater
&= ~UNDERWATER_INWATER
;
19065 else if ((z
< (water_z
- 2)) && (flag1
& 0x01))
19066 m_isunderwater
|= UNDERWATER_INWATER
;
19068 //!in lava check, anywhere under lava level
19069 if ((terrain_z
<= INVALID_HEIGHT
|| z
< (terrain_z
- 0)) && (flag1
== 0x00) && IsInWater())
19070 m_isunderwater
|= UNDERWATER_INLAVA
;
19072 m_isunderwater
&= ~UNDERWATER_INLAVA
;
19075 void Player::SetCanParry( bool value
)
19077 if(m_canParry
==value
)
19080 m_canParry
= value
;
19081 UpdateParryPercentage();
19084 void Player::SetCanBlock( bool value
)
19086 if(m_canBlock
==value
)
19089 m_canBlock
= value
;
19090 UpdateBlockPercentage();
19093 bool ItemPosCount::isContainedIn(ItemPosCountVec
const& vec
) const
19095 for(ItemPosCountVec::const_iterator itr
= vec
.begin(); itr
!= vec
.end();++itr
)
19096 if(itr
->pos
== pos
)
19102 bool Player::isAllowUseBattleGroundObject()
19104 return ( //InBattleGround() && // in battleground - not need, check in other cases
19105 !IsMounted() && // not mounted
19106 !HasStealthAura() && // not stealthed
19107 !HasInvisibilityAura() && // not invisible
19108 !HasAura(SPELL_RECENTLY_DROPPED_FLAG
, 0) && // can't pickup
19109 isAlive() // live player
19113 uint32
Player::GetBarberShopCost(uint8 newhairstyle
, uint8 newhaircolor
, uint8 newfacialhair
)
19115 uint32 level
= getLevel();
19117 if(level
> GT_MAX_LEVEL
)
19118 level
= GT_MAX_LEVEL
; // max level in this dbc
19120 uint8 hairstyle
= GetByteValue(PLAYER_BYTES
, 2);
19121 uint8 haircolor
= GetByteValue(PLAYER_BYTES
, 3);
19122 uint8 facialhair
= GetByteValue(PLAYER_BYTES_2
, 0);
19124 if((hairstyle
== newhairstyle
) && (haircolor
== newhaircolor
) && (facialhair
== newfacialhair
))
19127 GtBarberShopCostBaseEntry
const *bsc
= sGtBarberShopCostBaseStore
.LookupEntry(level
- 1);
19129 if(!bsc
) // shouldn't happen
19134 if(hairstyle
!= newhairstyle
)
19135 cost
+= bsc
->cost
; // full price
19137 if((haircolor
!= newhaircolor
) && (hairstyle
== newhairstyle
))
19138 cost
+= bsc
->cost
* 0.5f
; // +1/2 of price
19140 if(facialhair
!= newfacialhair
)
19141 cost
+= bsc
->cost
* 0.75f
; // +3/4 of price
19143 return uint32(cost
);
19146 void Player::InitGlyphsForLevel()
19148 for(uint32 i
= 0; i
< sGlyphSlotStore
.GetNumRows(); ++i
)
19149 if(GlyphSlotEntry
const * gs
= sGlyphSlotStore
.LookupEntry(i
))
19151 SetGlyphSlot(gs
->Order
- 1, gs
->Id
);
19153 uint32 level
= getLevel();
19156 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19158 value
|= (0x01 | 0x02);
19168 SetUInt32Value(PLAYER_GLYPHS_ENABLED
, value
);
19171 void Player::EnterVehicle(Vehicle
*vehicle
)
19173 VehicleEntry
const *ve
= sVehicleStore
.LookupEntry(vehicle
->GetVehicleId());
19177 VehicleSeatEntry
const *veSeat
= sVehicleSeatStore
.LookupEntry(ve
->m_seatID
[0]);
19181 vehicle
->SetCharmerGUID(GetGUID());
19182 vehicle
->RemoveFlag(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_SPELLCLICK
);
19183 vehicle
->SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_UNK_24
);
19184 vehicle
->setFaction(getFaction());
19186 SetCharm(vehicle
); // charm
19187 SetFarSightGUID(vehicle
->GetGUID()); // set view
19189 SetClientControl(vehicle
, 1); // redirect controls to vehicle
19191 WorldPacket
data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA
, 0);
19192 GetSession()->SendPacket(&data
);
19194 data
.Initialize(MSG_MOVE_TELEPORT_ACK
, 30);
19195 data
.append(GetPackGUID());
19196 data
<< uint32(0); // counter?
19197 data
<< uint32(MOVEMENTFLAG_ONTRANSPORT
); // transport
19198 data
<< uint16(0); // special flags
19199 data
<< uint32(getMSTime()); // time
19200 data
<< vehicle
->GetPositionX(); // x
19201 data
<< vehicle
->GetPositionY(); // y
19202 data
<< vehicle
->GetPositionZ(); // z
19203 data
<< vehicle
->GetOrientation(); // o
19204 // transport part, TODO: load/calculate seat offsets
19205 data
<< uint64(vehicle
->GetGUID()); // transport guid
19206 data
<< float(veSeat
->m_attachmentOffsetX
); // transport offsetX
19207 data
<< float(veSeat
->m_attachmentOffsetY
); // transport offsetY
19208 data
<< float(veSeat
->m_attachmentOffsetZ
); // transport offsetZ
19209 data
<< float(0); // transport orientation
19210 data
<< uint32(getMSTime()); // transport time
19211 data
<< uint8(0); // seat
19212 // end of transport part
19213 data
<< uint32(0); // fall time
19214 GetSession()->SendPacket(&data
);
19216 data
.Initialize(SMSG_PET_SPELLS
, 8+4+4+4+4*10+1+1);
19217 data
<< uint64(vehicle
->GetGUID());
19218 data
<< uint32(0x00000000);
19219 data
<< uint32(0x00000000);
19220 data
<< uint32(0x00000101);
19222 for(uint32 i
= 0; i
< 10; ++i
)
19223 data
<< uint16(0) << uint8(0) << uint8(i
+8);
19227 GetSession()->SendPacket(&data
);
19230 void Player::ExitVehicle(Vehicle
*vehicle
)
19232 vehicle
->SetCharmerGUID(0);
19233 vehicle
->SetFlag(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_SPELLCLICK
);
19234 vehicle
->RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_UNK_24
);
19235 vehicle
->setFaction((GetTeam() == ALLIANCE
) ? vehicle
->GetCreatureInfo()->faction_A
: vehicle
->GetCreatureInfo()->faction_H
);
19238 SetFarSightGUID(0);
19240 SetClientControl(vehicle
, 0);
19242 WorldPacket
data(MSG_MOVE_TELEPORT_ACK
, 30);
19243 data
.append(GetPackGUID());
19244 data
<< uint32(0); // counter?
19245 data
<< uint32(MOVEMENTFLAG_FLY_UNK1
); // fly unk
19246 data
<< uint16(0x40); // special flags
19247 data
<< uint32(getMSTime()); // time
19248 data
<< vehicle
->GetPositionX(); // x
19249 data
<< vehicle
->GetPositionY(); // y
19250 data
<< vehicle
->GetPositionZ(); // z
19251 data
<< vehicle
->GetOrientation(); // o
19252 data
<< uint32(0); // fall time
19253 GetSession()->SendPacket(&data
);
19255 data
.Initialize(SMSG_PET_SPELLS
, 8+4);
19258 GetSession()->SendPacket(&data
);
19260 // only for flyable vehicles?
19261 CastSpell(this, 45472, true); // Parachute
19264 bool Player::HasTitle(uint32 bitIndex
)
19266 if (bitIndex
> 128)
19269 uint32 fieldIndexOffset
= bitIndex
/32;
19270 uint32 flag
= 1 << (bitIndex
%32);
19271 return HasFlag(PLAYER__FIELD_KNOWN_TITLES
+fieldIndexOffset
, flag
);
19274 void Player::SetTitle(CharTitlesEntry
const* title
)
19276 uint32 fieldIndexOffset
= title
->bit_index
/32;
19277 uint32 flag
= 1 << (title
->bit_index
%32);
19278 SetFlag(PLAYER__FIELD_KNOWN_TITLES
+fieldIndexOffset
, flag
);
19281 void Player::ConvertRune(uint8 index
, uint8 newType
)
19283 SetCurrentRune(index
, newType
);
19285 WorldPacket
data(SMSG_CONVERT_RUNE
, 2);
19286 data
<< uint8(index
);
19287 data
<< uint8(newType
);
19288 GetSession()->SendPacket(&data
);
19291 void Player::ResyncRunes(uint8 count
)
19293 WorldPacket
data(SMSG_RESYNC_RUNES
, count
* 2);
19294 for(uint32 i
= 0; i
< count
; ++i
)
19296 data
<< uint8(GetCurrentRune(i
)); // rune type
19297 data
<< uint8(255 - (GetRuneCooldown(i
) * 51)); // passed cooldown time (0-255)
19299 GetSession()->SendPacket(&data
);
19302 void Player::AddRunePower(uint8 index
)
19304 WorldPacket
data(SMSG_ADD_RUNE_POWER
, 4);
19305 data
<< uint32(1 << index
); // mask (0x00-0x3F probably)
19306 GetSession()->SendPacket(&data
);
19309 void Player::InitRunes()
19311 if(getClass() != CLASS_DEATH_KNIGHT
)
19314 m_runes
= new Runes
;
19316 m_runes
->runeState
= 0;
19318 for(uint32 i
= 0; i
< MAX_RUNES
; ++i
)
19320 SetBaseRune(i
, i
/ 2); // init base types
19321 SetCurrentRune(i
, i
/ 2); // init current types
19322 SetRuneCooldown(i
, 0); // reset cooldowns
19323 m_runes
->SetRuneState(i
);
19326 for(uint32 i
= 0; i
< NUM_RUNE_TYPES
; ++i
)
19327 SetFloatValue(PLAYER_RUNE_REGEN_1
+ i
, 0.1f
);
19330 void Player::AutoStoreLootItem(uint8 bag
, uint8 slot
, uint32 loot_id
, LootStore
const& store
)
19333 loot
.FillLoot (loot_id
,store
,this);
19334 if(loot
.items
.empty ())
19336 LootItem
const* lootItem
= &loot
.items
[0];
19338 ItemPosCountVec dest
;
19339 uint8 msg
= CanStoreNewItem (bag
,slot
,dest
,lootItem
->itemid
,lootItem
->count
);
19340 if(msg
!= EQUIP_ERR_OK
&& slot
!= NULL_SLOT
)
19341 msg
= CanStoreNewItem( bag
, NULL_SLOT
,dest
,lootItem
->itemid
,lootItem
->count
);
19342 if( msg
!= EQUIP_ERR_OK
&& bag
!= NULL_BAG
)
19343 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
,dest
,lootItem
->itemid
,lootItem
->count
);
19344 if(msg
!= EQUIP_ERR_OK
)
19347 StoreNewItem (dest
,lootItem
->itemid
,true,lootItem
->randomPropertyId
);
19350 uint32
Player::CalculateTalentsPoints() const
19352 uint32 base_talent
= getLevel() < 10 ? 0 : uint32((getLevel()-9)*sWorld
.getRate(RATE_TALENT
));
19354 if(getClass() != CLASS_DEATH_KNIGHT
)
19355 return base_talent
;
19357 uint32 talentPointsForLevel
=
19358 (getLevel() < 56 ? 0 : uint32((getLevel()-55)*sWorld
.getRate(RATE_TALENT
)))
19359 + m_questRewardTalentCount
;
19361 if(talentPointsForLevel
> base_talent
)
19362 talentPointsForLevel
= base_talent
;
19364 return talentPointsForLevel
;