2 * Copyright (C) 2005-2008 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"
64 #define ZONE_UPDATE_INTERVAL 1000
66 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
67 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
68 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
70 #define SKILL_VALUE(x) PAIR32_LOPART(x)
71 #define SKILL_MAX(x) PAIR32_HIPART(x)
72 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
74 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
75 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
76 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
80 CHARACTER_FLAG_NONE
= 0x00000000,
81 CHARACTER_FLAG_UNK1
= 0x00000001,
82 CHARACTER_FLAG_UNK2
= 0x00000002,
83 CHARACTER_LOCKED_FOR_TRANSFER
= 0x00000004,
84 CHARACTER_FLAG_UNK4
= 0x00000008,
85 CHARACTER_FLAG_UNK5
= 0x00000010,
86 CHARACTER_FLAG_UNK6
= 0x00000020,
87 CHARACTER_FLAG_UNK7
= 0x00000040,
88 CHARACTER_FLAG_UNK8
= 0x00000080,
89 CHARACTER_FLAG_UNK9
= 0x00000100,
90 CHARACTER_FLAG_UNK10
= 0x00000200,
91 CHARACTER_FLAG_HIDE_HELM
= 0x00000400,
92 CHARACTER_FLAG_HIDE_CLOAK
= 0x00000800,
93 CHARACTER_FLAG_UNK13
= 0x00001000,
94 CHARACTER_FLAG_GHOST
= 0x00002000,
95 CHARACTER_FLAG_RENAME
= 0x00004000,
96 CHARACTER_FLAG_UNK16
= 0x00008000,
97 CHARACTER_FLAG_UNK17
= 0x00010000,
98 CHARACTER_FLAG_UNK18
= 0x00020000,
99 CHARACTER_FLAG_UNK19
= 0x00040000,
100 CHARACTER_FLAG_UNK20
= 0x00080000,
101 CHARACTER_FLAG_UNK21
= 0x00100000,
102 CHARACTER_FLAG_UNK22
= 0x00200000,
103 CHARACTER_FLAG_UNK23
= 0x00400000,
104 CHARACTER_FLAG_UNK24
= 0x00800000,
105 CHARACTER_FLAG_LOCKED_BY_BILLING
= 0x01000000,
106 CHARACTER_FLAG_DECLINED
= 0x02000000,
107 CHARACTER_FLAG_UNK27
= 0x04000000,
108 CHARACTER_FLAG_UNK28
= 0x08000000,
109 CHARACTER_FLAG_UNK29
= 0x10000000,
110 CHARACTER_FLAG_UNK30
= 0x20000000,
111 CHARACTER_FLAG_UNK31
= 0x40000000,
112 CHARACTER_FLAG_UNK32
= 0x80000000
115 // corpse reclaim times
116 #define DEATH_EXPIRE_STEP (5*MINUTE)
117 #define MAX_DEATH_COUNT 3
119 static uint32 copseReclaimDelay
[MAX_DEATH_COUNT
] = { 30, 60, 120 };
121 //== PlayerTaxi ================================================
123 PlayerTaxi::PlayerTaxi()
126 memset(m_taximask
, 0, sizeof(m_taximask
));
129 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race
, uint32 level
)
131 // capital and taxi hub masks
134 case RACE_HUMAN
: SetTaximaskNode(2); break; // Human
135 case RACE_ORC
: SetTaximaskNode(23); break; // Orc
136 case RACE_DWARF
: SetTaximaskNode(6); break; // Dwarf
137 case RACE_NIGHTELF
: SetTaximaskNode(26);
138 SetTaximaskNode(27); break; // Night Elf
139 case RACE_UNDEAD_PLAYER
: SetTaximaskNode(11); break;// Undead
140 case RACE_TAUREN
: SetTaximaskNode(22); break; // Tauren
141 case RACE_GNOME
: SetTaximaskNode(6); break; // Gnome
142 case RACE_TROLL
: SetTaximaskNode(23); break; // Troll
143 case RACE_BLOODELF
: SetTaximaskNode(82); break; // Blood Elf
144 case RACE_DRAENEI
: SetTaximaskNode(94); break; // Draenei
146 // new continent starting masks (It will be accessible only at new map)
147 switch(Player::TeamForRace(race
))
149 case ALLIANCE
: SetTaximaskNode(100); break;
150 case HORDE
: SetTaximaskNode(99); break;
152 // level dependent taxi hubs
154 SetTaximaskNode(213); //Shattered Sun Staging Area
157 void PlayerTaxi::LoadTaxiMask(const char* data
)
159 Tokens tokens
= StrSplit(data
, " ");
162 Tokens::iterator iter
;
163 for (iter
= tokens
.begin(), index
= 0;
164 (index
< TaxiMaskSize
) && (iter
!= tokens
.end()); ++iter
, ++index
)
166 // load and set bits only for existed taxi nodes
167 m_taximask
[index
] = sTaxiNodesMask
[index
] & uint32(atol((*iter
).c_str()));
171 void PlayerTaxi::AppendTaximaskTo( ByteBuffer
& data
, bool all
)
175 for (uint8 i
=0; i
<TaxiMaskSize
; i
++)
176 data
<< sTaxiNodesMask
[i
]; // all existed nodes
180 for (uint8 i
=0; i
<TaxiMaskSize
; i
++)
181 data
<< uint32(m_taximask
[i
]); // known nodes
185 bool PlayerTaxi::LoadTaxiDestinationsFromString( std::string values
)
187 ClearTaxiDestinations();
189 Tokens tokens
= StrSplit(values
," ");
191 for(Tokens::iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
)
193 uint32 node
= uint32(atol(iter
->c_str()));
194 AddTaxiDestination(node
);
197 if(m_TaxiDestinations
.empty())
201 if(m_TaxiDestinations
.size() < 2)
204 for(size_t i
= 1; i
< m_TaxiDestinations
.size(); ++i
)
208 objmgr
.GetTaxiPath(m_TaxiDestinations
[i
-1],m_TaxiDestinations
[i
],path
,cost
);
216 std::string
PlayerTaxi::SaveTaxiDestinationsToString()
218 if(m_TaxiDestinations
.empty())
221 std::ostringstream ss
;
223 for(size_t i
=0; i
< m_TaxiDestinations
.size(); ++i
)
224 ss
<< m_TaxiDestinations
[i
] << " ";
229 uint32
PlayerTaxi::GetCurrentTaxiPath() const
231 if(m_TaxiDestinations
.size() < 2)
237 objmgr
.GetTaxiPath(m_TaxiDestinations
[0],m_TaxiDestinations
[1],path
,cost
);
242 //== Player ====================================================
244 const int32
Player::ReputationRank_Length
[MAX_REPUTATION_RANK
] = {36000, 3000, 3000, 3000, 6000, 12000, 21000, 1000};
246 UpdateMask
Player::updateVisualBits
;
248 Player::Player (WorldSession
*session
): Unit()
255 m_objectType
|= TYPEMASK_PLAYER
;
256 m_objectTypeId
= TYPEID_PLAYER
;
258 m_valuesCount
= PLAYER_END
;
265 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER
)
266 SetAcceptTicket(true);
268 // players always accept
269 if(GetSession()->GetSecurity() == SEC_PLAYER
)
270 SetAcceptWhispers(true);
278 m_usedTalentCount
= 0;
281 m_weaponChangeTimer
= 0;
284 m_zoneUpdateTimer
= 0;
288 m_nextSave
= sWorld
.getConfig(CONFIG_INTERVAL_SAVE
);
290 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
291 // this must help in case next save after mass player load after server startup
292 m_nextSave
= urand(m_nextSave
/2,m_nextSave
*3/2);
294 clearResurrectRequestData();
296 m_SpellModRemoveCount
= 0;
298 memset(m_items
, 0, sizeof(Item
*)*PLAYER_SLOTS_COUNT
);
302 // group is initialized in the reference constructor
303 SetGroupInvite(NULL
);
304 m_groupUpdateMask
= 0;
305 m_auraUpdateMask
= 0;
309 m_GuildIdInvited
= 0;
310 m_ArenaTeamIdInvited
= 0;
312 m_atLoginFlags
= AT_LOGIN_NONE
;
321 PlayerTalkClass
= new PlayerMenu( GetSession() );
322 m_currentBuybackSlot
= BUYBACK_SLOT_START
;
324 for ( int aX
= 0 ; aX
< 8 ; aX
++ )
325 m_Tutorials
[ aX
] = 0x00;
326 m_TutorialsChanged
= false;
328 m_DailyQuestChanged
= false;
329 m_lastDailyQuestTime
= 0;
332 m_weaponChangeTimer
= 0;
340 m_deathExpireTime
= 0;
344 m_DetectInvTimer
= 1000;
346 m_bgBattleGroundID
= 0;
347 for (int j
=0; j
< PLAYER_MAX_BATTLEGROUND_QUEUES
; j
++)
349 m_bgBattleGroundQueueID
[j
].bgType
= 0;
350 m_bgBattleGroundQueueID
[j
].invited
= false;
354 m_logintime
= time(NULL
);
355 m_Last_tick
= m_logintime
;
356 m_WeaponProficiency
= 0;
357 m_ArmorProficiency
= 0;
360 m_canDualWield
= false;
363 m_temporaryUnsummonedPetNumber
= 0;
364 //cache for UNIT_CREATED_BY_SPELL to allow
365 //returning reagests for temporarily removed pets
366 //when dying/logging out
369 ////////////////////Rest System/////////////////////
376 rest_type
=REST_TYPE_NO
;
377 ////////////////////Rest System/////////////////////
379 m_mailsLoaded
= false;
380 m_mailsUpdated
= false;
382 m_nextMailDelivereTime
= 0;
384 m_resetTalentsCost
= 0;
385 m_resetTalentsTime
= 0;
386 m_itemUpdateQueueBlocked
= false;
388 for (int i
= 0; i
< MAX_MOVE_TYPE
; ++i
)
389 m_forced_speed_changes
[i
] = 0;
393 /////////////////// Instance System /////////////////////
396 m_InstanceValid
= true;
397 m_dungeonDifficulty
= DIFFICULTY_NORMAL
;
399 for (int i
= 0; i
< BASEMOD_END
; i
++)
401 m_auraBaseMod
[i
][FLAT_MOD
] = 0.0f
;
402 m_auraBaseMod
[i
][PCT_MOD
] = 1.0f
;
406 m_lastHonorUpdateTime
= time(NULL
);
415 //Default movement to run mode
416 m_unit_movement_flags
= 0;
419 m_bgAfkReportedTimer
= 0;
420 m_contestedPvPTimer
= 0;
422 m_declinedname
= NULL
;
427 CleanupsBeforeDelete();
429 // it must be unloaded already in PlayerLogout and accessed only for loggined player
432 // Note: buy back item already deleted from DB when player was saved
433 for(int i
= 0; i
< PLAYER_SLOTS_COUNT
; ++i
)
440 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
443 //all mailed items should be deleted, also all mail should be deallocated
444 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
447 for (ItemMap::iterator iter
= mMitems
.begin(); iter
!= mMitems
.end(); ++iter
)
448 delete iter
->second
; //if item is duplicated... then server may crash ... but that item should be deallocated
450 delete PlayerTalkClass
;
454 m_transport
->RemovePassenger(this);
457 for(size_t x
= 0; x
< ItemSetEff
.size(); x
++)
459 delete ItemSetEff
[x
];
461 // clean up player-instance binds, may unload some instance saves
462 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
463 for(BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
464 itr
->second
.save
->RemovePlayer(this);
466 delete m_declinedname
;
469 void Player::CleanupsBeforeDelete()
471 if(m_uint32Values
) // only for fully created Object
474 DuelComplete(DUEL_INTERUPTED
);
476 Unit::CleanupsBeforeDelete();
479 bool Player::Create( uint32 guidlow
, std::string name
, uint8 race
, uint8 class_
, uint8 gender
, uint8 skin
, uint8 face
, uint8 hairStyle
, uint8 hairColor
, uint8 facialHair
, uint8 outfitId
)
481 Object::_Create(guidlow
, 0, HIGHGUID_PLAYER
);
485 PlayerInfo
const* info
= objmgr
.GetPlayerInfo(race
, class_
);
488 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
492 for (int i
= 0; i
< PLAYER_SLOTS_COUNT
; i
++)
495 //for(int j = BUYBACK_SLOT_START; j < BUYBACK_SLOT_END; j++)
497 // SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1+j*2,0);
498 // SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1+j,0);
499 // SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1+j,0);
505 SetMapId(info
->mapId
);
506 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
);
508 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(class_
);
511 sLog
.outError("Class %u not found in DBC (Wrong DBC files?)",class_
);
515 uint8 powertype
= cEntry
->powerType
;
523 unitfield
= 0x00000000;
526 unitfield
= 0x00110000;
529 sLog
.outError("Invalid default powertype %u for player (class %u)",powertype
,class_
);
533 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, DEFAULT_WORLD_OBJECT_SIZE
);
534 SetFloatValue(UNIT_FIELD_COMBATREACH
, 1.5f
);
539 SetDisplayId(info
->displayId_f
);
540 SetNativeDisplayId(info
->displayId_f
);
543 SetDisplayId(info
->displayId_m
);
544 SetNativeDisplayId(info
->displayId_m
);
547 sLog
.outError("Invalid gender %u for player",gender
);
552 setFactionForRace(m_race
);
554 SetUInt32Value(UNIT_FIELD_BYTES_0
, ( ( race
) | ( class_
<< 8 ) | ( gender
<< 16 ) | ( powertype
<< 24 ) ) );
555 SetUInt32Value(UNIT_FIELD_BYTES_1
, unitfield
);
556 SetByteValue(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_UNK3
| UNIT_BYTE2_FLAG_UNK5
);
557 SetUInt32Value(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
);
558 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
); // fix cast time showed in spell tooltip on client
560 //-1 is default value
561 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX
, uint32(-1));
563 SetUInt32Value(PLAYER_BYTES
, (skin
| (face
<< 8) | (hairStyle
<< 16) | (hairColor
<< 24)));
564 SetUInt32Value(PLAYER_BYTES_2
, (facialHair
| (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
565 SetByteValue(PLAYER_BYTES_3
, 0, gender
);
567 SetUInt32Value( PLAYER_GUILDID
, 0 );
568 SetUInt32Value( PLAYER_GUILDRANK
, 0 );
569 SetUInt32Value( PLAYER_GUILD_TIMESTAMP
, 0 );
571 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES
, 0 ); // 0=disabled
572 SetUInt32Value( PLAYER_CHOSEN_TITLE
, 0 );
573 SetUInt32Value( PLAYER_FIELD_KILLS
, 0 );
574 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 0 );
575 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION
, 0 );
576 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0 );
578 // set starting level
579 SetUInt32Value( UNIT_FIELD_LEVEL
, sWorld
.getConfig(CONFIG_START_PLAYER_LEVEL
) );
582 m_Last_tick
= time(NULL
);
583 m_Played_time
[0] = 0;
584 m_Played_time
[1] = 0;
586 // base stats and related field values
588 InitTaxiNodesForLevel();
589 InitTalentForLevel();
590 InitPrimaryProffesions(); // to max set before any spell added
592 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
593 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
594 SetHealth(GetMaxHealth());
595 if (getPowerType()==POWER_MANA
)
597 UpdateMaxPower(POWER_MANA
); // Update max Mana (for add bonus from intelect)
598 SetPower(POWER_MANA
,GetMaxPower(POWER_MANA
));
601 learnDefaultSpells(true);
603 std::list
<uint16
>::const_iterator action_itr
[4];
604 for(int i
=0; i
<4; i
++)
605 action_itr
[i
] = info
->action
[i
].begin();
607 for (; action_itr
[0]!=info
->action
[0].end() && action_itr
[1]!=info
->action
[1].end();)
610 for(int i
=0; i
<4 ;i
++)
611 taction
[i
] = (*action_itr
[i
]);
613 addActionButton((uint8
)taction
[0], taction
[1], (uint8
)taction
[2], (uint8
)taction
[3]);
615 for(int i
=0; i
<4 ;i
++)
619 for (PlayerCreateInfoItems::const_iterator item_id_itr
= info
->item
.begin(); item_id_itr
!=info
->item
.end(); ++item_id_itr
++)
621 uint32 titem_id
= item_id_itr
->item_id
;
622 uint32 titem_amount
= item_id_itr
->item_amount
;
624 sLog
.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id
, titem_amount
);
628 uint8 msg
= CanEquipNewItem( NULL_SLOT
, eDest
, titem_id
, titem_amount
, false );
629 if( msg
== EQUIP_ERR_OK
)
631 EquipNewItem( eDest
, titem_id
, titem_amount
, true);
632 AutoUnequipOffhandIfNeed();
633 continue; // equipped, to next
637 ItemPosCountVec sDest
;
638 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
639 msg
= CanStoreNewItem( INVENTORY_SLOT_BAG_0
, NULL_SLOT
, sDest
, titem_id
, titem_amount
);
640 if( msg
== EQUIP_ERR_OK
)
642 StoreNewItem( sDest
, titem_id
, true, Item::GenerateItemRandomPropertyId(titem_id
) );
643 continue; // stored, to next
646 // item can't be added
647 sLog
.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id
,race
,class_
,msg
);
650 // bags and main-hand weapon must equipped at this moment
651 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
652 // or ammo not equipped in special bag
653 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
655 if(Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
658 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
659 uint8 msg
= CanEquipItem( NULL_SLOT
, eDest
, pItem
, false );
660 if( msg
== EQUIP_ERR_OK
)
662 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
663 EquipItem( eDest
, pItem
, true);
665 // move other items to more appropriate slots (ammo not equipped in special bag)
668 ItemPosCountVec sDest
;
669 msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, sDest
, pItem
, false );
670 if( msg
== EQUIP_ERR_OK
)
672 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
673 pItem
= StoreItem( sDest
, pItem
, true);
676 // if this is ammo then use it
677 uint8 msg
= CanUseAmmo( pItem
->GetProto()->ItemId
);
678 if( msg
== EQUIP_ERR_OK
)
679 SetAmmo( pItem
->GetProto()->ItemId
);
683 // all item positions resolved
688 void Player::StartMirrorTimer(MirrorTimerType Type
, uint32 MaxValue
)
690 uint32 BreathRegen
= (uint32
)-1;
692 WorldPacket
data(SMSG_START_MIRROR_TIMER
, (21));
693 data
<< (uint32
)Type
;
698 data
<< (uint32
)0; // spell id
699 GetSession()->SendPacket(&data
);
702 void Player::ModifyMirrorTimer(MirrorTimerType Type
, uint32 MaxValue
, uint32 CurrentValue
, uint32 Regen
)
704 if(Type
==BREATH_TIMER
)
705 m_breathTimer
= ((MaxValue
+ 1000) - CurrentValue
) / Regen
;
707 WorldPacket
data(SMSG_START_MIRROR_TIMER
, (21));
708 data
<< (uint32
)Type
;
709 data
<< CurrentValue
;
713 data
<< (uint32
)0; // spell id
714 GetSession()->SendPacket( &data
);
717 void Player::StopMirrorTimer(MirrorTimerType Type
)
719 if(Type
==BREATH_TIMER
)
722 WorldPacket
data(SMSG_STOP_MIRROR_TIMER
, 4);
723 data
<< (uint32
)Type
;
724 GetSession()->SendPacket( &data
);
727 void Player::EnvironmentalDamage(uint64 guid
, EnviromentalDamage type
, uint32 damage
)
729 WorldPacket
data(SMSG_ENVIRONMENTALDAMAGELOG
, (21));
730 data
<< (uint64
)guid
;
731 data
<< (uint8
)(type
!=DAMAGE_FALL_TO_VOID
? type
: DAMAGE_FALL
);
732 data
<< (uint32
)damage
;
735 //m_session->SendPacket(&data);
736 //Let other players see that you get damage
737 SendMessageToSet(&data
, true);
738 DealDamage(this, damage
, NULL
, SELF_DAMAGE
, SPELL_SCHOOL_MASK_NORMAL
, NULL
, false);
740 if(type
==DAMAGE_FALL
&& !isAlive()) // DealDamage not apply item durability loss at self damage
742 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
743 DurabilityLossAll(0.10f
,false);
744 // durability lost message
745 WorldPacket
data(SMSG_DURABILITY_DAMAGE_DEATH
, 0);
746 GetSession()->SendPacket(&data
);
750 void Player::HandleDrowning()
755 //if have water breath , then remove bar
756 if(waterbreath
|| isGameMaster() || !isAlive())
758 StopMirrorTimer(BREATH_TIMER
);
763 uint32 UnderWaterTime
= 1*MINUTE
*1000; // default leangthL 1 min
765 AuraList
const& mModWaterBreathing
= GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING
);
766 for(AuraList::const_iterator i
= mModWaterBreathing
.begin(); i
!= mModWaterBreathing
.end(); ++i
)
767 UnderWaterTime
= uint32(UnderWaterTime
* (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
);
769 if ((m_isunderwater
& 0x01) && !(m_isunderwater
& 0x80) && isAlive())
771 //single trigger timer
772 if (!(m_isunderwater
& 0x02))
774 m_isunderwater
|= 0x02;
775 m_breathTimer
= UnderWaterTime
+ 1000;
777 //single trigger "Breathbar"
778 if ( m_breathTimer
<= UnderWaterTime
&& !(m_isunderwater
& 0x04))
780 m_isunderwater
|= 0x04;
781 StartMirrorTimer(BREATH_TIMER
, UnderWaterTime
);
783 //continius trigger drowning "Damage"
784 if ((m_breathTimer
== 0) && (m_isunderwater
& 0x01))
786 //TODO: Check this formula
787 uint64 guid
= GetGUID();
788 uint32 damage
= GetMaxHealth() / 5 + urand(0, getLevel()-1);
790 EnvironmentalDamage(guid
, DAMAGE_DROWNING
,damage
);
791 m_breathTimer
= 2000;
794 //single trigger retract bar
795 else if (!(m_isunderwater
& 0x01) && !(m_isunderwater
& 0x08) && (m_isunderwater
& 0x02) && (m_breathTimer
> 0) && isAlive())
797 m_isunderwater
= 0x08;
799 uint32 BreathRegen
= 10;
800 ModifyMirrorTimer(BREATH_TIMER
, UnderWaterTime
, m_breathTimer
,BreathRegen
);
801 m_isunderwater
= 0x10;
804 else if ((m_breathTimer
< 50) && !(m_isunderwater
& 0x01) && (m_isunderwater
== 0x10))
806 StopMirrorTimer(BREATH_TIMER
);
811 void Player::HandleLava()
813 bool ValidArea
= false;
815 if ((m_isunderwater
& 0x80) && isAlive())
817 //Single trigger Set BreathTimer
818 if (!(m_isunderwater
& 0x80))
820 m_isunderwater
|= 0x04;
821 m_breathTimer
= 1000;
823 //Reset BreathTimer and still in the lava
826 uint64 guid
= GetGUID();
827 uint32 damage
= urand(600, 700); // TODO: Get more detailed information about lava damage
828 uint32 dmgZone
= GetZoneId(); // TODO: Find correct "lava dealing zone" flag in Area Table
830 // Deal lava damage only in lava zones.
846 if (dmgZone
/ 5 & 0x408)
850 // if is valid area and is not gamemaster then deal damage
851 if ( ValidArea
&& !isGameMaster() )
852 EnvironmentalDamage(guid
, DAMAGE_LAVA
, damage
);
854 m_breathTimer
= 1000;
858 //Death timer disabled and WaterFlags reset
859 else if (m_deathState
== DEAD
)
866 ///The player sobers by 256 every 10 seconds
867 void Player::HandleSobering()
871 uint32 drunk
= (m_drunk
<= 256) ? 0 : (m_drunk
- 256);
872 SetDrunkValue(drunk
);
875 DrunkenState
Player::GetDrunkenstateByValue(uint16 value
)
878 return DRUNKEN_SMASHED
;
880 return DRUNKEN_DRUNK
;
882 return DRUNKEN_TIPSY
;
883 return DRUNKEN_SOBER
;
886 void Player::SetDrunkValue(uint16 newDrunkenValue
, uint32 itemId
)
888 uint32 oldDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
890 m_drunk
= newDrunkenValue
;
891 SetUInt32Value(PLAYER_BYTES_3
,(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFF0001) | (m_drunk
& 0xFFFE));
893 uint32 newDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
895 // special drunk invisibility detection
896 if(newDrunkenState
>= DRUNKEN_DRUNK
)
897 m_detectInvisibilityMask
|= (1<<6);
899 m_detectInvisibilityMask
&= ~(1<<6);
901 if(newDrunkenState
== oldDrunkenState
)
904 WorldPacket
data(SMSG_CROSSED_INEBRIATION_THRESHOLD
, (8+4+4));
906 data
<< uint32(newDrunkenState
);
907 data
<< uint32(itemId
);
909 SendMessageToSet(&data
, true);
912 void Player::Update( uint32 p_time
)
918 if(m_nextMailDelivereTime
&& m_nextMailDelivereTime
<= time(NULL
))
923 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
924 m_nextMailDelivereTime
= 0;
927 Unit::Update( p_time
);
929 // update player only attacks
930 if(uint32 ranged_att
= getAttackTimer(RANGED_ATTACK
))
932 setAttackTimer(RANGED_ATTACK
, (p_time
>= ranged_att
? 0 : ranged_att
- p_time
) );
935 if(uint32 off_att
= getAttackTimer(OFF_ATTACK
))
937 setAttackTimer(OFF_ATTACK
, (p_time
>= off_att
? 0 : off_att
- p_time
) );
940 time_t now
= time (NULL
);
944 UpdateContestedPvP(p_time
);
948 CheckDuelDistance(now
);
950 UpdateAfkReport(now
);
952 CheckExploreSystem();
954 // Update items that have just a limited lifetime
956 UpdateItemDuration(uint32(now
- m_Last_tick
));
958 if (!m_timedquests
.empty())
960 std::set
<uint32
>::iterator iter
= m_timedquests
.begin();
961 while (iter
!= m_timedquests
.end())
963 QuestStatusData
& q_status
= mQuestStatus
[*iter
];
964 if( q_status
.m_timer
<= p_time
)
966 uint32 quest_id
= *iter
;
967 ++iter
; // current iter will be removed in FailTimedQuest
968 FailTimedQuest( quest_id
);
972 q_status
.m_timer
-= p_time
;
973 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
979 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING
))
981 Unit
*pVictim
= getVictim();
982 if( !IsNonMeleeSpellCasted(false) && pVictim
)
984 // default combat reach 10
985 // TODO add weapon,skill check
987 float pldistance
= ATTACK_DISTANCE
;
989 if (isAttackReady(BASE_ATTACK
))
991 if(!IsWithinDistInMap(pVictim
, pldistance
))
993 setAttackTimer(BASE_ATTACK
,100);
994 if(m_swingErrorMsg
!= 1) // send single time (client auto repeat)
996 SendAttackSwingNotInRange();
1000 //120 degrees of radiant range
1001 else if( !HasInArc( 2*M_PI
/3, pVictim
))
1003 setAttackTimer(BASE_ATTACK
,100);
1004 if(m_swingErrorMsg
!= 2) // send single time (client auto repeat)
1006 SendAttackSwingBadFacingAttack();
1007 m_swingErrorMsg
= 2;
1012 m_swingErrorMsg
= 0; // reset swing error state
1014 // prevent base and off attack in same time, delay attack at 0.2 sec
1015 if(haveOffhandWeapon())
1017 uint32 off_att
= getAttackTimer(OFF_ATTACK
);
1018 if(off_att
< ATTACK_DISPLAY_DELAY
)
1019 setAttackTimer(OFF_ATTACK
,ATTACK_DISPLAY_DELAY
);
1021 AttackerStateUpdate(pVictim
, BASE_ATTACK
);
1022 resetAttackTimer(BASE_ATTACK
);
1026 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK
))
1028 if(!IsWithinDistInMap(pVictim
, pldistance
))
1030 setAttackTimer(OFF_ATTACK
,100);
1032 else if( !HasInArc( 2*M_PI
/3, pVictim
))
1034 setAttackTimer(OFF_ATTACK
,100);
1038 // prevent base and off attack in same time, delay attack at 0.2 sec
1039 uint32 base_att
= getAttackTimer(BASE_ATTACK
);
1040 if(base_att
< ATTACK_DISPLAY_DELAY
)
1041 setAttackTimer(BASE_ATTACK
,ATTACK_DISPLAY_DELAY
);
1043 AttackerStateUpdate(pVictim
, OFF_ATTACK
);
1044 resetAttackTimer(OFF_ATTACK
);
1048 Unit
*owner
= pVictim
->GetOwner();
1049 Unit
*u
= owner
? owner
: pVictim
;
1050 if(u
->IsPvP() && (!duel
|| duel
->opponent
!= u
))
1053 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT
);
1058 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
))
1060 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1062 int time_inn
= time(NULL
)-GetTimeInnEnter();
1063 if (time_inn
>= 10) //freeze update
1065 float bubble
= 0.125*sWorld
.getRate(RATE_REST_INGAME
);
1066 //speed collect rest bonus (section/in hour)
1067 SetRestBonus( GetRestBonus()+ time_inn
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
1068 UpdateInnerTime(time(NULL
));
1073 if(m_regenTimer
> 0)
1075 if(p_time
>= m_regenTimer
)
1078 m_regenTimer
-= p_time
;
1081 if (m_weaponChangeTimer
> 0)
1083 if(p_time
>= m_weaponChangeTimer
)
1084 m_weaponChangeTimer
= 0;
1086 m_weaponChangeTimer
-= p_time
;
1089 if (m_zoneUpdateTimer
> 0)
1091 if(p_time
>= m_zoneUpdateTimer
)
1093 uint32 newzone
= GetZoneId();
1094 if( m_zoneUpdateId
!= newzone
)
1095 UpdateZone(newzone
); // also update area
1098 // use area updates as well
1099 // needed for free far all arenas for example
1100 uint32 newarea
= GetAreaId();
1101 if( m_areaUpdateId
!= newarea
)
1102 UpdateArea(newarea
);
1104 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
1108 m_zoneUpdateTimer
-= p_time
;
1116 if (m_deathState
== JUST_DIED
)
1123 if(p_time
>= m_nextSave
)
1125 // m_nextSave reseted in SaveToDB call
1127 sLog
.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1131 m_nextSave
-= p_time
;
1136 if(m_breathTimer
> 0)
1138 if(p_time
>= m_breathTimer
)
1141 m_breathTimer
-= p_time
;
1145 //Handle Water/drowning
1151 //Handle detect stealth players
1152 if (m_DetectInvTimer
> 0)
1154 if (p_time
>= m_DetectInvTimer
)
1156 m_DetectInvTimer
= 3000;
1157 HandleStealthedUnitsDetection();
1160 m_DetectInvTimer
-= p_time
;
1164 if (now
> m_Last_tick
)
1166 uint32 elapsed
= uint32(now
- m_Last_tick
);
1167 m_Played_time
[0] += elapsed
; // Total played time
1168 m_Played_time
[1] += elapsed
; // Level played time
1174 m_drunkTimer
+= p_time
;
1176 if (m_drunkTimer
> 10000)
1180 // not auto-free ghost from body in instances
1181 if(m_deathTimer
> 0 && !GetBaseMap()->Instanceable())
1183 if(p_time
>= m_deathTimer
)
1190 m_deathTimer
-= p_time
;
1193 UpdateEnchantTime(p_time
);
1194 UpdateHomebindTime(p_time
);
1197 SendUpdateToOutOfRangeGroupMembers();
1199 Pet
* pet
= GetPet();
1200 if(pet
&& !IsWithinDistInMap(pet
, OWNER_MAX_DISTANCE
))
1202 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
, true);
1207 void Player::setDeathState(DeathState s
)
1209 uint32 ressSpellId
= 0;
1211 bool cur
= isAlive();
1213 if(s
== JUST_DIED
&& cur
)
1215 // drunken state is cleared on death
1217 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1220 clearResurrectRequestData();
1222 // remove form before other mods to prevent incorrect stats calculation
1223 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId
);
1225 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1226 RemovePet(NULL
, PET_SAVE_NOT_IN_SLOT
, true);
1228 // remove uncontrolled pets
1232 // save value before aura remove in Unit::setDeathState
1233 ressSpellId
= GetUInt32Value(PLAYER_SELF_RES_SPELL
);
1237 ressSpellId
= GetResurrectionSpellId();
1239 Unit::setDeathState(s
);
1241 // restore resurrection spell id for player after aura remove
1242 if(s
== JUST_DIED
&& cur
&& ressSpellId
)
1243 SetUInt32Value(PLAYER_SELF_RES_SPELL
, ressSpellId
);
1245 if(isAlive() && !cur
)
1247 //clear aura case after resurrection by another way (spells will be applied before next death)
1248 SetUInt32Value(PLAYER_SELF_RES_SPELL
, 0);
1250 // restore default warrior stance
1251 if(getClass()== CLASS_WARRIOR
)
1252 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
1256 void Player::BuildEnumData( QueryResult
* result
, WorldPacket
* p_data
)
1258 *p_data
<< GetGUID();
1261 *p_data
<< getRace();
1262 uint8 pClass
= getClass();
1264 *p_data
<< getGender();
1266 uint32 bytes
= GetUInt32Value(PLAYER_BYTES
);
1267 *p_data
<< uint8(bytes
);
1268 *p_data
<< uint8(bytes
>> 8);
1269 *p_data
<< uint8(bytes
>> 16);
1270 *p_data
<< uint8(bytes
>> 24);
1272 bytes
= GetUInt32Value(PLAYER_BYTES_2
);
1273 *p_data
<< uint8(bytes
);
1275 *p_data
<< uint8(getLevel()); // player level
1276 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1277 uint32 zoneId
= MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY());
1280 *p_data
<< GetMapId();
1282 *p_data
<< GetPositionX();
1283 *p_data
<< GetPositionY();
1284 *p_data
<< GetPositionZ();
1286 *p_data
<< GetUInt32Value(PLAYER_GUILDID
); // guild id
1288 uint32 char_flags
= 0;
1289 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
1290 char_flags
|= CHARACTER_FLAG_HIDE_HELM
;
1291 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
1292 char_flags
|= CHARACTER_FLAG_HIDE_CLOAK
;
1293 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
))
1294 char_flags
|= CHARACTER_FLAG_GHOST
;
1295 if(HasAtLoginFlag(AT_LOGIN_RENAME
))
1296 char_flags
|= CHARACTER_FLAG_RENAME
;
1297 // always send the flag if declined names aren't used
1298 // to let the client select a default method of declining the name
1299 if(!sWorld
.getConfig(CONFIG_DECLINED_NAMES_USED
) || (result
&& result
->Fetch()[13].GetCppString() != ""))
1300 char_flags
|= CHARACTER_FLAG_DECLINED
;
1302 *p_data
<< (uint32
)char_flags
; // character flags
1304 *p_data
<< (uint8
)1; // unknown
1308 uint32 petDisplayId
= 0;
1309 uint32 petLevel
= 0;
1310 uint32 petFamily
= 0;
1312 // show pet at selection character in character list only for non-ghost character
1313 if(result
&& isAlive() && (pClass
== CLASS_WARLOCK
|| pClass
== CLASS_HUNTER
))
1315 Field
* fields
= result
->Fetch();
1317 uint32 entry
= fields
[10].GetUInt32();
1318 CreatureInfo
const* cInfo
= sCreatureStorage
.LookupEntry
<CreatureInfo
>(entry
);
1321 petDisplayId
= fields
[11].GetUInt32();
1322 petLevel
= fields
[12].GetUInt32();
1323 petFamily
= cInfo
->family
;
1327 *p_data
<< (uint32
)petDisplayId
;
1328 *p_data
<< (uint32
)petLevel
;
1329 *p_data
<< (uint32
)petFamily
;
1332 /*ItemPrototype const *items[EQUIPMENT_SLOT_END];
1333 for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
1336 QueryResult *result = CharacterDatabase.PQuery("SELECT slot,item_template FROM character_inventory WHERE guid = '%u' AND bag = 0",GetGUIDLow());
1341 Field *fields = result->Fetch();
1342 uint8 slot = fields[0].GetUInt8() & 255;
1343 uint32 item_id = fields[1].GetUInt32();
1344 if( slot >= EQUIPMENT_SLOT_END )
1347 items[slot] = objmgr.GetItemPrototype(item_id);
1350 sLog.outError( "Player::BuildEnumData: Player %s have unknown item (id: #%u) in inventory, skipped.", GetName(),item_id );
1353 } while (result->NextRow());
1357 for (uint8 slot
= 0; slot
< EQUIPMENT_SLOT_END
; slot
++)
1359 uint32 visualbase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
1360 uint32 item_id
= GetUInt32Value(visualbase
);
1361 const ItemPrototype
* proto
= objmgr
.GetItemPrototype(item_id
);
1362 SpellItemEnchantmentEntry
const *enchant
= NULL
;
1364 for(uint8 enchantSlot
= PERM_ENCHANTMENT_SLOT
; enchantSlot
<=TEMP_ENCHANTMENT_SLOT
; enchantSlot
++)
1366 uint32 enchantId
= GetUInt32Value(visualbase
+1+enchantSlot
);
1367 if(enchant
= sSpellItemEnchantmentStore
.LookupEntry(enchantId
))
1373 *p_data
<< (uint32
)proto
->DisplayInfoID
;
1374 *p_data
<< (uint8
)proto
->InventoryType
;
1375 *p_data
<< (uint32
)(enchant
?enchant
->aura_id
:0);
1379 *p_data
<< (uint32
)0;
1380 *p_data
<< (uint8
)0;
1381 *p_data
<< (uint32
)0; // enchant?
1384 *p_data
<< (uint32
)0; // first bag display id
1385 *p_data
<< (uint8
)0; // first bag inventory type
1386 *p_data
<< (uint32
)0; // enchant?
1389 bool Player::ToggleAFK()
1391 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1393 bool state
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1395 // afk player not allowed in battleground
1396 if(state
&& InBattleGround())
1397 LeaveBattleground();
1402 bool Player::ToggleDND()
1404 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1406 return HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1409 uint8
Player::chatTag() const
1426 bool Player::TeleportTo(uint32 mapid
, float x
, float y
, float z
, float orientation
, uint32 options
)
1428 if(!MapManager::IsValidMapCoord(mapid
, x
, y
, z
, orientation
))
1430 sLog
.outError("TeleportTo: invalid map %d or absent instance template.", mapid
);
1434 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1435 Pet
* pet
= GetPet();
1437 MapEntry
const* mEntry
= sMapStore
.LookupEntry(mapid
);
1439 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1440 if(!InBattleGround() && mEntry
->IsBattleGround() && !GetSession()->GetSecurity())
1443 // client without expansion support
1444 if(GetSession()->Expansion() < mEntry
->Expansion())
1446 sLog
.outDebug("Player %s using client without required expansion tried teleport to non accessable map %u", GetName(), mapid
);
1449 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1451 SendTransferAborted(mapid
, TRANSFER_ABORT_INSUF_EXPAN_LVL1
);
1453 return false; // normal client can't teleport to this map...
1457 sLog
.outDebug("Player %s will teleported to map %u", GetName(), mapid
);
1460 // if we were on a transport, leave
1461 if (!(options
& TELE_TO_NOT_LEAVE_TRANSPORT
) && m_transport
)
1463 m_transport
->RemovePassenger(this);
1465 m_movementInfo
.t_x
= 0.0f
;
1466 m_movementInfo
.t_y
= 0.0f
;
1467 m_movementInfo
.t_z
= 0.0f
;
1468 m_movementInfo
.t_o
= 0.0f
;
1469 m_movementInfo
.t_time
= 0;
1472 SetSemaphoreTeleport(true);
1474 // The player was ported to another map and looses the duel immediatly.
1475 // We have to perform this check before the teleport, otherwise the
1476 // ObjectAccessor won't find the flag.
1477 if (duel
&& this->GetMapId()!=mapid
)
1479 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER
));
1481 DuelComplete(DUEL_FLED
);
1484 // reset movement flags at teleport, because player will continue move with these flags after teleport
1485 SetUnitMovementFlags(0);
1487 if ((this->GetMapId() == mapid
) && (!m_transport
))
1489 // prepare zone change detect
1490 uint32 old_zone
= GetZoneId();
1493 if(!GetSession()->PlayerLogout())
1496 BuildTeleportAckMsg(&data
, x
, y
, z
, orientation
);
1497 GetSession()->SendPacket(&data
);
1498 SetPosition( x
, y
, z
, orientation
, true);
1501 // this will be used instead of the current location in SaveToDB
1502 m_teleport_dest
= WorldLocation(mapid
, x
, y
, z
, orientation
);
1504 //BuildHeartBeatMsg(&data);
1505 //SendMessageToSet(&data, true);
1506 if (!(options
& TELE_TO_NOT_UNSUMMON_PET
))
1508 //same map, only remove pet if out of range
1509 if(pet
&& !IsWithinDistInMap(pet
, OWNER_MAX_DISTANCE
))
1511 if(pet
->isControlled() && !pet
->isTemporarySummoned() )
1512 m_temporaryUnsummonedPetNumber
= pet
->GetCharmInfo()->GetPetNumber();
1514 m_temporaryUnsummonedPetNumber
= 0;
1516 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
);
1520 if(!(options
& TELE_TO_NOT_LEAVE_COMBAT
))
1523 if (!(options
& TELE_TO_NOT_UNSUMMON_PET
))
1526 if(pet
&& m_temporaryUnsummonedPetNumber
)
1528 Pet
* NewPet
= new Pet
;
1529 if(!NewPet
->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber
, true))
1532 m_temporaryUnsummonedPetNumber
= 0;
1536 if(!GetSession()->PlayerLogout())
1538 // don't reset teleport semaphore while logging out, otherwise m_teleport_dest won't be used in Player::SaveToDB
1539 SetSemaphoreTeleport(false);
1541 UpdateZone(GetZoneId());
1545 if(old_zone
!= GetZoneId())
1548 if(pvpInfo
.inHostileArea
)
1549 CastSpell(this, 2479, true);
1554 // far teleport to another map
1555 Map
* oldmap
= IsInWorld() ? MapManager::Instance().GetMap(GetMapId(), this) : NULL
;
1556 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1558 // Check enter rights before map getting to avoid creating instance copy for player
1559 // this check not dependent from map instance copy and same for all instance copies of selected map
1560 if (!MapManager::Instance().CanPlayerEnter(mapid
, this))
1562 SetSemaphoreTeleport(false);
1566 // If the map is not created, assume it is possible to enter it.
1567 // It will be created in the WorldPortAck.
1568 Map
*map
= MapManager::Instance().FindMap(mapid
);
1569 if (!map
|| map
->CanEnter(this))
1575 ResetContestedPvP();
1577 // remove player from battleground on far teleport (when changing maps)
1578 if(BattleGround
const* bg
= GetBattleGround())
1580 // Note: at battleground join battleground id set before teleport
1581 // and we already will found "current" battleground
1582 // just need check that this is targeted map or leave
1583 if(bg
->GetMapId() != mapid
)
1584 LeaveBattleground(false); // don't teleport to entry point
1587 // remove pet on map change
1590 //leaving map -> delete pet right away (doing this later will cause problems)
1591 if(pet
->isControlled() && !pet
->isTemporarySummoned())
1592 m_temporaryUnsummonedPetNumber
= pet
->GetCharmInfo()->GetPetNumber();
1594 m_temporaryUnsummonedPetNumber
= 0;
1596 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
);
1599 // remove all dyn objects
1600 RemoveAllDynObjects();
1602 // stop spellcasting
1603 // not attempt interrupt teleportation spell at caster teleport
1604 if(!(options
& TELE_TO_SPELL
))
1605 if(IsNonMeleeSpellCasted(true))
1606 InterruptNonMeleeSpells(true);
1608 if(!GetSession()->PlayerLogout())
1610 // send transfer packets
1611 WorldPacket
data(SMSG_TRANSFER_PENDING
, (4+4+4));
1612 data
<< uint32(mapid
);
1615 data
<< m_transport
->GetEntry() << GetMapId();
1617 GetSession()->SendPacket(&data
);
1619 data
.Initialize(SMSG_NEW_WORLD
, (20));
1622 data
<< (uint32
)mapid
<< m_movementInfo
.t_x
<< m_movementInfo
.t_y
<< m_movementInfo
.t_z
<< m_movementInfo
.t_o
;
1626 data
<< (uint32
)mapid
<< (float)x
<< (float)y
<< (float)z
<< (float)orientation
;
1628 GetSession()->SendPacket( &data
);
1629 SendSavedInstances();
1631 // remove from old map now
1632 if(oldmap
) oldmap
->Remove(this, false);
1635 // new final coordinates
1639 float final_o
= orientation
;
1643 final_x
+= m_movementInfo
.t_x
;
1644 final_y
+= m_movementInfo
.t_y
;
1645 final_z
+= m_movementInfo
.t_z
;
1646 final_o
+= m_movementInfo
.t_o
;
1649 m_teleport_dest
= WorldLocation(mapid
, final_x
, final_y
, final_z
, final_o
);
1650 // if the player is saved before worldportack (at logout for example)
1651 // this will be used instead of the current location in SaveToDB
1653 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP
);
1655 // move packet sent by client always after far teleport
1656 // SetPosition(final_x, final_y, final_z, final_o, true);
1659 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1667 void Player::AddToWorld()
1669 ///- Do not add/remove the player from the object storage
1670 ///- It will crash when updating the ObjectAccessor
1671 ///- The player should only be added when logging in
1674 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; i
++)
1677 m_items
[i
]->AddToWorld();
1681 void Player::RemoveFromWorld()
1686 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1688 UnsummonAllTotems();
1693 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; i
++)
1696 m_items
[i
]->RemoveFromWorld();
1699 ///- Do not add/remove the player from the object storage
1700 ///- It will crash when updating the ObjectAccessor
1701 ///- The player should only be removed when logging out
1702 Unit::RemoveFromWorld();
1705 void Player::RewardRage( uint32 damage
, uint32 weaponSpeedHitFactor
, bool attacker
)
1709 float rageconversion
= ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1713 addRage
= ((damage
/rageconversion
*7.5 + weaponSpeedHitFactor
)/2);
1715 // talent who gave more rage on attack
1716 addRage
*= 1.0f
+ GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT
) / 100.0f
;
1720 addRage
= damage
/rageconversion
*2.5;
1722 // Berserker Rage effect
1723 if(HasAura(18499,0))
1727 addRage
*= sWorld
.getRate(RATE_POWER_RAGE_INCOME
);
1729 ModifyPower(POWER_RAGE
, uint32(addRage
*10));
1732 void Player::RegenerateAll()
1734 if (m_regenTimer
!= 0)
1736 uint32 regenDelay
= 2000;
1738 // Not in combat or they have regeneration
1739 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) ||
1740 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
) || IsPolymorphed() )
1743 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN
))
1744 Regenerate(POWER_RAGE
);
1747 Regenerate( POWER_ENERGY
);
1749 Regenerate( POWER_MANA
);
1751 m_regenTimer
= regenDelay
;
1754 void Player::Regenerate(Powers power
)
1756 uint32 curValue
= GetPower(power
);
1757 uint32 maxValue
= GetMaxPower(power
);
1759 float addvalue
= 0.0f
;
1765 bool recentCast
= IsUnderLastManaUseEffect();
1766 float ManaIncreaseRate
= sWorld
.getRate(RATE_POWER_MANA
);
1769 // Mangos Updates Mana in intervals of 2s, which is correct
1770 addvalue
= GetFloatValue(PLAYER_FIELD_MOD_MANA_REGEN_INTERRUPT
) * ManaIncreaseRate
* 2.00f
;
1774 addvalue
= GetFloatValue(PLAYER_FIELD_MOD_MANA_REGEN
) * ManaIncreaseRate
* 2.00f
;
1777 case POWER_RAGE
: // Regenerate rage
1779 float RageDecreaseRate
= sWorld
.getRate(RATE_POWER_RAGE_LOSS
);
1780 addvalue
= 30 * RageDecreaseRate
; // 3 rage by tick
1782 case POWER_ENERGY
: // Regenerate energy (rogue)
1786 case POWER_HAPPINESS
:
1790 // Mana regen calculated in Player::UpdateManaRegen()
1791 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1792 if(power
!= POWER_MANA
)
1794 AuraList
const& ModPowerRegenPCTAuras
= GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT
);
1795 for(AuraList::const_iterator i
= ModPowerRegenPCTAuras
.begin(); i
!= ModPowerRegenPCTAuras
.end(); ++i
)
1796 if ((*i
)->GetModifier()->m_miscvalue
== power
)
1797 addvalue
*= ((*i
)->GetModifier()->m_amount
+ 100) / 100.0f
;
1800 if (power
!= POWER_RAGE
)
1802 curValue
+= uint32(addvalue
);
1803 if (curValue
> maxValue
)
1804 curValue
= maxValue
;
1808 if(curValue
<= uint32(addvalue
))
1811 curValue
-= uint32(addvalue
);
1813 SetPower(power
, curValue
);
1816 void Player::RegenerateHealth()
1818 uint32 curValue
= GetHealth();
1819 uint32 maxValue
= GetMaxHealth();
1821 if (curValue
>= maxValue
) return;
1823 float HealthIncreaseRate
= sWorld
.getRate(RATE_HEALTH
);
1825 float addvalue
= 0.0f
;
1828 if ( IsPolymorphed() )
1829 addvalue
= GetMaxHealth()/3;
1830 // normal regen case (maybe partly in combat case)
1831 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) )
1833 addvalue
= OCTRegenHPPerSpirit()* HealthIncreaseRate
;
1836 AuraList
const& mModHealthRegenPct
= GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT
);
1837 for(AuraList::const_iterator i
= mModHealthRegenPct
.begin(); i
!= mModHealthRegenPct
.end(); ++i
)
1838 addvalue
*= (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
;
1840 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
))
1841 addvalue
*= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) / 100.0f
;
1847 // always regeneration bonus (including combat)
1848 addvalue
+= GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
);
1853 ModifyHealth(int32(addvalue
));
1856 bool Player::CanInteractWithNPCs(bool alive
) const
1858 if(alive
&& !isAlive())
1866 bool Player::IsUnderWater() const
1868 return IsInWater() &&
1869 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
1872 void Player::SetInWater(bool apply
)
1874 if(m_isInWater
==apply
)
1877 //define player in water by opcodes
1878 //move player's guid into HateOfflineList of those mobs
1879 //which can't swim and move guid back into ThreatList when
1881 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
1882 m_isInWater
= apply
;
1884 // remove auras that need water/land
1885 RemoveAurasWithInterruptFlags(apply
? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER
: AURA_INTERRUPT_FLAG_NOT_UNDERWATER
);
1887 getHostilRefManager().updateThreatTables();
1890 void Player::SetGameMaster(bool on
)
1894 m_ExtraFlags
|= PLAYER_EXTRA_GM_ON
;
1896 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
1898 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_FFA_PVP
);
1899 ResetContestedPvP();
1901 getHostilRefManager().setOnlineOfflineState(false);
1906 m_ExtraFlags
&= ~ PLAYER_EXTRA_GM_ON
;
1907 setFactionForRace(getRace());
1908 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
1910 // restore FFA PvP Server state
1911 if(sWorld
.IsFFAPvPRealm())
1912 SetFlag(PLAYER_FLAGS
,PLAYER_FLAGS_FFA_PVP
);
1914 // restore FFA PvP area state, remove not allowed for GM mounts
1915 UpdateArea(m_areaUpdateId
);
1917 getHostilRefManager().setOnlineOfflineState(true);
1920 ObjectAccessor::UpdateVisibilityForPlayer(this);
1923 void Player::SetGMVisible(bool on
)
1927 m_ExtraFlags
&= ~PLAYER_EXTRA_GM_INVISIBLE
; //remove flag
1929 // Reapply stealth/invisibility if active or show if not any
1930 if(HasAuraType(SPELL_AURA_MOD_STEALTH
))
1931 SetVisibility(VISIBILITY_GROUP_STEALTH
);
1932 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY
))
1933 SetVisibility(VISIBILITY_GROUP_INVISIBILITY
);
1935 SetVisibility(VISIBILITY_ON
);
1939 m_ExtraFlags
|= PLAYER_EXTRA_GM_INVISIBLE
; //add flag
1941 SetAcceptWhispers(false);
1942 SetGameMaster(true);
1944 SetVisibility(VISIBILITY_OFF
);
1948 bool Player::IsGroupVisibleFor(Player
* p
) const
1950 switch(sWorld
.getConfig(CONFIG_GROUP_VISIBILITY
))
1952 default: return IsInSameGroupWith(p
);
1953 case 1: return IsInSameRaidWith(p
);
1954 case 2: return GetTeam()==p
->GetTeam();
1958 bool Player::IsInSameGroupWith(Player
const* p
) const
1960 return p
==this || GetGroup() != NULL
&&
1961 GetGroup() == p
->GetGroup() &&
1962 GetGroup()->SameSubGroup((Player
*)this, (Player
*)p
);
1965 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
1966 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
1967 void Player::UninviteFromGroup()
1969 if(GetGroupInvite()) // uninvited invitee
1971 Group
* group
= GetGroupInvite();
1972 group
->RemoveInvite(this);
1974 if(group
->GetMembersCount() <= 1) // group has just 1 member => disband
1976 if(group
->IsCreated())
1978 group
->Disband(true);
1979 objmgr
.RemoveGroup(group
);
1982 group
->RemoveAllInvites();
1989 void Player::RemoveFromGroup(Group
* group
, uint64 guid
)
1993 if (group
->RemoveMember(guid
, 0) <= 1)
1995 // group->Disband(); already disbanded in RemoveMember
1996 objmgr
.RemoveGroup(group
);
1998 // removemember sets the player's group pointer to NULL
2003 void Player::SendLogXPGain(uint32 GivenXP
, Unit
* victim
, uint32 RestXP
)
2005 WorldPacket
data(SMSG_LOG_XPGAIN
, 21);
2006 data
<< uint64(victim
? victim
->GetGUID() : 0); // guid
2007 data
<< uint32(GivenXP
+RestXP
); // given experience
2008 data
<< uint8(victim
? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2011 data
<< uint32(GivenXP
); // experience without rested bonus
2012 data
<< float(1); // 1 - none 0 - 100% group bonus output
2014 data
<< uint8(0); // new 2.4.0
2015 GetSession()->SendPacket(&data
);
2018 void Player::GiveXP(uint32 xp
, Unit
* victim
)
2026 uint32 level
= getLevel();
2028 // XP to money conversion processed in Player::RewardQuest
2029 if(level
>= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
2032 // handle SPELL_AURA_MOD_XP_PCT auras
2033 Unit::AuraList
const& ModXPPctAuras
= GetAurasByType(SPELL_AURA_MOD_XP_PCT
);
2034 for(Unit::AuraList::const_iterator i
= ModXPPctAuras
.begin();i
!= ModXPPctAuras
.end(); ++i
)
2035 xp
= uint32(xp
*(1.0f
+ (*i
)->GetModifier()->m_amount
/ 100.0f
));
2037 // XP resting bonus for kill
2038 uint32 rested_bonus_xp
= victim
? GetXPRestBonus(xp
) : 0;
2040 SendLogXPGain(xp
,victim
,rested_bonus_xp
);
2042 uint32 curXP
= GetUInt32Value(PLAYER_XP
);
2043 uint32 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2044 uint32 newXP
= curXP
+ xp
+ rested_bonus_xp
;
2046 while( newXP
>= nextLvlXP
&& level
< sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
2050 if ( level
< sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
2051 GiveLevel(level
+ 1);
2054 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2057 SetUInt32Value(PLAYER_XP
, newXP
);
2060 // Update player to next level
2061 // Current player experience not update (must be update by caller)
2062 void Player::GiveLevel(uint32 level
)
2064 if ( level
== getLevel() )
2067 PlayerLevelInfo info
;
2068 objmgr
.GetPlayerLevelInfo(getRace(),getClass(),level
,&info
);
2070 PlayerClassLevelInfo classInfo
;
2071 objmgr
.GetPlayerClassLevelInfo(getClass(),level
,&classInfo
);
2073 // send levelup info to client
2074 WorldPacket
data(SMSG_LEVELUP_INFO
, (4+4+MAX_POWERS
*4+MAX_STATS
*4));
2075 data
<< uint32(level
);
2076 data
<< uint32(int32(classInfo
.basehealth
) - int32(GetCreateHealth()));
2077 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2078 data
<< uint32(int32(classInfo
.basemana
) - int32(GetCreateMana()));
2084 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
) // Stats loop (0-4)
2085 data
<< uint32(int32(info
.stats
[i
]) - GetCreateStat(Stats(i
)));
2087 GetSession()->SendPacket(&data
);
2089 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, MaNGOS::XP::xp_to_level(level
));
2091 //update level, max level of skills
2092 if(getLevel()!= level
)
2093 m_Played_time
[1] = 0; // Level Played Time reset
2097 // save base values (bonuses already included in stored stats
2098 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2099 SetCreateStat(Stats(i
), info
.stats
[i
]);
2101 SetCreateHealth(classInfo
.basehealth
);
2102 SetCreateMana(classInfo
.basemana
);
2104 InitTalentForLevel();
2105 InitTaxiNodesForLevel();
2109 // set current level health and mana/energy to maximum after applying all mods.
2110 SetHealth(GetMaxHealth());
2111 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2112 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2113 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2114 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2115 SetPower(POWER_FOCUS
, 0);
2116 SetPower(POWER_HAPPINESS
, 0);
2118 // give level to summoned pet
2119 Pet
* pet
= GetPet();
2120 if(pet
&& pet
->getPetType()==SUMMON_PET
)
2121 pet
->GivePetLevel(level
);
2124 void Player::InitTalentForLevel()
2126 uint32 level
= getLevel();
2127 // talents base at level diff ( talents = level - 9 but some can be used already)
2130 // Remove all talent points
2131 if(m_usedTalentCount
> 0) // Free any used talents
2134 SetFreeTalentPoints(0);
2139 uint32 talentPointsForLevel
= uint32((level
-9)*sWorld
.getRate(RATE_TALENT
));
2140 // if used more that have then reset
2141 if(m_usedTalentCount
> talentPointsForLevel
)
2143 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR
)
2146 SetFreeTalentPoints(0);
2148 // else update amount of free points
2150 SetFreeTalentPoints(talentPointsForLevel
-m_usedTalentCount
);
2154 void Player::InitStatsForLevel(bool reapplyMods
)
2156 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2157 _RemoveAllStatBonuses();
2159 PlayerClassLevelInfo classInfo
;
2160 objmgr
.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo
);
2162 PlayerLevelInfo info
;
2163 objmgr
.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info
);
2165 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL
, sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) );
2166 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, MaNGOS::XP::xp_to_level(getLevel()));
2170 // set default cast time multiplier
2171 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
);
2173 // reset size before reapply auras
2174 SetFloatValue(OBJECT_FIELD_SCALE_X
,1.0f
);
2176 // save base values (bonuses already included in stored stats
2177 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2178 SetCreateStat(Stats(i
), info
.stats
[i
]);
2180 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2181 SetStat(Stats(i
), info
.stats
[i
]);
2183 SetCreateHealth(classInfo
.basehealth
);
2186 SetCreateMana(classInfo
.basemana
);
2188 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2192 //reset rating fields values
2193 for(uint16 index
= PLAYER_FIELD_COMBAT_RATING_1
; index
< PLAYER_FIELD_COMBAT_RATING_1
+ MAX_COMBAT_RATING
; ++index
)
2194 SetUInt32Value(index
, 0);
2196 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS
,0);
2197 for (int i
= 0; i
< 7; i
++)
2199 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG
+i
, 0);
2200 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS
+i
, 0);
2201 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT
+i
, 1.00f
);
2204 //reset attack power, damage and attack speed fields
2205 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
, 2000.0f
);
2206 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
+ 1, 2000.0f
); // offhand attack time
2207 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME
, 2000.0f
);
2209 SetFloatValue(UNIT_FIELD_MINDAMAGE
, 0.0f
);
2210 SetFloatValue(UNIT_FIELD_MAXDAMAGE
, 0.0f
);
2211 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
, 0.0f
);
2212 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
, 0.0f
);
2213 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
, 0.0f
);
2214 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
, 0.0f
);
2216 SetUInt32Value(UNIT_FIELD_ATTACK_POWER
, 0 );
2217 SetUInt32Value(UNIT_FIELD_ATTACK_POWER_MODS
, 0 );
2218 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER
,0.0f
);
2219 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER
, 0 );
2220 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS
,0 );
2221 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER
,0.0f
);
2223 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2224 SetFloatValue(PLAYER_CRIT_PERCENTAGE
,0.0f
);
2225 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE
,0.0f
);
2226 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE
,0.0f
);
2228 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2229 for (uint8 i
= 0; i
< 7; ++i
)
2230 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1
+i
, 0.0f
);
2232 SetFloatValue(PLAYER_PARRY_PERCENTAGE
, 0.0f
);
2233 SetFloatValue(PLAYER_BLOCK_PERCENTAGE
, 0.0f
);
2234 SetUInt32Value(PLAYER_SHIELD_BLOCK
, 0);
2237 SetFloatValue(PLAYER_DODGE_PERCENTAGE
, 0.0f
);
2239 // set armor (resistance 0) to original value (create_agility*2)
2240 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2241 SetResistanceBuffMods(SpellSchools(0), true, 0.0f
);
2242 SetResistanceBuffMods(SpellSchools(0), false, 0.0f
);
2243 // set other resistance to original value (0)
2244 for (int i
= 1; i
< MAX_SPELL_SCHOOL
; i
++)
2246 SetResistance(SpellSchools(i
), 0);
2247 SetResistanceBuffMods(SpellSchools(i
), true, 0.0f
);
2248 SetResistanceBuffMods(SpellSchools(i
), false, 0.0f
);
2251 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE
,0);
2252 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE
,0);
2253 for(int i
= 0; i
< MAX_SPELL_SCHOOL
; ++i
)
2255 SetFloatValue(UNIT_FIELD_POWER_COST_MODIFIER
+i
,0.0f
);
2256 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER
+i
,0.0f
);
2258 // Init data for form but skip reapply item mods for form
2259 InitDataForForm(reapplyMods
);
2262 for (int i
= POWER_MANA
; i
< MAX_POWERS
; i
++)
2263 SetMaxPower(Powers(i
), uint32(GetCreatePowers(Powers(i
))));
2265 SetMaxHealth(classInfo
.basehealth
); // stamina bonus will applied later
2267 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2268 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID
, 0);
2270 // cleanup unit flags (will be re-applied if need at aura load).
2271 RemoveFlag( UNIT_FIELD_FLAGS
,
2272 UNIT_FLAG_NON_ATTACKABLE
| UNIT_FLAG_DISABLE_MOVE
| UNIT_FLAG_NOT_ATTACKABLE_1
|
2273 UNIT_FLAG_PET_IN_COMBAT
| UNIT_FLAG_SILENCED
| UNIT_FLAG_PACIFIED
|
2274 UNIT_FLAG_DISABLE_ROTATE
| UNIT_FLAG_IN_COMBAT
| UNIT_FLAG_DISARMED
|
2275 UNIT_FLAG_CONFUSED
| UNIT_FLAG_FLEEING
| UNIT_FLAG_NOT_SELECTABLE
|
2276 UNIT_FLAG_SKINNABLE
| UNIT_FLAG_MOUNT
| UNIT_FLAG_TAXI_FLIGHT
);
2277 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
); // must be set
2279 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2280 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
| PLAYER_FLAGS_DND
| PLAYER_FLAGS_GM
| PLAYER_FLAGS_GHOST
| PLAYER_FLAGS_FFA_PVP
);
2282 SetByteValue(UNIT_FIELD_BYTES_1
, 2, 0x00); // one form stealth modified bytes
2284 // restore if need some important flags
2285 SetUInt32Value(PLAYER_FIELD_BYTES2
, 0 ); // flags empty by default
2287 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2288 _ApplyAllStatBonuses();
2290 // set current level health and mana/energy to maximum after applying all mods.
2291 SetHealth(GetMaxHealth());
2292 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2293 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2294 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2295 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2296 SetPower(POWER_FOCUS
, 0);
2297 SetPower(POWER_HAPPINESS
, 0);
2300 void Player::SendInitialSpells()
2302 uint16 spellCount
= 0;
2304 WorldPacket
data(SMSG_INITIAL_SPELLS
, (1+2+4*m_spells
.size()+2+m_spellCooldowns
.size()*(2+2+2+4+4)));
2307 size_t countPos
= data
.wpos();
2308 data
<< uint16(spellCount
); // spell count placeholder
2310 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2312 if(itr
->second
->state
== PLAYERSPELL_REMOVED
)
2315 if(!itr
->second
->active
|| itr
->second
->disabled
)
2318 data
<< uint16(itr
->first
);
2319 //data << uint16(itr->second->slotId);
2320 data
<< uint16(0); // it's not slot id
2325 data
.put
<uint16
>(countPos
,spellCount
); // write real count value
2327 uint16 spellCooldowns
= m_spellCooldowns
.size();
2328 data
<< uint16(spellCooldowns
);
2329 for(SpellCooldowns::const_iterator itr
=m_spellCooldowns
.begin(); itr
!=m_spellCooldowns
.end(); itr
++)
2331 SpellEntry
const *sEntry
= sSpellStore
.LookupEntry(itr
->first
);
2335 data
<< uint16(itr
->first
);
2337 time_t cooldown
= 0;
2338 time_t curTime
= time(NULL
);
2339 if(itr
->second
.end
> curTime
)
2340 cooldown
= (itr
->second
.end
-curTime
)*1000;
2342 data
<< uint16(itr
->second
.itemid
); // cast item id
2343 data
<< uint16(sEntry
->Category
); // spell category
2344 if(sEntry
->Category
) // may be wrong, but anyway better than nothing...
2347 data
<< uint32(cooldown
);
2351 data
<< uint32(cooldown
);
2356 GetSession()->SendPacket(&data
);
2358 sLog
.outDetail( "CHARACTER: Sent Initial Spells" );
2361 void Player::RemoveMail(uint32 id
)
2363 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
2365 if ((*itr
)->messageID
== id
)
2367 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2374 void Player::SendMailResult(uint32 mailId
, uint32 mailAction
, uint32 mailError
, uint32 equipError
, uint32 item_guid
, uint32 item_count
)
2376 WorldPacket
data(SMSG_SEND_MAIL_RESULT
, (4+4+4+(mailError
== MAIL_ERR_BAG_FULL
?4:(mailAction
== MAIL_ITEM_TAKEN
?4+4:0))));
2377 data
<< (uint32
) mailId
;
2378 data
<< (uint32
) mailAction
;
2379 data
<< (uint32
) mailError
;
2380 if ( mailError
== MAIL_ERR_BAG_FULL
)
2381 data
<< (uint32
) equipError
;
2382 else if( mailAction
== MAIL_ITEM_TAKEN
)
2384 data
<< (uint32
) item_guid
; // item guid low?
2385 data
<< (uint32
) item_count
; // item count?
2387 GetSession()->SendPacket(&data
);
2390 void Player::SendNewMail()
2392 // deliver undelivered mail
2393 WorldPacket
data(SMSG_RECEIVED_MAIL
, 4);
2395 GetSession()->SendPacket(&data
);
2398 void Player::UpdateNextMailTimeAndUnreads()
2400 // calculate next delivery time (min. from non-delivered mails
2401 // and recalculate unReadMail
2402 time_t cTime
= time(NULL
);
2403 m_nextMailDelivereTime
= 0;
2405 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
2407 if((*itr
)->deliver_time
> cTime
)
2409 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> (*itr
)->deliver_time
)
2410 m_nextMailDelivereTime
= (*itr
)->deliver_time
;
2412 else if(((*itr
)->checked
& MAIL_CHECK_MASK_READ
) == 0)
2417 void Player::AddNewMailDeliverTime(time_t deliver_time
)
2419 if(deliver_time
<= time(NULL
)) // ready now
2424 else // not ready and no have ready mails
2426 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> deliver_time
)
2427 m_nextMailDelivereTime
= deliver_time
;
2431 bool Player::addSpell(uint32 spell_id
, bool active
, bool learning
, bool loading
, uint16 slot_id
, bool disabled
)
2433 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
2436 // do character spell book cleanup (all characters)
2437 if(loading
&& !learning
) // spell load case
2439 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id
);
2440 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2443 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id
);
2448 if(!SpellMgr::IsSpellValid(spellInfo
,this,false))
2450 // do character spell book cleanup (all characters)
2451 if(loading
&& !learning
) // spell load case
2453 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id
);
2454 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2457 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id
);
2462 PlayerSpellState state
= learning
? PLAYERSPELL_NEW
: PLAYERSPELL_UNCHANGED
;
2464 bool disabled_case
= false;
2465 bool superceded_old
= false;
2467 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2468 if (itr
!= m_spells
.end())
2470 // update active state for known spell
2471 if(itr
->second
->active
!= active
&& itr
->second
->state
!= PLAYERSPELL_REMOVED
&& !itr
->second
->disabled
)
2473 itr
->second
->active
= active
;
2475 // loading && !learning == explicitly load from DB and then exist in it already and set correctly
2476 if(loading
&& !learning
)
2477 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2478 else if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2479 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2483 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
2484 data
<< uint16(spell_id
);
2485 GetSession()->SendPacket(&data
);
2487 return active
; // learn (show in spell book if active now)
2490 if(itr
->second
->disabled
!= disabled
&& itr
->second
->state
!= PLAYERSPELL_REMOVED
)
2492 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2493 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2494 itr
->second
->disabled
= disabled
;
2499 disabled_case
= true;
2501 else switch(itr
->second
->state
)
2503 case PLAYERSPELL_UNCHANGED
: // known saved spell
2505 case PLAYERSPELL_REMOVED
: // re-learning removed not saved spell
2508 m_spells
.erase(itr
);
2509 state
= PLAYERSPELL_CHANGED
;
2510 break; // need re-add
2512 default: // known not saved yet spell (new or modified)
2514 // can be in case spell loading but learned at some previous spell loading
2515 if(loading
&& !learning
)
2516 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2523 if(!disabled_case
) // skip new spell adding if spell already known (disabled spells case)
2525 // talent: unlearn all other talent ranks (high and low)
2526 if(TalentSpellPos
const* talentPos
= GetTalentSpellPos(spell_id
))
2528 if(TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry( talentPos
->talent_id
))
2530 for(int i
=0; i
<5; ++i
)
2532 // skip learning spell and no rank spell case
2533 uint32 rankSpellId
= talentInfo
->RankID
[i
];
2534 if(!rankSpellId
|| rankSpellId
==spell_id
)
2537 // skip unknown ranks
2538 if(!HasSpell(rankSpellId
))
2541 removeSpell(rankSpellId
);
2545 // non talent spell: learn low ranks (recursive call)
2546 else if(uint32 prev_spell
= spellmgr
.GetPrevSpellInChain(spell_id
))
2548 if(loading
) // at spells loading, no output, but allow save
2549 addSpell(prev_spell
,active
,true,loading
,SPELL_WITHOUT_SLOT_ID
,disabled
);
2550 else // at normal learning
2551 learnSpell(prev_spell
);
2554 PlayerSpell
*newspell
= new PlayerSpell
;
2555 newspell
->active
= active
;
2556 newspell
->state
= state
;
2557 newspell
->disabled
= disabled
;
2559 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2560 if(newspell
->active
&& !newspell
->disabled
&& !SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
2562 for( PlayerSpellMap::iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2564 if(itr
->second
->state
== PLAYERSPELL_REMOVED
) continue;
2565 SpellEntry
const *i_spellInfo
= sSpellStore
.LookupEntry(itr
->first
);
2566 if(!i_spellInfo
) continue;
2568 if( spellmgr
.IsRankSpellDueToSpell(spellInfo
,itr
->first
) )
2570 if(itr
->second
->active
)
2572 if(spellmgr
.IsHighRankOfSpell(spell_id
,itr
->first
))
2574 if(!loading
) // not send spell (re-/over-)learn packets at loading
2576 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2577 data
<< uint16(itr
->first
);
2578 data
<< uint16(spell_id
);
2579 GetSession()->SendPacket( &data
);
2582 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2583 itr
->second
->active
= false;
2584 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2585 superceded_old
= true; // new spell replace old in action bars and spell book.
2587 else if(spellmgr
.IsHighRankOfSpell(itr
->first
,spell_id
))
2589 if(!loading
) // not send spell (re-/over-)learn packets at loading
2591 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2592 data
<< uint16(spell_id
);
2593 data
<< uint16(itr
->first
);
2594 GetSession()->SendPacket( &data
);
2597 // mark new spell as disable (not learned yet for client and will not learned)
2598 newspell
->active
= false;
2599 if(newspell
->state
!= PLAYERSPELL_NEW
)
2600 newspell
->state
= PLAYERSPELL_CHANGED
;
2607 uint16 tmpslot
=slot_id
;
2609 if (tmpslot
== SPELL_WITHOUT_SLOT_ID
)
2612 PlayerSpellMap::iterator itr
;
2613 for (itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2615 if(itr
->second
->state
== PLAYERSPELL_REMOVED
)
2617 if (itr
->second
->slotId
> maxid
)
2618 maxid
= itr
->second
->slotId
;
2620 tmpslot
= maxid
+ 1;
2623 newspell
->slotId
= tmpslot
;
2624 m_spells
[spell_id
] = newspell
;
2626 // return false if spell disabled
2627 if (newspell
->disabled
)
2631 uint32 talentCost
= GetTalentSpellCost(spell_id
);
2633 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2634 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2635 if( talentCost
> 0 && IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_LEARN_SPELL
) )
2637 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2638 CastSpell(this, spell_id
, true);
2640 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2641 else if (IsPassiveSpell(spell_id
))
2643 // if spell doesn't require a stance or the player is in the required stance
2644 if( ( !spellInfo
->Stances
&&
2645 spell_id
!= 5420 && spell_id
!= 5419 && spell_id
!= 7376 &&
2646 spell_id
!= 7381 && spell_id
!= 21156 && spell_id
!= 21009 &&
2647 spell_id
!= 21178 && spell_id
!= 33948 && spell_id
!= 40121 ) ||
2648 m_form
!= 0 && (spellInfo
->Stances
& (1<<(m_form
-1))) ||
2649 (spell_id
== 5420 && m_form
== FORM_TREE
) ||
2650 (spell_id
== 5419 && m_form
== FORM_TRAVEL
) ||
2651 (spell_id
== 7376 && m_form
== FORM_DEFENSIVESTANCE
) ||
2652 (spell_id
== 7381 && m_form
== FORM_BERSERKERSTANCE
) ||
2653 (spell_id
== 21156 && m_form
== FORM_BATTLESTANCE
)||
2654 (spell_id
== 21178 && (m_form
== FORM_BEAR
|| m_form
== FORM_DIREBEAR
) ) ||
2655 (spell_id
== 33948 && m_form
== FORM_FLIGHT
) ||
2656 (spell_id
== 40121 && m_form
== FORM_FLIGHT_EPIC
) )
2657 //Check CasterAuraStates
2658 if (!spellInfo
->CasterAuraState
|| HasAuraState(AuraState(spellInfo
->CasterAuraState
)))
2659 CastSpell(this, spell_id
, true);
2661 else if( IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_SKILL_STEP
) )
2663 CastSpell(this, spell_id
, true);
2667 // update used talent points count
2668 m_usedTalentCount
+= talentCost
;
2670 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2671 if(uint32 freeProfs
= GetFreePrimaryProffesionPoints())
2673 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
2674 SetFreePrimaryProffesions(freeProfs
-1);
2677 // add dependent skills
2678 uint16 maxskill
= GetMaxSkillValueForLevel();
2680 SpellLearnSkillNode
const* spellLearnSkill
= spellmgr
.GetSpellLearnSkill(spell_id
);
2684 uint32 skill_value
= GetPureSkillValue(spellLearnSkill
->skill
);
2685 uint32 skill_max_value
= GetPureMaxSkillValue(spellLearnSkill
->skill
);
2687 if(skill_value
< spellLearnSkill
->value
)
2688 skill_value
= spellLearnSkill
->value
;
2690 uint32 new_skill_max_value
= spellLearnSkill
->maxvalue
== 0 ? maxskill
: spellLearnSkill
->maxvalue
;
2692 if(skill_max_value
< new_skill_max_value
)
2693 skill_max_value
= new_skill_max_value
;
2695 SetSkill(spellLearnSkill
->skill
,skill_value
,skill_max_value
);
2699 // not ranked skills
2700 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
2701 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
2703 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
2705 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
2709 if(HasSkill(pSkill
->id
))
2712 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
2713 // poison special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2714 pSkill
->id
==SKILL_POISONS
&& _spell_idx
->second
->max_value
==0 ||
2715 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2716 pSkill
->id
==SKILL_LOCKPICKING
&& _spell_idx
->second
->max_value
==0 )
2718 switch(GetSkillRangeType(pSkill
,_spell_idx
->second
->racemask
!=0))
2720 case SKILL_RANGE_LANGUAGE
:
2721 SetSkill(pSkill
->id
, 300, 300 );
2723 case SKILL_RANGE_LEVEL
:
2724 SetSkill(pSkill
->id
, 1, GetMaxSkillValueForLevel() );
2726 case SKILL_RANGE_MONO
:
2727 SetSkill(pSkill
->id
, 1, 1 );
2736 // learn dependent spells
2737 SpellLearnSpellMap::const_iterator spell_begin
= spellmgr
.GetBeginSpellLearnSpell(spell_id
);
2738 SpellLearnSpellMap::const_iterator spell_end
= spellmgr
.GetEndSpellLearnSpell(spell_id
);
2740 for(SpellLearnSpellMap::const_iterator itr
= spell_begin
; itr
!= spell_end
; ++itr
)
2742 if(!itr
->second
.autoLearned
)
2744 if(loading
) // at spells loading, no output, but allow save
2745 addSpell(itr
->second
.spell
,true,true,loading
);
2746 else // at normal learning
2747 learnSpell(itr
->second
.spell
);
2751 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2752 return active
&& !disabled
&& !superceded_old
;
2755 void Player::learnSpell(uint32 spell_id
)
2757 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2759 bool disabled
= (itr
!= m_spells
.end()) ? itr
->second
->disabled
: false;
2760 bool active
= disabled
? itr
->second
->active
: true;
2762 bool learning
= addSpell(spell_id
,active
);
2764 // learn all disabled higher ranks (recursive)
2765 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
2766 for(SpellChainMapNext::const_iterator i
= nextMap
.lower_bound(spell_id
); i
!= nextMap
.upper_bound(spell_id
); ++i
)
2768 PlayerSpellMap::iterator iter
= m_spells
.find(i
->second
);
2769 if (disabled
&& iter
!= m_spells
.end() && iter
->second
->disabled
)
2770 learnSpell(i
->second
);
2773 // prevent duplicated entires in spell book
2777 WorldPacket
data(SMSG_LEARNED_SPELL
, 4);
2778 data
<< uint32(spell_id
);
2779 GetSession()->SendPacket(&data
);
2782 void Player::removeSpell(uint32 spell_id
, bool disabled
)
2784 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2785 if (itr
== m_spells
.end())
2788 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| disabled
&& itr
->second
->disabled
)
2791 // unlearn non talent higher ranks (recursive)
2792 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
2793 for(SpellChainMapNext::const_iterator itr2
= nextMap
.lower_bound(spell_id
); itr2
!= nextMap
.upper_bound(spell_id
); ++itr2
)
2794 if(HasSpell(itr2
->second
) && !GetTalentSpellPos(itr2
->second
))
2795 removeSpell(itr2
->second
,disabled
);
2798 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
2799 data
<< uint16(spell_id
);
2800 GetSession()->SendPacket(&data
);
2804 itr
->second
->disabled
= disabled
;
2805 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2806 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2810 if(itr
->second
->state
== PLAYERSPELL_NEW
)
2813 m_spells
.erase(itr
);
2816 itr
->second
->state
= PLAYERSPELL_REMOVED
;
2819 RemoveAurasDueToSpell(spell_id
);
2822 if(PetAura
const* petSpell
= spellmgr
.GetPetAura(spell_id
))
2823 RemovePetAura(petSpell
);
2825 // free talent points
2826 uint32 talentCosts
= GetTalentSpellCost(spell_id
);
2829 if(talentCosts
< m_usedTalentCount
)
2830 m_usedTalentCount
-= talentCosts
;
2832 m_usedTalentCount
= 0;
2835 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
2836 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
2838 uint32 freeProfs
= GetFreePrimaryProffesionPoints()+1;
2839 if(freeProfs
<= sWorld
.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL
))
2840 SetFreePrimaryProffesions(freeProfs
);
2843 // remove dependent skill
2844 SpellLearnSkillNode
const* spellLearnSkill
= spellmgr
.GetSpellLearnSkill(spell_id
);
2847 uint32 prev_spell
= spellmgr
.GetPrevSpellInChain(spell_id
);
2848 if(!prev_spell
) // first rank, remove skill
2849 SetSkill(spellLearnSkill
->skill
,0,0);
2852 // search prev. skill setting by spell ranks chain
2853 SpellLearnSkillNode
const* prevSkill
= spellmgr
.GetSpellLearnSkill(prev_spell
);
2854 while(!prevSkill
&& prev_spell
)
2856 prev_spell
= spellmgr
.GetPrevSpellInChain(prev_spell
);
2857 prevSkill
= spellmgr
.GetSpellLearnSkill(spellmgr
.GetFirstSpellInChain(prev_spell
));
2860 if(!prevSkill
) // not found prev skill setting, remove skill
2861 SetSkill(spellLearnSkill
->skill
,0,0);
2862 else // set to prev. skill setting values
2864 uint32 skill_value
= GetPureSkillValue(prevSkill
->skill
);
2865 uint32 skill_max_value
= GetPureMaxSkillValue(prevSkill
->skill
);
2867 if(skill_value
> prevSkill
->value
)
2868 skill_value
= prevSkill
->value
;
2870 uint32 new_skill_max_value
= prevSkill
->maxvalue
== 0 ? GetMaxSkillValueForLevel() : prevSkill
->maxvalue
;
2872 if(skill_max_value
> new_skill_max_value
)
2873 skill_max_value
= new_skill_max_value
;
2875 SetSkill(prevSkill
->skill
,skill_value
,skill_max_value
);
2882 // not ranked skills
2883 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
2884 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
2886 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
2888 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
2892 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
2893 // poison special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2894 pSkill
->id
==SKILL_POISONS
&& _spell_idx
->second
->max_value
==0 ||
2895 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2896 pSkill
->id
==SKILL_LOCKPICKING
&& _spell_idx
->second
->max_value
==0 )
2898 // not reset skills for professions and racial abilities
2899 if( (pSkill
->categoryId
==SKILL_CATEGORY_SECONDARY
|| pSkill
->categoryId
==SKILL_CATEGORY_PROFESSION
) &&
2900 (IsProfessionSkill(pSkill
->id
) || _spell_idx
->second
->racemask
!=0) )
2903 SetSkill(pSkill
->id
, 0, 0 );
2908 // remove dependent spells
2909 SpellLearnSpellMap::const_iterator spell_begin
= spellmgr
.GetBeginSpellLearnSpell(spell_id
);
2910 SpellLearnSpellMap::const_iterator spell_end
= spellmgr
.GetEndSpellLearnSpell(spell_id
);
2912 for(SpellLearnSpellMap::const_iterator itr2
= spell_begin
; itr2
!= spell_end
; ++itr2
)
2913 removeSpell(itr2
->second
.spell
, disabled
);
2916 void Player::RemoveArenaSpellCooldowns()
2918 // remove cooldowns on spells that has < 15 min CD
2919 SpellCooldowns::iterator itr
, next
;
2920 // iterate spell cooldowns
2921 for(itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); itr
= next
)
2925 SpellEntry
const * entry
= sSpellStore
.LookupEntry(itr
->first
);
2926 // check if spellentry is present and if the cooldown is less than 15 mins
2928 entry
->RecoveryTime
<= 15 * MINUTE
* 1000 &&
2929 entry
->CategoryRecoveryTime
<= 15 * MINUTE
* 1000 )
2932 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, (4+8));
2933 data
<< uint32(itr
->first
);
2935 GetSession()->SendPacket(&data
);
2937 m_spellCooldowns
.erase(itr
);
2942 void Player::RemoveAllSpellCooldown()
2944 if(!m_spellCooldowns
.empty())
2946 for(SpellCooldowns::const_iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); ++itr
)
2948 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, (4+8));
2949 data
<< uint32(itr
->first
);
2950 data
<< uint64(GetGUID());
2951 GetSession()->SendPacket(&data
);
2953 m_spellCooldowns
.clear();
2957 void Player::_LoadSpellCooldowns(QueryResult
*result
)
2959 m_spellCooldowns
.clear();
2961 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
2965 time_t curTime
= time(NULL
);
2969 Field
*fields
= result
->Fetch();
2971 uint32 spell_id
= fields
[0].GetUInt32();
2972 uint32 item_id
= fields
[1].GetUInt32();
2973 time_t db_time
= (time_t)fields
[2].GetUInt64();
2975 if(!sSpellStore
.LookupEntry(spell_id
))
2977 sLog
.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id
);
2981 // skip outdated cooldown
2982 if(db_time
<= curTime
)
2985 AddSpellCooldown(spell_id
, item_id
, db_time
);
2987 sLog
.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id
, item_id
, uint32(db_time
-curTime
));
2989 while( result
->NextRow() );
2995 void Player::_SaveSpellCooldowns()
2997 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
2999 time_t curTime
= time(NULL
);
3001 // remove outdated and save active
3002 for(SpellCooldowns::iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end();)
3004 if(itr
->second
.end
<= curTime
)
3005 m_spellCooldowns
.erase(itr
++);
3008 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
));
3014 uint32
Player::resetTalentsCost() const
3016 // The first time reset costs 1 gold
3017 if(m_resetTalentsCost
< 1*GOLD
)
3020 else if(m_resetTalentsCost
< 5*GOLD
)
3022 // After that it increases in increments of 5 gold
3023 else if(m_resetTalentsCost
< 10*GOLD
)
3027 uint32 months
= (sWorld
.GetGameTime() - m_resetTalentsTime
)/MONTH
;
3030 // This cost will be reduced by a rate of 5 gold per month
3031 int32 new_cost
= int32(m_resetTalentsCost
) - 5*GOLD
*months
;
3032 // to a minimum of 10 gold.
3033 return (new_cost
< 10*GOLD
? 10*GOLD
: new_cost
);
3037 // After that it increases in increments of 5 gold
3038 int32 new_cost
= m_resetTalentsCost
+ 5*GOLD
;
3039 // until it hits a cap of 50 gold.
3040 if(new_cost
> 50*GOLD
)
3047 bool Player::resetTalents(bool no_cost
)
3049 // not need after this call
3050 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS
))
3052 m_atLoginFlags
= m_atLoginFlags
& ~AT_LOGIN_RESET_TALENTS
;
3053 CharacterDatabase
.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS
), GetGUIDLow());
3056 uint32 level
= getLevel();
3057 uint32 talentPointsForLevel
= level
< 10 ? 0 : uint32((level
-9)*sWorld
.getRate(RATE_TALENT
));
3059 if (m_usedTalentCount
== 0)
3061 SetFreeTalentPoints(talentPointsForLevel
);
3069 cost
= resetTalentsCost();
3071 if (GetMoney() < cost
)
3073 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, 0, 0, 0);
3078 for (unsigned int i
= 0; i
< sTalentStore
.GetNumRows(); i
++)
3080 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry(i
);
3082 if (!talentInfo
) continue;
3084 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentInfo
->TalentTab
);
3089 // unlearn only talents for character class
3090 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3091 // to prevent unexpected lost normal learned spell skip another class talents
3092 if( (getClassMask() & talentTabInfo
->ClassMask
) == 0 )
3095 for (int j
= 0; j
< 5; j
++)
3097 for(PlayerSpellMap::iterator itr
= GetSpellMap().begin(); itr
!= GetSpellMap().end();)
3099 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->second
->disabled
)
3105 // remove learned spells (all ranks)
3106 uint32 itrFirstId
= spellmgr
.GetFirstSpellInChain(itr
->first
);
3108 // unlearn if first rank is talent or learned by talent
3109 if (itrFirstId
== talentInfo
->RankID
[j
] || spellmgr
.IsSpellLearnToSpell(talentInfo
->RankID
[j
],itrFirstId
))
3111 removeSpell(itr
->first
,!IsPassiveSpell(itr
->first
));
3112 itr
= GetSpellMap().begin();
3121 SetFreeTalentPoints(talentPointsForLevel
);
3125 ModifyMoney(-(int32
)cost
);
3127 m_resetTalentsCost
= cost
;
3128 m_resetTalentsTime
= time(NULL
);
3131 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3132 RemovePet(NULL
,PET_SAVE_NOT_IN_SLOT
, true);
3137 bool Player::_removeSpell(uint16 spell_id
)
3139 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
3140 if (itr
!= m_spells
.end())
3143 m_spells
.erase(itr
);
3149 Mail
* Player::GetMail(uint32 id
)
3151 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); itr
++)
3153 if ((*itr
)->messageID
== id
)
3161 void Player::_SetCreateBits(UpdateMask
*updateMask
, Player
*target
) const
3165 Object::_SetCreateBits(updateMask
, target
);
3169 for(uint16 index
= 0; index
< m_valuesCount
; index
++)
3171 if(GetUInt32Value(index
) != 0 && updateVisualBits
.GetBit(index
))
3172 updateMask
->SetBit(index
);
3177 void Player::_SetUpdateBits(UpdateMask
*updateMask
, Player
*target
) const
3181 Object::_SetUpdateBits(updateMask
, target
);
3185 Object::_SetUpdateBits(updateMask
, target
);
3186 *updateMask
&= updateVisualBits
;
3190 void Player::InitVisibleBits()
3192 updateVisualBits
.SetCount(PLAYER_END
);
3194 // TODO: really implement OWNER_ONLY and GROUP_ONLY. Flags can be found in UpdateFields.h
3196 updateVisualBits
.SetBit(OBJECT_FIELD_GUID
);
3197 updateVisualBits
.SetBit(OBJECT_FIELD_TYPE
);
3198 updateVisualBits
.SetBit(OBJECT_FIELD_SCALE_X
);
3200 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
);
3201 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+1);
3203 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
);
3204 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+1);
3206 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
);
3207 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+1);
3209 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
);
3210 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+1);
3212 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
);
3213 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+1);
3215 updateVisualBits
.SetBit(UNIT_FIELD_HEALTH
);
3216 updateVisualBits
.SetBit(UNIT_FIELD_POWER1
);
3217 updateVisualBits
.SetBit(UNIT_FIELD_POWER2
);
3218 updateVisualBits
.SetBit(UNIT_FIELD_POWER3
);
3219 updateVisualBits
.SetBit(UNIT_FIELD_POWER4
);
3220 updateVisualBits
.SetBit(UNIT_FIELD_POWER5
);
3222 updateVisualBits
.SetBit(UNIT_FIELD_MAXHEALTH
);
3223 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER1
);
3224 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER2
);
3225 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER3
);
3226 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER4
);
3227 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER5
);
3229 updateVisualBits
.SetBit(UNIT_FIELD_LEVEL
);
3230 updateVisualBits
.SetBit(UNIT_FIELD_FACTIONTEMPLATE
);
3231 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_0
);
3232 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS
);
3233 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS_2
);
3234 for(uint16 i
= UNIT_FIELD_AURA
; i
< UNIT_FIELD_AURASTATE
; ++i
)
3235 updateVisualBits
.SetBit(i
);
3236 updateVisualBits
.SetBit(UNIT_FIELD_AURASTATE
);
3237 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
);
3238 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 1);
3239 updateVisualBits
.SetBit(UNIT_FIELD_BOUNDINGRADIUS
);
3240 updateVisualBits
.SetBit(UNIT_FIELD_COMBATREACH
);
3241 updateVisualBits
.SetBit(UNIT_FIELD_DISPLAYID
);
3242 updateVisualBits
.SetBit(UNIT_FIELD_NATIVEDISPLAYID
);
3243 updateVisualBits
.SetBit(UNIT_FIELD_MOUNTDISPLAYID
);
3244 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_1
);
3245 updateVisualBits
.SetBit(UNIT_FIELD_PETNUMBER
);
3246 updateVisualBits
.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP
);
3247 updateVisualBits
.SetBit(UNIT_DYNAMIC_FLAGS
);
3248 updateVisualBits
.SetBit(UNIT_CHANNEL_SPELL
);
3249 updateVisualBits
.SetBit(UNIT_MOD_CAST_SPEED
);
3250 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_2
);
3252 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
);
3253 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+1);
3254 updateVisualBits
.SetBit(PLAYER_FLAGS
);
3255 updateVisualBits
.SetBit(PLAYER_GUILDID
);
3256 updateVisualBits
.SetBit(PLAYER_GUILDRANK
);
3257 updateVisualBits
.SetBit(PLAYER_BYTES
);
3258 updateVisualBits
.SetBit(PLAYER_BYTES_2
);
3259 updateVisualBits
.SetBit(PLAYER_BYTES_3
);
3260 updateVisualBits
.SetBit(PLAYER_DUEL_TEAM
);
3261 updateVisualBits
.SetBit(PLAYER_GUILD_TIMESTAMP
);
3263 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3264 for(uint16 i
= PLAYER_QUEST_LOG_1_1
; i
< PLAYER_QUEST_LOG_25_2
; i
+=4)
3265 updateVisualBits
.SetBit(i
);
3267 //Players visible items are not inventory stuff
3268 //431) = 884 (0x374) = main weapon
3269 for(uint16 i
= 0; i
< EQUIPMENT_SLOT_END
; i
++)
3272 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (i
*MAX_VISIBLE_ITEM_OFFSET
) + 0);
3273 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (i
*MAX_VISIBLE_ITEM_OFFSET
) + 1);
3275 uint16 visual_base
= PLAYER_VISIBLE_ITEM_1_0
+ (i
*MAX_VISIBLE_ITEM_OFFSET
);
3278 updateVisualBits
.SetBit(visual_base
+ 0);
3280 // item enchantment IDs
3281 for(uint8 j
= 0; j
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++j
)
3282 updateVisualBits
.SetBit(visual_base
+ 1 + j
);
3284 // random properties
3285 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 0 + (i
*MAX_VISIBLE_ITEM_OFFSET
));
3286 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (i
*MAX_VISIBLE_ITEM_OFFSET
));
3289 updateVisualBits
.SetBit(PLAYER_CHOSEN_TITLE
);
3292 void Player::BuildCreateUpdateBlockForPlayer( UpdateData
*data
, Player
*target
) const
3294 for(int i
= 0; i
< EQUIPMENT_SLOT_END
; i
++)
3296 if(m_items
[i
] == NULL
)
3299 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3305 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
3307 if(m_items
[i
] == NULL
)
3310 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3312 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
3314 if(m_items
[i
] == NULL
)
3317 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3321 Unit::BuildCreateUpdateBlockForPlayer( data
, target
);
3324 void Player::DestroyForPlayer( Player
*target
) const
3326 Unit::DestroyForPlayer( target
);
3328 for(int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
3330 if(m_items
[i
] == NULL
)
3333 m_items
[i
]->DestroyForPlayer( target
);
3339 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
3341 if(m_items
[i
] == NULL
)
3344 m_items
[i
]->DestroyForPlayer( target
);
3346 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
3348 if(m_items
[i
] == NULL
)
3351 m_items
[i
]->DestroyForPlayer( target
);
3356 bool Player::HasSpell(uint32 spell
) const
3358 PlayerSpellMap::const_iterator itr
= m_spells
.find((uint16
)spell
);
3359 return (itr
!= m_spells
.end() && itr
->second
->state
!= PLAYERSPELL_REMOVED
&& !itr
->second
->disabled
);
3362 TrainerSpellState
Player::GetTrainerSpellState(TrainerSpell
const* trainer_spell
) const
3365 return TRAINER_SPELL_RED
;
3367 if (!trainer_spell
->spell
)
3368 return TRAINER_SPELL_RED
;
3371 if(HasSpell(trainer_spell
->spell
))
3372 return TRAINER_SPELL_GRAY
;
3374 // check race/class requirement
3375 if(!IsSpellFitByClassAndRace(trainer_spell
->spell
))
3376 return TRAINER_SPELL_RED
;
3378 // check level requirement
3379 if(getLevel() < trainer_spell
->reqlevel
)
3380 return TRAINER_SPELL_RED
;
3382 if(SpellChainNode
const* spell_chain
= spellmgr
.GetSpellChainNode(trainer_spell
->spell
))
3384 // check prev.rank requirement
3385 if(spell_chain
->prev
&& !HasSpell(spell_chain
->prev
))
3386 return TRAINER_SPELL_RED
;
3388 // check additional spell requirement
3389 if(spell_chain
->req
&& !HasSpell(spell_chain
->req
))
3390 return TRAINER_SPELL_RED
;
3393 // check skill requirement
3394 if(trainer_spell
->reqskill
&& GetBaseSkillValue(trainer_spell
->reqskill
) < trainer_spell
->reqskillvalue
)
3395 return TRAINER_SPELL_RED
;
3397 // exist, already checked at loading
3398 SpellEntry
const* spell
= sSpellStore
.LookupEntry(trainer_spell
->spell
);
3400 // secondary prof. or not prof. spell
3401 uint32 skill
= spell
->EffectMiscValue
[1];
3403 if(spell
->Effect
[1] != SPELL_EFFECT_SKILL
|| !IsPrimaryProfessionSkill(skill
))
3404 return TRAINER_SPELL_GREEN
;
3406 // check primary prof. limit
3407 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell
->Id
) && GetFreePrimaryProffesionPoints() == 0)
3408 return TRAINER_SPELL_RED
;
3410 return TRAINER_SPELL_GREEN
;
3413 void Player::DeleteFromDB(uint64 playerguid
, uint32 accountId
, bool updateRealmChars
)
3415 uint32 guid
= GUID_LOPART(playerguid
);
3417 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3418 // bones will be deleted by corpse/bones deleting thread shortly
3419 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid
);
3421 // remove from guild
3422 uint32 guildId
= GetGuildIdFromDB(playerguid
);
3425 Guild
* guild
= objmgr
.GetGuildById(guildId
);
3427 guild
->DelMember(guid
);
3430 // the player was uninvited already on logout so just remove from group
3431 QueryResult
*resultGroup
= CharacterDatabase
.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid
);
3434 uint64 leaderGuid
= MAKE_NEW_GUID((*resultGroup
)[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
3436 Group
* group
= objmgr
.GetGroupByLeader(leaderGuid
);
3439 RemoveFromGroup(group
, playerguid
);
3443 // remove signs from petitions (also remove petitions if owner);
3444 RemovePetitionsAndSigns(playerguid
, 10);
3446 // return back all mails with COD and Item 0 1 2 3 4 5 6
3447 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
);
3452 Field
*fields
= resultMail
->Fetch();
3454 uint32 mail_id
= fields
[0].GetUInt32();
3455 uint16 mailTemplateId
= fields
[1].GetUInt16();
3456 uint32 sender
= fields
[2].GetUInt32();
3457 std::string subject
= fields
[3].GetCppString();
3458 uint32 itemTextId
= fields
[4].GetUInt32();
3459 uint32 money
= fields
[5].GetUInt32();
3460 bool has_items
= fields
[6].GetBool();
3462 //we can return mail now
3463 //so firstly delete the old one
3464 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id
);
3469 QueryResult
*resultItems
= CharacterDatabase
.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", mail_id
);
3474 Field
*fields2
= resultItems
->Fetch();
3476 uint32 item_guidlow
= fields2
[0].GetUInt32();
3477 uint32 item_template
= fields2
[1].GetUInt32();
3479 ItemPrototype
const* itemProto
= objmgr
.GetItemPrototype(item_template
);
3482 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow
);
3486 Item
*pItem
= NewItemOrBag(itemProto
);
3487 if(!pItem
->LoadFromDB(item_guidlow
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
)))
3489 pItem
->FSetState(ITEM_REMOVED
);
3490 pItem
->SaveToDB(); // it also deletes item object !
3494 mi
.AddItem(item_guidlow
, item_template
, pItem
);
3496 while (resultItems
->NextRow());
3502 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id
);
3504 uint32 pl_account
= objmgr
.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
3506 WorldSession::SendReturnToSender(MAIL_NORMAL
, pl_account
, guid
, sender
, subject
, itemTextId
, &mi
, money
, 0, mailTemplateId
);
3508 while (resultMail
->NextRow());
3513 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3514 // Get guids of character's pets, will deleted in transaction
3515 QueryResult
*resultPets
= CharacterDatabase
.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid
);
3517 // NOW we can finally clear other DB data related to character
3518 CharacterDatabase
.BeginTransaction();
3523 Field
*fields3
= resultPets
->Fetch();
3524 uint32 petguidlow
= fields3
[0].GetUInt32();
3525 Pet::DeleteFromDB(petguidlow
);
3526 } while (resultPets
->NextRow());
3530 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",guid
);
3531 CharacterDatabase
.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid
);
3532 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid
);
3533 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid
);
3534 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid
);
3535 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid
);
3536 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid
);
3537 CharacterDatabase
.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid
);
3538 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid
);
3539 CharacterDatabase
.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid
);
3540 CharacterDatabase
.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid
);
3541 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid
);
3542 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid
);
3543 CharacterDatabase
.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid
);
3544 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid
);
3545 CharacterDatabase
.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid
,guid
);
3546 CharacterDatabase
.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid
);
3547 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid
);
3548 CharacterDatabase
.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid
);
3549 CharacterDatabase
.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid
);
3550 CharacterDatabase
.CommitTransaction();
3552 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3553 if(updateRealmChars
) sWorld
.UpdateRealmCharCount(accountId
);
3556 void Player::SetMovement(PlayerMovementType pType
)
3561 case MOVE_ROOT
: data
.Initialize(SMSG_FORCE_MOVE_ROOT
, GetPackGUID().size()+4); break;
3562 case MOVE_UNROOT
: data
.Initialize(SMSG_FORCE_MOVE_UNROOT
, GetPackGUID().size()+4); break;
3563 case MOVE_WATER_WALK
: data
.Initialize(SMSG_MOVE_WATER_WALK
, GetPackGUID().size()+4); break;
3564 case MOVE_LAND_WALK
: data
.Initialize(SMSG_MOVE_LAND_WALK
, GetPackGUID().size()+4); break;
3566 sLog
.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType
);
3569 data
.append(GetPackGUID());
3571 GetSession()->SendPacket( &data
);
3575 - a resurrectable corpse must not be loaded for the player (only bones)
3576 - the player must be in world
3578 void Player::BuildPlayerRepop()
3580 if(getRace() == RACE_NIGHTELF
)
3581 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)
3582 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3584 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3585 // there must be SMSG.STOP_MIRROR_TIMER
3586 // there we must send 888 opcode
3588 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3591 sLog
.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3595 // create a corpse and place it at the player's location
3597 Corpse
*corpse
= GetCorpse();
3600 sLog
.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3603 GetMap()->Add(corpse
);
3605 // convert player body to ghost
3608 SetMovement(MOVE_WATER_WALK
);
3609 if(!GetSession()->isLogingOut())
3610 SetMovement(MOVE_UNROOT
);
3612 // BG - remove insignia related
3613 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_SKINNABLE
);
3615 SendCorpseReclaimDelay();
3617 // to prevent cheating
3618 corpse
->ResetGhostTime();
3620 StopMirrorTimers(); //disable timers(bars)
3622 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, (float)1.0); //see radius of death player?
3624 SetByteValue(UNIT_FIELD_BYTES_1
, 3, PLAYER_STATE_FLAG_ALWAYS_STAND
);
3627 void Player::SendDelayResponse(const uint32 ml_seconds
)
3629 WorldPacket
data( SMSG_QUERY_TIME_RESPONSE
, 4+4 );
3630 data
<< (uint32
)time(NULL
);
3632 GetSession()->SendPacket( &data
);
3635 void Player::ResurrectPlayer(float restore_percent
, bool updateToWorld
, bool applySickness
)
3637 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // remove spirit healer position
3642 GetSession()->SendPacket(&data
);
3644 // speed change, land walk
3646 // remove death flag + set aura
3647 SetByteValue(UNIT_FIELD_BYTES_1
, 3, 0x00);
3648 if(getRace() == RACE_NIGHTELF
)
3649 RemoveAurasDueToSpell(20584); // speed bonuses
3650 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3652 setDeathState(ALIVE
);
3654 SetMovement(MOVE_LAND_WALK
);
3655 SetMovement(MOVE_UNROOT
);
3659 // set health/powers (0- will be set in caller)
3660 if(restore_percent
>0.0f
)
3662 SetHealth(uint32(GetMaxHealth()*restore_percent
));
3663 SetPower(POWER_MANA
, uint32(GetMaxPower(POWER_MANA
)*restore_percent
));
3664 SetPower(POWER_RAGE
, 0);
3665 SetPower(POWER_ENERGY
, uint32(GetMaxPower(POWER_ENERGY
)*restore_percent
));
3669 ObjectAccessor::UpdateVisibilityForPlayer(this);
3671 // some items limited to specific map
3672 DestroyZoneLimitedItem( true, GetZoneId());
3674 if(!applySickness
|| getLevel() <= 10)
3677 //Characters from level 1-10 are not affected by resurrection sickness.
3678 //Characters from level 11-19 will suffer from one minute of sickness
3679 //for each level they are above 10.
3680 //Characters level 20 and up suffer from ten minutes of sickness.
3681 int32 startLevel
= sWorld
.getConfig(CONFIG_DEATH_SICKNESS_LEVEL
);
3683 if(int32(getLevel()) >= startLevel
)
3685 // set resurrection sickness
3686 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,true);
3688 // not full duration
3689 if(int32(getLevel()) < startLevel
+9)
3691 int32 delta
= (int32(getLevel()) - startLevel
+ 1)*MINUTE
;
3693 for(int i
=0; i
< 3; ++i
)
3695 if(Aura
* Aur
= GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,i
))
3697 Aur
->SetAuraDuration(delta
*1000);
3698 Aur
->UpdateAuraDuration();
3705 void Player::KillPlayer()
3707 SetMovement(MOVE_ROOT
);
3709 StopMirrorTimers(); //disable timers(bars)
3711 setDeathState(CORPSE
);
3712 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
3714 SetFlag(UNIT_DYNAMIC_FLAGS
, 0x00);
3715 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, !sMapStore
.LookupEntry(GetMapId())->Instanceable());
3717 // 6 minutes until repop at graveyard
3718 m_deathTimer
= 6*MINUTE
*1000;
3720 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
3722 // don't create corpse at this moment, player might be falling
3724 // update visibility
3725 ObjectAccessor::UpdateObjectVisibility(this);
3728 void Player::CreateCorpse()
3730 // prevent existence 2 corpse for player
3733 uint32 _uf
, _pb
, _pb2
, _cfb1
, _cfb2
;
3735 Corpse
*corpse
= new Corpse( (m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
) ? CORPSE_RESURRECTABLE_PVP
: CORPSE_RESURRECTABLE_PVE
);
3738 if(!corpse
->Create(objmgr
.GenerateLowGuid(HIGHGUID_CORPSE
), this, GetMapId(), GetPositionX(),
3739 GetPositionY(), GetPositionZ(), GetOrientation()))
3745 _uf
= GetUInt32Value(UNIT_FIELD_BYTES_0
);
3746 _pb
= GetUInt32Value(PLAYER_BYTES
);
3747 _pb2
= GetUInt32Value(PLAYER_BYTES_2
);
3749 uint8 race
= (uint8
)(_uf
);
3750 uint8 skin
= (uint8
)(_pb
);
3751 uint8 face
= (uint8
)(_pb
>> 8);
3752 uint8 hairstyle
= (uint8
)(_pb
>> 16);
3753 uint8 haircolor
= (uint8
)(_pb
>> 24);
3754 uint8 facialhair
= (uint8
)(_pb2
);
3756 _cfb1
= ((0x00) | (race
<< 8) | (getGender() << 16) | (skin
<< 24));
3757 _cfb2
= ((face
) | (hairstyle
<< 8) | (haircolor
<< 16) | (facialhair
<< 24));
3759 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_1
, _cfb1
);
3760 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_2
, _cfb2
);
3762 uint32 flags
= CORPSE_FLAG_UNK2
;
3763 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
3764 flags
|= CORPSE_FLAG_HIDE_HELM
;
3765 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
3766 flags
|= CORPSE_FLAG_HIDE_CLOAK
;
3767 if(InBattleGround())
3768 flags
|= CORPSE_FLAG_LOOTABLE
; // to be able to remove insignia
3769 corpse
->SetUInt32Value( CORPSE_FIELD_FLAGS
, flags
);
3771 corpse
->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID
, GetNativeDisplayId() );
3773 corpse
->SetUInt32Value( CORPSE_FIELD_GUILD
, GetGuildId() );
3776 uint16 iIventoryType
;
3778 for (int i
= 0; i
< EQUIPMENT_SLOT_END
; i
++)
3782 iDisplayID
= m_items
[i
]->GetProto()->DisplayInfoID
;
3783 iIventoryType
= (uint16
)m_items
[i
]->GetProto()->InventoryType
;
3785 _cfi
= (uint16(iDisplayID
)) | (iIventoryType
)<< 24;
3786 corpse
->SetUInt32Value(CORPSE_FIELD_ITEM
+ i
,_cfi
);
3790 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
3791 const MapEntry
*entry
= sMapStore
.LookupEntry(corpse
->GetMapId());
3793 if(entry
->map_type
!= MAP_BATTLEGROUND
)
3796 // register for player, but not show
3797 ObjectAccessor::Instance().AddCorpse(corpse
);
3800 void Player::SpawnCorpseBones()
3802 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
3803 SaveToDB(); // prevent loading as ghost without corpse
3806 Corpse
* Player::GetCorpse() const
3808 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
3811 void Player::DurabilityLossAll(double percent
, bool inventory
)
3813 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
3814 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3815 DurabilityLoss(pItem
,percent
);
3819 // bags not have durability
3820 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3822 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
3823 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3824 DurabilityLoss(pItem
,percent
);
3826 // keys not have durability
3827 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3829 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
3830 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3831 if(ItemPrototype
const *pBagProto
= pBag
->GetProto())
3832 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
3833 if(Item
* pItem
= GetItemByPos( i
, j
))
3834 DurabilityLoss(pItem
,percent
);
3838 void Player::DurabilityLoss(Item
* item
, double percent
)
3843 uint32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
3848 uint32 pDurabilityLoss
= uint32(pMaxDurability
*percent
);
3850 if(pDurabilityLoss
< 1 )
3851 pDurabilityLoss
= 1;
3853 DurabilityPointsLoss(item
,pDurabilityLoss
);
3856 void Player::DurabilityPointsLossAll(int32 points
, bool inventory
)
3858 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
3859 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3860 DurabilityPointsLoss(pItem
,points
);
3864 // bags not have durability
3865 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3867 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
3868 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3869 DurabilityPointsLoss(pItem
,points
);
3871 // keys not have durability
3872 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3874 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
3875 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3876 if(ItemPrototype
const *pBagProto
= pBag
->GetProto())
3877 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
3878 if(Item
* pItem
= GetItemByPos( i
, j
))
3879 DurabilityPointsLoss(pItem
,points
);
3883 void Player::DurabilityPointsLoss(Item
* item
, int32 points
)
3885 int32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
3886 int32 pOldDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
3887 int32 pNewDurability
= pOldDurability
- points
;
3889 if (pNewDurability
< 0)
3891 else if (pNewDurability
> pMaxDurability
)
3892 pNewDurability
= pMaxDurability
;
3894 if (pOldDurability
!= pNewDurability
)
3896 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
3897 if ( pNewDurability
== 0 && pOldDurability
> 0 && item
->IsEquipped())
3898 _ApplyItemMods(item
,item
->GetSlot(), false);
3900 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, pNewDurability
);
3902 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
3903 if ( pNewDurability
> 0 && pOldDurability
== 0 && item
->IsEquipped())
3904 _ApplyItemMods(item
,item
->GetSlot(), true);
3906 item
->SetState(ITEM_CHANGED
, this);
3910 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot
)
3912 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
))
3913 DurabilityPointsLoss(pItem
,1);
3916 uint32
Player::DurabilityRepairAll(bool cost
, float discountMod
, bool guildBank
)
3918 uint32 TotalCost
= 0;
3919 // equipped, backpack, bags itself
3920 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
3921 TotalCost
+= DurabilityRepair(( (INVENTORY_SLOT_BAG_0
<< 8) | i
),cost
,discountMod
, guildBank
);
3923 // bank, buyback and keys not repaired
3925 // items in inventory bags
3926 for(int j
= INVENTORY_SLOT_BAG_START
; j
< INVENTORY_SLOT_BAG_END
; j
++)
3927 for(int i
= 0; i
< MAX_BAG_SIZE
; i
++)
3928 TotalCost
+= DurabilityRepair(( (j
<< 8) | i
),cost
,discountMod
, guildBank
);
3932 uint32
Player::DurabilityRepair(uint16 pos
, bool cost
, float discountMod
, bool guildBank
)
3934 Item
* item
= GetItemByPos(pos
);
3936 uint32 TotalCost
= 0;
3940 uint32 maxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
3944 uint32 curDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
3948 uint32 LostDurability
= maxDurability
- curDurability
;
3949 if(LostDurability
>0)
3951 ItemPrototype
const *ditemProto
= sItemStorage
.LookupEntry
<ItemPrototype
>(item
->GetEntry());
3954 sLog
.outError("ERROR: RepairDurability: Unknown item id %u", ditemProto
);
3958 DurabilityCostsEntry
const *dcost
= sDurabilityCostsStore
.LookupEntry(ditemProto
->ItemLevel
);
3961 sLog
.outError("ERROR: RepairDurability: Wrong item lvl %u", dcost
);
3965 DurabilityQualityEntry
const *dQualitymodEntry
= sDurabilityQualityStore
.LookupEntry((ditemProto
->Quality
+1)*2);
3966 if(!dQualitymodEntry
)
3968 sLog
.outError("ERROR: RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntry
);
3972 uint32 dmultiplier
= dcost
->multiplier
[ItemSubClassToDurabilityMultiplierId(ditemProto
->Class
,ditemProto
->SubClass
)];
3973 uint32 costs
= uint32(LostDurability
*dmultiplier
*double(dQualitymodEntry
->quality_mod
));
3975 costs
= uint32(costs
* discountMod
);
3977 if (costs
==0) //fix for ITEM_QUALITY_ARTIFACT
3982 if (GetGuildId()==0)
3984 DEBUG_LOG("You are not member of a guild");
3988 Guild
*pGuild
= objmgr
.GetGuildById(GetGuildId());
3992 if (!pGuild
->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR
))
3994 DEBUG_LOG("You do not have rights to withdraw for repairs");
3998 if (pGuild
->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs
)
4000 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4004 if (pGuild
->GetGuildBankMoney() < costs
)
4006 DEBUG_LOG("There is not enough money in bank");
4010 pGuild
->MemberMoneyWithdraw(costs
, GetGUIDLow());
4013 else if (GetMoney() < costs
)
4015 DEBUG_LOG("You do not have enough money");
4019 ModifyMoney( -int32(costs
) );
4023 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, maxDurability
);
4024 item
->SetState(ITEM_CHANGED
, this);
4026 // reapply mods for total broken and repaired item if equipped
4027 if(IsEquipmentPos(pos
) && !curDurability
)
4028 _ApplyItemMods(item
,pos
& 255, true);
4032 void Player::RepopAtGraveyard()
4034 // note: this can be called also when the player is alive
4035 // for example from WorldSession::HandleMovementOpcodes
4037 AreaTableEntry
const *zone
= GetAreaEntryByAreaID(GetAreaId());
4039 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4040 if(!isAlive() && zone
&& zone
->flags
& AREA_FLAG_NEED_FLY
|| GetTransport())
4042 ResurrectPlayer(0.5f
);
4046 WorldSafeLocsEntry
const *ClosestGrave
= NULL
;
4048 // Special handle for battleground maps
4049 BattleGround
*bg
= sBattleGroundMgr
.GetBattleGround(GetBattleGroundId());
4051 if(bg
&& (bg
->GetTypeID() == BATTLEGROUND_AB
|| bg
->GetTypeID() == BATTLEGROUND_EY
))
4052 ClosestGrave
= bg
->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetTeam());
4054 ClosestGrave
= objmgr
.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4056 // stop countdown until repop
4059 // if no grave found, stay at the current location
4060 // and don't show spirit healer location
4063 TeleportTo(ClosestGrave
->map_id
, ClosestGrave
->x
, ClosestGrave
->y
, ClosestGrave
->z
, GetOrientation());
4064 if(isDead()) // not send if alive, because it used in TeleportTo()
4066 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // show spirit healer position on minimap
4067 data
<< ClosestGrave
->map_id
;
4068 data
<< ClosestGrave
->x
;
4069 data
<< ClosestGrave
->y
;
4070 data
<< ClosestGrave
->z
;
4071 GetSession()->SendPacket(&data
);
4076 void Player::JoinedChannel(Channel
*c
)
4078 m_channels
.push_back(c
);
4081 void Player::LeftChannel(Channel
*c
)
4083 m_channels
.remove(c
);
4086 void Player::CleanupChannels()
4088 while(!m_channels
.empty())
4090 Channel
* ch
= *m_channels
.begin();
4091 m_channels
.erase(m_channels
.begin()); // remove from player's channel list
4092 ch
->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4093 if (ChannelMgr
* cMgr
= channelMgr(GetTeam()))
4094 cMgr
->LeftChannel(ch
->GetName()); // deleted channel if empty
4097 sLog
.outDebug("Player: channels cleaned up!");
4100 void Player::UpdateLocalChannels(uint32 newZone
)
4102 if(m_channels
.empty())
4105 AreaTableEntry
const* current_zone
= GetAreaEntryByAreaID(newZone
);
4109 ChannelMgr
* cMgr
= channelMgr(GetTeam());
4113 std::string current_zone_name
= current_zone
->area_name
[GetSession()->GetSessionDbcLocale()];
4115 for(JoinedChannelsList::iterator i
= m_channels
.begin(), next
; i
!= m_channels
.end(); i
= next
)
4119 // skip non built-in channels
4120 if(!(*i
)->IsConstant())
4123 ChatChannelsEntry
const* ch
= GetChannelEntryFor((*i
)->GetChannelId());
4127 if((ch
->flags
& 4) == 4) // global channel without zone name in pattern
4131 char new_channel_name_buf
[100];
4132 snprintf(new_channel_name_buf
,100,ch
->pattern
[m_session
->GetSessionDbcLocale()],current_zone_name
.c_str());
4133 Channel
* new_channel
= cMgr
->GetJoinChannel(new_channel_name_buf
,ch
->ChannelID
);
4135 if((*i
)!=new_channel
)
4137 new_channel
->Join(GetGUID(),""); // will output Changed Channel: N. Name
4139 // leave old channel
4140 (*i
)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4141 std::string name
= (*i
)->GetName(); // stroe name, (*i)erase in LeftChannel
4142 LeftChannel(*i
); // remove from player's channel list
4143 cMgr
->LeftChannel(name
); // delete if empty
4146 sLog
.outDebug("Player: channels cleaned up!");
4149 void Player::LeaveLFGChannel()
4151 for(JoinedChannelsList::iterator i
= m_channels
.begin(); i
!= m_channels
.end(); ++i
)
4155 (*i
)->Leave(GetGUID());
4161 void Player::UpdateDefense()
4163 uint32 defense_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_DEFENSE
);
4165 if(UpdateSkill(SKILL_DEFENSE
,defense_skill_gain
))
4167 // update dependent from defense skill part
4168 UpdateDefenseBonusesMod();
4172 void Player::HandleBaseModValue(BaseModGroup modGroup
, BaseModType modType
, float amount
, bool apply
, bool affectStats
)
4174 if(modGroup
>= BASEMOD_END
|| modType
>= MOD_END
)
4176 sLog
.outError("ERROR in HandleBaseModValue(): nonexisted BaseModGroup of wrong BaseModType!");
4185 m_auraBaseMod
[modGroup
][modType
] += apply
? amount
: -amount
;
4188 if(amount
<= -100.0f
)
4191 val
= (100.0f
+ amount
) / 100.0f
;
4192 m_auraBaseMod
[modGroup
][modType
] *= apply
? val
: (1.0f
/val
);
4196 if(!CanModifyStats())
4201 case CRIT_PERCENTAGE
: UpdateCritPercentage(BASE_ATTACK
); break;
4202 case RANGED_CRIT_PERCENTAGE
: UpdateCritPercentage(RANGED_ATTACK
); break;
4203 case OFFHAND_CRIT_PERCENTAGE
: UpdateCritPercentage(OFF_ATTACK
); break;
4204 case SHIELD_BLOCK_VALUE
: UpdateShieldBlockValue(); break;
4209 float Player::GetBaseModValue(BaseModGroup modGroup
, BaseModType modType
) const
4211 if(modGroup
>= BASEMOD_END
|| modType
> MOD_END
)
4213 sLog
.outError("ERROR: trial to access nonexisted BaseModGroup or wrong BaseModType!");
4217 if(modType
== PCT_MOD
&& m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4220 return m_auraBaseMod
[modGroup
][modType
];
4223 float Player::GetTotalBaseModValue(BaseModGroup modGroup
) const
4225 if(modGroup
>= BASEMOD_END
)
4227 sLog
.outError("ERROR: wrong BaseModGroup in GetTotalBaseModValue()!");
4231 if(m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4234 return m_auraBaseMod
[modGroup
][FLAT_MOD
] * m_auraBaseMod
[modGroup
][PCT_MOD
];
4237 uint32
Player::GetShieldBlockValue() const
4239 BaseModGroup modGroup
= SHIELD_BLOCK_VALUE
;
4241 float value
= GetTotalBaseModValue(modGroup
) + GetStat(STAT_STRENGTH
)/20 - 1;
4243 value
= (value
< 0) ? 0 : value
;
4245 return uint32(value
);
4248 float Player::GetMeleeCritFromAgility()
4250 uint32 level
= getLevel();
4251 uint32 pclass
= getClass();
4253 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4255 GtChanceToMeleeCritBaseEntry
const *critBase
= sGtChanceToMeleeCritBaseStore
.LookupEntry(pclass
-1);
4256 GtChanceToMeleeCritEntry
const *critRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4257 if (critBase
==NULL
|| critRatio
==NULL
)
4260 float crit
=critBase
->base
+ GetStat(STAT_AGILITY
)*critRatio
->ratio
;
4264 float Player::GetDodgeFromAgility()
4266 // Table for base dodge values
4267 float dodge_base
[MAX_CLASSES
] = {
4269 0.00652f
, // Paladin
4276 0.02011f
, // Warlock
4280 // Crit/agility to dodge/agility coefficient multipliers
4281 float crit_to_dodge
[MAX_CLASSES
] = {
4295 uint32 level
= getLevel();
4296 uint32 pclass
= getClass();
4298 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4300 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4301 GtChanceToMeleeCritEntry
const *dodgeRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4302 if (dodgeRatio
==NULL
|| pclass
> MAX_CLASSES
)
4305 float dodge
=dodge_base
[pclass
-1] + GetStat(STAT_AGILITY
) * dodgeRatio
->ratio
* crit_to_dodge
[pclass
-1];
4306 return dodge
*100.0f
;
4309 float Player::GetSpellCritFromIntellect()
4311 uint32 level
= getLevel();
4312 uint32 pclass
= getClass();
4314 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4316 GtChanceToSpellCritBaseEntry
const *critBase
= sGtChanceToSpellCritBaseStore
.LookupEntry(pclass
-1);
4317 GtChanceToSpellCritEntry
const *critRatio
= sGtChanceToSpellCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4318 if (critBase
==NULL
|| critRatio
==NULL
)
4321 float crit
=critBase
->base
+ GetStat(STAT_INTELLECT
)*critRatio
->ratio
;
4325 float Player::GetRatingCoefficient(CombatRating cr
) const
4327 uint32 level
= getLevel();
4329 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4331 GtCombatRatingsEntry
const *Rating
= sGtCombatRatingsStore
.LookupEntry(cr
*GT_MAX_LEVEL
+level
-1);
4333 return 1.0f
; // By default use minimum coefficient (not must be called)
4335 return Rating
->ratio
;
4338 float Player::GetRatingBonusValue(CombatRating cr
) const
4340 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
)) / GetRatingCoefficient(cr
);
4343 uint32
Player::GetMeleeCritDamageReduction(uint32 damage
) const
4345 float melee
= GetRatingBonusValue(CR_CRIT_TAKEN_MELEE
)*2.0f
;
4346 if (melee
>25.0f
) melee
= 25.0f
;
4347 return uint32 (melee
* damage
/100.0f
);
4350 uint32
Player::GetRangedCritDamageReduction(uint32 damage
) const
4352 float ranged
= GetRatingBonusValue(CR_CRIT_TAKEN_RANGED
)*2.0f
;
4353 if (ranged
>25.0f
) ranged
=25.0f
;
4354 return uint32 (ranged
* damage
/100.0f
);
4357 uint32
Player::GetSpellCritDamageReduction(uint32 damage
) const
4359 float spell
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
)*2.0f
;
4360 // In wow script resilience limited to 25%
4363 return uint32 (spell
* damage
/ 100.0f
);
4366 uint32
Player::GetDotDamageReduction(uint32 damage
) const
4368 float spellDot
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
);
4369 // Dot resilience not limited (limit it by 100%)
4370 if (spellDot
> 100.0f
)
4372 return uint32 (spellDot
* damage
/ 100.0f
);
4375 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType
) const
4380 return GetUInt32Value(PLAYER_EXPERTISE
) / 4.0f
;
4382 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE
) / 4.0f
;
4389 float Player::OCTRegenHPPerSpirit()
4391 uint32 level
= getLevel();
4392 uint32 pclass
= getClass();
4394 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4396 GtOCTRegenHPEntry
const *baseRatio
= sGtOCTRegenHPStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4397 GtRegenHPPerSptEntry
const *moreRatio
= sGtRegenHPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4398 if (baseRatio
==NULL
|| moreRatio
==NULL
)
4401 // Formula from PaperDollFrame script
4402 float spirit
= GetStat(STAT_SPIRIT
);
4403 float baseSpirit
= spirit
;
4404 if (baseSpirit
>50) baseSpirit
= 50;
4405 float moreSpirit
= spirit
- baseSpirit
;
4406 float regen
= baseSpirit
* baseRatio
->ratio
+ moreSpirit
* moreRatio
->ratio
;
4410 float Player::OCTRegenMPPerSpirit()
4412 uint32 level
= getLevel();
4413 uint32 pclass
= getClass();
4415 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4417 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4418 GtRegenMPPerSptEntry
const *moreRatio
= sGtRegenMPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4419 if (moreRatio
==NULL
)
4422 // Formula get from PaperDollFrame script
4423 float spirit
= GetStat(STAT_SPIRIT
);
4424 float regen
= spirit
* moreRatio
->ratio
;
4428 void Player::ApplyRatingMod(CombatRating cr
, int32 value
, bool apply
)
4430 ApplyModUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
, value
, apply
);
4432 float RatingCoeffecient
= GetRatingCoefficient(cr
);
4433 float RatingChange
= 0.0f
;
4435 bool affectStats
= CanModifyStats();
4439 case CR_WEAPON_SKILL
: // Implemented in Unit::RollMeleeOutcomeAgainst
4440 case CR_DEFENSE_SKILL
:
4441 UpdateDefenseBonusesMod();
4444 UpdateDodgePercentage();
4447 UpdateParryPercentage();
4450 UpdateBlockPercentage();
4453 RatingChange
= value
/ RatingCoeffecient
;
4454 m_modMeleeHitChance
+= apply
? RatingChange
: -RatingChange
;
4457 RatingChange
= value
/ RatingCoeffecient
;
4458 m_modRangedHitChance
+= apply
? RatingChange
: -RatingChange
;
4461 RatingChange
= value
/ RatingCoeffecient
;
4462 m_modSpellHitChance
+= apply
? RatingChange
: -RatingChange
;
4467 UpdateCritPercentage(BASE_ATTACK
);
4468 UpdateCritPercentage(OFF_ATTACK
);
4471 case CR_CRIT_RANGED
:
4473 UpdateCritPercentage(RANGED_ATTACK
);
4477 UpdateAllSpellCritChances();
4479 case CR_HIT_TAKEN_MELEE
: // Implemented in Unit::MeleeMissChanceCalc
4480 case CR_HIT_TAKEN_RANGED
:
4482 case CR_HIT_TAKEN_SPELL
: // Implemented in Unit::MagicSpellHitResult
4484 case CR_CRIT_TAKEN_MELEE
: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4485 case CR_CRIT_TAKEN_RANGED
:
4487 case CR_CRIT_TAKEN_SPELL
: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4489 case CR_HASTE_MELEE
:
4490 RatingChange
= value
/ RatingCoeffecient
;
4491 ApplyAttackTimePercentMod(BASE_ATTACK
,RatingChange
,apply
);
4492 ApplyAttackTimePercentMod(OFF_ATTACK
,RatingChange
,apply
);
4494 case CR_HASTE_RANGED
:
4495 RatingChange
= value
/ RatingCoeffecient
;
4496 ApplyAttackTimePercentMod(RANGED_ATTACK
, RatingChange
, apply
);
4498 case CR_HASTE_SPELL
:
4499 RatingChange
= value
/ RatingCoeffecient
;
4500 ApplyCastTimePercentMod(RatingChange
,apply
);
4502 case CR_WEAPON_SKILL_MAINHAND
: // Implemented in Unit::RollMeleeOutcomeAgainst
4503 case CR_WEAPON_SKILL_OFFHAND
:
4504 case CR_WEAPON_SKILL_RANGED
:
4509 UpdateExpertise(BASE_ATTACK
);
4510 UpdateExpertise(OFF_ATTACK
);
4516 void Player::SetRegularAttackTime()
4518 for(int i
= 0; i
< MAX_ATTACK
; ++i
)
4520 Item
*tmpitem
= GetWeaponForAttack(WeaponAttackType(i
));
4521 if(tmpitem
&& !tmpitem
->IsBroken())
4523 ItemPrototype
const *proto
= tmpitem
->GetProto();
4525 SetAttackTime(WeaponAttackType(i
), proto
->Delay
);
4527 SetAttackTime(WeaponAttackType(i
), BASE_ATTACK_TIME
);
4532 //skill+step, checking for max value
4533 bool Player::UpdateSkill(uint32 skill_id
, uint32 step
)
4539 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4540 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill_id
)
4543 if(i
>=PLAYER_MAX_SKILLS
)
4546 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4547 uint32 value
= SKILL_VALUE(data
);
4548 uint32 max
= SKILL_MAX(data
);
4550 if ((!max
) || (!value
) || (value
>= max
))
4553 if (value
*512 < max
*urand(0,512))
4555 uint32 new_value
= value
+step
;
4559 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,max
));
4566 inline int SkillGainChance(uint32 SkillValue
, uint32 GrayLevel
, uint32 GreenLevel
, uint32 YellowLevel
)
4568 if ( SkillValue
>= GrayLevel
)
4569 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREY
)*10;
4570 if ( SkillValue
>= GreenLevel
)
4571 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREEN
)*10;
4572 if ( SkillValue
>= YellowLevel
)
4573 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_YELLOW
)*10;
4574 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_ORANGE
)*10;
4577 bool Player::UpdateCraftSkill(uint32 spellid
)
4579 sLog
.outDebug("UpdateCraftSkill spellid %d", spellid
);
4581 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spellid
);
4582 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spellid
);
4584 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
4586 if(_spell_idx
->second
->skillId
)
4588 uint32 SkillValue
= GetPureSkillValue(_spell_idx
->second
->skillId
);
4590 // Alchemy Discoveries here
4591 SpellEntry
const* spellEntry
= sSpellStore
.LookupEntry(spellid
);
4592 if(spellEntry
&& spellEntry
->Mechanic
==MECHANIC_DISCOVERY
)
4594 if(uint32 discoveredSpell
= GetSkillDiscoverySpell(_spell_idx
->second
->skillId
, spellid
, this))
4595 learnSpell(discoveredSpell
);
4598 uint32 craft_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_CRAFTING
);
4600 return UpdateSkillPro(_spell_idx
->second
->skillId
, SkillGainChance(SkillValue
,
4601 _spell_idx
->second
->max_value
,
4602 (_spell_idx
->second
->max_value
+ _spell_idx
->second
->min_value
)/2,
4603 _spell_idx
->second
->min_value
),
4610 bool Player::UpdateGatherSkill(uint32 SkillId
, uint32 SkillValue
, uint32 RedLevel
, uint32 Multiplicator
)
4612 sLog
.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId
, SkillValue
, RedLevel
);
4614 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
4616 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4619 case SKILL_HERBALISM
:
4620 case SKILL_LOCKPICKING
:
4621 case SKILL_JEWELCRAFTING
:
4622 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4623 case SKILL_SKINNING
:
4624 if( sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)==0)
4625 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4627 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)), gathering_skill_gain
);
4629 if (sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)==0)
4630 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4632 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)),gathering_skill_gain
);
4637 bool Player::UpdateFishingSkill()
4639 sLog
.outDebug("UpdateFishingSkill");
4641 uint32 SkillValue
= GetPureSkillValue(SKILL_FISHING
);
4643 int32 chance
= SkillValue
< 75 ? 100 : 2500/(SkillValue
-50);
4645 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
4647 return UpdateSkillPro(SKILL_FISHING
,chance
*10,gathering_skill_gain
);
4650 bool Player::UpdateSkillPro(uint16 SkillId
, int32 Chance
, uint32 step
)
4652 sLog
.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId
, Chance
/10.0);
4656 if(Chance
<= 0) // speedup in 0 chance case
4658 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
4663 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4664 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i
))) == SkillId
) break;
4665 if ( i
>= PLAYER_MAX_SKILLS
)
4668 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4669 uint16 SkillValue
= SKILL_VALUE(data
);
4670 uint16 MaxValue
= SKILL_MAX(data
);
4672 if ( !MaxValue
|| !SkillValue
|| SkillValue
>= MaxValue
)
4675 int32 Roll
= irand(1,1000);
4677 if ( Roll
<= Chance
)
4679 uint32 new_value
= SkillValue
+step
;
4680 if(new_value
> MaxValue
)
4681 new_value
= MaxValue
;
4683 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,MaxValue
));
4684 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance
/10.0);
4688 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
4692 void Player::UpdateWeaponSkill (WeaponAttackType attType
)
4694 // no skill gain in pvp
4695 Unit
*pVictim
= getVictim();
4696 if(pVictim
&& pVictim
->GetTypeId() == TYPEID_PLAYER
)
4700 return; // always maximized SKILL_FERAL_COMBAT in fact
4702 if(m_form
== FORM_TREE
)
4703 return; // use weapon but not skill up
4705 uint32 weapon_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_WEAPON
);
4711 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
4714 UpdateSkill(SKILL_UNARMED
,weapon_skill_gain
);
4715 else if(tmpitem
->GetProto()->SubClass
!= ITEM_SUBCLASS_WEAPON_FISHING_POLE
)
4716 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
4722 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
4724 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
4728 UpdateAllCritPercentages();
4731 void Player::UpdateCombatSkills(Unit
*pVictim
, WeaponAttackType attType
, MeleeHitOutcome outcome
, bool defence
)
4735 case MELEE_HIT_CRIT
:
4736 case MELEE_HIT_DODGE
:
4737 case MELEE_HIT_PARRY
:
4738 case MELEE_HIT_BLOCK
:
4739 case MELEE_HIT_BLOCK_CRIT
:
4746 uint32 plevel
= getLevel(); // if defense than pVictim == attacker
4747 uint32 greylevel
= MaNGOS::XP::GetGrayLevel(plevel
);
4748 uint32 moblevel
= pVictim
->getLevelForTarget(this);
4749 if(moblevel
< greylevel
)
4752 if (moblevel
> plevel
+ 5)
4753 moblevel
= plevel
+ 5;
4755 uint32 lvldif
= moblevel
- greylevel
;
4759 uint32 skilldif
= 5 * plevel
- (defence
? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType
));
4763 float chance
= float(3 * lvldif
* skilldif
) / plevel
;
4766 if(getClass() == CLASS_WARRIOR
|| getClass() == CLASS_ROGUE
)
4767 chance
*= 0.1f
* GetStat(STAT_INTELLECT
);
4770 chance
= chance
< 1.0f
? 1.0f
: chance
; //minimum chance to increase skill is 1%
4772 if(roll_chance_f(chance
))
4777 UpdateWeaponSkill(attType
);
4783 void Player::ModifySkillBonus(uint32 skillid
,int32 val
, bool talent
)
4785 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4786 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skillid
)
4788 uint32 bonus_val
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
4789 int16 temp_bonus
= SKILL_TEMP_BONUS(bonus_val
);
4790 int16 perm_bonus
= SKILL_PERM_BONUS(bonus_val
);
4792 if(talent
) // permanent bonus stored in high part
4793 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
,perm_bonus
+val
));
4794 else // temporary/item bonus stored in low part
4795 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
+val
,perm_bonus
));
4800 void Player::UpdateMaxSkills()
4802 uint16 maxconfskill
= sWorld
.GetConfigMaxSkillValue();
4804 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4805 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
4807 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
4809 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(pskill
);
4813 if(GetSkillRangeType(pSkill
,false) != SKILL_RANGE_LEVEL
)
4816 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4817 uint32 max
= SKILL_MAX(data
);
4818 uint32 val
= SKILL_VALUE(data
);
4820 // update only level dependent max skill values
4821 if(max
!=1 && max
!= maxconfskill
)
4823 uint32 max_Skill
= GetMaxSkillValueForLevel();
4824 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(val
,max_Skill
));
4829 void Player::UpdateSkillsToMaxSkillsForLevel()
4831 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4832 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
4834 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
4835 if( IsProfessionSkill(pskill
) || pskill
== SKILL_RIDING
)
4837 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4839 uint32 max
= SKILL_MAX(data
);
4842 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(max
,max
));
4844 if(pskill
== SKILL_DEFENSE
)
4845 UpdateDefenseBonusesMod();
4849 // This functions sets a skill line value (and adds if doesn't exist yet)
4850 // To "remove" a skill line, set it's values to zero
4851 void Player::SetSkill(uint32 id
, uint16 currVal
, uint16 maxVal
)
4857 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4858 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == id
) break;
4860 if(i
<PLAYER_MAX_SKILLS
) //has skill
4863 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
4866 // clear skill fields
4867 SetUInt32Value(PLAYER_SKILL_INDEX(i
),0);
4868 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),0);
4869 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
4871 // remove spells that depend on this skill when removing the skill
4872 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(), next
= m_spells
.begin(); itr
!= m_spells
.end(); itr
= next
)
4875 if(itr
->second
->state
== PLAYERSPELL_REMOVED
)
4878 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(itr
->first
);
4879 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(itr
->first
);
4881 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
4883 if (_spell_idx
->second
->skillId
== id
)
4885 // this may remove more than one spell (dependants)
4886 removeSpell(itr
->first
);
4887 next
= m_spells
.begin();
4894 else if(currVal
) //add
4896 for (i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4897 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
4899 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
4902 sLog
.outError("Skill not found in SkillLineStore: skill #%u", id
);
4905 // enable unlearn button for primary professions only
4906 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
4907 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
4909 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
4910 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
4912 // apply skill bonuses
4913 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
4915 // temporary bonuses
4916 AuraList
const& mModSkill
= GetAurasByType(SPELL_AURA_MOD_SKILL
);
4917 for(AuraList::const_iterator i
= mModSkill
.begin(); i
!= mModSkill
.end(); ++i
)
4918 if ((*i
)->GetModifier()->m_miscvalue
== int32(id
))
4919 (*i
)->ApplyModifier(true);
4921 // permanent bonuses
4922 AuraList
const& mModSkillTalent
= GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT
);
4923 for(AuraList::const_iterator i
= mModSkillTalent
.begin(); i
!= mModSkillTalent
.end(); ++i
)
4924 if ((*i
)->GetModifier()->m_miscvalue
== int32(id
))
4925 (*i
)->ApplyModifier(true);
4927 // Learn all spells for skill
4928 learnSkillRewardedSpells(id
);
4934 bool Player::HasSkill(uint32 skill
) const
4936 if(!skill
)return false;
4937 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4939 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
4947 uint16
Player::GetSkillValue(uint32 skill
) const
4952 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4954 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
4956 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
4958 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
4959 result
+= SKILL_TEMP_BONUS(bonus
);
4960 result
+= SKILL_PERM_BONUS(bonus
);
4961 return result
< 0 ? 0 : result
;
4967 uint16
Player::GetMaxSkillValue(uint32 skill
) const
4970 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4972 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
4974 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
4976 int32 result
= int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
4977 result
+= SKILL_TEMP_BONUS(bonus
);
4978 result
+= SKILL_PERM_BONUS(bonus
);
4979 return result
< 0 ? 0 : result
;
4985 uint16
Player::GetPureMaxSkillValue(uint32 skill
) const
4988 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4990 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
4992 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
4998 uint16
Player::GetBaseSkillValue(uint32 skill
) const
5001 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5003 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5005 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5006 result
+= SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5007 return result
< 0 ? 0 : result
;
5013 uint16
Player::GetPureSkillValue(uint32 skill
) const
5016 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5018 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5020 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5026 int16
Player::GetSkillTempBonusValue(uint32 skill
) const
5031 for (int i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
5033 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5035 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5042 void Player::SendInitialActionButtons()
5044 sLog
.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5046 WorldPacket
data(SMSG_ACTION_BUTTONS
, (MAX_ACTION_BUTTONS
*4));
5047 for(int button
= 0; button
< MAX_ACTION_BUTTONS
; ++button
)
5049 ActionButtonList::const_iterator itr
= m_actionButtons
.find(button
);
5050 if(itr
!= m_actionButtons
.end() && itr
->second
.uState
!= ACTIONBUTTON_DELETED
)
5052 data
<< uint16(itr
->second
.action
);
5053 data
<< uint8(itr
->second
.misc
);
5054 data
<< uint8(itr
->second
.type
);
5062 GetSession()->SendPacket( &data
);
5063 sLog
.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5066 void Player::addActionButton(const uint8 button
, const uint16 action
, const uint8 type
, const uint8 misc
)
5068 if(button
>= MAX_ACTION_BUTTONS
)
5070 sLog
.outError( "Action %u not added into button %u for player %s: button must be < 132", action
, button
, GetName() );
5074 // check cheating with adding non-known spells to action bar
5075 if(type
==ACTION_BUTTON_SPELL
)
5077 if(!sSpellStore
.LookupEntry(action
))
5079 sLog
.outError( "Action %u not added into button %u for player %s: spell not exist", action
, button
, GetName() );
5083 if(!HasSpell(action
))
5085 sLog
.outError( "Action %u not added into button %u for player %s: player don't known this spell", action
, button
, GetName() );
5090 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5092 if (buttonItr
==m_actionButtons
.end())
5093 { // just add new button
5094 m_actionButtons
[button
] = ActionButton(action
,type
,misc
);
5097 { // change state of current button
5098 ActionButtonUpdateState uState
= buttonItr
->second
.uState
;
5099 buttonItr
->second
= ActionButton(action
,type
,misc
);
5100 if (uState
!= ACTIONBUTTON_NEW
) buttonItr
->second
.uState
= ACTIONBUTTON_CHANGED
;
5103 sLog
.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action
, button
);
5106 void Player::removeActionButton(uint8 button
)
5108 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5109 if (buttonItr
==m_actionButtons
.end())
5112 if(buttonItr
->second
.uState
==ACTIONBUTTON_NEW
)
5113 m_actionButtons
.erase(buttonItr
); // new and not saved
5115 buttonItr
->second
.uState
= ACTIONBUTTON_DELETED
; // saved, will deleted at next save
5117 sLog
.outDetail( "Action Button '%u' Removed from Player '%u'", button
, GetGUIDLow() );
5120 void Player::SetDontMove(bool dontMove
)
5122 m_dontMove
= dontMove
;
5125 bool Player::SetPosition(float x
, float y
, float z
, float orientation
, bool teleport
)
5127 // prevent crash when a bad coord is sent by the client
5128 if(!MaNGOS::IsValidMapCoord(x
,y
,z
,orientation
))
5130 sLog
.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x
,y
,z
,orientation
,teleport
,GetGUIDLow());
5134 Map
*m
= MapManager::Instance().GetMap(GetMapId(), this);
5136 const float old_x
= GetPositionX();
5137 const float old_y
= GetPositionY();
5138 const float old_z
= GetPositionZ();
5139 const float old_r
= GetOrientation();
5141 if( teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
|| old_r
!= orientation
)
5143 if (teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
)
5144 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE
| AURA_INTERRUPT_FLAG_TURNING
);
5146 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING
);
5148 // move and update visible state if need
5149 m
->PlayerRelocation(this, x
, y
, z
, orientation
);
5151 // reread after Map::Relocation
5152 m
= MapManager::Instance().GetMap(GetMapId(), this);
5158 // code block for underwater state update
5159 UpdateUnderwaterState(m
, x
, y
, z
);
5161 CheckExploreSystem();
5165 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION
);
5170 void Player::SaveRecallPosition()
5172 m_recallMap
= GetMapId();
5173 m_recallX
= GetPositionX();
5174 m_recallY
= GetPositionY();
5175 m_recallZ
= GetPositionZ();
5176 m_recallO
= GetOrientation();
5179 void Player::SendMessageToSet(WorldPacket
*data
, bool self
)
5181 MapManager::Instance().GetMap(GetMapId(), this)->MessageBroadcast(this, data
, self
);
5184 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
)
5186 MapManager::Instance().GetMap(GetMapId(), this)->MessageDistBroadcast(this, data
, dist
, self
);
5189 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
, bool own_team_only
)
5191 MapManager::Instance().GetMap(GetMapId(), this)->MessageDistBroadcast(this, data
, dist
, self
,own_team_only
);
5194 void Player::SendDirectMessage(WorldPacket
*data
)
5196 GetSession()->SendPacket(data
);
5199 void Player::CheckExploreSystem()
5207 uint16 areaFlag
=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY());
5208 if(areaFlag
==0xffff)
5210 int offset
= areaFlag
/ 32;
5214 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 < 64 ).",areaFlag
,GetPositionX(),GetPositionY(),offset
,offset
);
5218 uint32 val
= (uint32
)(1 << (areaFlag
% 32));
5219 uint32 currFields
= GetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
);
5221 if( !(currFields
& val
) )
5223 SetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
, (uint32
)(currFields
| val
));
5225 AreaTableEntry
const *p
= GetAreaEntryByAreaFlagAndMap(areaFlag
,GetMapId());
5228 sLog
.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5230 else if(p
->area_level
> 0)
5232 uint32 area
= p
->ID
;
5233 if (getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
5235 SendExplorationExperience(area
,0);
5239 int32 diff
= int32(getLevel()) - p
->area_level
;
5243 XP
= uint32(objmgr
.GetBaseXP(getLevel()+5)*sWorld
.getRate(RATE_XP_EXPLORE
));
5247 int32 exploration_percent
= (100-((diff
-5)*5));
5248 if (exploration_percent
> 100)
5249 exploration_percent
= 100;
5250 else if (exploration_percent
< 0)
5251 exploration_percent
= 0;
5253 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*exploration_percent
/100*sWorld
.getRate(RATE_XP_EXPLORE
));
5257 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*sWorld
.getRate(RATE_XP_EXPLORE
));
5261 SendExplorationExperience(area
,XP
);
5263 sLog
.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area
);
5268 uint32
Player::TeamForRace(uint8 race
)
5270 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5273 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5277 switch(rEntry
->TeamID
)
5279 case 7: return ALLIANCE
;
5280 case 1: return HORDE
;
5283 sLog
.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race
),rEntry
->TeamID
);
5287 uint32
Player::getFactionForRace(uint8 race
)
5289 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5292 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5296 return rEntry
->FactionID
;
5299 void Player::setFactionForRace(uint8 race
)
5301 m_team
= TeamForRace(race
);
5302 setFaction( getFactionForRace(race
) );
5305 void Player::UpdateReputation() const
5307 sLog
.outDetail( "WORLD: Player::UpdateReputation" );
5309 for(FactionStateList::const_iterator itr
= m_factions
.begin(); itr
!= m_factions
.end(); ++itr
)
5311 SendFactionState(&(itr
->second
));
5315 void Player::SendFactionState(FactionState
const* faction
) const
5317 if(faction
->Flags
& FACTION_FLAG_VISIBLE
) //If faction is visible then update it
5319 WorldPacket
data(SMSG_SET_FACTION_STANDING
, (16)); // last check 2.4.0
5320 data
<< (float) 0; // unk 2.4.0
5321 data
<< (uint32
) 1; // count
5323 data
<< (uint32
) faction
->ReputationListID
;
5324 data
<< (uint32
) faction
->Standing
;
5326 GetSession()->SendPacket(&data
);
5330 void Player::SendInitialReputations()
5332 WorldPacket
data(SMSG_INITIALIZE_FACTIONS
, (4+128*5));
5333 data
<< uint32 (0x00000080);
5337 for (FactionStateList::const_iterator itr
= m_factions
.begin(); itr
!= m_factions
.end(); itr
++)
5339 // fill in absent fields
5340 for (; a
!= itr
->first
; a
++)
5342 data
<< uint8 (0x00);
5343 data
<< uint32 (0x00000000);
5346 // fill in encountered data
5347 data
<< uint8 (itr
->second
.Flags
);
5348 data
<< uint32 (itr
->second
.Standing
);
5353 // fill in absent fields
5354 for (; a
!= 128; a
++)
5356 data
<< uint8 (0x00);
5357 data
<< uint32 (0x00000000);
5360 GetSession()->SendPacket(&data
);
5363 FactionState
const* Player::GetFactionState( FactionEntry
const* factionEntry
) const
5365 FactionStateList::const_iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5366 if (itr
!= m_factions
.end())
5367 return &itr
->second
;
5372 void Player::SetFactionAtWar(FactionState
* faction
, bool atWar
)
5374 // not allow declare war to own faction
5375 if(atWar
&& (faction
->Flags
& FACTION_FLAG_PEACE_FORCED
) )
5379 if(((faction
->Flags
& FACTION_FLAG_AT_WAR
) != 0) == atWar
)
5383 faction
->Flags
|= FACTION_FLAG_AT_WAR
;
5385 faction
->Flags
&= ~FACTION_FLAG_AT_WAR
;
5387 faction
->Changed
= true;
5390 void Player::SetFactionInactive(FactionState
* faction
, bool inactive
)
5392 // always invisible or hidden faction can't be inactive
5393 if(inactive
&& ((faction
->Flags
& (FACTION_FLAG_INVISIBLE_FORCED
|FACTION_FLAG_HIDDEN
)) || !(faction
->Flags
& FACTION_FLAG_VISIBLE
) ) )
5397 if(((faction
->Flags
& FACTION_FLAG_INACTIVE
) != 0) == inactive
)
5401 faction
->Flags
|= FACTION_FLAG_INACTIVE
;
5403 faction
->Flags
&= ~FACTION_FLAG_INACTIVE
;
5405 faction
->Changed
= true;
5408 void Player::SetFactionVisibleForFactionTemplateId(uint32 FactionTemplateId
)
5410 FactionTemplateEntry
const*factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5412 if(!factionTemplateEntry
)
5415 SetFactionVisibleForFactionId(factionTemplateEntry
->faction
);
5418 void Player::SetFactionVisibleForFactionId(uint32 FactionId
)
5420 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(FactionId
);
5424 if(factionEntry
->reputationListID
< 0)
5427 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5428 if (itr
== m_factions
.end())
5431 SetFactionVisible(&itr
->second
);
5434 void Player::SetFactionVisible(FactionState
* faction
)
5436 // always invisible or hidden faction can't be make visible
5437 if(faction
->Flags
& (FACTION_FLAG_INVISIBLE_FORCED
|FACTION_FLAG_HIDDEN
))
5441 if(faction
->Flags
& FACTION_FLAG_VISIBLE
)
5444 faction
->Flags
|= FACTION_FLAG_VISIBLE
;
5445 faction
->Changed
= true;
5447 if(!m_session
->PlayerLoading())
5449 // make faction visible in reputation list at client
5450 WorldPacket
data(SMSG_SET_FACTION_VISIBLE
, 4);
5451 data
<< faction
->ReputationListID
;
5452 GetSession()->SendPacket(&data
);
5456 void Player::SetInitialFactions()
5458 for(unsigned int i
= 1; i
< sFactionStore
.GetNumRows(); i
++)
5460 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(i
);
5462 if( factionEntry
&& (factionEntry
->reputationListID
>= 0))
5464 FactionState newFaction
;
5465 newFaction
.ID
= factionEntry
->ID
;
5466 newFaction
.ReputationListID
= factionEntry
->reputationListID
;
5467 newFaction
.Standing
= 0;
5468 newFaction
.Flags
= GetDefaultReputationFlags(factionEntry
);
5469 newFaction
.Changed
= true;
5471 m_factions
[newFaction
.ReputationListID
] = newFaction
;
5476 uint32
Player::GetDefaultReputationFlags(const FactionEntry
*factionEntry
) const
5481 uint32 raceMask
= getRaceMask();
5482 uint32 classMask
= getClassMask();
5483 for (int i
=0; i
< 4; i
++)
5485 if( (factionEntry
->BaseRepRaceMask
[i
] & raceMask
) &&
5486 (factionEntry
->BaseRepClassMask
[i
]==0 ||
5487 (factionEntry
->BaseRepClassMask
[i
] & classMask
) ) )
5488 return factionEntry
->ReputationFlags
[i
];
5493 int32
Player::GetBaseReputation(const FactionEntry
*factionEntry
) const
5498 uint32 raceMask
= getRaceMask();
5499 uint32 classMask
= getClassMask();
5500 for (int i
=0; i
< 4; i
++)
5502 if( (factionEntry
->BaseRepRaceMask
[i
] & raceMask
) &&
5503 (factionEntry
->BaseRepClassMask
[i
]==0 ||
5504 (factionEntry
->BaseRepClassMask
[i
] & classMask
) ) )
5505 return factionEntry
->BaseRepValue
[i
];
5508 // in faction.dbc exist factions with (RepListId >=0, listed in character reputation list) with all BaseRepRaceMask[i]==0
5512 int32
Player::GetReputation(uint32 faction_id
) const
5514 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(faction_id
);
5518 sLog
.outError("Player::GetReputation: Can't get reputation of %s for unknown faction (faction template id) #%u.",GetName(), faction_id
);
5522 return GetReputation(factionEntry
);
5525 int32
Player::GetReputation(const FactionEntry
*factionEntry
) const
5527 // Faction without recorded reputation. Just ignore.
5531 FactionStateList::const_iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5532 if (itr
!= m_factions
.end())
5533 return GetBaseReputation(factionEntry
) + itr
->second
.Standing
;
5538 ReputationRank
Player::GetReputationRank(uint32 faction
) const
5540 FactionEntry
const*factionEntry
= sFactionStore
.LookupEntry(faction
);
5542 return MIN_REPUTATION_RANK
;
5544 return GetReputationRank(factionEntry
);
5547 ReputationRank
Player::ReputationToRank(int32 standing
) const
5549 int32 Limit
= Reputation_Cap
+ 1;
5550 for (int i
= MAX_REPUTATION_RANK
-1; i
>= MIN_REPUTATION_RANK
; --i
)
5552 Limit
-= ReputationRank_Length
[i
];
5553 if (standing
>= Limit
)
5554 return ReputationRank(i
);
5556 return MIN_REPUTATION_RANK
;
5559 ReputationRank
Player::GetReputationRank(const FactionEntry
*factionEntry
) const
5561 int32 Reputation
= GetReputation(factionEntry
);
5562 return ReputationToRank(Reputation
);
5565 ReputationRank
Player::GetBaseReputationRank(const FactionEntry
*factionEntry
) const
5567 int32 Reputation
= GetBaseReputation(factionEntry
);
5568 return ReputationToRank(Reputation
);
5571 bool Player::ModifyFactionReputation(uint32 FactionTemplateId
, int32 DeltaReputation
)
5573 FactionTemplateEntry
const* factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5575 if(!factionTemplateEntry
)
5577 sLog
.outError("Player::ModifyFactionReputation: Can't update reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId
);
5581 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(factionTemplateEntry
->faction
);
5583 // Faction without recorded reputation. Just ignore.
5587 return ModifyFactionReputation(factionEntry
, DeltaReputation
);
5590 bool Player::ModifyFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5592 SimpleFactionsList
const* flist
= GetFactionTeamList(factionEntry
->ID
);
5596 for (SimpleFactionsList::const_iterator itr
= flist
->begin();itr
!= flist
->end();++itr
)
5598 FactionEntry
const *factionEntryCalc
= sFactionStore
.LookupEntry(*itr
);
5599 if(factionEntryCalc
)
5600 res
= ModifyOneFactionReputation(factionEntryCalc
, standing
);
5605 return ModifyOneFactionReputation(factionEntry
, standing
);
5608 bool Player::ModifyOneFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5610 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5611 if (itr
!= m_factions
.end())
5613 int32 BaseRep
= GetBaseReputation(factionEntry
);
5614 int32 new_rep
= BaseRep
+ itr
->second
.Standing
+ standing
;
5616 if (new_rep
> Reputation_Cap
)
5617 new_rep
= Reputation_Cap
;
5619 if (new_rep
< Reputation_Bottom
)
5620 new_rep
= Reputation_Bottom
;
5622 if(ReputationToRank(new_rep
) <= REP_HOSTILE
)
5623 SetFactionAtWar(&itr
->second
,true);
5625 itr
->second
.Standing
= new_rep
- BaseRep
;
5626 itr
->second
.Changed
= true;
5628 SetFactionVisible(&itr
->second
);
5630 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
5632 if(uint32 questid
= GetQuestSlotQuestId(i
))
5634 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
5635 if( qInfo
&& qInfo
->GetRepObjectiveFaction() == factionEntry
->ID
)
5637 QuestStatusData
& q_status
= mQuestStatus
[questid
];
5638 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
5640 if(GetReputation(factionEntry
) >= qInfo
->GetRepObjectiveValue())
5641 if ( CanCompleteQuest( questid
) )
5642 CompleteQuest( questid
);
5644 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
5646 if(GetReputation(factionEntry
) < qInfo
->GetRepObjectiveValue())
5647 IncompleteQuest( questid
);
5653 SendFactionState(&(itr
->second
));
5660 bool Player::SetFactionReputation(uint32 FactionTemplateId
, int32 standing
)
5662 FactionTemplateEntry
const* factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5664 if(!factionTemplateEntry
)
5666 sLog
.outError("Player::SetFactionReputation: Can't set reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId
);
5670 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(factionTemplateEntry
->faction
);
5672 // Faction without recorded reputation. Just ignore.
5676 return SetFactionReputation(factionEntry
, standing
);
5679 bool Player::SetFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5681 SimpleFactionsList
const* flist
= GetFactionTeamList(factionEntry
->ID
);
5685 for (SimpleFactionsList::const_iterator itr
= flist
->begin();itr
!= flist
->end();++itr
)
5687 FactionEntry
const *factionEntryCalc
= sFactionStore
.LookupEntry(*itr
);
5688 if(factionEntryCalc
)
5689 res
= SetOneFactionReputation(factionEntryCalc
, standing
);
5694 return SetOneFactionReputation(factionEntry
, standing
);
5697 bool Player::SetOneFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5699 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5700 if (itr
!= m_factions
.end())
5702 if (standing
> Reputation_Cap
)
5703 standing
= Reputation_Cap
;
5705 if (standing
< Reputation_Bottom
)
5706 standing
= Reputation_Bottom
;
5708 int32 BaseRep
= GetBaseReputation(factionEntry
);
5709 itr
->second
.Standing
= standing
- BaseRep
;
5710 itr
->second
.Changed
= true;
5712 SetFactionVisible(&itr
->second
);
5714 if(ReputationToRank(standing
) <= REP_HOSTILE
)
5715 SetFactionAtWar(&itr
->second
,true);
5717 SendFactionState(&(itr
->second
));
5723 //Calculate total reputation percent player gain with quest/creature level
5724 int32
Player::CalculateReputationGain(uint32 creatureOrQuestLevel
, int32 rep
, bool for_quest
)
5726 // for grey creature kill received 20%, in other case 100.
5727 int32 percent
= (!for_quest
&& (creatureOrQuestLevel
<= MaNGOS::XP::GetGrayLevel(getLevel()))) ? 20 : 100;
5729 int32 repMod
= GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN
);
5731 percent
+= rep
> 0 ? repMod
: -repMod
;
5736 return int32(sWorld
.getRate(RATE_REPUTATION_GAIN
)*rep
*percent
/100);
5739 //Calculates how many reputation points player gains in victim's enemy factions
5740 void Player::RewardReputation(Unit
*pVictim
, float rate
)
5742 if(!pVictim
|| pVictim
->GetTypeId() == TYPEID_PLAYER
)
5745 ReputationOnKillEntry
const* Rep
= objmgr
.GetReputationOnKilEntry(((Creature
*)pVictim
)->GetCreatureInfo()->Entry
);
5750 if(Rep
->repfaction1
&& (!Rep
->team_dependent
|| GetTeam()==ALLIANCE
))
5752 int32 donerep1
= CalculateReputationGain(pVictim
->getLevel(),Rep
->repvalue1
,false);
5753 donerep1
= int32(donerep1
*rate
);
5754 FactionEntry
const *factionEntry1
= sFactionStore
.LookupEntry(Rep
->repfaction1
);
5755 uint32 current_reputation_rank1
= GetReputationRank(factionEntry1
);
5756 if(factionEntry1
&& current_reputation_rank1
<= Rep
->reputation_max_cap1
)
5757 ModifyFactionReputation(factionEntry1
, donerep1
);
5759 // Wiki: Team factions value divided by 2
5760 if(Rep
->is_teamaward1
)
5762 FactionEntry
const *team1_factionEntry
= sFactionStore
.LookupEntry(factionEntry1
->team
);
5763 if(team1_factionEntry
)
5764 ModifyFactionReputation(team1_factionEntry
, donerep1
/ 2);
5768 if(Rep
->repfaction2
&& (!Rep
->team_dependent
|| GetTeam()==HORDE
))
5770 int32 donerep2
= CalculateReputationGain(pVictim
->getLevel(),Rep
->repvalue2
,false);
5771 donerep2
= int32(donerep2
*rate
);
5772 FactionEntry
const *factionEntry2
= sFactionStore
.LookupEntry(Rep
->repfaction2
);
5773 uint32 current_reputation_rank2
= GetReputationRank(factionEntry2
);
5774 if(factionEntry2
&& current_reputation_rank2
<= Rep
->reputation_max_cap2
)
5775 ModifyFactionReputation(factionEntry2
, donerep2
);
5777 // Wiki: Team factions value divided by 2
5778 if(Rep
->is_teamaward2
)
5780 FactionEntry
const *team2_factionEntry
= sFactionStore
.LookupEntry(factionEntry2
->team
);
5781 if(team2_factionEntry
)
5782 ModifyFactionReputation(team2_factionEntry
, donerep2
/ 2);
5787 //Calculate how many reputation points player gain with the quest
5788 void Player::RewardReputation(Quest
const *pQuest
)
5790 // quest reputation reward/loss
5791 for(int i
= 0; i
< QUEST_REPUTATIONS_COUNT
; ++i
)
5793 if(pQuest
->RewRepFaction
[i
] && pQuest
->RewRepValue
[i
] )
5795 int32 rep
= CalculateReputationGain(pQuest
->GetQuestLevel(),pQuest
->RewRepValue
[i
],true);
5796 FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(pQuest
->RewRepFaction
[i
]);
5798 ModifyFactionReputation(factionEntry
, rep
);
5802 // TODO: implement reputation spillover
5805 void Player::UpdateArenaFields(void)
5807 /* arena calcs go here */
5810 void Player::UpdateHonorFields()
5812 /// called when rewarding honor and at each save
5813 uint64 now
= time(NULL
);
5814 uint64 today
= uint64(time(NULL
) / DAY
) * DAY
;
5816 if(m_lastHonorUpdateTime
< today
)
5818 uint64 yesterday
= today
- DAY
;
5820 uint16 kills_today
= PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS
));
5822 // update yesterday's contribution
5823 if(m_lastHonorUpdateTime
>= yesterday
)
5825 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
));
5827 // this is the first update today, reset today's contribution
5828 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, 0);
5829 SetUInt32Value(PLAYER_FIELD_KILLS
, MAKE_PAIR32(0,kills_today
));
5833 // no honor/kills yesterday or today, reset
5834 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0);
5835 SetUInt32Value(PLAYER_FIELD_KILLS
, 0);
5839 m_lastHonorUpdateTime
= now
;
5842 ///Calculate the amount of honor gained based on the victim
5843 ///and the size of the group for which the honor is divided
5844 ///An exact honor value can also be given (overriding the calcs)
5845 bool Player::RewardHonor(Unit
*uVictim
, uint32 groupsize
, float honor
)
5847 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5848 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE
))
5851 uint64 victim_guid
= 0;
5852 uint32 victim_rank
= 0;
5853 time_t now
= time(NULL
);
5855 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5856 UpdateHonorFields();
5860 if(!uVictim
|| uVictim
== this || uVictim
->HasAuraType(SPELL_AURA_NO_PVP_CREDIT
))
5863 victim_guid
= uVictim
->GetGUID();
5865 if( uVictim
->GetTypeId() == TYPEID_PLAYER
)
5867 Player
*pVictim
= (Player
*)uVictim
;
5869 if( GetTeam() == pVictim
->GetTeam() && !sWorld
.IsFFAPvPRealm() )
5872 float f
= 1; //need for total kills (?? need more info)
5874 uint32 k_level
= getLevel();
5875 uint32 v_level
= pVictim
->getLevel();
5878 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
5880 // [1..14] Alliance honor titles and player name
5881 // [15..28] Horde honor titles and player name
5882 // [29..38] Other title and player name
5884 uint32 victim_title
= pVictim
->GetUInt32Value(PLAYER_CHOSEN_TITLE
);
5885 // Get Killer titles, CharTitlesEntry::bit_index
5887 // title[1..14] -> rank[5..18]
5888 // title[15..28] -> rank[5..18]
5889 // title[other] -> 0
5890 if (victim_title
== 0)
5891 victim_guid
= 0; // Don't show HK: <rank> message, only log.
5892 else if (victim_title
< 15)
5893 victim_rank
= victim_title
+ 4;
5894 else if (victim_title
< 29)
5895 victim_rank
= victim_title
- 14 + 4;
5897 victim_guid
= 0; // Don't show HK: <rank> message, only log.
5902 else if( k_level
<= 39 )
5903 k_grey
= k_level
- 5 - k_level
/10;
5905 k_grey
= k_level
- 1 - k_level
/5;
5910 float diff_level
= (k_level
== k_grey
) ? 1 : ((float(v_level
) - float(k_grey
)) / (float(k_level
) - float(k_grey
)));
5912 int32 v_rank
=1; //need more info
5914 honor
= ((f
* diff_level
* (190 + v_rank
*10))/6);
5915 honor
*= ((float)k_level
) / 70.0f
; //factor of dependence on levels of the killer
5917 // count the number of playerkills in one day
5918 ApplyModUInt32Value(PLAYER_FIELD_KILLS
, 1, true);
5919 // and those in a lifetime
5920 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 1, true);
5924 Creature
*cVictim
= (Creature
*)uVictim
;
5926 if (!cVictim
->isRacialLeader())
5929 honor
= 100; // ??? need more info
5930 victim_rank
= 19; // HK: Leader
5934 if (uVictim
!= NULL
)
5936 honor
*= sWorld
.getRate(RATE_HONOR
);
5941 honor
*= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
5944 // honor - for show honor points in log
5945 // victim_guid - for show victim name in log
5946 // victim_rank [1..4] HK: <dishonored rank>
5947 // victim_rank [5..19] HK: <alliance\horde rank>
5948 // victim_rank [0,20+] HK: <>
5949 WorldPacket
data(SMSG_PVP_CREDIT
,4+8+4);
5950 data
<< (uint32
) honor
;
5951 data
<< (uint64
) victim_guid
;
5952 data
<< (uint32
) victim_rank
;
5954 GetSession()->SendPacket(&data
);
5957 ModifyHonorPoints(int32(honor
));
5959 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, uint32(honor
), true);
5963 void Player::ModifyHonorPoints( int32 value
)
5967 if (GetHonorPoints() > sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
))
5968 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) + value
);
5970 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() > uint32(-value
) ? GetHonorPoints() + value
: 0);
5973 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() < sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) - value
? GetHonorPoints() + value
: sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
));
5976 void Player::ModifyArenaPoints( int32 value
)
5980 if (GetArenaPoints() > sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
))
5981 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) + value
);
5983 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() > uint32(-value
) ? GetArenaPoints() + value
: 0);
5986 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() < sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) - value
? GetArenaPoints() + value
: sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
));
5989 uint32
Player::GetGuildIdFromDB(uint64 guid
)
5991 std::ostringstream ss
;
5992 ss
<<"SELECT guildid FROM guild_member WHERE guid='"<<guid
<<"'";
5993 QueryResult
*result
= CharacterDatabase
.Query( ss
.str().c_str() );
5996 uint32 v
= result
->Fetch()[0].GetUInt32();
6004 uint32
Player::GetRankFromDB(uint64 guid
)
6006 std::ostringstream ss
;
6007 ss
<<"SELECT rank FROM guild_member WHERE guid='"<<guid
<<"'";
6008 QueryResult
*result
= CharacterDatabase
.Query( ss
.str().c_str() );
6011 uint32 v
= result
->Fetch()[0].GetUInt32();
6019 uint32
Player::GetArenaTeamIdFromDB(uint64 guid
, uint8 type
)
6022 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT arenateamid FROM arena_team_member WHERE guid='%u'", GUID_LOPART(guid
));
6025 // init id to 0, check the arena type before assigning a value to id
6029 QueryResult
*result2
= CharacterDatabase
.PQuery("SELECT type FROM arena_team WHERE arenateamid='%u'", id
);
6032 uint8 dbtype
= (*result2
)[0].GetUInt32();
6036 // if the type matches, we've found the id
6037 id
= (*result
)[0].GetUInt32();
6041 } while(result
->NextRow());
6045 // no arenateam for the specified guid, return 0
6049 uint32
Player::GetZoneIdFromDB(uint64 guid
)
6051 std::ostringstream ss
;
6053 ss
<<"SELECT zone FROM characters WHERE guid='"<<GUID_LOPART(guid
)<<"'";
6054 QueryResult
*result
= CharacterDatabase
.Query( ss
.str().c_str() );
6057 Field
* fields
= result
->Fetch();
6058 uint32 zone
= fields
[0].GetUInt32();
6063 // stored zone is zero, use generic and slow zone detection
6065 ss
<<"SELECT map,position_x,position_y FROM characters WHERE guid='"<<GUID_LOPART(guid
)<<"'";
6066 result
= CharacterDatabase
.Query(ss
.str().c_str());
6069 fields
= result
->Fetch();
6070 uint32 map
= fields
[0].GetUInt32();
6071 float posx
= fields
[1].GetFloat();
6072 float posy
= fields
[2].GetFloat();
6075 zone
= MapManager::Instance().GetZoneId(map
,posx
,posy
);
6078 ss
<< "UPDATE characters SET zone='"<<zone
<<"' WHERE guid='"<<GUID_LOPART(guid
)<<"'";
6079 CharacterDatabase
.Execute(ss
.str().c_str());
6085 void Player::UpdateArea(uint32 newArea
)
6087 // FFA_PVP flags are area and not zone id dependent
6088 // so apply them accordingly
6089 m_areaUpdateId
= newArea
;
6091 AreaTableEntry
const* area
= GetAreaEntryByAreaID(newArea
);
6093 if(area
&& (area
->flags
& AREA_FLAG_ARENA
))
6096 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_FFA_PVP
);
6100 // remove ffa flag only if not ffapvp realm
6101 // removal in sanctuaries and capitals is handled in zone update
6102 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_FFA_PVP
) && !sWorld
.IsFFAPvPRealm())
6103 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_FFA_PVP
);
6106 UpdateAreaDependentAuras(newArea
);
6109 void Player::UpdateZone(uint32 newZone
)
6111 m_zoneUpdateId
= newZone
;
6112 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
6114 // zone changed, so area changed as well, update it
6115 UpdateArea(GetAreaId());
6117 AreaTableEntry
const* zone
= GetAreaEntryByAreaID(newZone
);
6121 if (sWorld
.getConfig(CONFIG_WEATHER
))
6123 Weather
*wth
= sWorld
.FindWeather(zone
->ID
);
6126 wth
->SendWeatherUpdateToPlayer(this);
6130 if(!sWorld
.AddWeather(zone
->ID
))
6132 // send fine weather packet to remove old zone's weather
6133 Weather::SendFineWeatherUpdateToPlayer(this);
6138 pvpInfo
.inHostileArea
=
6139 GetTeam() == ALLIANCE
&& zone
->team
== AREATEAM_HORDE
||
6140 GetTeam() == HORDE
&& zone
->team
== AREATEAM_ALLY
||
6141 sWorld
.IsPvPRealm() && zone
->team
== AREATEAM_NONE
||
6142 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6144 if(pvpInfo
.inHostileArea
) // in hostile area
6146 if(!IsPvP() || pvpInfo
.endTimer
!= 0)
6147 UpdatePvP(true, true);
6149 else // in friendly area
6151 if(IsPvP() && !HasFlag(PLAYER_FLAGS
,PLAYER_FLAGS_IN_PVP
) && pvpInfo
.endTimer
== 0)
6152 pvpInfo
.endTimer
= time(0); // start toggle-off
6155 if(zone
->flags
& AREA_FLAG_SANCTUARY
) // in sanctuary
6157 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_SANCTUARY
);
6158 if(sWorld
.IsFFAPvPRealm())
6159 RemoveFlag(PLAYER_FLAGS
,PLAYER_FLAGS_FFA_PVP
);
6163 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_SANCTUARY
);
6166 if(zone
->flags
& AREA_FLAG_CAPITAL
) // in capital city
6168 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6169 SetRestType(REST_TYPE_IN_CITY
);
6170 InnEnter(time(0),GetMapId(),0,0,0);
6172 if(sWorld
.IsFFAPvPRealm())
6173 RemoveFlag(PLAYER_FLAGS
,PLAYER_FLAGS_FFA_PVP
);
6175 else // anywhere else
6177 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6179 if(GetRestType()==REST_TYPE_IN_TAVERN
) // has been in tavern. Is still in?
6181 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6183 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6184 SetRestType(REST_TYPE_NO
);
6186 if(sWorld
.IsFFAPvPRealm())
6187 SetFlag(PLAYER_FLAGS
,PLAYER_FLAGS_FFA_PVP
);
6190 else // not in tavern (leave city then)
6192 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6193 SetRestType(REST_TYPE_NO
);
6195 // Set player to FFA PVP when not in rested enviroment.
6196 if(sWorld
.IsFFAPvPRealm())
6197 SetFlag(PLAYER_FLAGS
,PLAYER_FLAGS_FFA_PVP
);
6202 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6203 // if player resurrected at teleport this will be applied in resurrect code
6205 DestroyZoneLimitedItem( true, newZone
);
6207 // recent client version not send leave/join channel packets for built-in local channels
6208 UpdateLocalChannels( newZone
);
6212 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE
);
6214 UpdateZoneDependentAuras(newZone
);
6217 //If players are too far way of duel flag... then player loose the duel
6218 void Player::CheckDuelDistance(time_t currTime
)
6223 uint64 duelFlagGUID
= GetUInt64Value(PLAYER_DUEL_ARBITER
);
6224 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, duelFlagGUID
);
6228 if(duel
->outOfBound
== 0)
6230 if(!IsWithinDistInMap(obj
, 50))
6232 duel
->outOfBound
= currTime
;
6234 WorldPacket
data(SMSG_DUEL_OUTOFBOUNDS
, 0);
6235 GetSession()->SendPacket(&data
);
6240 if(IsWithinDistInMap(obj
, 40))
6242 duel
->outOfBound
= 0;
6244 WorldPacket
data(SMSG_DUEL_INBOUNDS
, 0);
6245 GetSession()->SendPacket(&data
);
6247 else if(currTime
>= (duel
->outOfBound
+10))
6249 DuelComplete(DUEL_FLED
);
6254 void Player::DuelComplete(DuelCompleteType type
)
6256 // duel not requested
6260 WorldPacket
data(SMSG_DUEL_COMPLETE
, (1));
6261 data
<< (uint8
)((type
!= DUEL_INTERUPTED
) ? 1 : 0);
6262 GetSession()->SendPacket(&data
);
6263 duel
->opponent
->GetSession()->SendPacket(&data
);
6265 if(type
!= DUEL_INTERUPTED
)
6267 data
.Initialize(SMSG_DUEL_WINNER
, (1+20)); // we guess size
6268 data
<< (uint8
)((type
==DUEL_WON
) ? 0 : 1); // 0 = just won; 1 = fled
6269 data
<< duel
->opponent
->GetName();
6271 SendMessageToSet(&data
,true);
6274 // cool-down duel spell
6275 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6282 GetSession()->SendPacket(&data);
6283 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6284 data<<duel->opponent->GetGUID();
6288 duel->opponent->GetSession()->SendPacket(&data);*/
6290 //Remove Duel Flag object
6291 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER
));
6293 duel
->initiator
->RemoveGameObject(obj
,true);
6296 std::vector
<uint32
> auras2remove
;
6297 AuraMap
const& vAuras
= duel
->opponent
->GetAuras();
6298 for (AuraMap::const_iterator i
= vAuras
.begin(); i
!= vAuras
.end(); i
++)
6300 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6301 auras2remove
.push_back(i
->second
->GetId());
6304 for(size_t i
=0; i
<auras2remove
.size(); i
++)
6305 duel
->opponent
->RemoveAurasDueToSpell(auras2remove
[i
]);
6307 auras2remove
.clear();
6308 AuraMap
const& auras
= GetAuras();
6309 for (AuraMap::const_iterator i
= auras
.begin(); i
!= auras
.end(); i
++)
6311 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == duel
->opponent
->GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6312 auras2remove
.push_back(i
->second
->GetId());
6314 for(size_t i
=0; i
<auras2remove
.size(); i
++)
6315 RemoveAurasDueToSpell(auras2remove
[i
]);
6317 // cleanup combo points
6318 if(GetComboTarget()==duel
->opponent
->GetGUID())
6320 else if(GetComboTarget()==duel
->opponent
->GetPetGUID())
6323 if(duel
->opponent
->GetComboTarget()==GetGUID())
6324 duel
->opponent
->ClearComboPoints();
6325 else if(duel
->opponent
->GetComboTarget()==GetPetGUID())
6326 duel
->opponent
->ClearComboPoints();
6329 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6330 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6331 duel
->opponent
->SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6332 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6334 delete duel
->opponent
->duel
;
6335 duel
->opponent
->duel
= NULL
;
6340 //---------------------------------------------------------//
6342 void Player::_ApplyItemMods(Item
*item
, uint8 slot
,bool apply
)
6344 if(slot
>= INVENTORY_SLOT_BAG_END
|| !item
)
6347 // not apply/remove mods for broken item
6348 if(item
->IsBroken())
6351 ItemPrototype
const *proto
= item
->GetProto();
6356 sLog
.outDetail("applying mods for item %u ",item
->GetGUIDLow());
6358 uint32 attacktype
= Player::GetAttackBySlot(slot
);
6359 if(attacktype
< MAX_ATTACK
)
6360 _ApplyWeaponDependentAuraMods(item
,WeaponAttackType(attacktype
),apply
);
6362 _ApplyItemBonuses(proto
,slot
,apply
);
6364 if( slot
==EQUIPMENT_SLOT_RANGED
)
6365 _ApplyAmmoBonuses();
6367 ApplyItemEquipSpell(item
,apply
);
6368 ApplyEnchantment(item
, apply
);
6370 if(proto
->Socket
[0].Color
) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6371 CorrectMetaGemEnchants(slot
, apply
);
6373 sLog
.outDebug("_ApplyItemMods complete.");
6376 void Player::_ApplyItemBonuses(ItemPrototype
const *proto
,uint8 slot
,bool apply
)
6378 if(slot
>= INVENTORY_SLOT_BAG_END
|| !proto
)
6381 for (int i
= 0; i
< 10; i
++)
6383 float val
= float (proto
->ItemStat
[i
].ItemStatValue
);
6388 switch (proto
->ItemStat
[i
].ItemStatType
)
6391 HandleStatModifier(UNIT_MOD_MANA
, BASE_VALUE
, float(val
), apply
);
6393 case ITEM_MOD_HEALTH
: // modify HP
6394 HandleStatModifier(UNIT_MOD_HEALTH
, BASE_VALUE
, float(val
), apply
);
6396 case ITEM_MOD_AGILITY
: // modify agility
6397 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, BASE_VALUE
, float(val
), apply
);
6398 ApplyStatBuffMod(STAT_AGILITY
, val
, apply
);
6400 case ITEM_MOD_STRENGTH
: //modify strength
6401 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, BASE_VALUE
, float(val
), apply
);
6402 ApplyStatBuffMod(STAT_STRENGTH
, val
, apply
);
6404 case ITEM_MOD_INTELLECT
: //modify intellect
6405 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, BASE_VALUE
, float(val
), apply
);
6406 ApplyStatBuffMod(STAT_INTELLECT
, val
, apply
);
6408 case ITEM_MOD_SPIRIT
: //modify spirit
6409 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, BASE_VALUE
, float(val
), apply
);
6410 ApplyStatBuffMod(STAT_SPIRIT
, val
, apply
);
6412 case ITEM_MOD_STAMINA
: //modify stamina
6413 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, BASE_VALUE
, float(val
), apply
);
6414 ApplyStatBuffMod(STAT_STAMINA
, val
, apply
);
6416 case ITEM_MOD_DEFENSE_SKILL_RATING
:
6417 ApplyRatingMod(CR_DEFENSE_SKILL
, int32(val
), apply
);
6419 case ITEM_MOD_DODGE_RATING
:
6420 ApplyRatingMod(CR_DODGE
, int32(val
), apply
);
6422 case ITEM_MOD_PARRY_RATING
:
6423 ApplyRatingMod(CR_PARRY
, int32(val
), apply
);
6425 case ITEM_MOD_BLOCK_RATING
:
6426 ApplyRatingMod(CR_BLOCK
, int32(val
), apply
);
6428 case ITEM_MOD_HIT_MELEE_RATING
:
6429 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6431 case ITEM_MOD_HIT_RANGED_RATING
:
6432 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6434 case ITEM_MOD_HIT_SPELL_RATING
:
6435 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6437 case ITEM_MOD_CRIT_MELEE_RATING
:
6438 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6440 case ITEM_MOD_CRIT_RANGED_RATING
:
6441 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6443 case ITEM_MOD_CRIT_SPELL_RATING
:
6444 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6446 case ITEM_MOD_HIT_TAKEN_MELEE_RATING
:
6447 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6449 case ITEM_MOD_HIT_TAKEN_RANGED_RATING
:
6450 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6452 case ITEM_MOD_HIT_TAKEN_SPELL_RATING
:
6453 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6455 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING
:
6456 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6458 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING
:
6459 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6461 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING
:
6462 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6464 case ITEM_MOD_HASTE_MELEE_RATING
:
6465 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6467 case ITEM_MOD_HASTE_RANGED_RATING
:
6468 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6470 case ITEM_MOD_HASTE_SPELL_RATING
:
6471 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6473 case ITEM_MOD_HIT_RATING
:
6474 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6475 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6476 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6478 case ITEM_MOD_CRIT_RATING
:
6479 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6480 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6481 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6483 case ITEM_MOD_HIT_TAKEN_RATING
:
6484 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6485 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6486 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6488 case ITEM_MOD_CRIT_TAKEN_RATING
:
6489 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6490 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6491 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6493 case ITEM_MOD_RESILIENCE_RATING
:
6494 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6495 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6496 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6498 case ITEM_MOD_HASTE_RATING
:
6499 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6500 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6501 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6503 case ITEM_MOD_EXPERTISE_RATING
:
6504 ApplyRatingMod(CR_EXPERTISE
, int32(val
), apply
);
6510 HandleStatModifier(UNIT_MOD_ARMOR
, BASE_VALUE
, float(proto
->Armor
), apply
);
6513 HandleBaseModValue(SHIELD_BLOCK_VALUE
, FLAT_MOD
, float(proto
->Block
), apply
);
6516 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY
, BASE_VALUE
, float(proto
->HolyRes
), apply
);
6519 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE
, BASE_VALUE
, float(proto
->FireRes
), apply
);
6521 if (proto
->NatureRes
)
6522 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE
, BASE_VALUE
, float(proto
->NatureRes
), apply
);
6524 if (proto
->FrostRes
)
6525 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST
, BASE_VALUE
, float(proto
->FrostRes
), apply
);
6527 if (proto
->ShadowRes
)
6528 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW
, BASE_VALUE
, float(proto
->ShadowRes
), apply
);
6530 if (proto
->ArcaneRes
)
6531 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE
, BASE_VALUE
, float(proto
->ArcaneRes
), apply
);
6533 WeaponAttackType attType
= BASE_ATTACK
;
6534 float damage
= 0.0f
;
6536 if( slot
== EQUIPMENT_SLOT_RANGED
&& (
6537 proto
->InventoryType
== INVTYPE_RANGED
|| proto
->InventoryType
== INVTYPE_THROWN
||
6538 proto
->InventoryType
== INVTYPE_RANGEDRIGHT
))
6540 attType
= RANGED_ATTACK
;
6542 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6544 attType
= OFF_ATTACK
;
6547 if (proto
->Damage
[0].DamageMin
> 0 )
6549 damage
= apply
? proto
->Damage
[0].DamageMin
: BASE_MINDAMAGE
;
6550 SetBaseWeaponDamage(attType
, MINDAMAGE
, damage
);
6551 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6554 if (proto
->Damage
[0].DamageMax
> 0 )
6556 damage
= apply
? proto
->Damage
[0].DamageMax
: BASE_MAXDAMAGE
;
6557 SetBaseWeaponDamage(attType
, MAXDAMAGE
, damage
);
6560 if(!IsUseEquipedWeapon(slot
==EQUIPMENT_SLOT_MAINHAND
))
6565 if(slot
== EQUIPMENT_SLOT_RANGED
)
6566 SetAttackTime(RANGED_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6567 else if(slot
==EQUIPMENT_SLOT_MAINHAND
)
6568 SetAttackTime(BASE_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6569 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6570 SetAttackTime(OFF_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6573 if(CanModifyStats() && (damage
|| proto
->Delay
))
6574 UpdateDamagePhysical(attType
);
6577 void Player::_ApplyWeaponDependentAuraMods(Item
*item
,WeaponAttackType attackType
,bool apply
)
6579 AuraList
const& auraCritList
= GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT
);
6580 for(AuraList::const_iterator itr
= auraCritList
.begin(); itr
!=auraCritList
.end();++itr
)
6581 _ApplyWeaponDependentAuraCritMod(item
,attackType
,*itr
,apply
);
6583 AuraList
const& auraDamageFlatList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE
);
6584 for(AuraList::const_iterator itr
= auraDamageFlatList
.begin(); itr
!=auraDamageFlatList
.end();++itr
)
6585 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6587 AuraList
const& auraDamagePCTList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
);
6588 for(AuraList::const_iterator itr
= auraDamagePCTList
.begin(); itr
!=auraDamagePCTList
.end();++itr
)
6589 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6592 void Player::_ApplyWeaponDependentAuraCritMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6594 // generic not weapon specific case processes in aura code
6595 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6598 BaseModGroup mod
= BASEMOD_END
;
6601 case BASE_ATTACK
: mod
= CRIT_PERCENTAGE
; break;
6602 case OFF_ATTACK
: mod
= OFFHAND_CRIT_PERCENTAGE
;break;
6603 case RANGED_ATTACK
: mod
= RANGED_CRIT_PERCENTAGE
; break;
6607 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6609 HandleBaseModValue(mod
, FLAT_MOD
, float (aura
->GetModifier()->m_amount
), apply
);
6613 void Player::_ApplyWeaponDependentAuraDamageMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6615 // ignore spell mods for not wands
6616 Modifier
const* modifier
= aura
->GetModifier();
6617 if((modifier
->m_miscvalue
& SPELL_SCHOOL_MASK_NORMAL
)==0 && (getClassMask() & CLASSMASK_WAND_USERS
)==0)
6620 // generic not weapon specific case processes in aura code
6621 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6624 UnitMods unitMod
= UNIT_MOD_END
;
6627 case BASE_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_MAINHAND
; break;
6628 case OFF_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_OFFHAND
; break;
6629 case RANGED_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_RANGED
; break;
6633 UnitModifierType unitModType
= TOTAL_VALUE
;
6634 switch(modifier
->m_auraname
)
6636 case SPELL_AURA_MOD_DAMAGE_DONE
: unitModType
= TOTAL_VALUE
; break;
6637 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
: unitModType
= TOTAL_PCT
; break;
6641 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6643 HandleStatModifier(unitMod
, unitModType
, float(modifier
->m_amount
),apply
);
6647 void Player::ApplyItemEquipSpell(Item
*item
, bool apply
, bool form_change
)
6652 ItemPrototype
const *proto
= item
->GetProto();
6656 for (int i
= 0; i
< 5; i
++)
6658 _Spell
const& spellData
= proto
->Spells
[i
];
6661 if(!spellData
.SpellId
)
6664 // wrong triggering type
6665 if(apply
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_EQUIP
)
6668 // check if it is valid spell
6669 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellData
.SpellId
);
6673 ApplyEquipSpell(spellproto
,item
,apply
,form_change
);
6677 void Player::ApplyEquipSpell(SpellEntry
const* spellInfo
, Item
* item
, bool apply
, bool form_change
)
6681 // Cannot be used in this stance/form
6682 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
)!=0)
6685 if(form_change
) // check aura active state from other form
6688 for (int k
=0; k
< 3; ++k
)
6690 spellEffectPair spair
= spellEffectPair(spellInfo
->Id
, k
);
6691 for (AuraMap::iterator iter
= m_Auras
.lower_bound(spair
); iter
!= m_Auras
.upper_bound(spair
); ++iter
)
6693 if(!item
|| iter
->second
->GetCastItemGUID() == item
->GetGUID())
6703 if(found
) // and skip re-cast already active aura at form change
6707 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item
? "item" : "itemset"), spellInfo
->Id
);
6709 CastSpell(this,spellInfo
,true,item
);
6713 if(form_change
) // check aura compatibility
6715 // Cannot be used in this stance/form
6716 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
)==0)
6717 return; // and remove only not compatible at form change
6721 RemoveAurasDueToItemSpell(item
,spellInfo
->Id
); // un-apply all spells , not only at-equipped
6723 RemoveAurasDueToSpell(spellInfo
->Id
); // un-apply spell (item set case)
6727 void Player::UpdateEquipSpellsAtFormChange()
6729 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6731 if(m_items
[i
] && !m_items
[i
]->IsBroken())
6733 ApplyItemEquipSpell(m_items
[i
],false,true); // remove spells that not fit to form
6734 ApplyItemEquipSpell(m_items
[i
],true,true); // add spells that fit form but not active
6738 // item set bonuses not dependent from item broken state
6739 for(size_t setindex
= 0; setindex
< ItemSetEff
.size(); ++setindex
)
6741 ItemSetEffect
* eff
= ItemSetEff
[setindex
];
6745 for(uint32 y
=0;y
<8; ++y
)
6747 SpellEntry
const* spellInfo
= eff
->spells
[y
];
6751 ApplyEquipSpell(spellInfo
,NULL
,false,true); // remove spells that not fit to form
6752 ApplyEquipSpell(spellInfo
,NULL
,true,true); // add spells that fit form but not active
6757 void Player::CastItemCombatSpell(Item
*item
,Unit
* Target
, WeaponAttackType attType
)
6759 if(!item
|| item
->IsBroken())
6762 ItemPrototype
const *proto
= item
->GetProto();
6766 if (!Target
|| Target
== this )
6769 for (int i
= 0; i
< 5; i
++)
6771 _Spell
const& spellData
= proto
->Spells
[i
];
6774 if(!spellData
.SpellId
)
6777 // wrong triggering type
6778 if(spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_CHANCE_ON_HIT
)
6781 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
6784 sLog
.outError("WORLD: unknown Item spellid %i", spellData
.SpellId
);
6788 // not allow proc extra attack spell at extra attack
6789 if( m_extraAttacks
&& IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_ADD_EXTRA_ATTACKS
) )
6792 float chance
= spellInfo
->procChance
;
6794 if(spellData
.SpellPPMRate
)
6796 uint32 WeaponSpeed
= GetAttackTime(attType
);
6797 chance
= GetPPMProcChance(WeaponSpeed
, spellData
.SpellPPMRate
);
6799 else if(chance
> 100.0f
)
6801 chance
= GetWeaponProcChance();
6804 if (roll_chance_f(chance
))
6805 this->CastSpell(Target
, spellInfo
->Id
, true, item
);
6808 // item combat enchantments
6809 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
6811 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
6812 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
6813 if(!pEnchant
) continue;
6814 for (int s
=0;s
<3;s
++)
6816 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
)
6819 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
6822 sLog
.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
6826 float chance
= pEnchant
->amount
[s
] != 0 ? float(pEnchant
->amount
[s
]) : GetWeaponProcChance();
6827 if (roll_chance_f(chance
))
6829 if(IsPositiveSpell(pEnchant
->spellid
[s
]))
6830 CastSpell(this, pEnchant
->spellid
[s
], true, item
);
6832 CastSpell(Target
, pEnchant
->spellid
[s
], true, item
);
6838 void Player::_RemoveAllItemMods()
6840 sLog
.outDebug("_RemoveAllItemMods start.");
6842 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6846 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6850 // item set bonuses not dependent from item broken state
6852 RemoveItemsSetItem(this,proto
);
6854 if(m_items
[i
]->IsBroken())
6857 ApplyItemEquipSpell(m_items
[i
],false);
6858 ApplyEnchantment(m_items
[i
], false);
6862 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6866 if(m_items
[i
]->IsBroken())
6868 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6872 uint32 attacktype
= Player::GetAttackBySlot(i
);
6873 if(attacktype
< MAX_ATTACK
)
6874 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),false);
6876 _ApplyItemBonuses(proto
,i
, false);
6878 if( i
== EQUIPMENT_SLOT_RANGED
)
6879 _ApplyAmmoBonuses();
6883 sLog
.outDebug("_RemoveAllItemMods complete.");
6886 void Player::_ApplyAllItemMods()
6888 sLog
.outDebug("_ApplyAllItemMods start.");
6890 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6894 if(m_items
[i
]->IsBroken())
6897 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6901 uint32 attacktype
= Player::GetAttackBySlot(i
);
6902 if(attacktype
< MAX_ATTACK
)
6903 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),true);
6905 _ApplyItemBonuses(proto
,i
, true);
6907 if( i
== EQUIPMENT_SLOT_RANGED
)
6908 _ApplyAmmoBonuses();
6912 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6916 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6920 // item set bonuses not dependent from item broken state
6922 AddItemsSetItem(this,m_items
[i
]);
6924 if(m_items
[i
]->IsBroken())
6927 ApplyItemEquipSpell(m_items
[i
],true);
6928 ApplyEnchantment(m_items
[i
], true);
6932 sLog
.outDebug("_ApplyAllItemMods complete.");
6935 void Player::_ApplyAmmoBonuses()
6938 uint32 ammo_id
= GetUInt32Value(PLAYER_AMMO_ID
);
6942 float currentAmmoDPS
;
6944 ItemPrototype
const *ammo_proto
= objmgr
.GetItemPrototype( ammo_id
);
6945 if( !ammo_proto
|| ammo_proto
->Class
!=ITEM_CLASS_PROJECTILE
|| !CheckAmmoCompatibility(ammo_proto
))
6946 currentAmmoDPS
= 0.0f
;
6948 currentAmmoDPS
= ammo_proto
->Damage
[0].DamageMin
;
6950 if(currentAmmoDPS
== GetAmmoDPS())
6953 m_ammoDPS
= currentAmmoDPS
;
6955 if(CanModifyStats())
6956 UpdateDamagePhysical(RANGED_ATTACK
);
6959 bool Player::CheckAmmoCompatibility(const ItemPrototype
*ammo_proto
) const
6964 // check ranged weapon
6965 Item
*weapon
= GetWeaponForAttack( RANGED_ATTACK
);
6966 if(!weapon
|| weapon
->IsBroken() )
6969 ItemPrototype
const* weapon_proto
= weapon
->GetProto();
6970 if(!weapon_proto
|| weapon_proto
->Class
!=ITEM_CLASS_WEAPON
)
6973 // check ammo ws. weapon compatibility
6974 switch(weapon_proto
->SubClass
)
6976 case ITEM_SUBCLASS_WEAPON_BOW
:
6977 case ITEM_SUBCLASS_WEAPON_CROSSBOW
:
6978 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_ARROW
)
6981 case ITEM_SUBCLASS_WEAPON_GUN
:
6982 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_BULLET
)
6992 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
6993 Called by remove insignia spell effect */
6994 void Player::RemovedInsignia(Player
* looterPlr
)
6996 if (!GetBattleGroundId())
6999 // If not released spirit, do it !
7000 if(m_deathTimer
> 0)
7007 Corpse
*corpse
= GetCorpse();
7011 // We have to convert player corpse to bones, not to be able to resurrect there
7012 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7013 Corpse
*bones
= ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
7017 // Now we must make bones lootable, and send player loot
7018 bones
->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS
, CORPSE_DYNFLAG_LOOTABLE
);
7020 // We store the level of our player in the gold field
7021 // We retrieve this information at Player::SendLoot()
7022 bones
->loot
.gold
= getLevel();
7023 bones
->lootRecipient
= looterPlr
;
7024 looterPlr
->SendLoot(bones
->GetGUID(), LOOT_INSIGNIA
);
7033 void Player::SendLootRelease( uint64 guid
)
7035 WorldPacket
data( SMSG_LOOT_RELEASE_RESPONSE
, (8+1) );
7036 data
<< uint64(guid
) << uint8(1);
7037 SendDirectMessage( &data
);
7040 void Player::SendLoot(uint64 guid
, LootType loot_type
)
7043 PermissionTypes permission
= ALL_PERMISSION
;
7045 sLog
.outDebug("Player::SendLoot");
7046 if (IS_GAMEOBJECT_GUID(guid
))
7048 sLog
.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7050 ObjectAccessor::GetGameObject(*this, guid
);
7052 // not check distance for GO in case owned GO (fishing bobber case, for example)
7053 // And permit out of range GO with no owner in case fishing hole
7054 if (!go
|| (loot_type
!= LOOT_FISHINGHOLE
&& (loot_type
!= LOOT_FISHING
|| go
->GetOwnerGUID() != GetGUID()) && !go
->IsWithinDistInMap(this,INTERACTION_DISTANCE
)))
7056 SendLootRelease(guid
);
7062 if(go
->getLootState() == GO_READY
)
7064 uint32 lootid
= go
->GetLootId();
7068 sLog
.outDebug(" if(lootid)");
7070 loot
->FillLoot(lootid
, LootTemplates_Gameobject
, this);
7073 if(loot_type
== LOOT_FISHING
)
7074 go
->getFishLoot(loot
);
7076 go
->SetLootState(GO_ACTIVATED
);
7079 else if (IS_ITEM_GUID(guid
))
7081 Item
*item
= GetItemByGuid( guid
);
7085 SendLootRelease(guid
);
7089 if(loot_type
== LOOT_DISENCHANTING
)
7093 if(!item
->m_lootGenerated
)
7095 item
->m_lootGenerated
= true;
7097 loot
->FillLoot(item
->GetProto()->DisenchantID
, LootTemplates_Disenchant
, this);
7100 else if(loot_type
== LOOT_PROSPECTING
)
7104 if(!item
->m_lootGenerated
)
7106 item
->m_lootGenerated
= true;
7108 loot
->FillLoot(item
->GetEntry(), LootTemplates_Prospecting
, this);
7115 if(!item
->m_lootGenerated
)
7117 item
->m_lootGenerated
= true;
7119 loot
->FillLoot(item
->GetEntry(), LootTemplates_Item
, this);
7121 loot
->generateMoneyLoot(item
->GetProto()->MinMoneyLoot
,item
->GetProto()->MaxMoneyLoot
);
7125 else if (IS_CORPSE_GUID(guid
)) // remove insignia
7127 Corpse
*bones
= ObjectAccessor::GetCorpse(*this, guid
);
7129 if (!bones
|| !((loot_type
== LOOT_CORPSE
) || (loot_type
== LOOT_INSIGNIA
)) || (bones
->GetType() != CORPSE_BONES
) )
7131 SendLootRelease(guid
);
7135 loot
= &bones
->loot
;
7137 if (!bones
->lootForBody
)
7139 bones
->lootForBody
= true;
7140 uint32 pLevel
= bones
->loot
.gold
;
7141 bones
->loot
.clear();
7142 // It may need a better formula
7143 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7144 bones
->loot
.gold
= (uint32
)( urand(50, 150) * 0.016f
* pow( ((float)pLevel
)/5.76f
, 2.5f
) * sWorld
.getRate(RATE_DROP_MONEY
) );
7147 if (bones
->lootRecipient
!= this)
7148 permission
= NONE_PERMISSION
;
7152 Creature
*creature
= ObjectAccessor::GetCreature(*this, guid
);
7154 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7155 if (!creature
|| creature
->isAlive()!=(loot_type
== LOOT_PICKPOCKETING
) || !creature
->IsWithinDistInMap(this,INTERACTION_DISTANCE
))
7157 SendLootRelease(guid
);
7161 if(loot_type
== LOOT_PICKPOCKETING
&& IsFriendlyTo(creature
))
7163 SendLootRelease(guid
);
7167 loot
= &creature
->loot
;
7169 if(loot_type
== LOOT_PICKPOCKETING
)
7171 if ( !creature
->lootForPickPocketed
)
7173 creature
->lootForPickPocketed
= true;
7176 if (uint32 lootid
= creature
->GetCreatureInfo()->pickpocketLootId
)
7177 loot
->FillLoot(lootid
, LootTemplates_Pickpocketing
, this);
7179 // Generate extra money for pick pocket loot
7180 const uint32 a
= urand(0, creature
->getLevel()/2);
7181 const uint32 b
= urand(0, getLevel()/2);
7182 loot
->gold
= uint32(10 * (a
+ b
) * sWorld
.getRate(RATE_DROP_MONEY
));
7187 // the player whose group may loot the corpse
7188 Player
*recipient
= creature
->GetLootRecipient();
7191 creature
->SetLootRecipient(this);
7195 if (creature
->lootForPickPocketed
)
7197 creature
->lootForPickPocketed
= false;
7201 if(!creature
->lootForBody
)
7203 creature
->lootForBody
= true;
7206 if (uint32 lootid
= creature
->GetCreatureInfo()->lootid
)
7207 loot
->FillLoot(lootid
, LootTemplates_Creature
, recipient
);
7209 loot
->generateMoneyLoot(creature
->GetCreatureInfo()->mingold
,creature
->GetCreatureInfo()->maxgold
);
7211 if(Group
* group
= recipient
->GetGroup())
7213 group
->UpdateLooterGuid(creature
,true);
7215 switch (group
->GetLootMethod())
7218 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7219 group
->GroupLoot(recipient
->GetGUID(), loot
, creature
);
7221 case NEED_BEFORE_GREED
:
7222 group
->NeedBeforeGreed(recipient
->GetGUID(), loot
, creature
);
7225 group
->MasterLoot(recipient
->GetGUID(), loot
, creature
);
7233 // possible only if creature->lootForBody && loot->empty() at spell cast check
7234 if (loot_type
== LOOT_SKINNING
)
7237 loot
->FillLoot(creature
->GetCreatureInfo()->SkinLootId
, LootTemplates_Skinning
, this);
7239 // set group rights only for loot_type != LOOT_SKINNING
7242 if(Group
* group
= GetGroup())
7244 if( group
== recipient
->GetGroup() )
7246 if(group
->GetLootMethod() == FREE_FOR_ALL
)
7247 permission
= ALL_PERMISSION
;
7248 else if(group
->GetLooterGuid() == GetGUID())
7250 if(group
->GetLootMethod() == MASTER_LOOT
)
7251 permission
= MASTER_PERMISSION
;
7253 permission
= ALL_PERMISSION
;
7256 permission
= GROUP_PERMISSION
;
7259 permission
= NONE_PERMISSION
;
7261 else if(recipient
== this)
7262 permission
= ALL_PERMISSION
;
7264 permission
= NONE_PERMISSION
;
7271 QuestItemList
*q_list
= 0;
7272 if (permission
!= NONE_PERMISSION
)
7274 QuestItemMap
const& lootPlayerQuestItems
= loot
->GetPlayerQuestItems();
7275 QuestItemMap::const_iterator itr
= lootPlayerQuestItems
.find(GetGUIDLow());
7276 if (itr
== lootPlayerQuestItems
.end())
7277 q_list
= loot
->FillQuestLoot(this);
7279 q_list
= itr
->second
;
7282 QuestItemList
*ffa_list
= 0;
7283 if (permission
!= NONE_PERMISSION
)
7285 QuestItemMap
const& lootPlayerFFAItems
= loot
->GetPlayerFFAItems();
7286 QuestItemMap::const_iterator itr
= lootPlayerFFAItems
.find(GetGUIDLow());
7287 if (itr
== lootPlayerFFAItems
.end())
7288 ffa_list
= loot
->FillFFALoot(this);
7290 ffa_list
= itr
->second
;
7293 QuestItemList
*conditional_list
= 0;
7294 if (permission
!= NONE_PERMISSION
)
7296 QuestItemMap
const& lootPlayerNonQuestNonFFAConditionalItems
= loot
->GetPlayerNonQuestNonFFAConditionalItems();
7297 QuestItemMap::const_iterator itr
= lootPlayerNonQuestNonFFAConditionalItems
.find(GetGUIDLow());
7298 if (itr
== lootPlayerNonQuestNonFFAConditionalItems
.end())
7299 conditional_list
= loot
->FillNonQuestNonFFAConditionalLoot(this);
7301 conditional_list
= itr
->second
;
7304 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING and LOOT_INSIGNIA unsupported by client, sending LOOT_SKINNING instead
7305 if(loot_type
== LOOT_PICKPOCKETING
|| loot_type
== LOOT_DISENCHANTING
|| loot_type
== LOOT_PROSPECTING
|| loot_type
== LOOT_INSIGNIA
)
7306 loot_type
= LOOT_SKINNING
;
7308 if(loot_type
== LOOT_FISHINGHOLE
)
7309 loot_type
= LOOT_FISHING
;
7311 WorldPacket
data(SMSG_LOOT_RESPONSE
, (9+50)); // we guess size
7313 data
<< uint64(guid
);
7314 data
<< uint8(loot_type
);
7315 data
<< LootView(*loot
, q_list
, ffa_list
, conditional_list
, this, permission
);
7317 SendDirectMessage(&data
);
7319 // add 'this' player as one of the players that are looting 'loot'
7320 if (permission
!= NONE_PERMISSION
)
7321 loot
->AddLooter(GetGUID());
7323 if ( loot_type
== LOOT_CORPSE
&& !IS_ITEM_GUID(guid
) )
7324 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_LOOTING
);
7327 void Player::SendNotifyLootMoneyRemoved()
7329 WorldPacket
data(SMSG_LOOT_CLEAR_MONEY
, 0);
7330 GetSession()->SendPacket( &data
);
7333 void Player::SendNotifyLootItemRemoved(uint8 lootSlot
)
7335 WorldPacket
data(SMSG_LOOT_REMOVED
, 1);
7336 data
<< uint8(lootSlot
);
7337 GetSession()->SendPacket( &data
);
7340 void Player::SendUpdateWorldState(uint32 Field
, uint32 Value
)
7342 WorldPacket
data(SMSG_UPDATE_WORLD_STATE
, 8);
7345 GetSession()->SendPacket(&data
);
7348 void Player::SendInitWorldStates()
7350 // data depends on zoneid/mapid...
7351 BattleGround
* bg
= GetBattleGround();
7352 uint16 NumberOfFields
= 0;
7353 uint32 mapid
= GetMapId();
7354 uint32 zoneid
= GetZoneId();
7355 uint32 areaid
= GetAreaId();
7356 sLog
.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid
, zoneid
);
7357 // may be exist better way to do this...
7380 NumberOfFields
= 81;
7383 NumberOfFields
= 14;
7387 NumberOfFields
= 38;
7390 NumberOfFields
= 22;
7393 NumberOfFields
= 36;
7396 NumberOfFields
= 35;
7407 NumberOfFields
= 10;
7411 WorldPacket
data(SMSG_INIT_WORLD_STATES
, (4+4+4+2+(NumberOfFields
*8)));
7412 data
<< uint32(mapid
); // mapid
7413 data
<< uint32(zoneid
); // zone id
7414 data
<< uint32(areaid
); // area id, new 2.1.0
7415 data
<< uint16(NumberOfFields
); // count of uint64 blocks
7416 data
<< uint32(0x8d8) << uint32(0x0); // 1
7417 data
<< uint32(0x8d7) << uint32(0x0); // 2
7418 data
<< uint32(0x8d6) << uint32(0x0); // 3
7419 data
<< uint32(0x8d5) << uint32(0x0); // 4
7420 data
<< uint32(0x8d4) << uint32(0x0); // 5
7421 data
<< uint32(0x8d3) << uint32(0x0); // 6
7422 if(mapid
== 530) // Outland
7424 data
<< uint32(0x9bf) << uint32(0x0); // 7
7425 data
<< uint32(0x9bd) << uint32(0xF); // 8
7426 data
<< uint32(0x9bb) << uint32(0xF); // 9
7441 data
<< uint32(0x7ae) << uint32(0x1); // 7
7442 data
<< uint32(0x532) << uint32(0x1); // 8
7443 data
<< uint32(0x531) << uint32(0x0); // 9
7444 data
<< uint32(0x52e) << uint32(0x0); // 10
7445 data
<< uint32(0x571) << uint32(0x0); // 11
7446 data
<< uint32(0x570) << uint32(0x0); // 12
7447 data
<< uint32(0x567) << uint32(0x1); // 13
7448 data
<< uint32(0x566) << uint32(0x1); // 14
7449 data
<< uint32(0x550) << uint32(0x1); // 15
7450 data
<< uint32(0x544) << uint32(0x0); // 16
7451 data
<< uint32(0x536) << uint32(0x0); // 17
7452 data
<< uint32(0x535) << uint32(0x1); // 18
7453 data
<< uint32(0x518) << uint32(0x0); // 19
7454 data
<< uint32(0x517) << uint32(0x0); // 20
7455 data
<< uint32(0x574) << uint32(0x0); // 21
7456 data
<< uint32(0x573) << uint32(0x0); // 22
7457 data
<< uint32(0x572) << uint32(0x0); // 23
7458 data
<< uint32(0x56f) << uint32(0x0); // 24
7459 data
<< uint32(0x56e) << uint32(0x0); // 25
7460 data
<< uint32(0x56d) << uint32(0x0); // 26
7461 data
<< uint32(0x56c) << uint32(0x0); // 27
7462 data
<< uint32(0x56b) << uint32(0x0); // 28
7463 data
<< uint32(0x56a) << uint32(0x1); // 29
7464 data
<< uint32(0x569) << uint32(0x1); // 30
7465 data
<< uint32(0x568) << uint32(0x1); // 13
7466 data
<< uint32(0x565) << uint32(0x0); // 32
7467 data
<< uint32(0x564) << uint32(0x0); // 33
7468 data
<< uint32(0x563) << uint32(0x0); // 34
7469 data
<< uint32(0x562) << uint32(0x0); // 35
7470 data
<< uint32(0x561) << uint32(0x0); // 36
7471 data
<< uint32(0x560) << uint32(0x0); // 37
7472 data
<< uint32(0x55f) << uint32(0x0); // 38
7473 data
<< uint32(0x55e) << uint32(0x0); // 39
7474 data
<< uint32(0x55d) << uint32(0x0); // 40
7475 data
<< uint32(0x3c6) << uint32(0x4); // 41
7476 data
<< uint32(0x3c4) << uint32(0x6); // 42
7477 data
<< uint32(0x3c2) << uint32(0x4); // 43
7478 data
<< uint32(0x516) << uint32(0x1); // 44
7479 data
<< uint32(0x515) << uint32(0x0); // 45
7480 data
<< uint32(0x3b6) << uint32(0x6); // 46
7481 data
<< uint32(0x55c) << uint32(0x0); // 47
7482 data
<< uint32(0x55b) << uint32(0x0); // 48
7483 data
<< uint32(0x55a) << uint32(0x0); // 49
7484 data
<< uint32(0x559) << uint32(0x0); // 50
7485 data
<< uint32(0x558) << uint32(0x0); // 51
7486 data
<< uint32(0x557) << uint32(0x0); // 52
7487 data
<< uint32(0x556) << uint32(0x0); // 53
7488 data
<< uint32(0x555) << uint32(0x0); // 54
7489 data
<< uint32(0x554) << uint32(0x1); // 55
7490 data
<< uint32(0x553) << uint32(0x1); // 56
7491 data
<< uint32(0x552) << uint32(0x1); // 57
7492 data
<< uint32(0x551) << uint32(0x1); // 58
7493 data
<< uint32(0x54f) << uint32(0x0); // 59
7494 data
<< uint32(0x54e) << uint32(0x0); // 60
7495 data
<< uint32(0x54d) << uint32(0x1); // 61
7496 data
<< uint32(0x54c) << uint32(0x0); // 62
7497 data
<< uint32(0x54b) << uint32(0x0); // 63
7498 data
<< uint32(0x545) << uint32(0x0); // 64
7499 data
<< uint32(0x543) << uint32(0x1); // 65
7500 data
<< uint32(0x542) << uint32(0x0); // 66
7501 data
<< uint32(0x540) << uint32(0x0); // 67
7502 data
<< uint32(0x53f) << uint32(0x0); // 68
7503 data
<< uint32(0x53e) << uint32(0x0); // 69
7504 data
<< uint32(0x53d) << uint32(0x0); // 70
7505 data
<< uint32(0x53c) << uint32(0x0); // 71
7506 data
<< uint32(0x53b) << uint32(0x0); // 72
7507 data
<< uint32(0x53a) << uint32(0x1); // 73
7508 data
<< uint32(0x539) << uint32(0x0); // 74
7509 data
<< uint32(0x538) << uint32(0x0); // 75
7510 data
<< uint32(0x537) << uint32(0x0); // 76
7511 data
<< uint32(0x534) << uint32(0x0); // 77
7512 data
<< uint32(0x533) << uint32(0x0); // 78
7513 data
<< uint32(0x530) << uint32(0x0); // 79
7514 data
<< uint32(0x52f) << uint32(0x0); // 80
7515 data
<< uint32(0x52d) << uint32(0x1); // 81
7518 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_WS
)
7519 bg
->FillInitialWorldStates(data
);
7522 data
<< uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7523 data
<< uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7524 data
<< uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7525 data
<< uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7526 data
<< uint32(0x60b) << uint32(0x2); // 11 1547 unk
7527 data
<< uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7528 data
<< uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7529 data
<< uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7533 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_AB
)
7534 bg
->FillInitialWorldStates(data
);
7537 data
<< uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7538 data
<< uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7539 data
<< uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7540 data
<< uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7541 data
<< uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7542 data
<< uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7543 data
<< uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7544 data
<< uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7545 data
<< uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7546 data
<< uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7547 data
<< uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7548 data
<< uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7549 data
<< uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7550 data
<< uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7551 data
<< uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7552 data
<< uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7553 data
<< uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7554 data
<< uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7555 data
<< uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7556 data
<< uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7557 data
<< uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7558 data
<< uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7559 data
<< uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7560 data
<< uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7561 data
<< uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7562 data
<< uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7563 data
<< uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7564 data
<< uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7565 data
<< uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7566 data
<< uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7567 data
<< uint32(0x745) << uint32(0x2); // 37 1861 unk
7568 data
<< uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7572 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_EY
)
7573 bg
->FillInitialWorldStates(data
);
7576 data
<< uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7577 data
<< uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7578 data
<< uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7579 data
<< uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7580 data
<< uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7581 data
<< uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7582 data
<< uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7583 data
<< uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7584 data
<< uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7585 data
<< uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7586 data
<< uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7587 data
<< uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7588 data
<< uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7589 data
<< uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7590 data
<< uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7591 data
<< uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7592 data
<< uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7593 data
<< uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7594 data
<< uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontroled (1 - yes, 0 - no)
7595 data
<< uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7596 data
<< uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7597 data
<< uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7598 data
<< uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7599 data
<< uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7600 data
<< uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7601 data
<< uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7602 data
<< uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7603 data
<< uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7604 data
<< uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7605 data
<< uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7606 data
<< uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7607 data
<< uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7608 // and some more ... unknown
7611 case 3483: // Hellfire Peninsula
7612 data
<< uint32(0x9ba) << uint32(0x1); // 10
7613 data
<< uint32(0x9b9) << uint32(0x1); // 11
7614 data
<< uint32(0x9b5) << uint32(0x0); // 12
7615 data
<< uint32(0x9b4) << uint32(0x1); // 13
7616 data
<< uint32(0x9b3) << uint32(0x0); // 14
7617 data
<< uint32(0x9b2) << uint32(0x0); // 15
7618 data
<< uint32(0x9b1) << uint32(0x1); // 16
7619 data
<< uint32(0x9b0) << uint32(0x0); // 17
7620 data
<< uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7621 data
<< uint32(0x9ac) << uint32(0x0); // 19
7622 data
<< uint32(0x9a8) << uint32(0x0); // 20
7623 data
<< uint32(0x9a7) << uint32(0x0); // 21
7624 data
<< uint32(0x9a6) << uint32(0x1); // 22
7626 case 3519: // Terokkar Forest
7627 data
<< uint32(0xa41) << uint32(0x0); // 10
7628 data
<< uint32(0xa40) << uint32(0x14); // 11
7629 data
<< uint32(0xa3f) << uint32(0x0); // 12
7630 data
<< uint32(0xa3e) << uint32(0x0); // 13
7631 data
<< uint32(0xa3d) << uint32(0x5); // 14
7632 data
<< uint32(0xa3c) << uint32(0x0); // 15
7633 data
<< uint32(0xa87) << uint32(0x0); // 16
7634 data
<< uint32(0xa86) << uint32(0x0); // 17
7635 data
<< uint32(0xa85) << uint32(0x0); // 18
7636 data
<< uint32(0xa84) << uint32(0x0); // 19
7637 data
<< uint32(0xa83) << uint32(0x0); // 20
7638 data
<< uint32(0xa82) << uint32(0x0); // 21
7639 data
<< uint32(0xa81) << uint32(0x0); // 22
7640 data
<< uint32(0xa80) << uint32(0x0); // 23
7641 data
<< uint32(0xa7e) << uint32(0x0); // 24
7642 data
<< uint32(0xa7d) << uint32(0x0); // 25
7643 data
<< uint32(0xa7c) << uint32(0x0); // 26
7644 data
<< uint32(0xa7b) << uint32(0x0); // 27
7645 data
<< uint32(0xa7a) << uint32(0x0); // 28
7646 data
<< uint32(0xa79) << uint32(0x0); // 29
7647 data
<< uint32(0x9d0) << uint32(0x5); // 30
7648 data
<< uint32(0x9ce) << uint32(0x0); // 31
7649 data
<< uint32(0x9cd) << uint32(0x0); // 32
7650 data
<< uint32(0x9cc) << uint32(0x0); // 33
7651 data
<< uint32(0xa88) << uint32(0x0); // 34
7652 data
<< uint32(0xad0) << uint32(0x0); // 35
7653 data
<< uint32(0xacf) << uint32(0x1); // 36
7655 case 3521: // Zangarmarsh
7656 data
<< uint32(0x9e1) << uint32(0x0); // 10
7657 data
<< uint32(0x9e0) << uint32(0x0); // 11
7658 data
<< uint32(0x9df) << uint32(0x0); // 12
7659 data
<< uint32(0xa5d) << uint32(0x1); // 13
7660 data
<< uint32(0xa5c) << uint32(0x0); // 14
7661 data
<< uint32(0xa5b) << uint32(0x1); // 15
7662 data
<< uint32(0xa5a) << uint32(0x0); // 16
7663 data
<< uint32(0xa59) << uint32(0x1); // 17
7664 data
<< uint32(0xa58) << uint32(0x0); // 18
7665 data
<< uint32(0xa57) << uint32(0x0); // 19
7666 data
<< uint32(0xa56) << uint32(0x0); // 20
7667 data
<< uint32(0xa55) << uint32(0x1); // 21
7668 data
<< uint32(0xa54) << uint32(0x0); // 22
7669 data
<< uint32(0x9e7) << uint32(0x0); // 23
7670 data
<< uint32(0x9e6) << uint32(0x0); // 24
7671 data
<< uint32(0x9e5) << uint32(0x0); // 25
7672 data
<< uint32(0xa00) << uint32(0x0); // 26
7673 data
<< uint32(0x9ff) << uint32(0x1); // 27
7674 data
<< uint32(0x9fe) << uint32(0x0); // 28
7675 data
<< uint32(0x9fd) << uint32(0x0); // 29
7676 data
<< uint32(0x9fc) << uint32(0x1); // 30
7677 data
<< uint32(0x9fb) << uint32(0x0); // 31
7678 data
<< uint32(0xa62) << uint32(0x0); // 32
7679 data
<< uint32(0xa61) << uint32(0x1); // 33
7680 data
<< uint32(0xa60) << uint32(0x1); // 34
7681 data
<< uint32(0xa5f) << uint32(0x0); // 35
7683 case 3698: // Nagrand Arena
7684 data
<< uint32(0xa0f) << uint32(0x0); // 7
7685 data
<< uint32(0xa10) << uint32(0x0); // 8
7686 data
<< uint32(0xa11) << uint32(0x0); // 9
7688 case 3702: // Blade's Edge Arena
7689 data
<< uint32(0x9f0) << uint32(0x0); // 7
7690 data
<< uint32(0x9f1) << uint32(0x0); // 8
7691 data
<< uint32(0x9f3) << uint32(0x0); // 9
7693 case 3968: // Ruins of Lordaeron
7694 data
<< uint32(0xbb8) << uint32(0x0); // 7
7695 data
<< uint32(0xbb9) << uint32(0x0); // 8
7696 data
<< uint32(0xbba) << uint32(0x0); // 9
7698 case 3703: // Shattrath City
7701 data
<< uint32(0x914) << uint32(0x0); // 7
7702 data
<< uint32(0x913) << uint32(0x0); // 8
7703 data
<< uint32(0x912) << uint32(0x0); // 9
7704 data
<< uint32(0x915) << uint32(0x0); // 10
7707 GetSession()->SendPacket(&data
);
7710 uint32
Player::GetXPRestBonus(uint32 xp
)
7712 uint32 rested_bonus
= (uint32
)GetRestBonus(); // xp for each rested bonus
7714 if(rested_bonus
> xp
) // max rested_bonus == xp or (r+x) = 200% xp
7717 SetRestBonus( GetRestBonus() - rested_bonus
);
7719 sLog
.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp
+rested_bonus
,rested_bonus
,GetRestBonus());
7720 return rested_bonus
;
7723 void Player::SetBindPoint(uint64 guid
)
7725 WorldPacket
data(SMSG_BINDER_CONFIRM
, 8);
7726 data
<< uint64(guid
);
7727 GetSession()->SendPacket( &data
);
7730 void Player::SendTalentWipeConfirm(uint64 guid
)
7732 WorldPacket
data(MSG_TALENT_WIPE_CONFIRM
, (8+4));
7733 data
<< uint64(guid
);
7734 data
<< uint32(resetTalentsCost());
7735 GetSession()->SendPacket( &data
);
7738 void Player::SendPetSkillWipeConfirm()
7740 Pet
* pet
= GetPet();
7743 WorldPacket
data(SMSG_PET_UNLEARN_CONFIRM
, (8+4));
7744 data
<< pet
->GetGUID();
7745 data
<< uint32(pet
->resetTalentsCost());
7746 GetSession()->SendPacket( &data
);
7749 /*********************************************************/
7750 /*** STORAGE SYSTEM ***/
7751 /*********************************************************/
7753 void Player::SetVirtualItemSlot( uint8 i
, Item
* item
)
7758 if(!item
->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT
))
7760 uint32 charges
= item
->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
);
7764 item
->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
,charges
-1);
7765 else if(charges
<= 1)
7767 ApplyEnchantment(item
,TEMP_ENCHANTMENT_SLOT
,false);
7768 item
->ClearEnchantment(TEMP_ENCHANTMENT_SLOT
);
7773 void Player::SetSheath( uint32 sheathed
)
7777 case SHEATH_STATE_UNARMED
: // no prepared weapon
7778 SetVirtualItemSlot(0,NULL
);
7779 SetVirtualItemSlot(1,NULL
);
7780 SetVirtualItemSlot(2,NULL
);
7782 case SHEATH_STATE_MELEE
: // prepared melee weapon
7784 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK
,true));
7785 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK
,true));
7786 SetVirtualItemSlot(2,NULL
);
7788 case SHEATH_STATE_RANGED
: // prepared ranged weapon
7789 SetVirtualItemSlot(0,NULL
);
7790 SetVirtualItemSlot(1,NULL
);
7791 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK
,true));
7794 SetVirtualItemSlot(0,NULL
);
7795 SetVirtualItemSlot(1,NULL
);
7796 SetVirtualItemSlot(2,NULL
);
7799 SetByteValue(UNIT_FIELD_BYTES_2
, 0, sheathed
); // this must visualize Sheath changing for other players...
7802 uint8
Player::FindEquipSlot( ItemPrototype
const* proto
, uint32 slot
, bool swap
) const
7804 uint8 pClass
= getClass();
7807 slots
[0] = NULL_SLOT
;
7808 slots
[1] = NULL_SLOT
;
7809 slots
[2] = NULL_SLOT
;
7810 slots
[3] = NULL_SLOT
;
7811 switch( proto
->InventoryType
)
7814 slots
[0] = EQUIPMENT_SLOT_HEAD
;
7817 slots
[0] = EQUIPMENT_SLOT_NECK
;
7819 case INVTYPE_SHOULDERS
:
7820 slots
[0] = EQUIPMENT_SLOT_SHOULDERS
;
7823 slots
[0] = EQUIPMENT_SLOT_BODY
;
7826 slots
[0] = EQUIPMENT_SLOT_CHEST
;
7829 slots
[0] = EQUIPMENT_SLOT_CHEST
;
7832 slots
[0] = EQUIPMENT_SLOT_WAIST
;
7835 slots
[0] = EQUIPMENT_SLOT_LEGS
;
7838 slots
[0] = EQUIPMENT_SLOT_FEET
;
7840 case INVTYPE_WRISTS
:
7841 slots
[0] = EQUIPMENT_SLOT_WRISTS
;
7844 slots
[0] = EQUIPMENT_SLOT_HANDS
;
7846 case INVTYPE_FINGER
:
7847 slots
[0] = EQUIPMENT_SLOT_FINGER1
;
7848 slots
[1] = EQUIPMENT_SLOT_FINGER2
;
7850 case INVTYPE_TRINKET
:
7851 slots
[0] = EQUIPMENT_SLOT_TRINKET1
;
7852 slots
[1] = EQUIPMENT_SLOT_TRINKET2
;
7855 slots
[0] = EQUIPMENT_SLOT_BACK
;
7857 case INVTYPE_WEAPON
:
7859 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
7861 // suggest offhand slot only if know dual wielding
7862 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
7864 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
7866 case INVTYPE_SHIELD
:
7867 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
7869 case INVTYPE_RANGED
:
7870 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7872 case INVTYPE_2HWEAPON
:
7873 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
7875 case INVTYPE_TABARD
:
7876 slots
[0] = EQUIPMENT_SLOT_TABARD
;
7878 case INVTYPE_WEAPONMAINHAND
:
7879 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
7881 case INVTYPE_WEAPONOFFHAND
:
7882 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
7884 case INVTYPE_HOLDABLE
:
7885 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
7887 case INVTYPE_THROWN
:
7888 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7890 case INVTYPE_RANGEDRIGHT
:
7891 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7894 slots
[0] = INVENTORY_SLOT_BAG_1
;
7895 slots
[1] = INVENTORY_SLOT_BAG_2
;
7896 slots
[2] = INVENTORY_SLOT_BAG_3
;
7897 slots
[3] = INVENTORY_SLOT_BAG_4
;
7901 switch(proto
->SubClass
)
7903 case ITEM_SUBCLASS_ARMOR_LIBRAM
:
7904 if (pClass
== CLASS_PALADIN
)
7905 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7907 case ITEM_SUBCLASS_ARMOR_IDOL
:
7908 if (pClass
== CLASS_DRUID
)
7909 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7911 case ITEM_SUBCLASS_ARMOR_TOTEM
:
7912 if (pClass
== CLASS_SHAMAN
)
7913 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7915 case ITEM_SUBCLASS_ARMOR_MISC
:
7916 if (pClass
== CLASS_WARLOCK
)
7917 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7926 if( slot
!= NULL_SLOT
)
7928 if( swap
|| !GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
) )
7930 for (int i
= 0; i
< 4; i
++)
7932 if ( slots
[i
] == slot
)
7939 // search free slot at first
7940 for (int i
= 0; i
< 4; i
++)
7942 if ( slots
[i
] != NULL_SLOT
&& !GetItemByPos( INVENTORY_SLOT_BAG_0
, slots
[i
] ) )
7944 // in case 2hand equipped weapon offhand slot empty but not free
7945 if(slots
[i
]==EQUIPMENT_SLOT_OFFHAND
)
7947 Item
* mainItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_MAINHAND
);
7948 if(!mainItem
|| mainItem
->GetProto()->InventoryType
!= INVTYPE_2HWEAPON
)
7956 // if not found free and can swap return first appropriate from used
7957 for (int i
= 0; i
< 4; i
++)
7959 if ( slots
[i
] != NULL_SLOT
&& swap
)
7968 uint8
Player::CanUnequipItems( uint32 item
, uint32 count
) const
7971 uint32 tempcount
= 0;
7973 uint8 res
= EQUIP_ERR_OK
;
7975 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
7977 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
7978 if( pItem
&& pItem
->GetEntry() == item
)
7980 uint8 ires
= CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
, false);
7981 if(ires
==EQUIP_ERR_OK
)
7983 tempcount
+= pItem
->GetCount();
7984 if( tempcount
>= count
)
7985 return EQUIP_ERR_OK
;
7991 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
7993 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
7994 if( pItem
&& pItem
->GetEntry() == item
)
7996 tempcount
+= pItem
->GetCount();
7997 if( tempcount
>= count
)
7998 return EQUIP_ERR_OK
;
8001 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
8003 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8004 if( pItem
&& pItem
->GetEntry() == item
)
8006 tempcount
+= pItem
->GetCount();
8007 if( tempcount
>= count
)
8008 return EQUIP_ERR_OK
;
8012 ItemPrototype
const *pBagProto
;
8013 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8015 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8018 pBagProto
= pBag
->GetProto();
8021 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
8023 pItem
= GetItemByPos( i
, j
);
8024 if( pItem
&& pItem
->GetEntry() == item
)
8026 tempcount
+= pItem
->GetCount();
8027 if( tempcount
>= count
)
8028 return EQUIP_ERR_OK
;
8035 // not found req. item count and have unequippable items
8039 uint32
Player::GetItemCount( uint32 item
, bool inBankAlso
, Item
* skipItem
) const
8042 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8044 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8045 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8046 count
+= pItem
->GetCount();
8048 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
8050 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8051 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8052 count
+= pItem
->GetCount();
8054 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8056 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8058 count
+= pBag
->GetItemCount(item
,skipItem
);
8061 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8063 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8065 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8066 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8067 count
+= pItem
->GetGemCountWithID(item
);
8073 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8075 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8076 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8077 count
+= pItem
->GetCount();
8079 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8081 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8083 count
+= pBag
->GetItemCount(item
,skipItem
);
8086 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8088 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8090 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8091 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8092 count
+= pItem
->GetGemCountWithID(item
);
8100 Item
* Player::GetItemByGuid( uint64 guid
) const
8102 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8104 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8105 if( pItem
&& pItem
->GetGUID() == guid
)
8108 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
8110 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8111 if( pItem
&& pItem
->GetGUID() == guid
)
8115 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8117 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8120 ItemPrototype
const *pBagProto
= pBag
->GetProto();
8123 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
8125 Item
* pItem
= pBag
->GetItemByPos( j
);
8126 if( pItem
&& pItem
->GetGUID() == guid
)
8132 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8134 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8137 ItemPrototype
const *pBagProto
= pBag
->GetProto();
8140 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
8142 Item
* pItem
= pBag
->GetItemByPos( j
);
8143 if( pItem
&& pItem
->GetGUID() == guid
)
8153 Item
* Player::GetItemByPos( uint16 pos
) const
8155 uint8 bag
= pos
>> 8;
8156 uint8 slot
= pos
& 255;
8157 return GetItemByPos( bag
, slot
);
8160 Item
* Player::GetItemByPos( uint8 bag
, uint8 slot
) const
8162 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< BANK_SLOT_BAG_END
|| slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_END
) )
8163 return m_items
[slot
];
8164 else if(bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
8165 || bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8167 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8169 return pBag
->GetItemByPos(slot
);
8174 Item
* Player::GetWeaponForAttack(WeaponAttackType attackType
, bool useable
) const
8179 case BASE_ATTACK
: slot
= EQUIPMENT_SLOT_MAINHAND
; break;
8180 case OFF_ATTACK
: slot
= EQUIPMENT_SLOT_OFFHAND
; break;
8181 case RANGED_ATTACK
: slot
= EQUIPMENT_SLOT_RANGED
; break;
8182 default: return NULL
;
8185 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, slot
);
8186 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_WEAPON
)
8192 if( item
->IsBroken() || !IsUseEquipedWeapon(attackType
==BASE_ATTACK
) )
8198 Item
* Player::GetShield(bool useable
) const
8200 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
8201 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_ARMOR
)
8207 if( item
->IsBroken())
8213 uint32
Player::GetAttackBySlot( uint8 slot
)
8217 case EQUIPMENT_SLOT_MAINHAND
: return BASE_ATTACK
;
8218 case EQUIPMENT_SLOT_OFFHAND
: return OFF_ATTACK
;
8219 case EQUIPMENT_SLOT_RANGED
: return RANGED_ATTACK
;
8220 default: return MAX_ATTACK
;
8224 bool Player::HasBankBagSlot( uint8 slot
) const
8226 uint32 maxslot
= GetByteValue(PLAYER_BYTES_2
, 2) + BANK_SLOT_BAG_START
;
8227 if( slot
< maxslot
)
8232 bool Player::IsInventoryPos( uint8 bag
, uint8 slot
)
8234 if( bag
== INVENTORY_SLOT_BAG_0
&& slot
== NULL_SLOT
)
8236 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
) )
8238 if( bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8240 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_END
) )
8245 bool Player::IsEquipmentPos( uint8 bag
, uint8 slot
)
8247 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< EQUIPMENT_SLOT_END
) )
8249 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8254 bool Player::IsBankPos( uint8 bag
, uint8 slot
)
8256 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
) )
8258 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8260 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8265 bool Player::IsBagPos( uint16 pos
)
8267 uint8 bag
= pos
>> 8;
8268 uint8 slot
= pos
& 255;
8269 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8271 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8276 bool Player::HasItemCount( uint32 item
, uint32 count
, bool inBankAlso
) const
8278 uint32 tempcount
= 0;
8279 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8281 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8282 if( pItem
&& pItem
->GetEntry() == item
)
8284 tempcount
+= pItem
->GetCount();
8285 if( tempcount
>= count
)
8289 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
8291 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8292 if( pItem
&& pItem
->GetEntry() == item
)
8294 tempcount
+= pItem
->GetCount();
8295 if( tempcount
>= count
)
8299 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8301 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8303 if(ItemPrototype
const *pBagProto
= pBag
->GetProto())
8305 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
8307 Item
* pItem
= GetItemByPos( i
, j
);
8308 if( pItem
&& pItem
->GetEntry() == item
)
8310 tempcount
+= pItem
->GetCount();
8311 if( tempcount
>= count
)
8321 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8323 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8324 if( pItem
&& pItem
->GetEntry() == item
)
8326 tempcount
+= pItem
->GetCount();
8327 if( tempcount
>= count
)
8331 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8333 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8335 if(ItemPrototype
const *pBagProto
= pBag
->GetProto())
8337 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
8339 Item
* pItem
= GetItemByPos( i
, j
);
8340 if( pItem
&& pItem
->GetEntry() == item
)
8342 tempcount
+= pItem
->GetCount();
8343 if( tempcount
>= count
)
8355 Item
* Player::GetItemOrItemWithGemEquipped( uint32 item
) const
8358 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
8360 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8361 if( pItem
&& pItem
->GetEntry() == item
)
8365 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(item
);
8366 if (pProto
&& pProto
->GemProperties
)
8368 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
8370 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8371 if( pItem
&& pItem
->GetProto()->Socket
[0].Color
)
8373 if (pItem
->GetGemCountWithID(item
) > 0 )
8382 uint8
Player::_CanTakeMoreSimilarItems(uint32 entry
, uint32 count
, Item
* pItem
, uint32
* no_space_count
) const
8384 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
8388 *no_space_count
= count
;
8389 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8393 if(pProto
->MaxCount
== 0)
8394 return EQUIP_ERR_OK
;
8396 uint32 curcount
= GetItemCount(pProto
->ItemId
,true,pItem
);
8398 if( curcount
+ count
> pProto
->MaxCount
)
8401 *no_space_count
= count
+curcount
- pProto
->MaxCount
;
8402 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8405 return EQUIP_ERR_OK
;
8408 bool Player::HasItemTotemCategory( uint32 TotemCategory
) const
8411 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8413 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8414 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8417 for(uint8 i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; ++i
)
8419 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8420 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8424 ItemPrototype
const *pBagProto
;
8425 for(uint8 i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8427 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8430 pBagProto
= pBag
->GetProto();
8433 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; ++j
)
8435 pItem
= GetItemByPos( i
, j
);
8436 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8445 uint8
Player::_CanStoreItem_InSpecificSlot( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, ItemPrototype
const *pProto
, uint32
& count
, bool swap
, Item
* pSrcItem
) const
8447 Item
* pItem2
= GetItemByPos( bag
, slot
);
8449 // ignore move item (this slot will be empty at move)
8450 if(pItem2
==pSrcItem
)
8455 // empty specific slot - check item fit to slot
8456 if( !pItem2
|| swap
)
8458 if( bag
== INVENTORY_SLOT_BAG_0
)
8461 if(slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_START
+GetMaxKeyringSize() && !(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
))
8462 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8465 if(slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
|| slot
>= PLAYER_SLOT_END
)
8466 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8470 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8472 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8474 ItemPrototype
const* pBagProto
= pBag
->GetProto();
8476 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8478 if( !ItemCanGoIntoBag(pProto
,pBagProto
) )
8479 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8482 // non empty stack with space
8483 need_space
= pProto
->Stackable
;
8485 // non empty slot, check item type
8489 if(pItem2
->GetEntry() != pProto
->ItemId
)
8490 return EQUIP_ERR_ITEM_CANT_STACK
;
8493 if(pItem2
->GetCount() >= pProto
->Stackable
)
8494 return EQUIP_ERR_ITEM_CANT_STACK
;
8496 need_space
= pProto
->Stackable
- pItem2
->GetCount();
8499 if(need_space
> count
)
8502 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | slot
, need_space
);
8503 if(!newPosition
.isContainedIn(dest
))
8505 dest
.push_back(newPosition
);
8506 count
-= need_space
;
8508 return EQUIP_ERR_OK
;
8511 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
8513 // skip specific bag already processed in first called _CanStoreItem_InBag
8515 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8517 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8519 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8521 ItemPrototype
const* pBagProto
= pBag
->GetProto();
8523 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8525 // specialized bag mode or non-specilized
8526 if( non_specialized
!= (pBagProto
->Class
== ITEM_CLASS_CONTAINER
&& pBagProto
->SubClass
== ITEM_SUBCLASS_CONTAINER
) )
8527 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8529 if( !ItemCanGoIntoBag(pProto
,pBagProto
) )
8530 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8532 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
8534 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8538 Item
* pItem2
= GetItemByPos( bag
, j
);
8540 // ignore move item (this slot will be empty at move)
8541 if(pItem2
==pSrcItem
)
8544 // if merge skip empty, if !merge skip non-empty
8545 if((pItem2
!=NULL
)!=merge
)
8550 if(pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->Stackable
)
8552 uint32 need_space
= pProto
->Stackable
- pItem2
->GetCount();
8553 if(need_space
> count
)
8556 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
8557 if(!newPosition
.isContainedIn(dest
))
8559 dest
.push_back(newPosition
);
8560 count
-= need_space
;
8563 return EQUIP_ERR_OK
;
8569 uint32 need_space
= pProto
->Stackable
;
8570 if(need_space
> count
)
8573 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
8574 if(!newPosition
.isContainedIn(dest
))
8576 dest
.push_back(newPosition
);
8577 count
-= need_space
;
8580 return EQUIP_ERR_OK
;
8584 return EQUIP_ERR_OK
;
8587 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
8589 for(uint32 j
= slot_begin
; j
< slot_end
; j
++)
8591 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8592 if(INVENTORY_SLOT_BAG_0
==skip_bag
&& j
==skip_slot
)
8595 Item
* pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, j
);
8597 // ignore move item (this slot will be empty at move)
8598 if(pItem2
==pSrcItem
)
8601 // if merge skip empty, if !merge skip non-empty
8602 if((pItem2
!=NULL
)!=merge
)
8607 if(pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->Stackable
)
8609 uint32 need_space
= pProto
->Stackable
- pItem2
->GetCount();
8610 if(need_space
> count
)
8612 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
8613 if(!newPosition
.isContainedIn(dest
))
8615 dest
.push_back(newPosition
);
8616 count
-= need_space
;
8619 return EQUIP_ERR_OK
;
8625 uint32 need_space
= pProto
->Stackable
;
8626 if(need_space
> count
)
8629 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
8630 if(!newPosition
.isContainedIn(dest
))
8632 dest
.push_back(newPosition
);
8633 count
-= need_space
;
8636 return EQUIP_ERR_OK
;
8640 return EQUIP_ERR_OK
;
8643 uint8
Player::_CanStoreItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, uint32 entry
, uint32 count
, Item
*pItem
, bool swap
, uint32
* no_space_count
) const
8645 sLog
.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, entry
, count
);
8647 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
8651 *no_space_count
= count
;
8652 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
:EQUIP_ERR_ITEM_NOT_FOUND
;
8655 if(pItem
&& pItem
->IsBindedNotWith(GetGUID()))
8658 *no_space_count
= count
;
8659 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
8662 // check count of items (skip for auto move for same player from bank)
8663 uint32 no_similar_count
= 0; // can't store this amount similar items
8664 uint8 res
= _CanTakeMoreSimilarItems(entry
,count
,pItem
,&no_similar_count
);
8665 if(res
!=EQUIP_ERR_OK
)
8667 if(count
==no_similar_count
)
8670 *no_space_count
= no_similar_count
;
8673 count
-= no_similar_count
;
8677 if( bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
8679 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
8680 if(res
!=EQUIP_ERR_OK
)
8683 *no_space_count
= count
+ no_similar_count
;
8689 if(no_similar_count
==0)
8690 return EQUIP_ERR_OK
;
8693 *no_space_count
= count
+ no_similar_count
;
8694 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8698 // not specific slot or have spece for partly store only in specific slot
8701 if( bag
!= NULL_BAG
)
8703 // search stack in bag for merge to
8704 if( pProto
->Stackable
> 1 )
8706 if( bag
== INVENTORY_SLOT_BAG_0
) // inventory
8708 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
8709 if(res
!=EQUIP_ERR_OK
)
8712 *no_space_count
= count
+ no_similar_count
;
8718 if(no_similar_count
==0)
8719 return EQUIP_ERR_OK
;
8722 *no_space_count
= count
+ no_similar_count
;
8723 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8726 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
8727 if(res
!=EQUIP_ERR_OK
)
8730 *no_space_count
= count
+ no_similar_count
;
8736 if(no_similar_count
==0)
8737 return EQUIP_ERR_OK
;
8740 *no_space_count
= count
+ no_similar_count
;
8741 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8744 else // equipped bag
8746 // we need check 2 time (specilized/non_specialized), use NULL_BAG to prevent skipping bag
8747 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
8748 if(res
!=EQUIP_ERR_OK
)
8749 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
8751 if(res
!=EQUIP_ERR_OK
)
8754 *no_space_count
= count
+ no_similar_count
;
8760 if(no_similar_count
==0)
8761 return EQUIP_ERR_OK
;
8764 *no_space_count
= count
+ no_similar_count
;
8765 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8770 // search free slot in bag for place to
8771 if( bag
== INVENTORY_SLOT_BAG_0
) // inventory
8773 // search free slot - keyring case
8774 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
8776 uint32 keyringSize
= GetMaxKeyringSize();
8777 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
8778 if(res
!=EQUIP_ERR_OK
)
8781 *no_space_count
= count
+ no_similar_count
;
8787 if(no_similar_count
==0)
8788 return EQUIP_ERR_OK
;
8791 *no_space_count
= count
+ no_similar_count
;
8792 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8796 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
8797 if(res
!=EQUIP_ERR_OK
)
8800 *no_space_count
= count
+ no_similar_count
;
8806 if(no_similar_count
==0)
8807 return EQUIP_ERR_OK
;
8810 *no_space_count
= count
+ no_similar_count
;
8811 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8814 else // equipped bag
8816 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
8817 if(res
!=EQUIP_ERR_OK
)
8818 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
8820 if(res
!=EQUIP_ERR_OK
)
8823 *no_space_count
= count
+ no_similar_count
;
8829 if(no_similar_count
==0)
8830 return EQUIP_ERR_OK
;
8833 *no_space_count
= count
+ no_similar_count
;
8834 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8839 // not specific bag or have space for partly store only in specific bag
8841 // search stack for merge to
8842 if( pProto
->Stackable
> 1 )
8844 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
8845 if(res
!=EQUIP_ERR_OK
)
8848 *no_space_count
= count
+ no_similar_count
;
8854 if(no_similar_count
==0)
8855 return EQUIP_ERR_OK
;
8858 *no_space_count
= count
+ no_similar_count
;
8859 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8862 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
8863 if(res
!=EQUIP_ERR_OK
)
8866 *no_space_count
= count
+ no_similar_count
;
8872 if(no_similar_count
==0)
8873 return EQUIP_ERR_OK
;
8876 *no_space_count
= count
+ no_similar_count
;
8877 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8880 if( pProto
->BagFamily
)
8882 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8884 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
8885 if(res
!=EQUIP_ERR_OK
)
8890 if(no_similar_count
==0)
8891 return EQUIP_ERR_OK
;
8894 *no_space_count
= count
+ no_similar_count
;
8895 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8900 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8902 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
8903 if(res
!=EQUIP_ERR_OK
)
8908 if(no_similar_count
==0)
8909 return EQUIP_ERR_OK
;
8912 *no_space_count
= count
+ no_similar_count
;
8913 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8918 // search free slot - special bag case
8919 if( pProto
->BagFamily
)
8921 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
8923 uint32 keyringSize
= GetMaxKeyringSize();
8924 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
8925 if(res
!=EQUIP_ERR_OK
)
8928 *no_space_count
= count
+ no_similar_count
;
8934 if(no_similar_count
==0)
8935 return EQUIP_ERR_OK
;
8938 *no_space_count
= count
+ no_similar_count
;
8939 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8943 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8945 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
8946 if(res
!=EQUIP_ERR_OK
)
8951 if(no_similar_count
==0)
8952 return EQUIP_ERR_OK
;
8955 *no_space_count
= count
+ no_similar_count
;
8956 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8962 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
8963 if(res
!=EQUIP_ERR_OK
)
8966 *no_space_count
= count
+ no_similar_count
;
8972 if(no_similar_count
==0)
8973 return EQUIP_ERR_OK
;
8976 *no_space_count
= count
+ no_similar_count
;
8977 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8980 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8982 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
8983 if(res
!=EQUIP_ERR_OK
)
8988 if(no_similar_count
==0)
8989 return EQUIP_ERR_OK
;
8992 *no_space_count
= count
+ no_similar_count
;
8993 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8998 *no_space_count
= count
+ no_similar_count
;
9000 return EQUIP_ERR_INVENTORY_FULL
;
9003 //////////////////////////////////////////////////////////////////////////
9004 uint8
Player::CanStoreItems( Item
**pItems
,int count
) const
9009 int inv_slot_items
[INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
];
9010 int inv_bags
[INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
][MAX_BAG_SIZE
];
9011 int inv_keys
[KEYRING_SLOT_END
-KEYRING_SLOT_START
];
9013 memset(inv_slot_items
,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
));
9014 memset(inv_bags
,0,sizeof(int)*(INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
)*MAX_BAG_SIZE
);
9015 memset(inv_keys
,0,sizeof(int)*(KEYRING_SLOT_END
-KEYRING_SLOT_START
));
9017 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
9019 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9021 if (pItem2
&& !pItem2
->IsInTrade())
9023 inv_slot_items
[i
-INVENTORY_SLOT_ITEM_START
] = pItem2
->GetCount();
9027 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
9029 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9031 if (pItem2
&& !pItem2
->IsInTrade())
9033 inv_keys
[i
-KEYRING_SLOT_START
] = pItem2
->GetCount();
9037 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9040 ItemPrototype
const *pBagProto
;
9042 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9045 pBagProto
= pBag
->GetProto();
9049 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
9051 pItem2
= GetItemByPos( i
, j
);
9052 if (pItem2
&& !pItem2
->IsInTrade())
9054 inv_bags
[i
-INVENTORY_SLOT_BAG_START
][j
] = pItem2
->GetCount();
9061 // check free space for all items
9062 for (int k
=0;k
<count
;k
++)
9064 Item
*pItem
= pItems
[k
];
9067 if (!pItem
) continue;
9069 sLog
.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k
+1, pItem
->GetEntry(), pItem
->GetCount());
9070 ItemPrototype
const *pProto
= pItem
->GetProto();
9074 return EQUIP_ERR_ITEM_NOT_FOUND
;
9077 if(pItem
->IsBindedNotWith(GetGUID()))
9078 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9081 ItemPrototype
const *pBagProto
;
9083 // item is 'one item only'
9084 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9085 if(res
!= EQUIP_ERR_OK
)
9088 // search stack for merge to
9089 if( pProto
->Stackable
> 1 )
9091 bool b_found
= false;
9093 for(int t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_END
; t
++)
9095 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9096 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_keys
[t
-KEYRING_SLOT_START
] + pItem
->GetCount() <= pProto
->Stackable
)
9098 inv_keys
[t
-KEYRING_SLOT_START
] += pItem
->GetCount();
9103 if (b_found
) continue;
9105 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; t
++)
9107 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9108 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] + pItem
->GetCount() <= pProto
->Stackable
)
9110 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] += pItem
->GetCount();
9115 if (b_found
) continue;
9117 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9119 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9122 pBagProto
= pBag
->GetProto();
9125 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
9127 pItem2
= GetItemByPos( t
, j
);
9128 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] + pItem
->GetCount() <= pProto
->Stackable
)
9130 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] += pItem
->GetCount();
9138 if (b_found
) continue;
9142 if( pProto
->BagFamily
)
9144 bool b_found
= false;
9145 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9147 uint32 keyringSize
= GetMaxKeyringSize();
9148 for(uint32 t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_START
+keyringSize
; ++t
)
9150 if( inv_keys
[t
-KEYRING_SLOT_START
] == 0 )
9152 inv_keys
[t
-KEYRING_SLOT_START
] = 1;
9159 if (b_found
) continue;
9161 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9163 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9166 pBagProto
= pBag
->GetProto();
9168 // not plain container check
9169 if( pBagProto
&& (pBagProto
->Class
!= ITEM_CLASS_CONTAINER
|| pBagProto
->SubClass
!= ITEM_SUBCLASS_CONTAINER
) &&
9170 ItemCanGoIntoBag(pProto
,pBagProto
) )
9172 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
9174 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9176 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9184 if (b_found
) continue;
9188 bool b_found
= false;
9189 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; t
++)
9191 if( inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] == 0 )
9193 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] = 1;
9198 if (b_found
) continue;
9200 // search free slot in bags
9201 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9203 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9206 pBagProto
= pBag
->GetProto();
9207 if( pBagProto
&& ItemCanGoIntoBag(pProto
,pBagProto
))
9209 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
9211 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9213 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9222 // no free slot found?
9224 return EQUIP_ERR_INVENTORY_FULL
;
9227 return EQUIP_ERR_OK
;
9230 //////////////////////////////////////////////////////////////////////////
9231 uint8
Player::CanEquipNewItem( uint8 slot
, uint16
&dest
, uint32 item
, uint32 count
, bool swap
) const
9234 Item
*pItem
= Item::CreateItem( item
, count
, this );
9237 uint8 result
= CanEquipItem(slot
, dest
, pItem
, swap
);
9242 return EQUIP_ERR_ITEM_NOT_FOUND
;
9245 uint8
Player::CanEquipItem( uint8 slot
, uint16
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
9250 sLog
.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot
, pItem
->GetEntry(), pItem
->GetCount());
9251 ItemPrototype
const *pProto
= pItem
->GetProto();
9254 // May be here should be more stronger checks; STUNNED checked
9255 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9256 if (not_loading
&& hasUnitState(UNIT_STAT_STUNNED
))
9257 return EQUIP_ERR_YOU_ARE_STUNNED
;
9259 if(pItem
->IsBindedNotWith(GetGUID()))
9260 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9262 // check count of items (skip for auto move for same player from bank)
9263 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9264 if(res
!= EQUIP_ERR_OK
)
9267 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9269 // - in-progress arenas
9270 if( !pProto
->CanChangeEquipStateInCombat() )
9273 return EQUIP_ERR_NOT_IN_COMBAT
;
9275 if(BattleGround
* bg
= GetBattleGround())
9276 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
9277 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
9280 if(isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
!= 0)
9281 return EQUIP_ERR_CANT_DO_RIGHT_NOW
; // maybe exist better err
9283 if(IsNonMeleeSpellCasted(false))
9284 return EQUIP_ERR_CANT_DO_RIGHT_NOW
;
9286 uint8 eslot
= FindEquipSlot( pProto
, slot
, swap
);
9287 if( eslot
== NULL_SLOT
)
9288 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9290 uint8 msg
= CanUseItem( pItem
, not_loading
);
9291 if( msg
!= EQUIP_ERR_OK
)
9293 if( !swap
&& GetItemByPos( INVENTORY_SLOT_BAG_0
, eslot
) )
9294 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE
;
9296 // check unique-equipped on item
9297 if (pProto
->Flags
& ITEM_FLAGS_UNIQUE_EQUIPPED
)
9299 // there is an equip limit on this item
9300 Item
* tItem
= GetItemOrItemWithGemEquipped(pProto
->ItemId
);
9301 if (tItem
&& (!swap
|| tItem
->GetSlot() != eslot
) )
9302 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
9305 // check unique-equipped on gems
9306 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
9308 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
9311 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
9315 ItemPrototype
const* pGem
= objmgr
.GetItemPrototype(enchantEntry
->GemID
);
9316 if(pGem
&& (pGem
->Flags
& ITEM_FLAGS_UNIQUE_EQUIPPED
))
9318 Item
* tItem
= GetItemOrItemWithGemEquipped(enchantEntry
->GemID
);
9319 if(tItem
&& (!swap
|| tItem
->GetSlot() != eslot
))
9320 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
9324 // check unique-equipped special item classes
9325 if (pProto
->Class
== ITEM_CLASS_QUIVER
)
9327 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9329 if( Item
* pBag
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
) )
9331 if( ItemPrototype
const* pBagProto
= pBag
->GetProto() )
9333 if( pBagProto
->Class
==pProto
->Class
&& pBagProto
->SubClass
==pProto
->SubClass
&&
9334 (!swap
|| pBag
->GetSlot() != eslot
) )
9336 if(pBagProto
->SubClass
== ITEM_SUBCLASS_AMMO_POUCH
)
9337 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
;
9339 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER
;
9346 uint32 type
= pProto
->InventoryType
;
9348 if(eslot
== EQUIPMENT_SLOT_OFFHAND
)
9350 if( type
== INVTYPE_WEAPON
|| type
== INVTYPE_WEAPONOFFHAND
)
9353 return EQUIP_ERR_CANT_DUAL_WIELD
;
9356 Item
*mainItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_MAINHAND
);
9359 if(mainItem
->GetProto()->InventoryType
== INVTYPE_2HWEAPON
)
9360 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED
;
9364 // equip two-hand weapon case (with possible unequip 2 items)
9365 if( type
== INVTYPE_2HWEAPON
)
9367 if(eslot
!= EQUIPMENT_SLOT_MAINHAND
)
9368 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9370 // offhand item must can be stored in inventitory for offhand item and it also must be unequipped
9371 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
9372 ItemPosCountVec off_dest
;
9373 if( offItem
&& (!not_loading
||
9374 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0
) << 8 | EQUIPMENT_SLOT_OFFHAND
,false) != EQUIP_ERR_OK
||
9375 CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false ) != EQUIP_ERR_OK
) )
9376 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_INVENTORY_FULL
;
9378 dest
= ((INVENTORY_SLOT_BAG_0
<< 8) | eslot
);
9379 return EQUIP_ERR_OK
;
9383 return EQUIP_ERR_ITEM_NOT_FOUND
;
9385 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
;
9388 uint8
Player::CanUnequipItem( uint16 pos
, bool swap
) const
9390 // Applied only to equipped items and bank bags
9391 if(!IsEquipmentPos(pos
) && !IsBagPos(pos
))
9392 return EQUIP_ERR_OK
;
9394 Item
* pItem
= GetItemByPos(pos
);
9396 // Applied only to existed equipped item
9398 return EQUIP_ERR_OK
;
9400 sLog
.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos
, pItem
->GetEntry(), pItem
->GetCount());
9402 ItemPrototype
const *pProto
= pItem
->GetProto();
9404 return EQUIP_ERR_ITEM_NOT_FOUND
;
9406 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9408 // - in-progress arenas
9409 if( !pProto
->CanChangeEquipStateInCombat() )
9412 return EQUIP_ERR_NOT_IN_COMBAT
;
9414 if(BattleGround
* bg
= GetBattleGround())
9415 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
9416 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
9419 if(!swap
&& pItem
->IsBag() && !((Bag
*)pItem
)->IsEmpty())
9420 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS
;
9422 return EQUIP_ERR_OK
;
9425 uint8
Player::CanBankItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
9428 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
9430 uint32 count
= pItem
->GetCount();
9432 sLog
.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), pItem
->GetCount());
9433 ItemPrototype
const *pProto
= pItem
->GetProto();
9435 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
9437 if( pItem
->IsBindedNotWith(GetGUID()) )
9438 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9440 // check count of items (skip for auto move for same player from bank)
9441 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9442 if(res
!= EQUIP_ERR_OK
)
9446 if( bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
9448 if( pProto
->InventoryType
== INVTYPE_BAG
)
9450 Bag
*pBag
= (Bag
*)pItem
;
9453 if( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
9455 if( !HasBankBagSlot( slot
) )
9456 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT
;
9457 if( uint8 cantuse
= CanUseItem( pItem
, not_loading
) != EQUIP_ERR_OK
)
9462 if( !pBag
->IsEmpty() )
9463 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
;
9469 if( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
9470 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
;
9473 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
9474 if(res
!=EQUIP_ERR_OK
)
9478 return EQUIP_ERR_OK
;
9481 // not specific slot or have spece for partly store only in specific slot
9484 if( bag
!= NULL_BAG
)
9486 if( pProto
->InventoryType
== INVTYPE_BAG
)
9488 Bag
*pBag
= (Bag
*)pItem
;
9489 if( pBag
&& !pBag
->IsEmpty() )
9490 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
;
9493 // search stack in bag for merge to
9494 if( pProto
->Stackable
> 1 )
9496 if( bag
== INVENTORY_SLOT_BAG_0
)
9498 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9499 if(res
!=EQUIP_ERR_OK
)
9503 return EQUIP_ERR_OK
;
9507 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
9508 if(res
!=EQUIP_ERR_OK
)
9509 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
9511 if(res
!=EQUIP_ERR_OK
)
9515 return EQUIP_ERR_OK
;
9519 // search free slot in bag
9520 if( bag
== INVENTORY_SLOT_BAG_0
)
9522 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9523 if(res
!=EQUIP_ERR_OK
)
9527 return EQUIP_ERR_OK
;
9531 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
9532 if(res
!=EQUIP_ERR_OK
)
9533 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
9535 if(res
!=EQUIP_ERR_OK
)
9539 return EQUIP_ERR_OK
;
9543 // not specific bag or have spece for partly store only in specific bag
9545 // search stack for merge to
9546 if( pProto
->Stackable
> 1 )
9549 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9550 if(res
!=EQUIP_ERR_OK
)
9554 return EQUIP_ERR_OK
;
9557 if( pProto
->BagFamily
)
9559 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
9561 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
9562 if(res
!=EQUIP_ERR_OK
)
9566 return EQUIP_ERR_OK
;
9570 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
9572 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
9573 if(res
!=EQUIP_ERR_OK
)
9577 return EQUIP_ERR_OK
;
9581 // search free place in special bag
9582 if( pProto
->BagFamily
)
9584 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
9586 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
9587 if(res
!=EQUIP_ERR_OK
)
9591 return EQUIP_ERR_OK
;
9595 // search free space
9596 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9597 if(res
!=EQUIP_ERR_OK
)
9601 return EQUIP_ERR_OK
;
9603 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
9605 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
9606 if(res
!=EQUIP_ERR_OK
)
9610 return EQUIP_ERR_OK
;
9612 return EQUIP_ERR_BANK_FULL
;
9615 uint8
Player::CanUseItem( Item
*pItem
, bool not_loading
) const
9619 sLog
.outDebug( "STORAGE: CanUseItem item = %u", pItem
->GetEntry());
9620 if( !isAlive() && not_loading
)
9621 return EQUIP_ERR_YOU_ARE_DEAD
;
9623 // return EQUIP_ERR_YOU_ARE_STUNNED;
9624 ItemPrototype
const *pProto
= pItem
->GetProto();
9627 if( pItem
->IsBindedNotWith(GetGUID()) )
9628 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9629 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
9630 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
9631 if( pItem
->GetSkill() != 0 )
9633 if( GetSkillValue( pItem
->GetSkill() ) == 0 )
9634 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9636 if( pProto
->RequiredSkill
!= 0 )
9638 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
9639 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9640 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
9641 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
9643 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
9644 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9645 if( pProto
->RequiredReputationFaction
&& uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
9646 return EQUIP_ERR_CANT_EQUIP_REPUTATION
;
9647 if( getLevel() < pProto
->RequiredLevel
)
9648 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
9649 return EQUIP_ERR_OK
;
9652 return EQUIP_ERR_ITEM_NOT_FOUND
;
9655 bool Player::CanUseItem( ItemPrototype
const *pProto
)
9657 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
9661 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
9663 if( pProto
->RequiredSkill
!= 0 )
9665 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
9667 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
9670 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
9672 if( getLevel() < pProto
->RequiredLevel
)
9679 uint8
Player::CanUseAmmo( uint32 item
) const
9681 sLog
.outDebug( "STORAGE: CanUseAmmo item = %u", item
);
9683 return EQUIP_ERR_YOU_ARE_DEAD
;
9685 // return EQUIP_ERR_YOU_ARE_STUNNED;
9686 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
9689 if( pProto
->InventoryType
!= INVTYPE_AMMO
)
9690 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE
;
9691 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
9692 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
9693 if( pProto
->RequiredSkill
!= 0 )
9695 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
9696 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9697 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
9698 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
9700 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
9701 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9702 /*if( GetReputation() < pProto->RequiredReputation )
9703 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9705 if( getLevel() < pProto
->RequiredLevel
)
9706 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
9709 if(GetDummyAura(46699))
9710 return EQUIP_ERR_BAG_FULL6
;
9712 return EQUIP_ERR_OK
;
9714 return EQUIP_ERR_ITEM_NOT_FOUND
;
9717 void Player::SetAmmo( uint32 item
)
9723 if( GetUInt32Value(PLAYER_AMMO_ID
) == item
)
9729 uint8 msg
= CanUseAmmo( item
);
9730 if( msg
!= EQUIP_ERR_OK
)
9732 SendEquipError( msg
, NULL
, NULL
);
9737 SetUInt32Value(PLAYER_AMMO_ID
, item
);
9739 _ApplyAmmoBonuses();
9742 void Player::RemoveAmmo()
9744 SetUInt32Value(PLAYER_AMMO_ID
, 0);
9748 if(CanModifyStats())
9749 UpdateDamagePhysical(RANGED_ATTACK
);
9752 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
9753 Item
* Player::StoreNewItem( ItemPosCountVec
const& dest
, uint32 item
, bool update
,int32 randomPropertyId
)
9756 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); ++itr
)
9757 count
+= itr
->count
;
9759 Item
*pItem
= Item::CreateItem( item
, count
, this );
9762 ItemAddedQuestCheck( item
, count
);
9763 if(randomPropertyId
)
9764 pItem
->SetItemRandomProperties(randomPropertyId
);
9765 pItem
= StoreItem( dest
, pItem
, update
);
9770 Item
* Player::StoreItem( ItemPosCountVec
const& dest
, Item
* pItem
, bool update
)
9775 Item
* lastItem
= pItem
;
9777 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); )
9779 uint16 pos
= itr
->pos
;
9780 uint32 count
= itr
->count
;
9784 if(itr
== dest
.end())
9786 lastItem
= _StoreItem(pos
,pItem
,count
,false,update
);
9790 lastItem
= _StoreItem(pos
,pItem
,count
,true,update
);
9796 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
9797 Item
* Player::_StoreItem( uint16 pos
, Item
*pItem
, uint32 count
, bool clone
, bool update
)
9802 uint8 bag
= pos
>> 8;
9803 uint8 slot
= pos
& 255;
9805 sLog
.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), count
);
9807 Item
*pItem2
= GetItemByPos( bag
, slot
);
9812 pItem
= pItem
->CloneItem(count
,this);
9814 pItem
->SetCount(count
);
9819 if( pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
9820 pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
9821 pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
) )
9822 pItem
->SetBinding( true );
9824 if( bag
== INVENTORY_SLOT_BAG_0
)
9826 m_items
[slot
] = pItem
;
9827 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), pItem
->GetGUID() );
9828 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
9829 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
9831 pItem
->SetSlot( slot
);
9832 pItem
->SetContainer( NULL
);
9834 if( IsInWorld() && update
)
9836 pItem
->AddToWorld();
9837 pItem
->SendUpdateToPlayer( this );
9840 pItem
->SetState(ITEM_CHANGED
, this);
9844 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
9847 pBag
->StoreItem( slot
, pItem
, update
);
9848 if( IsInWorld() && update
)
9850 pItem
->AddToWorld();
9851 pItem
->SendUpdateToPlayer( this );
9853 pItem
->SetState(ITEM_CHANGED
, this);
9854 pBag
->SetState(ITEM_CHANGED
, this);
9858 AddEnchantmentDurations(pItem
);
9859 AddItemDurations(pItem
);
9865 if( pItem2
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
9866 pItem2
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
9867 pItem2
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
) )
9868 pItem2
->SetBinding( true );
9870 pItem2
->SetCount( pItem2
->GetCount() + count
);
9871 if( IsInWorld() && update
)
9872 pItem2
->SendUpdateToPlayer( this );
9876 // delete item (it not in any slot currently)
9877 if( IsInWorld() && update
)
9879 pItem
->RemoveFromWorld();
9880 pItem
->DestroyForPlayer( this );
9883 RemoveEnchantmentDurations(pItem
);
9884 RemoveItemDurations(pItem
);
9886 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
9887 pItem
->SetState(ITEM_REMOVED
, this);
9889 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
9890 AddEnchantmentDurations(pItem2
);
9892 pItem2
->SetState(ITEM_CHANGED
, this);
9898 Item
* Player::EquipNewItem( uint16 pos
, uint32 item
, uint32 count
, bool update
)
9900 Item
*pItem
= Item::CreateItem( item
, count
, this );
9903 ItemAddedQuestCheck( item
, count
);
9904 Item
* retItem
= EquipItem( pos
, pItem
, update
);
9911 Item
* Player::EquipItem( uint16 pos
, Item
*pItem
, bool update
)
9915 AddEnchantmentDurations(pItem
);
9916 AddItemDurations(pItem
);
9918 uint8 bag
= pos
>> 8;
9919 uint8 slot
= pos
& 255;
9921 Item
*pItem2
= GetItemByPos( bag
, slot
);
9925 VisualizeItem( slot
, pItem
);
9929 ItemPrototype
const *pProto
= pItem
->GetProto();
9931 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
9932 if(pProto
&& pProto
->ItemSet
)
9933 AddItemsSetItem(this,pItem
);
9935 _ApplyItemMods(pItem
, slot
, true);
9937 if(pProto
&& isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
== 0)
9939 m_weaponChangeTimer
= DEFAULT_SWITCH_WEAPON
;
9940 if (getClass() == CLASS_ROGUE
)
9941 m_weaponChangeTimer
= ROGUE_SWITCH_WEAPON
;
9945 if( IsInWorld() && update
)
9947 pItem
->AddToWorld();
9948 pItem
->SendUpdateToPlayer( this );
9951 ApplyEquipCooldown(pItem
);
9953 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
9954 UpdateExpertise(BASE_ATTACK
);
9955 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
9956 UpdateExpertise(OFF_ATTACK
);
9960 pItem2
->SetCount( pItem2
->GetCount() + pItem
->GetCount() );
9961 if( IsInWorld() && update
)
9962 pItem2
->SendUpdateToPlayer( this );
9964 // delete item (it not in any slot currently)
9965 //pItem->DeleteFromDB();
9966 if( IsInWorld() && update
)
9968 pItem
->RemoveFromWorld();
9969 pItem
->DestroyForPlayer( this );
9972 RemoveEnchantmentDurations(pItem
);
9973 RemoveItemDurations(pItem
);
9975 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
9976 pItem
->SetState(ITEM_REMOVED
, this);
9977 pItem2
->SetState(ITEM_CHANGED
, this);
9979 ApplyEquipCooldown(pItem2
);
9988 void Player::QuickEquipItem( uint16 pos
, Item
*pItem
)
9992 AddEnchantmentDurations(pItem
);
9993 AddItemDurations(pItem
);
9995 uint8 slot
= pos
& 255;
9996 VisualizeItem( slot
, pItem
);
10000 pItem
->AddToWorld();
10001 pItem
->SendUpdateToPlayer( this );
10006 void Player::SetVisibleItemSlot(uint8 slot
, Item
*pItem
)
10008 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10009 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10010 // entry // Size: 1
10011 // inspected enchantments // Size: 6
10013 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10014 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10019 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), pItem
->GetUInt64Value(ITEM_FIELD_CREATOR
));
10021 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
10022 SetUInt32Value(VisibleBase
+ 0, pItem
->GetEntry());
10024 for(int i
= 0; i
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++i
)
10025 SetUInt32Value(VisibleBase
+ 1 + i
, pItem
->GetEnchantmentId(EnchantmentSlot(i
)));
10027 // Use SetInt16Value to prevent set high part to FFFF for negative value
10028 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0, pItem
->GetItemRandomPropertyId());
10029 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), pItem
->GetItemSuffixFactor());
10033 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10035 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
10036 SetUInt32Value(VisibleBase
+ 0, 0);
10038 for(int i
= 0; i
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++i
)
10039 SetUInt32Value(VisibleBase
+ 1 + i
, 0);
10041 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 0 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10042 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10046 void Player::VisualizeItem( uint8 slot
, Item
*pItem
)
10051 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10052 if( pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
|| pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
|| pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
)
10053 pItem
->SetBinding( true );
10055 sLog
.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot
, pItem
->GetEntry());
10057 m_items
[slot
] = pItem
;
10058 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), pItem
->GetGUID() );
10059 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10060 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10061 pItem
->SetSlot( slot
);
10062 pItem
->SetContainer( NULL
);
10064 if( slot
< EQUIPMENT_SLOT_END
)
10065 SetVisibleItemSlot(slot
,pItem
);
10067 pItem
->SetState(ITEM_CHANGED
, this);
10070 void Player::RemoveItem( uint8 bag
, uint8 slot
, bool update
)
10072 // note: removeitem does not actually change the item
10073 // it only takes the item out of storage temporarily
10074 // note2: if removeitem is to be used for delinking
10075 // the item must be removed from the player's updatequeue
10077 Item
*pItem
= GetItemByPos( bag
, slot
);
10080 sLog
.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10082 RemoveEnchantmentDurations(pItem
);
10083 RemoveItemDurations(pItem
);
10085 if( bag
== INVENTORY_SLOT_BAG_0
)
10087 if ( slot
< INVENTORY_SLOT_BAG_END
)
10089 ItemPrototype
const *pProto
= pItem
->GetProto();
10090 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10092 if(pProto
&& pProto
->ItemSet
)
10093 RemoveItemsSetItem(this,pProto
);
10095 _ApplyItemMods(pItem
, slot
, false);
10097 // remove item dependent auras and casts (only weapon and armor slots)
10098 if(slot
< EQUIPMENT_SLOT_END
)
10099 RemoveItemDependentAurasAndCasts(pItem
);
10101 // remove held enchantments
10102 if ( slot
== EQUIPMENT_SLOT_MAINHAND
)
10104 if (pItem
->GetItemSuffixFactor())
10106 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3
);
10107 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4
);
10111 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0
);
10112 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1
);
10117 m_items
[slot
] = NULL
;
10118 SetUInt64Value((uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
*2)), 0);
10120 if ( slot
< EQUIPMENT_SLOT_END
)
10121 SetVisibleItemSlot(slot
,NULL
);
10125 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
10127 pBag
->RemoveItem(slot
, update
);
10129 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10130 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10131 pItem
->SetSlot( NULL_SLOT
);
10132 if( IsInWorld() && update
)
10133 pItem
->SendUpdateToPlayer( this );
10135 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
10136 UpdateExpertise(BASE_ATTACK
);
10137 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10138 UpdateExpertise(OFF_ATTACK
);
10142 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10143 void Player::MoveItemFromInventory(uint8 bag
, uint8 slot
, bool update
)
10145 if(Item
* it
= GetItemByPos(bag
,slot
))
10147 ItemRemovedQuestCheck(it
->GetEntry(),it
->GetCount());
10148 RemoveItem( bag
,slot
,update
);
10149 it
->RemoveFromUpdateQueueOf(this);
10150 if(it
->IsInWorld())
10152 it
->RemoveFromWorld();
10153 it
->DestroyForPlayer( this );
10158 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10159 void Player::MoveItemToInventory(ItemPosCountVec
const& dest
, Item
* pItem
, bool update
, bool in_characterInventoryDB
)
10161 // update quest counters
10162 ItemAddedQuestCheck(pItem
->GetEntry(),pItem
->GetCount());
10165 Item
* pLastItem
= StoreItem( dest
, pItem
, update
);
10167 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10168 if(pLastItem
==pItem
)
10170 // update owner for last item (this can be original item with wrong owner
10171 if(pLastItem
->GetOwnerGUID() != GetGUID())
10172 pLastItem
->SetOwnerGUID(GetGUID());
10174 // if this original item then it need create record in inventory
10175 // in case trade we laready have item in other player inventory
10176 pLastItem
->SetState(in_characterInventoryDB
? ITEM_CHANGED
: ITEM_NEW
, this);
10180 void Player::DestroyItem( uint8 bag
, uint8 slot
, bool update
)
10182 Item
*pItem
= GetItemByPos( bag
, slot
);
10185 sLog
.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10187 // start from destroy contained items (only equipped bag can have its)
10188 if (pItem
->IsBag() && pItem
->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10190 for (int i
= 0; i
< MAX_BAG_SIZE
; i
++)
10191 DestroyItem(slot
,i
,update
);
10194 if(pItem
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_WRAPPED
))
10195 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem
->GetGUIDLow());
10197 ItemPrototype
const *pProto
= pItem
->GetProto();
10199 RemoveEnchantmentDurations(pItem
);
10200 RemoveItemDurations(pItem
);
10202 ItemRemovedQuestCheck( pItem
->GetEntry(), pItem
->GetCount() );
10204 if( bag
== INVENTORY_SLOT_BAG_0
)
10207 SetUInt64Value((uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
*2)), 0);
10209 // equipment and equipped bags can have applied bonuses
10210 if ( slot
< INVENTORY_SLOT_BAG_END
)
10212 ItemPrototype
const *pProto
= pItem
->GetProto();
10214 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10215 if(pProto
&& pProto
->ItemSet
)
10216 RemoveItemsSetItem(this,pProto
);
10218 _ApplyItemMods(pItem
, slot
, false);
10221 if ( slot
< EQUIPMENT_SLOT_END
)
10223 // remove item dependent auras and casts (only weapon and armor slots)
10224 RemoveItemDependentAurasAndCasts(pItem
);
10226 // equipment visual show
10227 SetVisibleItemSlot(slot
,NULL
);
10230 m_items
[slot
] = NULL
;
10232 else if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
))
10233 pBag
->RemoveItem(slot
, update
);
10235 if( IsInWorld() && update
)
10237 pItem
->RemoveFromWorld();
10238 pItem
->DestroyForPlayer(this);
10241 //pItem->SetOwnerGUID(0);
10242 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10243 pItem
->SetSlot( NULL_SLOT
);
10244 pItem
->SetState(ITEM_REMOVED
, this);
10248 void Player::DestroyItemCount( uint32 item
, uint32 count
, bool update
, bool unequip_check
)
10250 sLog
.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item
, count
);
10252 ItemPrototype
const *pProto
;
10253 uint32 remcount
= 0;
10256 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
10258 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10259 if( pItem
&& pItem
->GetEntry() == item
)
10261 if( pItem
->GetCount() + remcount
<= count
)
10263 // all items in inventory can unequipped
10264 remcount
+= pItem
->GetCount();
10265 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10267 if(remcount
>=count
)
10272 pProto
= pItem
->GetProto();
10273 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10274 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10275 if( IsInWorld() & update
)
10276 pItem
->SendUpdateToPlayer( this );
10277 pItem
->SetState(ITEM_CHANGED
, this);
10282 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
10284 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10285 if( pItem
&& pItem
->GetEntry() == item
)
10287 if( pItem
->GetCount() + remcount
<= count
)
10289 // all keys can be unequipped
10290 remcount
+= pItem
->GetCount();
10291 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10293 if(remcount
>=count
)
10298 pProto
= pItem
->GetProto();
10299 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10300 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10301 if( IsInWorld() & update
)
10302 pItem
->SendUpdateToPlayer( this );
10303 pItem
->SetState(ITEM_CHANGED
, this);
10309 // in inventory bags
10311 ItemPrototype
const *pBagProto
;
10312 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10314 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10317 pBagProto
= pBag
->GetProto();
10320 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
10322 pItem
= pBag
->GetItemByPos(j
);
10323 if( pItem
&& pItem
->GetEntry() == item
)
10325 // all items in bags can be unequipped
10326 if( pItem
->GetCount() + remcount
<= count
)
10328 remcount
+= pItem
->GetCount();
10329 DestroyItem( i
, j
, update
);
10331 if(remcount
>=count
)
10336 pProto
= pItem
->GetProto();
10337 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10338 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10339 if( IsInWorld() && update
)
10340 pItem
->SendUpdateToPlayer( this );
10341 pItem
->SetState(ITEM_CHANGED
, this);
10350 // in equipment and bag list
10351 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10353 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10354 if( pItem
&& pItem
->GetEntry() == item
)
10356 if( pItem
->GetCount() + remcount
<= count
)
10358 if(!unequip_check
|| CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
,false) == EQUIP_ERR_OK
)
10360 remcount
+= pItem
->GetCount();
10361 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10363 if(remcount
>=count
)
10369 pProto
= pItem
->GetProto();
10370 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10371 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10372 if( IsInWorld() & update
)
10373 pItem
->SendUpdateToPlayer( this );
10374 pItem
->SetState(ITEM_CHANGED
, this);
10381 void Player::DestroyZoneLimitedItem( bool update
, uint32 new_zone
)
10383 sLog
.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone
);
10386 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
10388 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10389 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
10390 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10392 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
10394 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10395 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
10396 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10399 // in inventory bags
10400 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10402 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10405 ItemPrototype
const *pBagProto
= pBag
->GetProto();
10408 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
10410 Item
* pItem
= pBag
->GetItemByPos(j
);
10411 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
10412 DestroyItem( i
, j
, update
);
10418 // in equipment and bag list
10419 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10421 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10422 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
10423 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10427 void Player::DestroyConjuredItems( bool update
)
10429 // used when entering arena
10430 // distroys all conjured items
10431 sLog
.outDebug( "STORAGE: DestroyConjuredItems" );
10434 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
10436 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10437 if( pItem
&& pItem
->GetProto() &&
10438 (pItem
->GetProto()->Class
== ITEM_CLASS_CONSUMABLE
) &&
10439 (pItem
->GetProto()->Flags
& ITEM_FLAGS_CONJURED
) )
10440 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10443 // in inventory bags
10444 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10446 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10449 ItemPrototype
const *pBagProto
= pBag
->GetProto();
10452 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
10454 Item
* pItem
= pBag
->GetItemByPos(j
);
10455 if( pItem
&& pItem
->GetProto() &&
10456 (pItem
->GetProto()->Class
== ITEM_CLASS_CONSUMABLE
) &&
10457 (pItem
->GetProto()->Flags
& ITEM_FLAGS_CONJURED
) )
10458 DestroyItem( i
, j
, update
);
10464 // in equipment and bag list
10465 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10467 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10468 if( pItem
&& pItem
->GetProto() &&
10469 (pItem
->GetProto()->Class
== ITEM_CLASS_CONSUMABLE
) &&
10470 (pItem
->GetProto()->Flags
& ITEM_FLAGS_CONJURED
) )
10471 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10475 void Player::DestroyItemCount( Item
* pItem
, uint32
&count
, bool update
)
10480 sLog
.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem
->GetGUIDLow(),pItem
->GetEntry(), count
);
10482 if( pItem
->GetCount() <= count
)
10484 count
-= pItem
->GetCount();
10486 DestroyItem( pItem
->GetBagSlot(),pItem
->GetSlot(), update
);
10490 ItemRemovedQuestCheck( pItem
->GetEntry(), count
);
10491 pItem
->SetCount( pItem
->GetCount() - count
);
10493 if( IsInWorld() & update
)
10494 pItem
->SendUpdateToPlayer( this );
10495 pItem
->SetState(ITEM_CHANGED
, this);
10499 void Player::SplitItem( uint16 src
, uint16 dst
, uint32 count
)
10501 uint8 srcbag
= src
>> 8;
10502 uint8 srcslot
= src
& 255;
10504 uint8 dstbag
= dst
>> 8;
10505 uint8 dstslot
= dst
& 255;
10507 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
10510 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
10514 // not let split all items (can be only at cheating)
10515 if(pSrcItem
->GetCount() == count
)
10517 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
10521 // not let split more existed items (can be only at cheating)
10522 if(pSrcItem
->GetCount() < count
)
10524 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT
, pSrcItem
, NULL
);
10528 if(pSrcItem
->m_lootGenerated
) // prevent split looting item (item
10530 //best error message found for attempting to split while looting
10531 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
10535 sLog
.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag
, dstslot
, pSrcItem
->GetEntry(), count
);
10536 Item
*pNewItem
= pSrcItem
->CloneItem( count
, this );
10539 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
10543 if( IsInventoryPos( dst
) )
10545 // change item amount before check (for unique max count check)
10546 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
10548 ItemPosCountVec dest
;
10549 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pNewItem
, false );
10550 if( msg
!= EQUIP_ERR_OK
)
10553 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
10554 SendEquipError( msg
, pSrcItem
, NULL
);
10559 pSrcItem
->SendUpdateToPlayer( this );
10560 pSrcItem
->SetState(ITEM_CHANGED
, this);
10561 StoreItem( dest
, pNewItem
, true);
10563 else if( IsBankPos ( dst
) )
10565 // change item amount before check (for unique max count check)
10566 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
10568 ItemPosCountVec dest
;
10569 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pNewItem
, false );
10570 if( msg
!= EQUIP_ERR_OK
)
10573 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
10574 SendEquipError( msg
, pSrcItem
, NULL
);
10579 pSrcItem
->SendUpdateToPlayer( this );
10580 pSrcItem
->SetState(ITEM_CHANGED
, this);
10581 BankItem( dest
, pNewItem
, true);
10583 else if( IsEquipmentPos ( dst
) )
10585 // change item amount before check (for unique max count check), provide space for splitted items
10586 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
10589 uint8 msg
= CanEquipItem( dstslot
, dest
, pNewItem
, false );
10590 if( msg
!= EQUIP_ERR_OK
)
10593 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
10594 SendEquipError( msg
, pSrcItem
, NULL
);
10599 pSrcItem
->SendUpdateToPlayer( this );
10600 pSrcItem
->SetState(ITEM_CHANGED
, this);
10601 EquipItem( dest
, pNewItem
, true);
10602 AutoUnequipOffhandIfNeed();
10606 void Player::SwapItem( uint16 src
, uint16 dst
)
10608 uint8 srcbag
= src
>> 8;
10609 uint8 srcslot
= src
& 255;
10611 uint8 dstbag
= dst
>> 8;
10612 uint8 dstslot
= dst
& 255;
10614 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
10615 Item
*pDstItem
= GetItemByPos( dstbag
, dstslot
);
10620 sLog
.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag
, dstslot
, pSrcItem
->GetEntry());
10624 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD
, pSrcItem
, pDstItem
);
10628 if(pSrcItem
->m_lootGenerated
) // prevent swap looting item
10630 //best error message found for attempting to swap while looting
10631 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pSrcItem
, NULL
);
10635 // check unequip potability for equipped items and bank bags
10636 if(IsEquipmentPos ( src
) || IsBagPos ( src
))
10638 // bags can be swapped with empty bag slots
10639 uint8 msg
= CanUnequipItem( src
, !IsBagPos ( src
) || IsBagPos ( dst
));
10640 if(msg
!= EQUIP_ERR_OK
)
10642 SendEquipError( msg
, pSrcItem
, pDstItem
);
10647 // prevent put equipped/bank bag in self
10648 if( IsBagPos ( src
) && srcslot
== dstbag
)
10650 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
10656 if( IsInventoryPos( dst
) )
10658 ItemPosCountVec dest
;
10659 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pSrcItem
, false );
10660 if( msg
!= EQUIP_ERR_OK
)
10662 SendEquipError( msg
, pSrcItem
, NULL
);
10666 RemoveItem(srcbag
, srcslot
, true);
10667 StoreItem( dest
, pSrcItem
, true);
10669 else if( IsBankPos ( dst
) )
10671 ItemPosCountVec dest
;
10672 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pSrcItem
, false);
10673 if( msg
!= EQUIP_ERR_OK
)
10675 SendEquipError( msg
, pSrcItem
, NULL
);
10679 RemoveItem(srcbag
, srcslot
, true);
10680 BankItem( dest
, pSrcItem
, true);
10682 else if( IsEquipmentPos ( dst
) )
10685 uint8 msg
= CanEquipItem( dstslot
, dest
, pSrcItem
, false );
10686 if( msg
!= EQUIP_ERR_OK
)
10688 SendEquipError( msg
, pSrcItem
, NULL
);
10692 RemoveItem(srcbag
, srcslot
, true);
10693 EquipItem( dest
, pSrcItem
, true);
10694 AutoUnequipOffhandIfNeed();
10697 else // if (!pDstItem)
10699 if(pDstItem
->m_lootGenerated
) // prevent swap looting item
10701 //best error message found for attempting to swap while looting
10702 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pDstItem
, NULL
);
10706 // check unequip potability for equipped items and bank bags
10707 if(IsEquipmentPos ( dst
) || IsBagPos ( dst
))
10709 // bags can be swapped with empty bag slots
10710 uint8 msg
= CanUnequipItem( dst
, !IsBagPos ( dst
) || IsBagPos ( src
) );
10711 if(msg
!= EQUIP_ERR_OK
)
10713 SendEquipError( msg
, pSrcItem
, pDstItem
);
10718 // attempt merge to / fill target item
10721 ItemPosCountVec sDest
;
10723 if( IsInventoryPos( dst
) )
10724 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
10725 else if( IsBankPos ( dst
) )
10726 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
10727 else if( IsEquipmentPos ( dst
) )
10728 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, false );
10732 // can be merge/fill
10733 if(msg
== EQUIP_ERR_OK
)
10735 if( pSrcItem
->GetCount() + pDstItem
->GetCount() <= pSrcItem
->GetProto()->Stackable
)
10737 RemoveItem(srcbag
, srcslot
, true);
10739 if( IsInventoryPos( dst
) )
10740 StoreItem( sDest
, pSrcItem
, true);
10741 else if( IsBankPos ( dst
) )
10742 BankItem( sDest
, pSrcItem
, true);
10743 else if( IsEquipmentPos ( dst
) )
10745 EquipItem( eDest
, pSrcItem
, true);
10746 AutoUnequipOffhandIfNeed();
10751 pSrcItem
->SetCount( pSrcItem
->GetCount() + pDstItem
->GetCount() - pSrcItem
->GetProto()->Stackable
);
10752 pDstItem
->SetCount( pSrcItem
->GetProto()->Stackable
);
10753 pSrcItem
->SetState(ITEM_CHANGED
, this);
10754 pDstItem
->SetState(ITEM_CHANGED
, this);
10757 pSrcItem
->SendUpdateToPlayer( this );
10758 pDstItem
->SendUpdateToPlayer( this );
10765 // impossible merge/fill, do real swap
10768 // check src->dest move possibility
10769 ItemPosCountVec sDest
;
10771 if( IsInventoryPos( dst
) )
10772 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
10773 else if( IsBankPos( dst
) )
10774 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
10775 else if( IsEquipmentPos( dst
) )
10777 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, true );
10778 if( msg
== EQUIP_ERR_OK
)
10779 msg
= CanUnequipItem( eDest
, true );
10782 if( msg
!= EQUIP_ERR_OK
)
10784 SendEquipError( msg
, pSrcItem
, pDstItem
);
10788 // check dest->src move possibility
10789 ItemPosCountVec sDest2
;
10791 if( IsInventoryPos( src
) )
10792 msg
= CanStoreItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
10793 else if( IsBankPos( src
) )
10794 msg
= CanBankItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
10795 else if( IsEquipmentPos( src
) )
10797 msg
= CanEquipItem( srcslot
, eDest2
, pDstItem
, true);
10798 if( msg
== EQUIP_ERR_OK
)
10799 msg
= CanUnequipItem( eDest2
, true);
10802 if( msg
!= EQUIP_ERR_OK
)
10804 SendEquipError( msg
, pDstItem
, pSrcItem
);
10808 // now do moves, remove...
10809 RemoveItem(dstbag
, dstslot
, false);
10810 RemoveItem(srcbag
, srcslot
, false);
10813 if( IsInventoryPos( dst
) )
10814 StoreItem(sDest
, pSrcItem
, true);
10815 else if( IsBankPos( dst
) )
10816 BankItem(sDest
, pSrcItem
, true);
10817 else if( IsEquipmentPos( dst
) )
10818 EquipItem(eDest
, pSrcItem
, true);
10821 if( IsInventoryPos( src
) )
10822 StoreItem(sDest2
, pDstItem
, true);
10823 else if( IsBankPos( src
) )
10824 BankItem(sDest2
, pDstItem
, true);
10825 else if( IsEquipmentPos( src
) )
10826 EquipItem(eDest2
, pDstItem
, true);
10828 AutoUnequipOffhandIfNeed();
10832 void Player::AddItemToBuyBackSlot( Item
*pItem
)
10836 uint32 slot
= m_currentBuybackSlot
;
10837 // if current back slot non-empty search oldest or free
10840 uint32 oldest_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
);
10841 uint32 oldest_slot
= BUYBACK_SLOT_START
;
10843 for(uint32 i
= BUYBACK_SLOT_START
+1; i
< BUYBACK_SLOT_END
; ++i
)
10852 uint32 i_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ i
- BUYBACK_SLOT_START
);
10854 if(oldest_time
> i_time
)
10856 oldest_time
= i_time
;
10862 slot
= oldest_slot
;
10865 RemoveItemFromBuyBackSlot( slot
, true );
10866 sLog
.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem
->GetEntry(), slot
);
10868 m_items
[slot
] = pItem
;
10869 time_t base
= time(NULL
);
10870 uint32 etime
= uint32(base
- m_logintime
+ (30 * 3600));
10871 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
10873 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ eslot
* 2, pItem
->GetGUID() );
10874 ItemPrototype
const *pProto
= pItem
->GetProto();
10876 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, pProto
->SellPrice
* pItem
->GetCount() );
10878 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
10879 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, (uint32
)etime
);
10881 // move to next (for non filled list is move most optimized choice)
10882 if(m_currentBuybackSlot
< BUYBACK_SLOT_END
-1)
10883 ++m_currentBuybackSlot
;
10887 Item
* Player::GetItemFromBuyBackSlot( uint32 slot
)
10889 sLog
.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot
);
10890 if( slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
10891 return m_items
[slot
];
10895 void Player::RemoveItemFromBuyBackSlot( uint32 slot
, bool del
)
10897 sLog
.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot
);
10898 if( slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
10900 Item
*pItem
= m_items
[slot
];
10903 pItem
->RemoveFromWorld();
10904 if(del
) pItem
->SetState(ITEM_REMOVED
, this);
10907 m_items
[slot
] = NULL
;
10909 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
10910 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ eslot
* 2, 0 );
10911 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
10912 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, 0 );
10914 // if current backslot is filled set to now free slot
10915 if(m_items
[m_currentBuybackSlot
])
10916 m_currentBuybackSlot
= slot
;
10920 void Player::SendEquipError( uint8 msg
, Item
* pItem
, Item
*pItem2
)
10922 sLog
.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg
);
10923 WorldPacket
data( SMSG_INVENTORY_CHANGE_FAILURE
, (msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
? 22 : 18) );
10924 data
<< uint8(msg
);
10928 data
<< uint64(pItem
? pItem
->GetGUID() : 0);
10929 data
<< uint64(pItem2
? pItem2
->GetGUID() : 0);
10930 data
<< uint8(0); // not 0 there...
10932 if(msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
)
10937 if(ItemPrototype
const* proto
= pItem
->GetProto())
10938 level
= proto
->RequiredLevel
;
10940 data
<< uint32(level
); // new 2.4.0
10943 GetSession()->SendPacket(&data
);
10946 void Player::SendBuyError( uint8 msg
, Creature
* pCreature
, uint32 item
, uint32 param
)
10948 sLog
.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
10949 WorldPacket
data( SMSG_BUY_FAILED
, (8+4+4+1) );
10950 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
10951 data
<< uint32(item
);
10953 data
<< uint32(param
);
10954 data
<< uint8(msg
);
10955 GetSession()->SendPacket(&data
);
10958 void Player::SendSellError( uint8 msg
, Creature
* pCreature
, uint64 guid
, uint32 param
)
10960 sLog
.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
10961 WorldPacket
data( SMSG_SELL_ITEM
,(8+8+(param
?4:0)+1)); // last check 2.0.10
10962 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
10963 data
<< uint64(guid
);
10965 data
<< uint32(param
);
10966 data
<< uint8(msg
);
10967 GetSession()->SendPacket(&data
);
10970 void Player::ClearTrade()
10973 acceptTrade
= false;
10974 for(int i
= 0; i
< TRADE_SLOT_COUNT
; i
++)
10975 tradeItems
[i
] = NULL_SLOT
;
10978 void Player::TradeCancel(bool sendback
)
10982 // send yellow "Trade cancelled" message to both traders
10986 ws
->SendCancelTrade();
10987 ws
= pTrader
->GetSession();
10988 if(!ws
->PlayerLogout())
10989 ws
->SendCancelTrade();
10993 pTrader
->ClearTrade();
10994 // prevent loss of reference
10995 pTrader
->pTrader
= NULL
;
11000 void Player::UpdateItemDuration(uint32 time
, bool realtimeonly
)
11002 if(m_itemDuration
.empty())
11005 sLog
.outDebug("Player::UpdateItemDuration(%u,%u)", time
,realtimeonly
);
11007 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); )
11010 ++itr
; // current element can be erased in UpdateDuration
11012 if (realtimeonly
&& item
->GetProto()->Duration
< 0 || !realtimeonly
)
11013 item
->UpdateDuration(this,time
);
11017 void Player::UpdateEnchantTime(uint32 time
)
11019 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11023 if(!itr
->item
->GetEnchantmentId(itr
->slot
))
11025 next
= m_enchantDuration
.erase(itr
);
11027 else if(itr
->leftduration
<= time
)
11029 ApplyEnchantment(itr
->item
,itr
->slot
,false,false);
11030 itr
->item
->ClearEnchantment(itr
->slot
);
11031 next
= m_enchantDuration
.erase(itr
);
11033 else if(itr
->leftduration
> time
)
11035 itr
->leftduration
-= time
;
11041 void Player::AddEnchantmentDurations(Item
*item
)
11043 for(int x
=0;x
<MAX_ENCHANTMENT_SLOT
;++x
)
11045 if(!item
->GetEnchantmentId(EnchantmentSlot(x
)))
11048 uint32 duration
= item
->GetEnchantmentDuration(EnchantmentSlot(x
));
11050 AddEnchantmentDuration(item
,EnchantmentSlot(x
),duration
);
11054 void Player::RemoveEnchantmentDurations(Item
*item
)
11056 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();)
11058 if(itr
->item
== item
)
11060 // save duration in item
11061 item
->SetEnchantmentDuration(EnchantmentSlot(itr
->slot
),itr
->leftduration
);
11062 itr
= m_enchantDuration
.erase(itr
);
11069 void Player::RemoveAllEnchantments(EnchantmentSlot slot
)
11071 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11072 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11075 if(itr
->slot
==slot
)
11077 if(itr
->item
&& itr
->item
->GetEnchantmentId(slot
))
11079 // remove from stats
11080 ApplyEnchantment(itr
->item
,slot
,false,false);
11082 itr
->item
->ClearEnchantment(slot
);
11084 // remove from update list
11085 next
= m_enchantDuration
.erase(itr
);
11091 // remove enchants from inventory items
11092 // NOTE: no need to remove these from stats, since these aren't equipped
11094 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
11096 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11097 if( pItem
&& pItem
->GetEnchantmentId(slot
) )
11098 pItem
->ClearEnchantment(slot
);
11101 // in inventory bags
11102 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11104 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11107 ItemPrototype
const *pBagProto
= pBag
->GetProto();
11110 for(uint32 j
= 0; j
< pBagProto
->ContainerSlots
; j
++)
11112 Item
* pItem
= pBag
->GetItemByPos(j
);
11113 if( pItem
&& pItem
->GetEnchantmentId(slot
) )
11114 pItem
->ClearEnchantment(slot
);
11121 // duration == 0 will remove item enchant
11122 void Player::AddEnchantmentDuration(Item
*item
,EnchantmentSlot slot
,uint32 duration
)
11127 if(slot
>= MAX_ENCHANTMENT_SLOT
)
11130 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
11132 if(itr
->item
== item
&& itr
->slot
== slot
)
11134 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
11135 m_enchantDuration
.erase(itr
);
11139 if(item
&& duration
> 0 )
11141 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item
->GetGUID(),slot
,uint32(duration
/1000));
11142 m_enchantDuration
.push_back(EnchantDuration(item
,slot
,duration
));
11146 void Player::ApplyEnchantment(Item
*item
,bool apply
)
11148 for(uint32 slot
= 0; slot
< MAX_ENCHANTMENT_SLOT
; ++slot
)
11149 ApplyEnchantment(item
, EnchantmentSlot(slot
), apply
);
11152 void Player::ApplyEnchantment(Item
*item
,EnchantmentSlot slot
,bool apply
, bool apply_dur
, bool ignore_condition
)
11157 if(!item
->IsEquipped())
11160 if(slot
>= MAX_ENCHANTMENT_SLOT
)
11163 uint32 enchant_id
= item
->GetEnchantmentId(slot
);
11167 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
11171 if(!ignore_condition
&& pEnchant
->EnchantmentCondition
&& !((Player
*)this)->EnchantmentFitsRequirements(pEnchant
->EnchantmentCondition
, -1))
11174 for (int s
=0; s
<3; s
++)
11176 uint32 enchant_display_type
= pEnchant
->type
[s
];
11177 uint32 enchant_amount
= pEnchant
->amount
[s
];
11178 uint32 enchant_spell_id
= pEnchant
->spellid
[s
];
11180 switch(enchant_display_type
)
11182 case ITEM_ENCHANTMENT_TYPE_NONE
:
11184 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
:
11185 // processed in Player::CastItemCombatSpell
11187 case ITEM_ENCHANTMENT_TYPE_DAMAGE
:
11188 if (item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
11189 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11190 else if (item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
11191 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11192 else if (item
->GetSlot() == EQUIPMENT_SLOT_RANGED
)
11193 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11195 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL
:
11196 if(enchant_spell_id
)
11200 int32 basepoints
= int32(enchant_amount
);
11201 // Random Property Exist - try found basepoints for spell (basepoints depencs from item suffix factor)
11202 if (item
->GetItemRandomPropertyId() !=0 && !enchant_amount
)
11204 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11207 // Search enchant_amount
11208 for (int k
=0; k
<3; k
++)
11210 if(item_rand
->enchant_id
[k
] == enchant_id
)
11212 basepoints
= int32((item_rand
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11218 // Cast custom spell vs all equal basepoints getted from enchant_amount
11220 CastCustomSpell(this,enchant_spell_id
,&basepoints
,&basepoints
,&basepoints
,true,item
);
11222 CastSpell(this,enchant_spell_id
,true,item
);
11225 RemoveAurasDueToItemSpell(item
,enchant_spell_id
);
11228 case ITEM_ENCHANTMENT_TYPE_RESISTANCE
:
11229 if (!enchant_amount
)
11231 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11234 for (int k
=0; k
<3; k
++)
11236 if(item_rand
->enchant_id
[k
] == enchant_id
)
11238 enchant_amount
= uint32((item_rand
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11245 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START
+ enchant_spell_id
), TOTAL_VALUE
, float(enchant_amount
), apply
);
11247 case ITEM_ENCHANTMENT_TYPE_STAT
:
11249 if (!enchant_amount
)
11251 ItemRandomSuffixEntry
const *item_rand_suffix
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11252 if(item_rand_suffix
)
11254 for (int k
=0; k
<3; k
++)
11256 if(item_rand_suffix
->enchant_id
[k
] == enchant_id
)
11258 enchant_amount
= uint32((item_rand_suffix
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11265 sLog
.outDebug("Adding %u to stat nb %u",enchant_amount
,enchant_spell_id
);
11266 switch (enchant_spell_id
)
11268 case ITEM_MOD_AGILITY
:
11269 sLog
.outDebug("+ %u AGILITY",enchant_amount
);
11270 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11271 ApplyStatBuffMod(STAT_AGILITY
, enchant_amount
, apply
);
11273 case ITEM_MOD_STRENGTH
:
11274 sLog
.outDebug("+ %u STRENGTH",enchant_amount
);
11275 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11276 ApplyStatBuffMod(STAT_STRENGTH
, enchant_amount
, apply
);
11278 case ITEM_MOD_INTELLECT
:
11279 sLog
.outDebug("+ %u INTELLECT",enchant_amount
);
11280 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11281 ApplyStatBuffMod(STAT_INTELLECT
, enchant_amount
, apply
);
11283 case ITEM_MOD_SPIRIT
:
11284 sLog
.outDebug("+ %u SPIRIT",enchant_amount
);
11285 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11286 ApplyStatBuffMod(STAT_SPIRIT
, enchant_amount
, apply
);
11288 case ITEM_MOD_STAMINA
:
11289 sLog
.outDebug("+ %u STAMINA",enchant_amount
);
11290 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11291 ApplyStatBuffMod(STAT_STAMINA
, enchant_amount
, apply
);
11293 case ITEM_MOD_DEFENSE_SKILL_RATING
:
11294 ((Player
*)this)->ApplyRatingMod(CR_DEFENSE_SKILL
, enchant_amount
, apply
);
11295 sLog
.outDebug("+ %u DEFENCE", enchant_amount
);
11297 case ITEM_MOD_DODGE_RATING
:
11298 ((Player
*)this)->ApplyRatingMod(CR_DODGE
, enchant_amount
, apply
);
11299 sLog
.outDebug("+ %u DODGE", enchant_amount
);
11301 case ITEM_MOD_PARRY_RATING
:
11302 ((Player
*)this)->ApplyRatingMod(CR_PARRY
, enchant_amount
, apply
);
11303 sLog
.outDebug("+ %u PARRY", enchant_amount
);
11305 case ITEM_MOD_BLOCK_RATING
:
11306 ((Player
*)this)->ApplyRatingMod(CR_BLOCK
, enchant_amount
, apply
);
11307 sLog
.outDebug("+ %u SHIELD_BLOCK", enchant_amount
);
11309 case ITEM_MOD_HIT_MELEE_RATING
:
11310 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
11311 sLog
.outDebug("+ %u MELEE_HIT", enchant_amount
);
11313 case ITEM_MOD_HIT_RANGED_RATING
:
11314 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
11315 sLog
.outDebug("+ %u RANGED_HIT", enchant_amount
);
11317 case ITEM_MOD_HIT_SPELL_RATING
:
11318 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
11319 sLog
.outDebug("+ %u SPELL_HIT", enchant_amount
);
11321 case ITEM_MOD_CRIT_MELEE_RATING
:
11322 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
11323 sLog
.outDebug("+ %u MELEE_CRIT", enchant_amount
);
11325 case ITEM_MOD_CRIT_RANGED_RATING
:
11326 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
11327 sLog
.outDebug("+ %u RANGED_CRIT", enchant_amount
);
11329 case ITEM_MOD_CRIT_SPELL_RATING
:
11330 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
11331 sLog
.outDebug("+ %u SPELL_CRIT", enchant_amount
);
11333 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11335 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11336 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11338 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11339 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11341 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11342 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11344 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11345 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11347 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11348 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11350 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11351 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11353 // case ITEM_MOD_HASTE_MELEE_RATING:
11354 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11356 // case ITEM_MOD_HASTE_RANGED_RATING:
11357 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11359 case ITEM_MOD_HASTE_SPELL_RATING
:
11360 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
11362 case ITEM_MOD_HIT_RATING
:
11363 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
11364 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
11365 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
11366 sLog
.outDebug("+ %u HIT", enchant_amount
);
11368 case ITEM_MOD_CRIT_RATING
:
11369 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
11370 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
11371 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
11372 sLog
.outDebug("+ %u CRITICAL", enchant_amount
);
11374 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11375 // case ITEM_MOD_HIT_TAKEN_RATING:
11376 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11377 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11378 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11380 // case ITEM_MOD_CRIT_TAKEN_RATING:
11381 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11382 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11383 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11385 case ITEM_MOD_RESILIENCE_RATING
:
11386 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, enchant_amount
, apply
);
11387 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, enchant_amount
, apply
);
11388 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, enchant_amount
, apply
);
11389 sLog
.outDebug("+ %u RESILIENCE", enchant_amount
);
11391 case ITEM_MOD_HASTE_RATING
:
11392 ((Player
*)this)->ApplyRatingMod(CR_HASTE_MELEE
, enchant_amount
, apply
);
11393 ((Player
*)this)->ApplyRatingMod(CR_HASTE_RANGED
, enchant_amount
, apply
);
11394 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
11395 sLog
.outDebug("+ %u HASTE", enchant_amount
);
11397 case ITEM_MOD_EXPERTISE_RATING
:
11398 ((Player
*)this)->ApplyRatingMod(CR_EXPERTISE
, enchant_amount
, apply
);
11399 sLog
.outDebug("+ %u EXPERTISE", enchant_amount
);
11406 case ITEM_ENCHANTMENT_TYPE_TOTEM
: // Shaman Rockbiter Weapon
11408 if(getClass() == CLASS_SHAMAN
)
11410 float addValue
= 0.0f
;
11411 if(item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
11413 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/1000.0f
);
11414 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, addValue
, apply
);
11416 else if(item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
11418 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/1000.0f
);
11419 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, addValue
, apply
);
11425 sLog
.outError("Unknown item enchantment display type: %d",enchant_display_type
);
11427 } /*switch(enchant_display_type)*/
11430 // visualize enchantment at player and equipped items
11431 if(slot
< MAX_INSPECTED_ENCHANTMENT_SLOT
)
11433 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (item
->GetSlot() * MAX_VISIBLE_ITEM_OFFSET
);
11434 SetUInt32Value(VisibleBase
+ 1 + slot
, apply
? item
->GetEnchantmentId(slot
) : 0);
11442 uint32 duration
= item
->GetEnchantmentDuration(slot
);
11444 AddEnchantmentDuration(item
,slot
,duration
);
11448 // duration == 0 will remove EnchantDuration
11449 AddEnchantmentDuration(item
,slot
,0);
11454 void Player::SendEnchantmentDurations()
11456 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
11458 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr
->item
->GetGUID(),itr
->slot
,uint32(itr
->leftduration
)/1000);
11462 void Player::SendItemDurations()
11464 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end();++itr
)
11466 (*itr
)->SendTimeUpdate(this);
11470 void Player::SendNewItem(Item
*item
, uint32 count
, bool received
, bool created
, bool broadcast
)
11472 if(!item
) // prevent crash
11475 // last check 2.0.10
11476 WorldPacket
data( SMSG_ITEM_PUSH_RESULT
, (8+4+4+4+1+4+4+4+4+4) );
11477 data
<< GetGUID(); // player GUID
11478 data
<< uint32(received
); // 0=looted, 1=from npc
11479 data
<< uint32(created
); // 0=received, 1=created
11480 data
<< uint32(1); // always 0x01 (probably meant to be count of listed items)
11481 data
<< (uint8
)item
->GetBagSlot(); // bagslot
11482 // item slot, but when added to stack: 0xFFFFFFFF
11483 data
<< (uint32
) ((item
->GetCount()==count
) ? item
->GetSlot() : -1);
11484 data
<< uint32(item
->GetEntry()); // item id
11485 data
<< uint32(item
->GetItemSuffixFactor()); // SuffixFactor
11486 data
<< uint32(item
->GetItemRandomPropertyId()); // random item property id
11487 data
<< uint32(count
); // count of items
11488 data
<< GetItemCount(item
->GetEntry()); // count of items in inventory
11490 if (broadcast
&& GetGroup())
11491 GetGroup()->BroadcastPacket(&data
);
11493 GetSession()->SendPacket(&data
);
11496 /*********************************************************/
11497 /*** QUEST SYSTEM ***/
11498 /*********************************************************/
11500 void Player::PrepareQuestMenu( uint64 guid
)
11503 QuestRelations
* pObjectQR
;
11504 QuestRelations
* pObjectQIR
;
11505 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
11508 pObject
= (Object
*)pCreature
;
11509 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
11510 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
11514 GameObject
*pGameObject
= ObjectAccessor::GetGameObject(*this, guid
);
11517 pObject
= (Object
*)pGameObject
;
11518 pObjectQR
= &objmgr
.mGOQuestRelations
;
11519 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
11525 QuestMenu
&qm
= PlayerTalkClass
->GetQuestMenu();
11528 for(QuestRelations::const_iterator i
= pObjectQIR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQIR
->upper_bound(pObject
->GetEntry()); ++i
)
11530 uint32 quest_id
= i
->second
;
11531 QuestStatus status
= GetQuestStatus( quest_id
);
11532 if ( status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus( quest_id
) )
11533 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_REWARD_REP
);
11534 else if ( status
== QUEST_STATUS_INCOMPLETE
)
11535 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_INCOMPLETE
);
11536 else if (status
== QUEST_STATUS_AVAILABLE
)
11537 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_CHAT
);
11540 for(QuestRelations::const_iterator i
= pObjectQR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++i
)
11542 uint32 quest_id
= i
->second
;
11543 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
11544 if(!pQuest
) continue;
11546 QuestStatus status
= GetQuestStatus( quest_id
);
11548 if (pQuest
->IsAutoComplete() && CanTakeQuest(pQuest
, false))
11549 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_REWARD_REP
);
11550 else if ( status
== QUEST_STATUS_NONE
&& CanTakeQuest( pQuest
, false ) )
11551 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_AVAILABLE
);
11555 void Player::SendPreparedQuest( uint64 guid
)
11557 QuestMenu
& questMenu
= PlayerTalkClass
->GetQuestMenu();
11558 if( questMenu
.Empty() )
11561 QuestMenuItem
const& qmi0
= questMenu
.GetItem( 0 );
11563 uint32 status
= qmi0
.m_qIcon
;
11565 // single element case
11566 if ( questMenu
.MenuItemCount() == 1 )
11568 // Auto open -- maybe also should verify there is no greeting
11569 uint32 quest_id
= qmi0
.m_qId
;
11570 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
11573 if( status
== DIALOG_STATUS_REWARD_REP
&& !GetQuestRewardStatus( quest_id
) )
11574 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, CanRewardQuest(pQuest
,false), true );
11575 else if( status
== DIALOG_STATUS_INCOMPLETE
)
11576 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, false, true );
11577 // Send completable on repeatable quest if player don't have quest
11578 else if( pQuest
->IsRepeatable() )
11579 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, CanCompleteRepeatableQuest(pQuest
), true );
11581 PlayerTalkClass
->SendQuestGiverQuestDetails( pQuest
, guid
, true );
11584 // multiply entries
11590 std::string title
= "";
11591 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
11594 uint32 textid
= pCreature
->GetNpcTextId();
11595 GossipText
* gossiptext
= objmgr
.GetGossipText(textid
);
11598 qe
._Delay
= 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
11599 qe
._Emote
= 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
11604 qe
= gossiptext
->Options
[0].Emotes
[0];
11606 if(!gossiptext
->Options
[0].Text_0
.empty())
11608 title
= gossiptext
->Options
[0].Text_0
;
11610 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
11613 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
11616 if (nl
->Text_0
[0].size() > loc_idx
&& !nl
->Text_0
[0][loc_idx
].empty())
11617 title
= nl
->Text_0
[0][loc_idx
];
11623 title
= gossiptext
->Options
[0].Text_1
;
11625 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
11628 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
11631 if (nl
->Text_1
[0].size() > loc_idx
&& !nl
->Text_1
[0][loc_idx
].empty())
11632 title
= nl
->Text_1
[0][loc_idx
];
11638 PlayerTalkClass
->SendQuestGiverQuestList( qe
, title
, guid
);
11642 bool Player::IsActiveQuest( uint32 quest_id
) const
11644 QuestStatusMap::const_iterator itr
= mQuestStatus
.find(quest_id
);
11646 return itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
;
11649 Quest
const * Player::GetNextQuest( uint64 guid
, Quest
const *pQuest
)
11652 QuestRelations
* pObjectQR
;
11653 QuestRelations
* pObjectQIR
;
11655 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
11658 pObject
= (Object
*)pCreature
;
11659 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
11660 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
11664 GameObject
*pGameObject
= ObjectAccessor::GetGameObject(*this, guid
);
11667 pObject
= (Object
*)pGameObject
;
11668 pObjectQR
= &objmgr
.mGOQuestRelations
;
11669 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
11675 uint32 nextQuestID
= pQuest
->GetNextQuestInChain();
11676 for(QuestRelations::const_iterator itr
= pObjectQR
->lower_bound(pObject
->GetEntry()); itr
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++itr
)
11678 if (itr
->second
== nextQuestID
)
11679 return objmgr
.GetQuestTemplate(nextQuestID
);
11685 bool Player::CanSeeStartQuest( Quest
const *pQuest
)
11687 if( SatisfyQuestRace( pQuest
, false ) && SatisfyQuestSkillOrClass( pQuest
, false ) &&
11688 SatisfyQuestExclusiveGroup( pQuest
, false ) && SatisfyQuestReputation( pQuest
, false ) &&
11689 SatisfyQuestPreviousQuest( pQuest
, false ) && SatisfyQuestNextChain( pQuest
, false ) &&
11690 SatisfyQuestPrevChain( pQuest
, false ) && SatisfyQuestDay( pQuest
, false ) )
11692 return getLevel() + sWorld
.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF
) >= pQuest
->GetMinLevel();
11698 bool Player::CanTakeQuest( Quest
const *pQuest
, bool msg
)
11700 return SatisfyQuestStatus( pQuest
, msg
) && SatisfyQuestExclusiveGroup( pQuest
, msg
)
11701 && SatisfyQuestRace( pQuest
, msg
) && SatisfyQuestLevel( pQuest
, msg
)
11702 && SatisfyQuestSkillOrClass( pQuest
, msg
) && SatisfyQuestReputation( pQuest
, msg
)
11703 && SatisfyQuestPreviousQuest( pQuest
, msg
) && SatisfyQuestTimed( pQuest
, msg
)
11704 && SatisfyQuestNextChain( pQuest
, msg
) && SatisfyQuestPrevChain( pQuest
, msg
)
11705 && SatisfyQuestDay( pQuest
, msg
);
11708 bool Player::CanAddQuest( Quest
const *pQuest
, bool msg
)
11710 if( !SatisfyQuestLog( msg
) )
11713 uint32 srcitem
= pQuest
->GetSrcItemId();
11716 uint32 count
= pQuest
->GetSrcItemCount();
11717 ItemPosCountVec dest
;
11718 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
11720 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
11721 if( msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
11723 else if( msg
!= EQUIP_ERR_OK
)
11725 SendEquipError( msg
, NULL
, NULL
);
11732 bool Player::CanCompleteQuest( uint32 quest_id
)
11736 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
11737 if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
11738 return false; // not allow re-complete quest
11740 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
11745 // auto complete quest
11746 if (qInfo
->IsAutoComplete() && CanTakeQuest(qInfo
, false))
11749 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
11752 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
11754 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
11756 if( qInfo
->ReqItemCount
[i
]!= 0 && q_status
.m_itemcount
[i
] < qInfo
->ReqItemCount
[i
] )
11761 if ( qInfo
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
11763 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
11765 if( qInfo
->ReqCreatureOrGOId
[i
] == 0 )
11768 if( qInfo
->ReqCreatureOrGOCount
[i
] != 0 && q_status
.m_creatureOrGOcount
[i
] < qInfo
->ReqCreatureOrGOCount
[i
] )
11773 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT
) && !q_status
.m_explored
)
11776 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && q_status
.m_timer
== 0 )
11779 if ( qInfo
->GetRewOrReqMoney() < 0 )
11781 if ( GetMoney() < uint32(-qInfo
->GetRewOrReqMoney()) )
11785 uint32 repFacId
= qInfo
->GetRepObjectiveFaction();
11786 if ( repFacId
&& GetReputation(repFacId
) < qInfo
->GetRepObjectiveValue() )
11795 bool Player::CanCompleteRepeatableQuest( Quest
const *pQuest
)
11797 // Solve problem that player don't have the quest and try complete it.
11798 // if repeatable she must be able to complete event if player don't have it.
11799 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
11800 if( !CanTakeQuest(pQuest
, false) )
11803 if (pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
11804 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
11805 if( pQuest
->ReqItemId
[i
] && pQuest
->ReqItemCount
[i
] && !HasItemCount(pQuest
->ReqItemId
[i
],pQuest
->ReqItemCount
[i
]) )
11808 if( !CanRewardQuest(pQuest
, false) )
11814 bool Player::CanRewardQuest( Quest
const *pQuest
, bool msg
)
11816 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
11817 if(!pQuest
->IsAutoComplete() && GetQuestStatus(pQuest
->GetQuestId()) != QUEST_STATUS_COMPLETE
)
11820 // daily quest can't be rewarded (10 daily quest already completed)
11821 if(!SatisfyQuestDay(pQuest
,true))
11824 // rewarded and not repeatable quest (only cheating case, then ignore without message)
11825 if(GetQuestRewardStatus(pQuest
->GetQuestId()))
11828 // prevent receive reward with quest items in bank
11829 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
11831 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
11833 if( pQuest
->ReqItemCount
[i
]!= 0 &&
11834 GetItemCount(pQuest
->ReqItemId
[i
]) < pQuest
->ReqItemCount
[i
] )
11837 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, NULL
, NULL
);
11843 // prevent receive reward with low money and GetRewOrReqMoney() < 0
11844 if(pQuest
->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest
->GetRewOrReqMoney()) )
11850 bool Player::CanRewardQuest( Quest
const *pQuest
, uint32 reward
, bool msg
)
11852 // prevent receive reward with quest items in bank or for not completed quest
11853 if(!CanRewardQuest(pQuest
,msg
))
11856 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
11858 if( pQuest
->RewChoiceItemId
[reward
] )
11860 ItemPosCountVec dest
;
11861 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] );
11862 if( res
!= EQUIP_ERR_OK
)
11864 SendEquipError( res
, NULL
, NULL
);
11870 if ( pQuest
->GetRewItemsCount() > 0 )
11872 for (uint32 i
= 0; i
< pQuest
->GetRewItemsCount(); ++i
)
11874 if( pQuest
->RewItemId
[i
] )
11876 ItemPosCountVec dest
;
11877 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] );
11878 if( res
!= EQUIP_ERR_OK
)
11880 SendEquipError( res
, NULL
, NULL
);
11890 void Player::AddQuest( Quest
const *pQuest
, Object
*questGiver
)
11892 uint16 log_slot
= FindQuestSlot( 0 );
11893 assert(log_slot
< MAX_QUEST_LOG_SIZE
);
11895 uint32 quest_id
= pQuest
->GetQuestId();
11897 // if not exist then created with set uState==NEW and rewarded=false
11898 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
11899 if (questStatusData
.uState
!= QUEST_NEW
)
11900 questStatusData
.uState
= QUEST_CHANGED
;
11902 // check for repeatable quests status reset
11903 questStatusData
.m_status
= QUEST_STATUS_INCOMPLETE
;
11904 questStatusData
.m_explored
= false;
11906 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
11908 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
11909 questStatusData
.m_itemcount
[i
] = 0;
11912 if ( pQuest
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
11914 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
11915 questStatusData
.m_creatureOrGOcount
[i
] = 0;
11918 GiveQuestSourceItem( pQuest
);
11919 AdjustQuestReqItemCount( pQuest
);
11921 if( pQuest
->GetRepObjectiveFaction() )
11922 SetFactionVisibleForFactionId(pQuest
->GetRepObjectiveFaction());
11925 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
11927 uint32 limittime
= pQuest
->GetLimitTime();
11929 // shared timed quest
11930 if(questGiver
&& questGiver
->GetTypeId()==TYPEID_PLAYER
)
11931 limittime
= ((Player
*)questGiver
)->getQuestStatusMap()[quest_id
].m_timer
/ 1000;
11933 AddTimedQuest( quest_id
);
11934 questStatusData
.m_timer
= limittime
* 1000;
11935 qtime
= static_cast<uint32
>(time(NULL
)) + limittime
;
11938 questStatusData
.m_timer
= 0;
11940 SetQuestSlot(log_slot
, quest_id
, qtime
);
11942 //starting initial quest script
11943 if(questGiver
&& pQuest
->GetQuestStartScript()!=0)
11944 sWorld
.ScriptsStart(sQuestStartScripts
, pQuest
->GetQuestStartScript(), questGiver
, this);
11946 UpdateForQuestsGO();
11949 void Player::CompleteQuest( uint32 quest_id
)
11953 SetQuestStatus( quest_id
, QUEST_STATUS_COMPLETE
);
11955 uint16 log_slot
= FindQuestSlot( quest_id
);
11956 if( log_slot
< MAX_QUEST_LOG_SIZE
)
11957 SetQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
11959 if(Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
))
11961 if( qInfo
->HasFlag(QUEST_FLAGS_AUTO_REWARDED
) )
11962 RewardQuest(qInfo
,0,this,false);
11964 SendQuestComplete( quest_id
);
11969 void Player::IncompleteQuest( uint32 quest_id
)
11973 SetQuestStatus( quest_id
, QUEST_STATUS_INCOMPLETE
);
11975 uint16 log_slot
= FindQuestSlot( quest_id
);
11976 if( log_slot
< MAX_QUEST_LOG_SIZE
)
11977 RemoveQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
11981 void Player::RewardQuest( Quest
const *pQuest
, uint32 reward
, Object
* questGiver
, bool announce
)
11983 uint32 quest_id
= pQuest
->GetQuestId();
11985 for (int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++ )
11987 if ( pQuest
->ReqItemId
[i
] )
11988 DestroyItemCount( pQuest
->ReqItemId
[i
], pQuest
->ReqItemCount
[i
], true);
11991 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
11992 // SetTimedQuest( 0 );
11993 m_timedquests
.erase(pQuest
->GetQuestId());
11995 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
11997 if( pQuest
->RewChoiceItemId
[reward
] )
11999 ItemPosCountVec dest
;
12000 if( CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] ) == EQUIP_ERR_OK
)
12002 Item
* item
= StoreNewItem( dest
, pQuest
->RewChoiceItemId
[reward
], true);
12003 SendNewItem(item
, pQuest
->RewChoiceItemCount
[reward
], true, false);
12008 if ( pQuest
->GetRewItemsCount() > 0 )
12010 for (uint32 i
=0; i
< pQuest
->GetRewItemsCount(); ++i
)
12012 if( pQuest
->RewItemId
[i
] )
12014 ItemPosCountVec dest
;
12015 if( CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] ) == EQUIP_ERR_OK
)
12017 Item
* item
= StoreNewItem( dest
, pQuest
->RewItemId
[i
], true);
12018 SendNewItem(item
, pQuest
->RewItemCount
[i
], true, false);
12024 RewardReputation( pQuest
);
12026 if( pQuest
->GetRewSpellCast() > 0 )
12027 CastSpell( this, pQuest
->GetRewSpellCast(), true);
12028 else if( pQuest
->GetRewSpell() > 0)
12029 CastSpell( this, pQuest
->GetRewSpell(), true);
12031 uint16 log_slot
= FindQuestSlot( quest_id
);
12032 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12033 SetQuestSlot(log_slot
,0);
12035 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12037 // Not give XP in case already completed once repeatable quest
12038 uint32 XP
= q_status
.m_rewarded
? 0 : uint32(pQuest
->XPValue( this )*sWorld
.getRate(RATE_XP_QUEST
));
12040 if ( getLevel() < sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
12041 GiveXP( XP
, NULL
);
12043 ModifyMoney( int32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getRate(RATE_DROP_MONEY
)) );
12045 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12046 ModifyMoney( pQuest
->GetRewOrReqMoney() );
12049 if(pQuest
->GetRewHonorableKills())
12050 RewardHonor(NULL
, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorableKills()));
12053 if(pQuest
->GetCharTitleId())
12055 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
12056 SetFlag64(PLAYER__FIELD_KNOWN_TITLES
, (uint64(1) << titleEntry
->bit_index
));
12059 // Send reward mail
12060 if(pQuest
->GetRewMailTemplateId())
12062 MailMessageType mailType
;
12063 uint32 senderGuidOrEntry
;
12064 switch(questGiver
->GetTypeId())
12067 mailType
= MAIL_CREATURE
;
12068 senderGuidOrEntry
= questGiver
->GetEntry();
12070 case TYPEID_GAMEOBJECT
:
12071 mailType
= MAIL_GAMEOBJECT
;
12072 senderGuidOrEntry
= questGiver
->GetEntry();
12075 mailType
= MAIL_ITEM
;
12076 senderGuidOrEntry
= questGiver
->GetEntry();
12078 case TYPEID_PLAYER
:
12079 mailType
= MAIL_NORMAL
;
12080 senderGuidOrEntry
= questGiver
->GetGUIDLow();
12083 mailType
= MAIL_NORMAL
;
12084 senderGuidOrEntry
= GetGUIDLow();
12088 Loot questMailLoot
;
12090 questMailLoot
.FillLoot(pQuest
->GetQuestId(), LootTemplates_QuestMail
, this);
12093 MailItemsInfo mi
; // item list preparing
12095 for(size_t i
= 0; mi
.size() < MAX_MAIL_ITEMS
&& i
< questMailLoot
.items
.size(); ++i
)
12097 if(LootItem
* lootitem
= questMailLoot
.LootItemInSlot(i
,this))
12099 if(Item
* item
= Item::CreateItem(lootitem
->itemid
,lootitem
->count
,this))
12101 item
->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12102 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
12107 for(size_t i
= 0; mi
.size() < MAX_MAIL_ITEMS
&& i
< questMailLoot
.quest_items
.size(); ++i
)
12109 if(LootItem
* lootitem
= questMailLoot
.LootItemInSlot(i
+questMailLoot
.items
.size(),this))
12111 if(Item
* item
= Item::CreateItem(lootitem
->itemid
,lootitem
->count
,this))
12113 item
->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12114 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
12119 WorldSession::SendMailTo(this, mailType
, MAIL_STATIONERY_NORMAL
, senderGuidOrEntry
, GetGUIDLow(), "", 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
,pQuest
->GetRewMailDelaySecs(),pQuest
->GetRewMailTemplateId());
12122 if(pQuest
->IsDaily())
12123 SetDailyQuestStatus(quest_id
);
12125 if ( !pQuest
->IsRepeatable() )
12126 SetQuestStatus(quest_id
, QUEST_STATUS_COMPLETE
);
12128 SetQuestStatus(quest_id
, QUEST_STATUS_NONE
);
12130 q_status
.m_rewarded
= true;
12133 SendQuestReward( pQuest
, XP
, questGiver
);
12135 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12138 void Player::FailQuest( uint32 quest_id
)
12142 IncompleteQuest( quest_id
);
12144 uint16 log_slot
= FindQuestSlot( quest_id
);
12145 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12147 SetQuestSlotTimer(log_slot
, 1 );
12148 SetQuestSlotState(log_slot
,QUEST_STATE_FAIL
);
12150 SendQuestFailed( quest_id
);
12154 void Player::FailTimedQuest( uint32 quest_id
)
12158 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12160 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12161 q_status
.m_timer
= 0;
12163 IncompleteQuest( quest_id
);
12165 uint16 log_slot
= FindQuestSlot( quest_id
);
12166 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12168 SetQuestSlotTimer(log_slot
, 1 );
12169 SetQuestSlotState(log_slot
,QUEST_STATE_FAIL
);
12171 SendQuestTimerFailed( quest_id
);
12175 bool Player::SatisfyQuestSkillOrClass( Quest
const* qInfo
, bool msg
)
12177 int32 zoneOrSort
= qInfo
->GetZoneOrSort();
12178 int32 skillOrClass
= qInfo
->GetSkillOrClass();
12180 // skip zone zoneOrSort and 0 case skillOrClass
12181 if( zoneOrSort
>= 0 && skillOrClass
== 0 )
12184 int32 questSort
= -zoneOrSort
;
12185 uint8 reqSortClass
= ClassByQuestSort(questSort
);
12187 // check class sort cases in zoneOrSort
12188 if( reqSortClass
!= 0 && getClass() != reqSortClass
)
12191 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12196 if( skillOrClass
< 0 )
12198 uint8 reqClass
= -int32(skillOrClass
);
12199 if(getClass() != reqClass
)
12202 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12207 else if( skillOrClass
> 0 )
12209 uint32 reqSkill
= skillOrClass
;
12210 if( GetSkillValue( reqSkill
) < qInfo
->GetRequiredSkillValue() )
12213 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12221 bool Player::SatisfyQuestLevel( Quest
const* qInfo
, bool msg
)
12223 if( getLevel() < qInfo
->GetMinLevel() )
12226 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12232 bool Player::SatisfyQuestLog( bool msg
)
12235 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE
)
12240 WorldPacket
data( SMSG_QUESTLOG_FULL
, 0 );
12241 GetSession()->SendPacket( &data
);
12242 sLog
.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12247 bool Player::SatisfyQuestPreviousQuest( Quest
const* qInfo
, bool msg
)
12249 // No previous quest (might be first quest in a series)
12250 if( qInfo
->prevQuests
.empty())
12253 for(Quest::PrevQuests::const_iterator iter
= qInfo
->prevQuests
.begin(); iter
!= qInfo
->prevQuests
.end(); ++iter
)
12255 uint32 prevId
= abs(*iter
);
12257 QuestStatusMap::iterator i_prevstatus
= mQuestStatus
.find( prevId
);
12258 Quest
const* qPrevInfo
= objmgr
.GetQuestTemplate(prevId
);
12260 if( qPrevInfo
&& i_prevstatus
!= mQuestStatus
.end() )
12262 // If any of the positive previous quests completed, return true
12263 if( *iter
> 0 && i_prevstatus
->second
.m_rewarded
)
12265 // skip one-from-all exclusive group
12266 if(qPrevInfo
->GetExclusiveGroup() >= 0)
12269 // each-from-all exclusive group ( < 0)
12270 // can be start if only all quests in prev quest exclusive group complited and rewarded
12271 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
12272 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
12274 assert(iter
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
12276 for(; iter
!= end
; ++iter
)
12278 uint32 exclude_Id
= iter
->second
;
12280 // skip checked quest id, only state of other quests in group is interesting
12281 if(exclude_Id
== prevId
)
12284 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12286 // alternative quest from group also must be completed and rewarded(reported)
12287 if( i_exstatus
== mQuestStatus
.end() || !i_exstatus
->second
.m_rewarded
)
12290 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12296 // If any of the negative previous quests active, return true
12297 if( *iter
< 0 && (i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
12298 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
))))
12300 // skip one-from-all exclusive group
12301 if(qPrevInfo
->GetExclusiveGroup() >= 0)
12304 // each-from-all exclusive group ( < 0)
12305 // can be start if only all quests in prev quest exclusive group active
12306 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
12307 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
12309 assert(iter
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
12311 for(; iter
!= end
; ++iter
)
12313 uint32 exclude_Id
= iter
->second
;
12315 // skip checked quest id, only state of other quests in group is interesting
12316 if(exclude_Id
== prevId
)
12319 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12321 // alternative quest from group also must be active
12322 if( i_exstatus
== mQuestStatus
.end() ||
12323 i_exstatus
->second
.m_status
!= QUEST_STATUS_INCOMPLETE
&&
12324 (i_prevstatus
->second
.m_status
!= QUEST_STATUS_COMPLETE
|| GetQuestRewardStatus(prevId
)) )
12327 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12336 // Has only positive prev. quests in non-rewarded state
12337 // and negative prev. quests in non-active state
12339 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12344 bool Player::SatisfyQuestRace( Quest
const* qInfo
, bool msg
)
12346 uint32 reqraces
= qInfo
->GetRequiredRaces();
12347 if ( reqraces
== 0 )
12349 if( (reqraces
& getRaceMask()) == 0 )
12352 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE
);
12358 bool Player::SatisfyQuestReputation( Quest
const* qInfo
, bool msg
)
12360 uint32 fIdMin
= qInfo
->GetRequiredMinRepFaction(); //Min required rep
12361 if(fIdMin
&& GetReputation(fIdMin
) < qInfo
->GetRequiredMinRepValue())
12364 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12368 uint32 fIdMax
= qInfo
->GetRequiredMaxRepFaction(); //Max required rep
12369 if(fIdMax
&& GetReputation(fIdMax
) >= qInfo
->GetRequiredMaxRepValue())
12372 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12379 bool Player::SatisfyQuestStatus( Quest
const* qInfo
, bool msg
)
12381 QuestStatusMap::iterator itr
= mQuestStatus
.find( qInfo
->GetQuestId() );
12382 if ( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
)
12385 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON
);
12391 bool Player::SatisfyQuestTimed( Quest
const* qInfo
, bool msg
)
12393 if ( (find(m_timedquests
.begin(), m_timedquests
.end(), qInfo
->GetQuestId()) != m_timedquests
.end()) && qInfo
->HasFlag(QUEST_MANGOS_FLAGS_TIMED
) )
12396 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED
);
12402 bool Player::SatisfyQuestExclusiveGroup( Quest
const* qInfo
, bool msg
)
12404 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12405 if(qInfo
->GetExclusiveGroup() <= 0)
12408 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qInfo
->GetExclusiveGroup());
12409 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qInfo
->GetExclusiveGroup());
12411 assert(iter
!=end
); // always must be found if qInfo->ExclusiveGroup != 0
12413 for(; iter
!= end
; ++iter
)
12415 uint32 exclude_Id
= iter
->second
;
12417 // skip checked quest id, only state of other quests in group is interesting
12418 if(exclude_Id
== qInfo
->GetQuestId())
12421 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12423 // alternative quest already started or completed
12424 if( i_exstatus
!= mQuestStatus
.end()
12425 && (i_exstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
|| i_exstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
12428 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12435 bool Player::SatisfyQuestNextChain( Quest
const* qInfo
, bool msg
)
12437 if(!qInfo
->GetNextQuestInChain())
12440 // next quest in chain already started or completed
12441 QuestStatusMap::iterator itr
= mQuestStatus
.find( qInfo
->GetNextQuestInChain() );
12442 if( itr
!= mQuestStatus
.end()
12443 && (itr
->second
.m_status
== QUEST_STATUS_COMPLETE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
12446 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12450 // check for all quests further up the chain
12451 // only necessary if there are quest chains with more than one quest that can be skipped
12452 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12456 bool Player::SatisfyQuestPrevChain( Quest
const* qInfo
, bool msg
)
12458 // No previous quest in chain
12459 if( qInfo
->prevChainQuests
.empty())
12462 for(Quest::PrevChainQuests::const_iterator iter
= qInfo
->prevChainQuests
.begin(); iter
!= qInfo
->prevChainQuests
.end(); ++iter
)
12464 uint32 prevId
= *iter
;
12466 QuestStatusMap::iterator i_prevstatus
= mQuestStatus
.find( prevId
);
12468 if( i_prevstatus
!= mQuestStatus
.end() )
12470 // If any of the previous quests in chain active, return false
12471 if( i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
12472 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
)))
12475 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12480 // check for all quests further down the chain
12481 // only necessary if there are quest chains with more than one quest that can be skipped
12482 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12486 // No previous quest in chain active
12490 bool Player::SatisfyQuestDay( Quest
const* qInfo
, bool msg
)
12492 if(!qInfo
->IsDaily())
12495 bool have_slot
= false;
12496 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
12498 uint32 id
= GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
);
12499 if(qInfo
->GetQuestId()==id
)
12509 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING
);
12516 bool Player::GiveQuestSourceItem( Quest
const *pQuest
)
12518 uint32 srcitem
= pQuest
->GetSrcItemId();
12521 uint32 count
= pQuest
->GetSrcItemCount();
12525 ItemPosCountVec dest
;
12526 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
12527 if( msg
== EQUIP_ERR_OK
)
12529 Item
* item
= StoreNewItem(dest
, srcitem
, true);
12530 SendNewItem(item
, count
, true, false);
12533 // player already have max amount required item, just report success
12534 else if( msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
12537 SendEquipError( msg
, NULL
, NULL
);
12544 bool Player::TakeQuestSourceItem( uint32 quest_id
, bool msg
)
12546 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12549 uint32 srcitem
= qInfo
->GetSrcItemId();
12552 uint32 count
= qInfo
->GetSrcItemCount();
12556 // exist one case when destroy source quest item not possible:
12557 // non un-equippable item (equipped non-empty bag, for example)
12558 uint8 res
= CanUnequipItems(srcitem
,count
);
12559 if(res
!= EQUIP_ERR_OK
)
12562 SendEquipError( res
, NULL
, NULL
);
12566 DestroyItemCount(srcitem
, count
, true, true);
12572 bool Player::GetQuestRewardStatus( uint32 quest_id
) const
12574 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12577 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
12578 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
12579 if( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
12580 && !qInfo
->IsRepeatable() )
12581 return itr
->second
.m_rewarded
;
12588 QuestStatus
Player::GetQuestStatus( uint32 quest_id
) const
12592 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
12593 if( itr
!= mQuestStatus
.end() )
12594 return itr
->second
.m_status
;
12596 return QUEST_STATUS_NONE
;
12599 bool Player::CanShareQuest(uint32 quest_id
) const
12601 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12602 if( qInfo
&& qInfo
->HasFlag(QUEST_FLAGS_SHARABLE
) )
12604 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
12605 if( itr
!= mQuestStatus
.end() )
12606 return itr
->second
.m_status
== QUEST_STATUS_NONE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
;
12611 void Player::SetQuestStatus( uint32 quest_id
, QuestStatus status
)
12613 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12616 if( status
== QUEST_STATUS_NONE
|| status
== QUEST_STATUS_INCOMPLETE
|| status
== QUEST_STATUS_COMPLETE
)
12618 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
12619 m_timedquests
.erase(qInfo
->GetQuestId());
12622 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12624 q_status
.m_status
= status
;
12625 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12628 UpdateForQuestsGO();
12631 // not used in MaNGOS, but used in scripting code
12632 uint32
Player::GetReqKillOrCastCurrentCount(uint32 quest_id
, int32 entry
)
12634 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12638 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
12639 if ( qInfo
->ReqCreatureOrGOId
[j
] == entry
)
12640 return mQuestStatus
[quest_id
].m_creatureOrGOcount
[j
];
12645 void Player::AdjustQuestReqItemCount( Quest
const* pQuest
)
12647 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12649 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12651 uint32 reqitemcount
= pQuest
->ReqItemCount
[i
];
12652 if( reqitemcount
!= 0 )
12654 uint32 quest_id
= pQuest
->GetQuestId();
12655 uint32 curitemcount
= GetItemCount(pQuest
->ReqItemId
[i
],true);
12657 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12658 q_status
.m_itemcount
[i
] = std::min(curitemcount
, reqitemcount
);
12659 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12665 uint16
Player::FindQuestSlot( uint32 quest_id
) const
12667 for ( uint16 i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
12668 if ( GetQuestSlotQuestId(i
) == quest_id
)
12671 return MAX_QUEST_LOG_SIZE
;
12674 void Player::AreaExploredOrEventHappens( uint32 questId
)
12678 uint16 log_slot
= FindQuestSlot( questId
);
12679 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12681 QuestStatusData
& q_status
= mQuestStatus
[questId
];
12683 if(!q_status
.m_explored
)
12685 q_status
.m_explored
= true;
12686 if (q_status
.uState
!= QUEST_NEW
)
12687 q_status
.uState
= QUEST_CHANGED
;
12690 if( CanCompleteQuest( questId
) )
12691 CompleteQuest( questId
);
12695 //not used in mangosd, function for external script library
12696 void Player::GroupEventHappens( uint32 questId
, WorldObject
const* pEventObject
)
12698 if( Group
*pGroup
= GetGroup() )
12700 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
12702 Player
*pGroupGuy
= itr
->getSource();
12704 // for any leave or dead (with not released body) group member at appropriate distance
12705 if( pGroupGuy
&& pGroupGuy
->IsAtGroupRewardDistance(pEventObject
) && !pGroupGuy
->GetCorpse() )
12706 pGroupGuy
->AreaExploredOrEventHappens(questId
);
12710 AreaExploredOrEventHappens(questId
);
12713 void Player::ItemAddedQuestCheck( uint32 entry
, uint32 count
)
12715 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
12717 uint32 questid
= GetQuestSlotQuestId(i
);
12718 if ( questid
== 0 )
12721 QuestStatusData
& q_status
= mQuestStatus
[questid
];
12723 if ( q_status
.m_status
!= QUEST_STATUS_INCOMPLETE
)
12726 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
12727 if( !qInfo
|| !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12730 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
12732 uint32 reqitem
= qInfo
->ReqItemId
[j
];
12733 if ( reqitem
== entry
)
12735 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
12736 uint32 curitemcount
= q_status
.m_itemcount
[j
];
12737 if ( curitemcount
< reqitemcount
)
12739 uint32 additemcount
= ( curitemcount
+ count
<= reqitemcount
? count
: reqitemcount
- curitemcount
);
12740 q_status
.m_itemcount
[j
] += additemcount
;
12741 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12743 SendQuestUpdateAddItem( qInfo
, j
, additemcount
);
12745 if ( CanCompleteQuest( questid
) )
12746 CompleteQuest( questid
);
12751 UpdateForQuestsGO();
12754 void Player::ItemRemovedQuestCheck( uint32 entry
, uint32 count
)
12756 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
12758 uint32 questid
= GetQuestSlotQuestId(i
);
12761 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
12764 if( !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12767 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
12769 uint32 reqitem
= qInfo
->ReqItemId
[j
];
12770 if ( reqitem
== entry
)
12772 QuestStatusData
& q_status
= mQuestStatus
[questid
];
12774 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
12775 uint32 curitemcount
;
12776 if( q_status
.m_status
!= QUEST_STATUS_COMPLETE
)
12777 curitemcount
= q_status
.m_itemcount
[j
];
12779 curitemcount
= GetItemCount(entry
,true);
12780 if ( curitemcount
< reqitemcount
+ count
)
12782 uint32 remitemcount
= ( curitemcount
<= reqitemcount
? count
: count
+ reqitemcount
- curitemcount
);
12783 q_status
.m_itemcount
[j
] = curitemcount
- remitemcount
;
12784 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12786 IncompleteQuest( questid
);
12792 UpdateForQuestsGO();
12795 void Player::KilledMonster( uint32 entry
, uint64 guid
)
12797 uint32 addkillcount
= 1;
12798 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
12800 uint32 questid
= GetQuestSlotQuestId(i
);
12804 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
12807 // just if !ingroup || !noraidgroup || raidgroup
12808 QuestStatusData
& q_status
= mQuestStatus
[questid
];
12809 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
&& (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo
->GetType() == QUEST_TYPE_RAID
))
12811 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
12813 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
12815 // skip GO activate objective or none
12816 if(qInfo
->ReqCreatureOrGOId
[j
] <=0)
12819 // skip Cast at creature objective
12820 if(qInfo
->ReqSpell
[j
] !=0 )
12823 uint32 reqkill
= qInfo
->ReqCreatureOrGOId
[j
];
12825 if ( reqkill
== entry
)
12827 uint32 reqkillcount
= qInfo
->ReqCreatureOrGOCount
[j
];
12828 uint32 curkillcount
= q_status
.m_creatureOrGOcount
[j
];
12829 if ( curkillcount
< reqkillcount
)
12831 q_status
.m_creatureOrGOcount
[j
] = curkillcount
+ addkillcount
;
12832 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12834 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curkillcount
, addkillcount
);
12836 if ( CanCompleteQuest( questid
) )
12837 CompleteQuest( questid
);
12839 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
12848 void Player::CastedCreatureOrGO( uint32 entry
, uint64 guid
, uint32 spell_id
)
12850 bool isCreature
= IS_CREATURE_GUID(guid
);
12852 uint32 addCastCount
= 1;
12853 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
12855 uint32 questid
= GetQuestSlotQuestId(i
);
12859 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
12863 QuestStatusData
& q_status
= mQuestStatus
[questid
];
12865 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
12867 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
12869 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
12871 // skip kill creature objective (0) or wrong spell casts
12872 if(qInfo
->ReqSpell
[j
] != spell_id
)
12875 uint32 reqTarget
= 0;
12879 // creature activate objectives
12880 if(qInfo
->ReqCreatureOrGOId
[j
] > 0)
12881 // checked at quest_template loading
12882 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
12886 // GO activate objective
12887 if(qInfo
->ReqCreatureOrGOId
[j
] < 0)
12888 // checked at quest_template loading
12889 reqTarget
= - qInfo
->ReqCreatureOrGOId
[j
];
12892 // other not this creature/GO related objectives
12893 if( reqTarget
!= entry
)
12896 uint32 reqCastCount
= qInfo
->ReqCreatureOrGOCount
[j
];
12897 uint32 curCastCount
= q_status
.m_creatureOrGOcount
[j
];
12898 if ( curCastCount
< reqCastCount
)
12900 q_status
.m_creatureOrGOcount
[j
] = curCastCount
+ addCastCount
;
12901 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12903 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curCastCount
, addCastCount
);
12906 if ( CanCompleteQuest( questid
) )
12907 CompleteQuest( questid
);
12909 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
12917 void Player::TalkedToCreature( uint32 entry
, uint64 guid
)
12919 uint32 addTalkCount
= 1;
12920 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
12922 uint32 questid
= GetQuestSlotQuestId(i
);
12926 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
12930 QuestStatusData
& q_status
= mQuestStatus
[questid
];
12932 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
12934 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
12936 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
12938 // skip spell casts and Gameobject objectives
12939 if(qInfo
->ReqSpell
[j
] > 0 || qInfo
->ReqCreatureOrGOId
[j
] < 0)
12942 uint32 reqTarget
= 0;
12944 if(qInfo
->ReqCreatureOrGOId
[j
] > 0) // creature activate objectives
12945 // checked at quest_template loading
12946 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
12950 if ( reqTarget
== entry
)
12952 uint32 reqTalkCount
= qInfo
->ReqCreatureOrGOCount
[j
];
12953 uint32 curTalkCount
= q_status
.m_creatureOrGOcount
[j
];
12954 if ( curTalkCount
< reqTalkCount
)
12956 q_status
.m_creatureOrGOcount
[j
] = curTalkCount
+ addTalkCount
;
12957 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12959 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curTalkCount
, addTalkCount
);
12961 if ( CanCompleteQuest( questid
) )
12962 CompleteQuest( questid
);
12964 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
12973 void Player::MoneyChanged( uint32 count
)
12975 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
12977 uint32 questid
= GetQuestSlotQuestId(i
);
12981 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
12982 if( qInfo
&& qInfo
->GetRewOrReqMoney() < 0 )
12984 QuestStatusData
& q_status
= mQuestStatus
[questid
];
12986 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
12988 if(int32(count
) >= -qInfo
->GetRewOrReqMoney())
12990 if ( CanCompleteQuest( questid
) )
12991 CompleteQuest( questid
);
12994 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
12996 if(int32(count
) < -qInfo
->GetRewOrReqMoney())
12997 IncompleteQuest( questid
);
13003 bool Player::HasQuestForItem( uint32 itemid
) const
13005 for( QuestStatusMap::const_iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
13007 QuestStatusData
const& q_status
= i
->second
;
13009 if (q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13011 Quest
const* qinfo
= objmgr
.GetQuestTemplate(i
->first
);
13015 // hide quest if player is in raid-group and quest is no raid quest
13016 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
13019 // There should be no mixed ReqItem/ReqSource drop
13020 // This part for ReqItem drop
13021 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13023 if(itemid
== qinfo
->ReqItemId
[j
] && q_status
.m_itemcount
[j
] < qinfo
->ReqItemCount
[j
] )
13026 // This part - for ReqSource
13027 for (int j
= 0; j
< QUEST_SOURCE_ITEM_IDS_COUNT
; j
++)
13029 // examined item is a source item
13030 if (qinfo
->ReqSourceId
[j
] == itemid
&& qinfo
->ReqSourceRef
[j
] > 0 && qinfo
->ReqSourceRef
[j
] <= QUEST_OBJECTIVES_COUNT
)
13032 uint32 idx
= qinfo
->ReqSourceRef
[j
]-1;
13034 // total count of created ReqItems and SourceItems is less than ReqItemCount
13035 if(qinfo
->ReqItemId
[idx
] != 0 &&
13036 q_status
.m_itemcount
[idx
] * qinfo
->ReqSourceCount
[j
] + GetItemCount(itemid
,true) < qinfo
->ReqItemCount
[idx
] * qinfo
->ReqSourceCount
[j
])
13039 // total count of casted ReqCreatureOrGOs and SourceItems is less than ReqCreatureOrGOCount
13040 if (qinfo
->ReqCreatureOrGOId
[idx
] != 0)
13042 if(q_status
.m_creatureOrGOcount
[idx
] * qinfo
->ReqSourceCount
[j
] + GetItemCount(itemid
,true) < qinfo
->ReqCreatureOrGOCount
[idx
] * qinfo
->ReqSourceCount
[j
])
13045 // spell with SPELL_EFFECT_QUEST_COMPLETE or SPELL_EFFECT_SEND_EVENT (with script) case
13046 else if(qinfo
->ReqSpell
[idx
] != 0)
13048 // not casted and need more reagents/item for use.
13049 if(!q_status
.m_explored
&& GetItemCount(itemid
,true) < qinfo
->ReqSourceCount
[j
])
13059 void Player::SendQuestComplete( uint32 quest_id
)
13063 WorldPacket
data( SMSG_QUESTUPDATE_COMPLETE
, 4 );
13065 GetSession()->SendPacket( &data
);
13066 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id
);
13070 void Player::SendQuestReward( Quest
const *pQuest
, uint32 XP
, Object
* questGiver
)
13072 uint32 questid
= pQuest
->GetQuestId();
13073 sLog
.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid
);
13074 WorldPacket
data( SMSG_QUESTGIVER_QUEST_COMPLETE
, (4+4+4+4+4+4+pQuest
->GetRewItemsCount()*8) );
13076 data
<< uint32(0x03);
13078 if ( getLevel() < sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
13081 data
<< uint32(pQuest
->GetRewOrReqMoney());
13086 data
<< uint32(pQuest
->GetRewOrReqMoney() + int32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getRate(RATE_DROP_MONEY
)));
13088 data
<< uint32(0); // new 2.3.0, HonorPoints?
13089 data
<< uint32( pQuest
->GetRewItemsCount() ); // max is 5
13091 for (uint32 i
= 0; i
< pQuest
->GetRewItemsCount(); ++i
)
13093 if ( pQuest
->RewItemId
[i
] > 0 )
13094 data
<< pQuest
->RewItemId
[i
] << pQuest
->RewItemCount
[i
];
13096 data
<< uint32(0) << uint32(0);
13098 GetSession()->SendPacket( &data
);
13100 if (pQuest
->GetQuestCompleteScript() != 0)
13101 sWorld
.ScriptsStart(sQuestEndScripts
, pQuest
->GetQuestCompleteScript(), questGiver
, this);
13104 void Player::SendQuestFailed( uint32 quest_id
)
13108 WorldPacket
data( SMSG_QUESTGIVER_QUEST_FAILED
, 4 );
13110 GetSession()->SendPacket( &data
);
13111 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13115 void Player::SendQuestTimerFailed( uint32 quest_id
)
13119 WorldPacket
data( SMSG_QUESTUPDATE_FAILEDTIMER
, 4 );
13121 GetSession()->SendPacket( &data
);
13122 sLog
.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13126 void Player::SendCanTakeQuestResponse( uint32 msg
)
13128 WorldPacket
data( SMSG_QUESTGIVER_QUEST_INVALID
, 4 );
13129 data
<< uint32(msg
);
13130 GetSession()->SendPacket( &data
);
13131 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13134 void Player::SendPushToPartyResponse( Player
*pPlayer
, uint32 msg
)
13138 WorldPacket
data( MSG_QUEST_PUSH_RESULT
, (8+1) );
13139 data
<< uint64(pPlayer
->GetGUID());
13140 data
<< uint8(msg
); // valid values: 0-8
13141 GetSession()->SendPacket( &data
);
13142 sLog
.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13146 void Player::SendQuestUpdateAddItem( Quest
const* pQuest
, uint32 item_idx
, uint32 count
)
13148 WorldPacket
data( SMSG_QUESTUPDATE_ADD_ITEM
, (4+4) );
13149 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13150 data
<< pQuest
->ReqItemId
[item_idx
];
13152 GetSession()->SendPacket( &data
);
13155 void Player::SendQuestUpdateAddCreatureOrGo( Quest
const* pQuest
, uint64 guid
, uint32 creatureOrGO_idx
, uint32 old_count
, uint32 add_count
)
13157 assert(old_count
+ add_count
< 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13159 int32 entry
= pQuest
->ReqCreatureOrGOId
[ creatureOrGO_idx
];
13161 // client expected gameobject template id in form (id|0x80000000)
13162 entry
= (-entry
) | 0x80000000;
13164 WorldPacket
data( SMSG_QUESTUPDATE_ADD_KILL
, (4*4+8) );
13165 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13166 data
<< uint32(pQuest
->GetQuestId());
13167 data
<< uint32(entry
);
13168 data
<< uint32(old_count
+ add_count
);
13169 data
<< uint32(pQuest
->ReqCreatureOrGOCount
[ creatureOrGO_idx
]);
13170 data
<< uint64(guid
);
13171 GetSession()->SendPacket(&data
);
13173 uint16 log_slot
= FindQuestSlot( pQuest
->GetQuestId() );
13174 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13175 SetQuestSlotCounter(log_slot
,creatureOrGO_idx
,GetQuestSlotCounter(log_slot
,creatureOrGO_idx
)+add_count
);
13178 /*********************************************************/
13179 /*** LOAD SYSTEM ***/
13180 /*********************************************************/
13182 bool Player::MinimalLoadFromDB( QueryResult
*result
, uint32 guid
)
13184 bool delete_result
= true;
13187 // 0 1 2 3 4 5 6 7 8 9
13188 result
= CharacterDatabase
.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid
);
13189 if(!result
) return false;
13191 else delete_result
= false;
13193 Field
*fields
= result
->Fetch();
13195 if(!LoadValues( fields
[1].GetString()))
13197 sLog
.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid
));
13198 if(delete_result
) delete result
;
13202 // overwrite possible wrong/corrupted guid
13203 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
13205 m_name
= fields
[2].GetCppString();
13207 Relocate(fields
[3].GetFloat(),fields
[4].GetFloat(),fields
[5].GetFloat());
13208 SetMapId(fields
[6].GetUInt32());
13209 // the instance id is not needed at character enum
13211 m_Played_time
[0] = fields
[7].GetUInt32();
13212 m_Played_time
[1] = fields
[8].GetUInt32();
13214 m_atLoginFlags
= fields
[9].GetUInt32();
13216 // I don't see these used anywhere ..
13219 _LoadBoundInstances();*/
13221 if (delete_result
) delete result
;
13223 for (int i
= 0; i
< PLAYER_SLOTS_COUNT
; i
++)
13226 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
13227 m_deathState
= DEAD
;
13232 void Player::_LoadDeclinedNames(QueryResult
* result
)
13238 delete m_declinedname
;
13240 m_declinedname
= new DeclinedName
;
13241 Field
*fields
= result
->Fetch();
13242 for(int i
= 0; i
< MAX_DECLINED_NAME_CASES
; ++i
)
13243 m_declinedname
->name
[i
] = fields
[i
].GetCppString();
13248 bool Player::LoadPositionFromDB(uint32
& mapid
, float& x
,float& y
,float& z
,float& o
, bool& in_flight
, uint64 guid
)
13250 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid
));
13254 Field
*fields
= result
->Fetch();
13256 x
= fields
[0].GetFloat();
13257 y
= fields
[1].GetFloat();
13258 z
= fields
[2].GetFloat();
13259 o
= fields
[3].GetFloat();
13260 mapid
= fields
[4].GetUInt32();
13261 in_flight
= !fields
[5].GetCppString().empty();
13267 bool Player::LoadValuesArrayFromDB(Tokens
& data
, uint64 guid
)
13269 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid
));
13273 Field
*fields
= result
->Fetch();
13275 data
= StrSplit(fields
[0].GetCppString(), " ");
13282 uint32
Player::GetUInt32ValueFromArray(Tokens
const& data
, uint16 index
)
13284 if(index
>= data
.size())
13287 return (uint32
)atoi(data
[index
].c_str());
13290 float Player::GetFloatValueFromArray(Tokens
const& data
, uint16 index
)
13293 uint32 temp
= Player::GetUInt32ValueFromArray(data
,index
);
13294 memcpy(&result
, &temp
, sizeof(result
));
13299 uint32
Player::GetUInt32ValueFromDB(uint16 index
, uint64 guid
)
13302 if(!LoadValuesArrayFromDB(data
,guid
))
13305 return GetUInt32ValueFromArray(data
,index
);
13308 float Player::GetFloatValueFromDB(uint16 index
, uint64 guid
)
13311 uint32 temp
= Player::GetUInt32ValueFromDB(index
, guid
);
13312 memcpy(&result
, &temp
, sizeof(result
));
13317 bool Player::LoadFromDB( uint32 guid
, SqlQueryHolder
*holder
)
13319 //// 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
13320 //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 FROM characters WHERE guid = '%u'", guid);
13321 QueryResult
*result
= holder
->GetResult(PLAYER_LOGIN_QUERY_LOADFROM
);
13325 sLog
.outError("ERROR: Player (GUID: %u) not found in table `characters`, can't load. ",guid
);
13329 Field
*fields
= result
->Fetch();
13331 uint32 dbAccountId
= fields
[1].GetUInt32();
13333 // check if the character's account in the db and the logged in account match.
13334 // player should be able to load/delete character only with correct account!
13335 if( dbAccountId
!= GetSession()->GetAccountId() )
13337 sLog
.outError("ERROR: Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid
,GetSession()->GetAccountId(),dbAccountId
);
13342 Object::_Create( guid
, 0, HIGHGUID_PLAYER
);
13344 m_name
= fields
[3].GetCppString();
13346 // check name limitations
13347 if(!ObjectMgr::IsValidName(m_name
) || GetSession()->GetSecurity() == SEC_PLAYER
&& objmgr
.IsReservedName(m_name
))
13350 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME
),guid
);
13354 if(!LoadValues( fields
[2].GetString()))
13356 sLog
.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid
));
13361 // overwrite possible wrong/corrupted guid
13362 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
13364 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13365 for(uint8 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
13367 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), 0 );
13368 SetVisibleItemSlot(slot
,NULL
);
13372 delete m_items
[slot
];
13373 m_items
[slot
] = NULL
;
13377 // update money limits
13378 if(GetMoney() > MAX_MONEY_AMOUNT
)
13379 SetMoney(MAX_MONEY_AMOUNT
);
13381 sLog
.outDebug("Load Basic value of player %s is: ", m_name
.c_str());
13384 m_race
= fields
[4].GetUInt8();
13385 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13386 //Other way is to saves m_team into characters table.
13387 setFactionForRace(m_race
);
13390 m_class
= fields
[5].GetUInt8();
13392 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(m_race
, m_class
);
13395 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
13400 InitPrimaryProffesions(); // to max set before any spell loaded
13402 uint32 transGUID
= fields
[24].GetUInt32();
13403 Relocate(fields
[6].GetFloat(),fields
[7].GetFloat(),fields
[8].GetFloat(),fields
[10].GetFloat());
13404 SetMapId(fields
[9].GetUInt32());
13405 SetDifficulty(fields
[32].GetUInt32()); // may be changed in _LoadGroup
13407 _LoadGroup(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP
));
13409 // check arena teams integrity
13410 for(uint32 arena_slot
= 0; arena_slot
< MAX_ARENA_SLOT
; ++arena_slot
)
13412 uint32 arena_team_id
= GetArenaTeamId(arena_slot
);
13416 if(ArenaTeam
* at
= objmgr
.GetArenaTeamById(arena_team_id
))
13417 if(at
->HaveMember(GetGUID()))
13420 // arena team not exist or not member, cleanup fields
13421 for(int j
=0; j
< 6; ++j
)
13422 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arena_slot
* 6 + j
, 0);
13425 _LoadBoundInstances(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES
));
13427 if(!IsPositionValid())
13429 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());
13431 SetMapId(info
->mapId
);
13432 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
,0.0f
);
13436 m_movementInfo
.t_x
= 0.0f
;
13437 m_movementInfo
.t_y
= 0.0f
;
13438 m_movementInfo
.t_z
= 0.0f
;
13439 m_movementInfo
.t_o
= 0.0f
;
13442 // load the player's map here if it's not already loaded
13443 Map
*map
= GetMap();
13444 // since the player may not be bound to the map yet, make sure subsequent
13445 // getmap calls won't create new maps
13446 SetInstanceId(map
->GetInstanceId());
13448 SaveRecallPosition();
13450 if (transGUID
!= 0)
13452 m_movementInfo
.t_x
= fields
[20].GetFloat();
13453 m_movementInfo
.t_y
= fields
[21].GetFloat();
13454 m_movementInfo
.t_z
= fields
[22].GetFloat();
13455 m_movementInfo
.t_o
= fields
[23].GetFloat();
13457 if( !MaNGOS::IsValidMapCoord(
13458 GetPositionX()+m_movementInfo
.t_x
,GetPositionY()+m_movementInfo
.t_y
,
13459 GetPositionZ()+m_movementInfo
.t_z
,GetOrientation()+m_movementInfo
.t_o
) ||
13460 // transport size limited
13461 m_movementInfo
.t_x
> 50 || m_movementInfo
.t_y
> 50 || m_movementInfo
.t_z
> 50 )
13463 sLog
.outError("ERROR: Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
13464 guid
,GetPositionX()+m_movementInfo
.t_x
,GetPositionY()+m_movementInfo
.t_y
,
13465 GetPositionZ()+m_movementInfo
.t_z
,GetOrientation()+m_movementInfo
.t_o
);
13467 SetMapId(info
->mapId
);
13468 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
,0.0f
);
13470 m_movementInfo
.t_x
= 0.0f
;
13471 m_movementInfo
.t_y
= 0.0f
;
13472 m_movementInfo
.t_z
= 0.0f
;
13473 m_movementInfo
.t_o
= 0.0f
;
13479 if (transGUID
!= 0)
13481 for (MapManager::TransportSet::iterator iter
= MapManager::Instance().m_Transports
.begin(); iter
!= MapManager::Instance().m_Transports
.end(); ++iter
)
13483 if( (*iter
)->GetGUIDLow() == transGUID
)
13485 m_transport
= *iter
;
13486 m_transport
->AddPassenger(this);
13487 SetMapId(m_transport
->GetMapId());
13494 sLog
.outError("ERROR: Player (guidlow %d) have invalid transport guid (%u). Teleport to default race/class locations.",
13497 SetMapId(info
->mapId
);
13498 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
,0.0f
);
13500 m_movementInfo
.t_x
= 0.0f
;
13501 m_movementInfo
.t_y
= 0.0f
;
13502 m_movementInfo
.t_z
= 0.0f
;
13503 m_movementInfo
.t_o
= 0.0f
;
13509 time_t now
= time(NULL
);
13510 time_t logoutTime
= time_t(fields
[16].GetUInt64());
13512 // since last logout (in seconds)
13513 uint64 time_diff
= uint64(now
- logoutTime
);
13515 // set value, including drunk invisibility detection
13516 // calculate sobering. after 15 minutes logged out, the player will be sober again
13518 if(time_diff
> 15*MINUTE
)
13521 soberFactor
= 1-time_diff
/(15.0f
*MINUTE
);
13522 uint16 newDrunkenValue
= uint16(soberFactor
*(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFE));
13523 SetDrunkValue(newDrunkenValue
);
13525 m_rest_bonus
= fields
[15].GetFloat();
13526 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
13527 float bubble0
= 0.031;
13528 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
13529 float bubble1
= 0.125;
13531 if((int32
)fields
[16].GetUInt32() > 0)
13533 float bubble
= fields
[17].GetUInt32() > 0
13534 ? bubble1
*sWorld
.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY
)
13535 : bubble0
*sWorld
.getRate(RATE_REST_OFFLINE_IN_WILDERNESS
);
13537 SetRestBonus(GetRestBonus()+ time_diff
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
13540 m_cinematic
= fields
[12].GetUInt32();
13541 m_Played_time
[0]= fields
[13].GetUInt32();
13542 m_Played_time
[1]= fields
[14].GetUInt32();
13544 m_resetTalentsCost
= fields
[18].GetUInt32();
13545 m_resetTalentsTime
= time_t(fields
[19].GetUInt64());
13547 // reserve some flags
13548 uint32 old_safe_flags
= GetUInt32Value(PLAYER_FLAGS
) & ( PLAYER_FLAGS_HIDE_CLOAK
| PLAYER_FLAGS_HIDE_HELM
);
13550 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
) )
13551 SetUInt32Value(PLAYER_FLAGS
, 0 | old_safe_flags
);
13553 m_taxi
.LoadTaxiMask( fields
[11].GetString() ); // must be before InitTaxiNodesForLevel
13555 uint32 extraflags
= fields
[25].GetUInt32();
13557 m_stableSlots
= fields
[26].GetUInt32();
13558 if(m_stableSlots
> 2)
13560 sLog
.outError("Player can have not more 2 stable slots, but have in DB %u",uint32(m_stableSlots
));
13564 m_atLoginFlags
= fields
[27].GetUInt32();
13567 // Update Honor kills data
13568 m_lastHonorUpdateTime
= logoutTime
;
13569 UpdateHonorFields();
13571 m_deathExpireTime
= (time_t)fields
[30].GetUInt64();
13572 if(m_deathExpireTime
> now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
)
13573 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
-1;
13575 std::string taxi_nodes
= fields
[31].GetCppString();
13579 // clear channel spell data (if saved at channel spell casting)
13580 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT
, 0);
13581 SetUInt32Value(UNIT_CHANNEL_SPELL
,0);
13583 // clear charm/summon related fields
13584 SetUInt64Value(UNIT_FIELD_CHARM
,0);
13585 SetUInt64Value(UNIT_FIELD_SUMMON
,0);
13586 SetUInt64Value(UNIT_FIELD_CHARMEDBY
,0);
13587 SetUInt64Value(UNIT_FIELD_SUMMONEDBY
,0);
13588 SetUInt64Value(UNIT_FIELD_CREATEDBY
,0);
13590 // reset some aura modifiers before aura apply
13591 SetUInt64Value(PLAYER_FARSIGHT
, 0);
13592 SetUInt32Value(PLAYER_TRACK_CREATURES
, 0 );
13593 SetUInt32Value(PLAYER_TRACK_RESOURCES
, 0 );
13595 // reset skill modifiers and set correct unlearn flags
13596 for (uint32 i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
13598 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
13600 // set correct unlearn bit
13601 uint32 id
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
13604 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
13605 if(!pSkill
) continue;
13607 // enable unlearn button for primary professions only
13608 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
13609 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
13611 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
13614 // make sure the unit is considered out of combat for proper loading
13617 // make sure the unit is considered not in duel for proper loading
13618 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
13619 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
13621 // remember loaded power/health values to restore after stats initialization and modifier applying
13622 uint32 savedHealth
= GetHealth();
13623 uint32 savedPower
[MAX_POWERS
];
13624 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
13625 savedPower
[i
] = GetPower(Powers(i
));
13627 // reset stats before loading any modifiers
13628 InitStatsForLevel();
13629 InitTaxiNodesForLevel();
13631 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
13633 //mails are loaded only when needed ;-) - when player in game click on mailbox.
13636 _LoadAuras(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS
), time_diff
);
13638 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
13639 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
13640 m_deathState
= DEAD
;
13642 _LoadSpells(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS
));
13644 // after spell load
13645 InitTalentForLevel();
13646 learnSkillRewardedSpells();
13648 // after spell load, learn rewarded spell if need also
13649 _LoadQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS
));
13650 _LoadDailyQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS
));
13652 _LoadTutorials(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS
));
13654 // must be before inventory (some items required reputation check)
13655 _LoadReputation(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION
));
13657 _LoadInventory(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY
), time_diff
);
13659 // update items with duration and realtime
13660 UpdateItemDuration(time_diff
, true);
13662 _LoadActions(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS
));
13664 // unread mails and next delivery time, actual mails not loaded
13665 _LoadMailInit(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT
), holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE
));
13667 m_social
= sSocialMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST
), GetGUIDLow());
13669 if(!_LoadHomeBind(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND
)))
13672 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
13673 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
13674 if(uint32 curTitle
= GetUInt32Value(PLAYER_CHOSEN_TITLE
))
13676 if(!HasFlag64(PLAYER__FIELD_KNOWN_TITLES
,uint64(1) << curTitle
))
13677 SetUInt32Value(PLAYER_CHOSEN_TITLE
,0);
13680 // Not finish taxi flight path
13681 if(!m_taxi
.LoadTaxiDestinationsFromString(taxi_nodes
))
13683 // problems with taxi path loading
13684 TaxiNodesEntry
const* nodeEntry
= NULL
;
13685 if(uint32 node_id
= m_taxi
.GetTaxiSource())
13686 nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
13688 if(!nodeEntry
) // don't know taxi start node, to homebind
13690 sLog
.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
13691 SetMapId(m_homebindMapId
);
13692 Relocate( m_homebindX
, m_homebindY
, m_homebindZ
,0.0f
);
13693 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
13695 else // have start node, to it
13697 sLog
.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
13698 SetMapId(nodeEntry
->map_id
);
13699 Relocate(nodeEntry
->x
, nodeEntry
->y
, nodeEntry
->z
,0.0f
);
13700 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
13702 m_taxi
.ClearTaxiDestinations();
13704 else if(uint32 node_id
= m_taxi
.GetTaxiSource())
13706 // save source node as recall coord to prevent recall and fall from sky
13707 TaxiNodesEntry
const* nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
13708 assert(nodeEntry
); // checked in m_taxi.LoadTaxiDestinationsFromString
13709 m_recallMap
= nodeEntry
->map_id
;
13710 m_recallX
= nodeEntry
->x
;
13711 m_recallY
= nodeEntry
->y
;
13712 m_recallZ
= nodeEntry
->z
;
13714 // flight will started later
13717 _LoadSpellCooldowns(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS
));
13719 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
13720 // Do now before stats re-calculation cleanup for ghost state unexpected auras
13722 RemoveAllAurasOnDeath();
13724 //apply all stat bonuses from items and auras
13725 SetCanModifyStats(true);
13728 // restore remembered power/health values (but not more max values)
13729 SetHealth(savedHealth
> GetMaxHealth() ? GetMaxHealth() : savedHealth
);
13730 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
13731 SetPower(Powers(i
),savedPower
[i
] > GetMaxPower(Powers(i
)) ? GetMaxPower(Powers(i
)) : savedPower
[i
]);
13733 sLog
.outDebug("The value of player %s after load item and aura is: ", m_name
.c_str());
13737 if(GetSession()->GetSecurity() > SEC_PLAYER
)
13739 switch(sWorld
.getConfig(CONFIG_GM_LOGIN_STATE
))
13742 case 0: break; // disable
13743 case 1: SetGameMaster(true); break; // enable
13744 case 2: // save state
13745 if(extraflags
& PLAYER_EXTRA_GM_ON
)
13746 SetGameMaster(true);
13750 switch(sWorld
.getConfig(CONFIG_GM_ACCEPT_TICKETS
))
13753 case 0: break; // disable
13754 case 1: SetAcceptTicket(true); break; // enable
13755 case 2: // save state
13756 if(extraflags
& PLAYER_EXTRA_GM_ACCEPT_TICKETS
)
13757 SetAcceptTicket(true);
13761 switch(sWorld
.getConfig(CONFIG_GM_CHAT
))
13764 case 0: break; // disable
13765 case 1: SetGMChat(true); break; // enable
13766 case 2: // save state
13767 if(extraflags
& PLAYER_EXTRA_GM_CHAT
)
13772 switch(sWorld
.getConfig(CONFIG_GM_WISPERING_TO
))
13775 case 0: break; // disable
13776 case 1: SetAcceptWhispers(true); break; // enable
13777 case 2: // save state
13778 if(extraflags
& PLAYER_EXTRA_ACCEPT_WHISPERS
)
13779 SetAcceptWhispers(true);
13784 _LoadDeclinedNames(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES
));
13789 bool Player::isAllowedToLoot(Creature
* creature
)
13791 if(Player
* recipient
= creature
->GetLootRecipient())
13793 if (recipient
== this)
13795 if( Group
* otherGroup
= recipient
->GetGroup())
13797 Group
* thisGroup
= GetGroup();
13800 return thisGroup
== otherGroup
;
13805 // prevent other players from looting if the recipient got disconnected
13806 return !creature
->hasLootRecipient();
13809 void Player::_LoadActions(QueryResult
*result
)
13811 m_actionButtons
.clear();
13813 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
13819 Field
*fields
= result
->Fetch();
13821 uint8 button
= fields
[0].GetUInt8();
13823 addActionButton(button
, fields
[1].GetUInt16(), fields
[2].GetUInt8(), fields
[3].GetUInt8());
13825 m_actionButtons
[button
].uState
= ACTIONBUTTON_UNCHANGED
;
13827 while( result
->NextRow() );
13833 void Player::_LoadAuras(QueryResult
*result
, uint32 timediff
)
13836 for (int i
= 0; i
< TOTAL_AURAS
; i
++)
13837 m_modAuras
[i
].clear();
13839 // all aura related fields
13840 for(int i
= UNIT_FIELD_AURA
; i
<= UNIT_FIELD_AURASTATE
; ++i
)
13841 SetUInt32Value(i
, 0);
13843 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
13849 Field
*fields
= result
->Fetch();
13850 uint64 caster_guid
= fields
[0].GetUInt64();
13851 uint32 spellid
= fields
[1].GetUInt32();
13852 uint32 effindex
= fields
[2].GetUInt32();
13853 int32 damage
= (int32
)fields
[3].GetUInt32();
13854 int32 maxduration
= (int32
)fields
[4].GetUInt32();
13855 int32 remaintime
= (int32
)fields
[5].GetUInt32();
13856 int32 remaincharges
= (int32
)fields
[6].GetUInt32();
13858 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellid
);
13861 sLog
.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid
,effindex
);
13867 sLog
.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid
,effindex
);
13871 // negative effects should continue counting down after logout
13872 if (remaintime
!= -1 && !IsPositiveEffect(spellid
, effindex
))
13874 if(remaintime
<= int32(timediff
))
13877 remaintime
-= timediff
;
13880 // prevent wrong values of remaincharges
13881 if(spellproto
->procCharges
)
13883 if(remaincharges
<= 0 || remaincharges
> spellproto
->procCharges
)
13884 remaincharges
= spellproto
->procCharges
;
13887 remaincharges
= -1;
13889 //do not load single target auras (unless they were cast by the player)
13890 if (caster_guid
!= GetGUID() && IsSingleTargetSpell(spellproto
))
13893 Aura
* aura
= CreateAura(spellproto
, effindex
, NULL
, this, NULL
);
13895 damage
= aura
->GetModifier()->m_amount
;
13896 aura
->SetLoadedState(caster_guid
,damage
,maxduration
,remaintime
,remaincharges
);
13899 while( result
->NextRow() );
13904 if(m_class
== CLASS_WARRIOR
)
13905 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
13908 void Player::LoadCorpse()
13912 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
13916 if(Corpse
*corpse
= GetCorpse())
13918 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, corpse
&& !sMapStore
.LookupEntry(corpse
->GetMapId())->Instanceable() );
13922 //Prevent Dead Player login without corpse
13923 ResurrectPlayer(0.5f
);
13928 void Player::_LoadInventory(QueryResult
*result
, uint32 timediff
)
13930 //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());
13931 std::map
<uint64
, Bag
*> bagMap
; // fast guid lookup for bags
13932 //NOTE: the "order by `bag`" is important because it makes sure
13933 //the bagMap is filled before items in the bags are loaded
13934 //NOTE2: the "order by `slot`" is needed becaue mainhand weapons are (wrongly?)
13935 //expected to be equipped before offhand items (TODO: fixme)
13937 uint32 zone
= GetZoneId();
13941 std::list
<Item
*> problematicItems
;
13943 // prevent items from being added to the queue when stored
13944 m_itemUpdateQueueBlocked
= true;
13947 Field
*fields
= result
->Fetch();
13948 uint32 bag_guid
= fields
[1].GetUInt32();
13949 uint8 slot
= fields
[2].GetUInt8();
13950 uint32 item_guid
= fields
[3].GetUInt32();
13951 uint32 item_id
= fields
[4].GetUInt32();
13953 ItemPrototype
const * proto
= objmgr
.GetItemPrototype(item_id
);
13957 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
13958 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid
);
13959 sLog
.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id
);
13963 Item
*item
= NewItemOrBag(proto
);
13965 if(!item
->LoadFromDB(item_guid
, GetGUID(), result
))
13967 sLog
.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id
);
13968 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
13969 item
->FSetState(ITEM_REMOVED
);
13970 item
->SaveToDB(); // it also deletes item object !
13974 // not allow have in alive state item limited to another map/zone
13975 if(isAlive() && item
->IsLimitedToAnotherMapOrZone(GetMapId(),zone
) )
13977 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
13978 item
->FSetState(ITEM_REMOVED
);
13979 item
->SaveToDB(); // it also deletes item object !
13983 // "Conjured items disappear if you are logged out for more than 15 minutes"
13984 if ((timediff
> 15*60) && (item
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_CONJURED
)))
13986 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
13987 item
->FSetState(ITEM_REMOVED
);
13988 item
->SaveToDB(); // it also deletes item object !
13992 bool success
= true;
13996 // the item is not in a bag
13997 item
->SetContainer( NULL
);
13998 item
->SetSlot(slot
);
14000 if( IsInventoryPos( INVENTORY_SLOT_BAG_0
, slot
) )
14002 ItemPosCountVec dest
;
14003 if( CanStoreItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false ) == EQUIP_ERR_OK
)
14004 item
= StoreItem(dest
, item
, true);
14008 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0
, slot
) )
14011 if( CanEquipItem( slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
14012 QuickEquipItem(dest
, item
);
14016 else if( IsBankPos( INVENTORY_SLOT_BAG_0
, slot
) )
14018 ItemPosCountVec dest
;
14019 if( CanBankItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
14020 item
= BankItem(dest
, item
, true);
14027 // store bags that may contain items in them
14028 if(item
->IsBag() && IsBagPos(item
->GetPos()))
14029 bagMap
[item_guid
] = (Bag
*)item
;
14034 item
->SetSlot(NULL_SLOT
);
14035 // the item is in a bag, find the bag
14036 std::map
<uint64
, Bag
*>::iterator itr
= bagMap
.find(bag_guid
);
14037 if(itr
!= bagMap
.end())
14038 itr
->second
->StoreItem(slot
, item
, true );
14043 // item's state may have changed after stored
14045 item
->SetState(ITEM_UNCHANGED
, this);
14048 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
);
14049 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14050 problematicItems
.push_back(item
);
14052 } while (result
->NextRow());
14055 m_itemUpdateQueueBlocked
= false;
14057 // send by mail problematic items
14058 while(!problematicItems
.empty())
14061 MailItemsInfo mi
; // item list prepering
14063 for(int i
= 0; !problematicItems
.empty() && i
< MAX_MAIL_ITEMS
; ++i
)
14065 Item
* item
= problematicItems
.front();
14066 problematicItems
.pop_front();
14068 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
14071 std::string subject
= GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM
);
14073 WorldSession::SendMailTo(this, MAIL_NORMAL
, MAIL_STATIONERY_GM
, GetGUIDLow(), GetGUIDLow(), subject
, 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
);
14077 _ApplyAllItemMods();
14080 // load mailed item which should receive current player
14081 void Player::_LoadMailedItems(Mail
*mail
)
14083 QueryResult
* result
= CharacterDatabase
.PQuery("SELECT item_guid, item_template FROM mail_items WHERE mail_id='%u'", mail
->messageID
);
14089 Field
*fields
= result
->Fetch();
14090 uint32 item_guid_low
= fields
[0].GetUInt32();
14091 uint32 item_template
= fields
[1].GetUInt32();
14093 mail
->AddItem(item_guid_low
, item_template
);
14095 ItemPrototype
const *proto
= objmgr
.GetItemPrototype(item_template
);
14099 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
);
14100 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
14101 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low
);
14105 Item
*item
= NewItemOrBag(proto
);
14107 if(!item
->LoadFromDB(item_guid_low
, 0))
14109 sLog
.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail
->messageID
, item_guid_low
);
14110 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
14111 item
->FSetState(ITEM_REMOVED
);
14112 item
->SaveToDB(); // it also deletes item object !
14117 } while (result
->NextRow());
14122 void Player::_LoadMailInit(QueryResult
*resultUnread
, QueryResult
*resultDelivery
)
14124 //set a count of unread mails
14125 //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);
14128 Field
*fieldMail
= resultUnread
->Fetch();
14129 unReadMails
= fieldMail
[0].GetUInt8();
14130 delete resultUnread
;
14133 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14134 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14135 if (resultDelivery
)
14137 Field
*fieldMail
= resultDelivery
->Fetch();
14138 m_nextMailDelivereTime
= (time_t)fieldMail
[0].GetUInt64();
14139 delete resultDelivery
;
14143 void Player::_LoadMail()
14146 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14147 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());
14152 Field
*fields
= result
->Fetch();
14153 Mail
*m
= new Mail
;
14154 m
->messageID
= fields
[0].GetUInt32();
14155 m
->messageType
= fields
[1].GetUInt8();
14156 m
->sender
= fields
[2].GetUInt32();
14157 m
->receiver
= fields
[3].GetUInt32();
14158 m
->subject
= fields
[4].GetCppString();
14159 m
->itemTextId
= fields
[5].GetUInt32();
14160 bool has_items
= fields
[6].GetBool();
14161 m
->expire_time
= (time_t)fields
[7].GetUInt64();
14162 m
->deliver_time
= (time_t)fields
[8].GetUInt64();
14163 m
->money
= fields
[9].GetUInt32();
14164 m
->COD
= fields
[10].GetUInt32();
14165 m
->checked
= fields
[11].GetUInt32();
14166 m
->stationery
= fields
[12].GetUInt8();
14167 m
->mailTemplateId
= fields
[13].GetInt16();
14169 if(m
->mailTemplateId
&& !sMailTemplateStore
.LookupEntry(m
->mailTemplateId
))
14171 sLog
.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m
->messageID
, m
->mailTemplateId
);
14172 m
->mailTemplateId
= 0;
14175 m
->state
= MAIL_STATE_UNCHANGED
;
14178 _LoadMailedItems(m
);
14180 m_mail
.push_back(m
);
14181 } while( result
->NextRow() );
14184 m_mailsLoaded
= true;
14187 void Player::LoadPet()
14189 //fixme: the pet should still be loaded if the player is not in world
14190 // just not added to the map
14193 Pet
*pet
= new Pet
;
14194 if(!pet
->LoadPetFromDB(this,0,0,true))
14199 void Player::_LoadQuestStatus(QueryResult
*result
)
14201 mQuestStatus
.clear();
14205 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14206 //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());
14212 Field
*fields
= result
->Fetch();
14214 uint32 quest_id
= fields
[0].GetUInt32();
14215 // used to be new, no delete?
14216 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
14220 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
14222 uint32 qstatus
= fields
[1].GetUInt32();
14223 if(qstatus
< MAX_QUEST_STATUS
)
14224 questStatusData
.m_status
= QuestStatus(qstatus
);
14227 questStatusData
.m_status
= QUEST_STATUS_NONE
;
14228 sLog
.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id
,qstatus
);
14231 questStatusData
.m_rewarded
= ( fields
[2].GetUInt8() > 0 );
14232 questStatusData
.m_explored
= ( fields
[3].GetUInt8() > 0 );
14234 time_t quest_time
= time_t(fields
[4].GetUInt64());
14236 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && !GetQuestRewardStatus(quest_id
) && questStatusData
.m_status
!= QUEST_STATUS_NONE
)
14238 AddTimedQuest( quest_id
);
14240 if (quest_time
<= sWorld
.GetGameTime())
14241 questStatusData
.m_timer
= 1;
14243 questStatusData
.m_timer
= (quest_time
- sWorld
.GetGameTime()) * 1000;
14248 questStatusData
.m_creatureOrGOcount
[0] = fields
[5].GetUInt32();
14249 questStatusData
.m_creatureOrGOcount
[1] = fields
[6].GetUInt32();
14250 questStatusData
.m_creatureOrGOcount
[2] = fields
[7].GetUInt32();
14251 questStatusData
.m_creatureOrGOcount
[3] = fields
[8].GetUInt32();
14252 questStatusData
.m_itemcount
[0] = fields
[9].GetUInt32();
14253 questStatusData
.m_itemcount
[1] = fields
[10].GetUInt32();
14254 questStatusData
.m_itemcount
[2] = fields
[11].GetUInt32();
14255 questStatusData
.m_itemcount
[3] = fields
[12].GetUInt32();
14257 questStatusData
.uState
= QUEST_UNCHANGED
;
14259 // add to quest log
14260 if( slot
< MAX_QUEST_LOG_SIZE
&&
14261 ( questStatusData
.m_status
==QUEST_STATUS_INCOMPLETE
||
14262 questStatusData
.m_status
==QUEST_STATUS_COMPLETE
&& !questStatusData
.m_rewarded
) )
14264 SetQuestSlot(slot
,quest_id
,quest_time
);
14266 if(questStatusData
.m_status
== QUEST_STATUS_COMPLETE
)
14267 SetQuestSlotState(slot
,QUEST_STATE_COMPLETE
);
14269 for(uint8 idx
= 0; idx
< QUEST_OBJECTIVES_COUNT
; ++idx
)
14270 if(questStatusData
.m_creatureOrGOcount
[idx
])
14271 SetQuestSlotCounter(slot
,idx
,questStatusData
.m_creatureOrGOcount
[idx
]);
14276 if(questStatusData
.m_rewarded
)
14278 // learn rewarded spell if unknown
14279 learnQuestRewardedSpells(pQuest
);
14281 // set rewarded title if any
14282 if(pQuest
->GetCharTitleId())
14284 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
14285 SetFlag64(PLAYER__FIELD_KNOWN_TITLES
, (uint64(1) << titleEntry
->bit_index
));
14289 sLog
.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData
.m_status
, quest_id
, GetGUIDLow());
14292 while( result
->NextRow() );
14297 // clear quest log tail
14298 for ( uint16 i
= slot
; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14302 void Player::_LoadDailyQuestStatus(QueryResult
*result
)
14304 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
14305 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
14307 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14311 uint32 quest_daily_idx
= 0;
14315 if(quest_daily_idx
>= PLAYER_MAX_DAILY_QUESTS
) // max amount with exist data in query
14317 sLog
.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
14321 Field
*fields
= result
->Fetch();
14323 uint32 quest_id
= fields
[0].GetUInt32();
14325 // save _any_ from daily quest times (it must be after last reset anyway)
14326 m_lastDailyQuestTime
= (time_t)fields
[1].GetUInt64();
14328 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
14332 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
14335 sLog
.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id
, GetGUIDLow());
14337 while( result
->NextRow() );
14342 m_DailyQuestChanged
= false;
14345 void Player::_LoadReputation(QueryResult
*result
)
14347 m_factions
.clear();
14349 // Set initial reputations (so everything is nifty before DB data load)
14350 SetInitialFactions();
14352 //QueryResult *result = CharacterDatabase.PQuery("SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'",GetGUIDLow());
14358 Field
*fields
= result
->Fetch();
14360 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(fields
[0].GetUInt32());
14361 if( factionEntry
&& (factionEntry
->reputationListID
>= 0))
14363 FactionState
* faction
= &m_factions
[factionEntry
->reputationListID
];
14365 // update standing to current
14366 faction
->Standing
= int32(fields
[1].GetUInt32());
14368 uint32 dbFactionFlags
= fields
[2].GetUInt32();
14370 if( dbFactionFlags
& FACTION_FLAG_VISIBLE
)
14371 SetFactionVisible(faction
); // have internal checks for forced invisibility
14373 if( dbFactionFlags
& FACTION_FLAG_INACTIVE
)
14374 SetFactionInactive(faction
,true); // have internal checks for visibility requirement
14376 if( dbFactionFlags
& FACTION_FLAG_AT_WAR
) // DB at war
14377 SetFactionAtWar(faction
,true); // have internal checks for FACTION_FLAG_PEACE_FORCED
14378 else // DB not at war
14380 // allow remove if visible (and then not FACTION_FLAG_INVISIBLE_FORCED or FACTION_FLAG_HIDDEN)
14381 if( faction
->Flags
& FACTION_FLAG_VISIBLE
)
14382 SetFactionAtWar(faction
,false); // have internal checks for FACTION_FLAG_PEACE_FORCED
14385 // set atWar for hostile
14386 if(GetReputationRank(factionEntry
) <= REP_HOSTILE
)
14387 SetFactionAtWar(faction
,true);
14389 // reset changed flag if values similar to saved in DB
14390 if(faction
->Flags
==dbFactionFlags
)
14391 faction
->Changed
= false;
14394 while( result
->NextRow() );
14400 void Player::_LoadSpells(QueryResult
*result
)
14402 for (PlayerSpellMap::iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
14403 delete itr
->second
;
14406 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,slot,active FROM character_spell WHERE guid = '%u'",GetGUIDLow());
14412 Field
*fields
= result
->Fetch();
14414 addSpell(fields
[0].GetUInt16(), fields
[2].GetBool(), false, true, fields
[1].GetUInt16(), fields
[3].GetBool());
14416 while( result
->NextRow() );
14422 void Player::_LoadTutorials(QueryResult
*result
)
14424 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
14430 Field
*fields
= result
->Fetch();
14432 for (int iI
=0; iI
<8; iI
++)
14433 m_Tutorials
[iI
] = fields
[iI
].GetUInt32();
14435 while( result
->NextRow() );
14440 m_TutorialsChanged
= false;
14443 void Player::_LoadGroup(QueryResult
*result
)
14445 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
14448 uint64 leaderGuid
= MAKE_NEW_GUID((*result
)[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
14450 Group
* group
= objmgr
.GetGroupByLeader(leaderGuid
);
14453 uint8 subgroup
= group
->GetMemberGroup(GetGUID());
14454 SetGroup(group
, subgroup
);
14455 if(getLevel() >= LEVELREQUIREMENT_HEROIC
)
14457 // the group leader may change the instance difficulty while the player is offline
14458 SetDifficulty(group
->GetDifficulty());
14464 void Player::_LoadBoundInstances(QueryResult
*result
)
14466 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
14467 m_boundInstances
[i
].clear();
14469 Group
*group
= GetGroup();
14471 //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));
14476 Field
*fields
= result
->Fetch();
14477 bool perm
= fields
[1].GetBool();
14478 uint32 mapId
= fields
[2].GetUInt32();
14479 uint32 instanceId
= fields
[0].GetUInt32();
14480 uint8 difficulty
= fields
[3].GetUInt8();
14481 time_t resetTime
= (time_t)fields
[4].GetUInt64();
14482 // the resettime for normal instances is only saved when the InstanceSave is unloaded
14483 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
14484 // and in that case it is not used
14488 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
);
14489 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
14493 // since non permanent binds are always solo bind, they can always be reset
14494 InstanceSave
*save
= sInstanceSaveManager
.AddInstanceSave(mapId
, instanceId
, difficulty
, resetTime
, !perm
, true);
14495 if(save
) BindToInstance(save
, perm
, true);
14496 } while(result
->NextRow());
14501 InstancePlayerBind
* Player::GetBoundInstance(uint32 mapid
, uint8 difficulty
)
14503 // some instances only have one difficulty
14504 const MapEntry
* entry
= sMapStore
.LookupEntry(mapid
);
14505 if(!entry
|| !entry
->SupportsHeroicMode()) difficulty
= DIFFICULTY_NORMAL
;
14507 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
14508 if(itr
!= m_boundInstances
[difficulty
].end())
14509 return &itr
->second
;
14514 void Player::UnbindInstance(uint32 mapid
, uint8 difficulty
, bool unload
)
14516 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
14517 UnbindInstance(itr
, difficulty
, unload
);
14520 void Player::UnbindInstance(BoundInstancesMap::iterator
&itr
, uint8 difficulty
, bool unload
)
14522 if(itr
!= m_boundInstances
[difficulty
].end())
14524 if(!unload
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr
->second
.save
->GetInstanceId());
14525 itr
->second
.save
->RemovePlayer(this); // save can become invalid
14526 m_boundInstances
[difficulty
].erase(itr
++);
14530 InstancePlayerBind
* Player::BindToInstance(InstanceSave
*save
, bool permanent
, bool load
)
14534 InstancePlayerBind
& bind
= m_boundInstances
[save
->GetDifficulty()][save
->GetMapId()];
14537 // update the save when the group kills a boss
14538 if(permanent
!= bind
.perm
|| save
!= bind
.save
)
14539 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());
14542 if(!load
) CharacterDatabase
.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save
->GetInstanceId(), permanent
);
14544 if(bind
.save
!= save
)
14546 if(bind
.save
) bind
.save
->RemovePlayer(this);
14547 save
->AddPlayer(this);
14550 if(permanent
) save
->SetCanReset(false);
14553 bind
.perm
= permanent
;
14554 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());
14561 void Player::SendRaidInfo()
14563 WorldPacket
data(SMSG_RAID_INSTANCE_INFO
, 4);
14565 uint32 counter
= 0, i
;
14566 for(i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
14567 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); itr
++)
14568 if(itr
->second
.perm
) counter
++;
14571 for(i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
14573 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); itr
++)
14575 if(itr
->second
.perm
)
14577 InstanceSave
*save
= itr
->second
.save
;
14578 data
<< (save
->GetMapId());
14579 data
<< (uint32
)(save
->GetResetTime() - time(NULL
));
14580 data
<< save
->GetInstanceId();
14581 data
<< uint32(counter
);
14586 GetSession()->SendPacket(&data
);
14590 - called on every successful teleportation to a map
14592 void Player::SendSavedInstances()
14594 bool hasBeenSaved
= false;
14597 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
14599 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
14601 if(itr
->second
.perm
) // only permanent binds are sent
14603 hasBeenSaved
= true;
14609 //Send opcode 811. true or flase means, whether you have current raid/heroic instances
14610 data
.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP
);
14611 data
<< uint32(hasBeenSaved
);
14612 GetSession()->SendPacket(&data
);
14617 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
14619 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
14621 if(itr
->second
.perm
)
14623 data
.Initialize(SMSG_UPDATE_LAST_INSTANCE
);
14624 data
<< uint32(itr
->second
.save
->GetMapId());
14625 GetSession()->SendPacket(&data
);
14631 /// convert the player's binds to the group
14632 void Player::ConvertInstancesToGroup(Player
*player
, Group
*group
, uint64 player_guid
)
14634 bool has_binds
= false;
14635 bool has_solo
= false;
14637 if(player
) { player_guid
= player
->GetGUID(); if(!group
) group
= player
->GetGroup(); }
14638 assert(player_guid
);
14640 // copy all binds to the group, when changing leader it's assumed the character
14641 // will not have any solo binds
14645 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
14647 for (BoundInstancesMap::iterator itr
= player
->m_boundInstances
[i
].begin(); itr
!= player
->m_boundInstances
[i
].end();)
14650 if(group
) group
->BindToInstance(itr
->second
.save
, itr
->second
.perm
, true);
14651 // permanent binds are not removed
14652 if(!itr
->second
.perm
)
14654 player
->UnbindInstance(itr
, i
, true); // increments itr
14663 // if the player's not online we don't know what binds it has
14664 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
));
14665 // the following should not get executed when changing leaders
14666 if(!player
|| has_solo
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid
));
14669 bool Player::_LoadHomeBind(QueryResult
*result
)
14672 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
14675 Field
*fields
= result
->Fetch();
14676 m_homebindMapId
= fields
[0].GetUInt32();
14677 m_homebindZoneId
= fields
[1].GetUInt16();
14678 m_homebindX
= fields
[2].GetFloat();
14679 m_homebindY
= fields
[3].GetFloat();
14680 m_homebindZ
= fields
[4].GetFloat();
14683 // accept saved data only for valid position (and non instanceable)
14684 if( MapManager::IsValidMapCoord(m_homebindMapId
,m_homebindX
,m_homebindY
,m_homebindZ
) &&
14685 !sMapStore
.LookupEntry(m_homebindMapId
)->Instanceable() )
14690 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
14695 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(), getClass());
14696 if(!info
) return false;
14698 m_homebindMapId
= info
->mapId
;
14699 m_homebindZoneId
= info
->zoneId
;
14700 m_homebindX
= info
->positionX
;
14701 m_homebindY
= info
->positionY
;
14702 m_homebindZ
= info
->positionZ
;
14704 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
);
14707 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",
14708 m_homebindMapId
, m_homebindZoneId
, m_homebindX
, m_homebindY
, m_homebindZ
);
14713 /*********************************************************/
14714 /*** SAVE SYSTEM ***/
14715 /*********************************************************/
14717 void Player::SaveToDB()
14719 // delay auto save at any saves (manual, in code, or autosave)
14720 m_nextSave
= sWorld
.getConfig(CONFIG_INTERVAL_SAVE
);
14722 // first save/honor gain after midnight will also update the player's honor fields
14723 UpdateHonorFields();
14725 // Must saved before enter into BattleGround
14726 if(InBattleGround())
14729 int is_save_resting
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
) ? 1 : 0;
14730 //save, far from tavern/city
14731 //save, but in tavern/city
14732 sLog
.outDebug("The value of player %s at save: ", m_name
.c_str());
14735 // save state (after auras removing), if aura remove some flags then it must set it back by self)
14736 uint32 tmp_bytes
= GetUInt32Value(UNIT_FIELD_BYTES_1
);
14737 uint32 tmp_bytes2
= GetUInt32Value(UNIT_FIELD_BYTES_2
);
14738 uint32 tmp_flags
= GetUInt32Value(UNIT_FIELD_FLAGS
);
14739 uint32 tmp_pflags
= GetUInt32Value(PLAYER_FLAGS
);
14740 uint32 tmp_displayid
= GetDisplayId();
14742 // Set player sit state to standing on save, also stealth and shifted form
14743 SetByteValue(UNIT_FIELD_BYTES_1
, 0, 0); // stand state
14744 SetByteValue(UNIT_FIELD_BYTES_2
, 3, 0); // shapeshift
14745 SetByteValue(UNIT_FIELD_BYTES_1
, 3, 0); // stand flags?
14746 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_DISABLE_ROTATE
);
14747 SetDisplayId(GetNativeDisplayId());
14749 bool inworld
= IsInWorld();
14751 CharacterDatabase
.BeginTransaction();
14753 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
14755 std::string sql_name
= m_name
;
14756 CharacterDatabase
.escape_string(sql_name
);
14758 std::ostringstream ss
;
14759 ss
<< "INSERT INTO characters (guid,account,name,race,class,"
14760 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
14761 "taximask, online, cinematic, "
14762 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
14763 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
14764 "death_expire_time, taxi_path) VALUES ("
14765 << GetGUIDLow() << ", "
14766 << GetSession()->GetAccountId() << ", '"
14767 << sql_name
<< "', "
14769 << m_class
<< ", ";
14771 bool save_to_dest
= false;
14772 if(IsBeingTeleported())
14774 // don't save to battlegrounds or arenas
14775 const MapEntry
*entry
= sMapStore
.LookupEntry(GetTeleportDest().mapid
);
14776 if(entry
&& entry
->map_type
!= MAP_BATTLEGROUND
&& entry
->map_type
!= MAP_ARENA
)
14777 save_to_dest
= true;
14782 ss
<< GetMapId() << ", "
14783 << (uint32
)GetDifficulty() << ", "
14784 << finiteAlways(GetPositionX()) << ", "
14785 << finiteAlways(GetPositionY()) << ", "
14786 << finiteAlways(GetPositionZ()) << ", "
14787 << finiteAlways(GetOrientation()) << ", '";
14791 ss
<< GetTeleportDest().mapid
<< ", "
14792 << (uint32
)GetDifficulty() << ", "
14793 << finiteAlways(GetTeleportDest().x
) << ", "
14794 << finiteAlways(GetTeleportDest().y
) << ", "
14795 << finiteAlways(GetTeleportDest().z
) << ", "
14796 << finiteAlways(GetTeleportDest().o
) << ", '";
14800 for( i
= 0; i
< m_valuesCount
; i
++ )
14802 ss
<< GetUInt32Value(i
) << " ";
14807 for( i
= 0; i
< 8; i
++ )
14808 ss
<< m_taxi
.GetTaximask(i
) << " ";
14811 ss
<< (inworld
? 1 : 0);
14817 ss
<< m_Played_time
[0];
14819 ss
<< m_Played_time
[1];
14822 ss
<< finiteAlways(m_rest_bonus
);
14824 ss
<< (uint64
)time(NULL
);
14826 ss
<< is_save_resting
;
14828 ss
<< m_resetTalentsCost
;
14830 ss
<< (uint64
)m_resetTalentsTime
;
14833 ss
<< finiteAlways(m_movementInfo
.t_x
);
14835 ss
<< finiteAlways(m_movementInfo
.t_y
);
14837 ss
<< finiteAlways(m_movementInfo
.t_z
);
14839 ss
<< finiteAlways(m_movementInfo
.t_o
);
14842 ss
<< m_transport
->GetGUIDLow();
14847 ss
<< m_ExtraFlags
;
14850 ss
<< uint32(m_stableSlots
); // to prevent save uint8 as char
14853 ss
<< uint32(m_atLoginFlags
);
14859 ss
<< (uint64
)m_deathExpireTime
;
14862 ss
<< m_taxi
.SaveTaxiDestinationsToString();
14865 CharacterDatabase
.Execute( ss
.str().c_str() );
14867 if(m_mailsUpdated
) //save mails only when needed
14871 _SaveQuestStatus();
14872 _SaveDailyQuestStatus();
14875 _SaveSpellCooldowns();
14880 CharacterDatabase
.CommitTransaction();
14882 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
14883 SetDisplayId(tmp_displayid
);
14884 SetUInt32Value(UNIT_FIELD_BYTES_1
, tmp_bytes
);
14885 SetUInt32Value(UNIT_FIELD_BYTES_2
, tmp_bytes2
);
14886 SetUInt32Value(UNIT_FIELD_FLAGS
, tmp_flags
);
14887 SetUInt32Value(PLAYER_FLAGS
, tmp_pflags
);
14889 // save pet (hunter pet level and experience and all type pets health/mana).
14890 if(Pet
* pet
= GetPet())
14891 pet
->SavePetToDB(PET_SAVE_AS_CURRENT
);
14894 // fast save function for item/money cheating preventing - save only inventory and money state
14895 void Player::SaveInventoryAndGoldToDB()
14898 SetUInt32ValueInDB(PLAYER_FIELD_COINAGE
,GetMoney(),GetGUID());
14901 void Player::_SaveActions()
14903 for(ActionButtonList::iterator itr
= m_actionButtons
.begin(); itr
!= m_actionButtons
.end(); )
14905 switch (itr
->second
.uState
)
14907 case ACTIONBUTTON_NEW
:
14908 CharacterDatabase
.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
14909 GetGUIDLow(), (uint32
)itr
->first
, (uint32
)itr
->second
.action
, (uint32
)itr
->second
.type
, (uint32
)itr
->second
.misc
);
14910 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
14913 case ACTIONBUTTON_CHANGED
:
14914 CharacterDatabase
.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
14915 (uint32
)itr
->second
.action
, (uint32
)itr
->second
.type
, (uint32
)itr
->second
.misc
, GetGUIDLow(), (uint32
)itr
->first
);
14916 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
14919 case ACTIONBUTTON_DELETED
:
14920 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32
)itr
->first
);
14921 m_actionButtons
.erase(itr
++);
14930 void Player::_SaveAuras()
14932 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14934 AuraMap
const& auras
= GetAuras();
14935 for(AuraMap::const_iterator itr
= auras
.begin(); itr
!= auras
.end(); ++itr
)
14937 SpellEntry
const *spellInfo
= itr
->second
->GetSpellProto();
14939 //skip all auras from spells that are passive or need a shapeshift
14940 if (itr
->second
->IsPassive() || itr
->second
->IsRemovedOnShapeLost())
14943 //do not save single target auras (unless they were cast by the player)
14944 if (itr
->second
->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo
))
14948 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
14949 for (i
= 0; i
< 3; i
++)
14950 if (spellInfo
->EffectApplyAuraName
[i
] == SPELL_AURA_MOD_SHAPESHIFT
||
14951 spellInfo
->EffectApplyAuraName
[i
] == SPELL_AURA_MOD_STEALTH
)
14956 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u' and spell = '%u' and effect_index= '%u'",GetGUIDLow(),(uint32
)(*itr
).second
->GetId(), (uint32
)(*itr
).second
->GetEffIndex());
14957 CharacterDatabase
.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges) "
14958 "VALUES ('%u', '" I64FMTD
"' ,'%u', '%u', '%d', '%d', '%d', '%d')",
14959 GetGUIDLow(), itr
->second
->GetCasterGUID(), (uint32
)(*itr
).second
->GetId(), (uint32
)(*itr
).second
->GetEffIndex(), (*itr
).second
->GetModifier()->m_amount
,int((*itr
).second
->GetAuraMaxDuration()),int((*itr
).second
->GetAuraDuration()),int((*itr
).second
->m_procCharges
));
14964 void Player::_SaveInventory()
14966 // force items in buyback slots to new state
14967 // and remove those that aren't already
14968 for (uint8 i
= BUYBACK_SLOT_START
; i
< BUYBACK_SLOT_END
; i
++)
14970 Item
*item
= m_items
[i
];
14971 if (!item
|| item
->GetState() == ITEM_NEW
) continue;
14972 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
14973 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item
->GetGUIDLow());
14974 m_items
[i
]->FSetState(ITEM_NEW
);
14977 // update enchantment durations
14978 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
14980 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
14984 if (m_itemUpdateQueue
.empty()) return;
14986 // do not save if the update queue is corrupt
14987 bool error
= false;
14988 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); i
++)
14990 Item
*item
= m_itemUpdateQueue
[i
];
14991 if(!item
|| item
->GetState() == ITEM_REMOVED
) continue;
14992 Item
*test
= GetItemByPos( item
->GetBagSlot(), item
->GetSlot());
14996 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());
14999 else if (test
!= item
)
15001 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());
15008 sLog
.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15009 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED
);
15013 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); i
++)
15015 Item
*item
= m_itemUpdateQueue
[i
];
15016 if(!item
) continue;
15018 Bag
*container
= item
->GetContainer();
15019 uint32 bag_guid
= container
? container
->GetGUIDLow() : 0;
15021 switch(item
->GetState())
15024 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());
15027 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());
15030 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
15032 case ITEM_UNCHANGED
:
15036 item
->SaveToDB(); // item have unchanged inventory record and can be save standalone
15038 m_itemUpdateQueue
.clear();
15041 void Player::_SaveMail()
15043 if (!m_mailsLoaded
)
15046 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); itr
++)
15049 if (m
->state
== MAIL_STATE_CHANGED
)
15051 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'",
15052 m
->itemTextId
, m
->HasItems() ? 1 : 0, (uint64
)m
->expire_time
, (uint64
)m
->deliver_time
, m
->money
, m
->COD
, m
->checked
, m
->messageID
);
15053 if(m
->removedItems
.size())
15055 for(std::vector
<uint32
>::iterator itr2
= m
->removedItems
.begin(); itr2
!= m
->removedItems
.end(); ++itr2
)
15056 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2
);
15057 m
->removedItems
.clear();
15059 m
->state
= MAIL_STATE_UNCHANGED
;
15061 else if (m
->state
== MAIL_STATE_DELETED
)
15064 for(std::vector
<MailItemInfo
>::iterator itr2
= m
->items
.begin(); itr2
!= m
->items
.end(); ++itr2
)
15065 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2
->item_guid
);
15067 CharacterDatabase
.PExecute("DELETE FROM item_text WHERE id = '%u'", m
->itemTextId
);
15068 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", m
->messageID
);
15069 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m
->messageID
);
15073 //deallocate deleted mails...
15074 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); )
15076 if ((*itr
)->state
== MAIL_STATE_DELETED
)
15081 itr
= m_mail
.begin();
15087 m_mailsUpdated
= false;
15090 void Player::_SaveQuestStatus()
15092 // we don't need transactions here.
15093 for( QuestStatusMap::iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
15095 switch (i
->second
.uState
)
15098 CharacterDatabase
.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15099 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD
"', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15100 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]);
15102 case QUEST_CHANGED
:
15103 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' ",
15104 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
);
15106 case QUEST_UNCHANGED
:
15109 i
->second
.uState
= QUEST_UNCHANGED
;
15113 void Player::_SaveDailyQuestStatus()
15115 if(!m_DailyQuestChanged
)
15118 m_DailyQuestChanged
= false;
15120 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15122 // we don't need transactions here.
15123 CharacterDatabase
.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15124 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
15125 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
15126 CharacterDatabase
.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD
"')",
15127 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
),uint64(m_lastDailyQuestTime
));
15130 void Player::_SaveReputation()
15132 for(FactionStateList::iterator itr
= m_factions
.begin(); itr
!= m_factions
.end(); ++itr
)
15134 if (itr
->second
.Changed
)
15136 CharacterDatabase
.PExecute("DELETE FROM character_reputation WHERE guid = '%u' AND faction='%u'", GetGUIDLow(), itr
->second
.ID
);
15137 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
);
15138 itr
->second
.Changed
= false;
15143 void Player::_SaveSpells()
15145 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(), next
= m_spells
.begin(); itr
!= m_spells
.end(); itr
= next
)
15148 if (itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->second
->state
== PLAYERSPELL_CHANGED
)
15149 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr
->first
);
15150 if (itr
->second
->state
== PLAYERSPELL_NEW
|| itr
->second
->state
== PLAYERSPELL_CHANGED
)
15151 CharacterDatabase
.PExecute("INSERT INTO character_spell (guid,spell,slot,active,disabled) VALUES ('%u', '%u', '%u','%u','%u')", GetGUIDLow(), itr
->first
, itr
->second
->slotId
,itr
->second
->active
? 1 : 0,itr
->second
->disabled
? 1 : 0);
15153 if (itr
->second
->state
== PLAYERSPELL_REMOVED
)
15154 _removeSpell(itr
->first
);
15156 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
15160 void Player::_SaveTutorials()
15162 if(!m_TutorialsChanged
)
15166 // it's better than rebuilding indexes multiple times
15167 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID
);
15170 Rows
= result
->Fetch()[0].GetUInt32();
15176 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'",
15177 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
);
15181 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]);
15184 m_TutorialsChanged
= false;
15187 void Player::outDebugValues() const
15189 if(!sLog
.IsOutDebug()) // optimize disabled debug output
15192 sLog
.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA
));
15193 sLog
.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY
), GetStat(STAT_STRENGTH
));
15194 sLog
.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT
), GetStat(STAT_SPIRIT
));
15195 sLog
.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA
), GetStat(STAT_SPIRIT
));
15196 sLog
.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE
));
15197 sLog
.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY
), GetResistance(SPELL_SCHOOL_FIRE
));
15198 sLog
.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE
), GetResistance(SPELL_SCHOOL_FROST
));
15199 sLog
.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW
), GetResistance(SPELL_SCHOOL_ARCANE
));
15200 sLog
.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE
), GetFloatValue(UNIT_FIELD_MAXDAMAGE
));
15201 sLog
.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
));
15202 sLog
.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
));
15203 sLog
.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK
), GetAttackTime(RANGED_ATTACK
));
15206 /*********************************************************/
15207 /*** FLOOD FILTER SYSTEM ***/
15208 /*********************************************************/
15210 void Player::UpdateSpeakTime()
15212 // ignore chat spam protection for GMs in any mode
15213 if(GetSession()->GetSecurity() > SEC_PLAYER
)
15216 time_t current
= time (NULL
);
15217 if(m_speakTime
> current
)
15219 uint32 max_count
= sWorld
.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT
);
15224 if(m_speakCount
>= max_count
)
15226 // prevent overwrite mute time, if message send just before mutes set, for example.
15227 time_t new_mute
= current
+ sWorld
.getConfig(CONFIG_CHATFLOOD_MUTE_TIME
);
15228 if(GetSession()->m_muteTime
< new_mute
)
15229 GetSession()->m_muteTime
= new_mute
;
15237 m_speakTime
= current
+ sWorld
.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY
);
15240 bool Player::CanSpeak() const
15242 return GetSession()->m_muteTime
<= time (NULL
);
15245 /*********************************************************/
15246 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15247 /*********************************************************/
15249 void Player::SendAttackSwingNotInRange()
15251 WorldPacket
data(SMSG_ATTACKSWING_NOTINRANGE
, 0);
15252 GetSession()->SendPacket( &data
);
15255 void Player::SavePositionInDB(uint32 mapid
, float x
,float y
,float z
,float o
,uint32 zone
,uint64 guid
)
15257 std::ostringstream ss
;
15258 ss
<< "UPDATE characters SET position_x='"<<x
<<"',position_y='"<<y
15259 << "',position_z='"<<z
<<"',orientation='"<<o
<<"',map='"<<mapid
15260 << "',zone='"<<zone
<<"',trans_x='0',trans_y='0',trans_z='0',"
15261 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
15262 sLog
.outDebug(ss
.str().c_str());
15263 CharacterDatabase
.Execute(ss
.str().c_str());
15266 bool Player::SaveValuesArrayInDB(Tokens
const& tokens
, uint64 guid
)
15268 std::ostringstream ss2
;
15269 ss2
<<"UPDATE characters SET data='";
15271 for (Tokens::const_iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
, ++i
)
15273 ss2
<<tokens
[i
]<<" ";
15275 ss2
<<"' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
15277 return CharacterDatabase
.Execute(ss2
.str().c_str());
15280 void Player::SetUInt32ValueInArray(Tokens
& tokens
,uint16 index
, uint32 value
)
15283 snprintf(buf
,11,"%u",value
);
15285 if(index
>= tokens
.size())
15288 tokens
[index
] = buf
;
15291 void Player::SetUInt32ValueInDB(uint16 index
, uint32 value
, uint64 guid
)
15294 if(!LoadValuesArrayFromDB(tokens
,guid
))
15297 if(index
>= tokens
.size())
15301 snprintf(buf
,11,"%u",value
);
15302 tokens
[index
] = buf
;
15304 SaveValuesArrayInDB(tokens
,guid
);
15307 void Player::SetFloatValueInDB(uint16 index
, float value
, uint64 guid
)
15310 memcpy(&temp
, &value
, sizeof(value
));
15311 Player::SetUInt32ValueInDB(index
, temp
, guid
);
15314 void Player::SendAttackSwingNotStanding()
15316 WorldPacket
data(SMSG_ATTACKSWING_NOTSTANDING
, 0);
15317 GetSession()->SendPacket( &data
);
15320 void Player::SendAttackSwingDeadTarget()
15322 WorldPacket
data(SMSG_ATTACKSWING_DEADTARGET
, 0);
15323 GetSession()->SendPacket( &data
);
15326 void Player::SendAttackSwingCantAttack()
15328 WorldPacket
data(SMSG_ATTACKSWING_CANT_ATTACK
, 0);
15329 GetSession()->SendPacket( &data
);
15332 void Player::SendAttackSwingCancelAttack()
15334 WorldPacket
data(SMSG_CANCEL_COMBAT
, 0);
15335 GetSession()->SendPacket( &data
);
15338 void Player::SendAttackSwingBadFacingAttack()
15340 WorldPacket
data(SMSG_ATTACKSWING_BADFACING
, 0);
15341 GetSession()->SendPacket( &data
);
15344 void Player::SendAutoRepeatCancel()
15346 WorldPacket
data(SMSG_CANCEL_AUTO_REPEAT
, 0);
15347 GetSession()->SendPacket( &data
);
15350 void Player::PlaySound(uint32 Sound
, bool OnlySelf
)
15352 WorldPacket
data(SMSG_PLAY_SOUND
, 4);
15355 GetSession()->SendPacket( &data
);
15357 SendMessageToSet( &data
, true );
15360 void Player::SendExplorationExperience(uint32 Area
, uint32 Experience
)
15362 WorldPacket
data( SMSG_EXPLORATION_EXPERIENCE
, 8 );
15364 data
<< Experience
;
15365 GetSession()->SendPacket(&data
);
15368 void Player::SendDungeonDifficulty(bool IsInGroup
)
15370 uint8 val
= 0x00000001;
15371 WorldPacket
data(MSG_SET_DUNGEON_DIFFICULTY
, 12);
15372 data
<< (uint32
)GetDifficulty();
15373 data
<< uint32(val
);
15374 data
<< uint32(IsInGroup
);
15375 GetSession()->SendPacket(&data
);
15378 void Player::SendResetFailedNotify(uint32 mapid
)
15380 WorldPacket
data(SMSG_RESET_FAILED_NOTIFY
, 4);
15381 data
<< uint32(mapid
);
15382 GetSession()->SendPacket(&data
);
15385 /// Reset all solo instances and optionally send a message on success for each
15386 void Player::ResetInstances(uint8 method
)
15388 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
15390 // we assume that when the difficulty changes, all instances that can be reset will be
15391 uint8 dif
= GetDifficulty();
15393 for (BoundInstancesMap::iterator itr
= m_boundInstances
[dif
].begin(); itr
!= m_boundInstances
[dif
].end();)
15395 InstanceSave
*p
= itr
->second
.save
;
15396 const MapEntry
*entry
= sMapStore
.LookupEntry(itr
->first
);
15397 if(!entry
|| !p
->CanReset())
15403 if(method
== INSTANCE_RESET_ALL
)
15405 // the "reset all instances" method can only reset normal maps
15406 if(dif
== DIFFICULTY_HEROIC
|| entry
->map_type
== MAP_RAID
)
15413 // if the map is loaded, reset it
15414 Map
*map
= MapManager::Instance().FindMap(p
->GetMapId(), p
->GetInstanceId());
15415 if(map
&& map
->IsDungeon())
15416 ((InstanceMap
*)map
)->Reset(method
);
15418 // since this is a solo instance there should not be any players inside
15419 if(method
== INSTANCE_RESET_ALL
|| method
== INSTANCE_RESET_CHANGE_DIFFICULTY
)
15420 SendResetInstanceSuccess(p
->GetMapId());
15423 m_boundInstances
[dif
].erase(itr
++);
15425 // the following should remove the instance save from the manager and delete it as well
15426 p
->RemovePlayer(this);
15430 void Player::SendResetInstanceSuccess(uint32 MapId
)
15432 WorldPacket
data(SMSG_INSTANCE_RESET
, 4);
15434 GetSession()->SendPacket(&data
);
15437 void Player::SendResetInstanceFailed(uint32 reason
, uint32 MapId
)
15439 // TODO: find what other fail reasons there are besides players in the instance
15440 WorldPacket
data(SMSG_INSTANCE_RESET_FAILED
, 4);
15443 GetSession()->SendPacket(&data
);
15446 /*********************************************************/
15447 /*** Update timers ***/
15448 /*********************************************************/
15450 ///checks the 15 afk reports per 5 minutes limit
15451 void Player::UpdateAfkReport(time_t currTime
)
15453 if(m_bgAfkReportedTimer
<= currTime
)
15455 m_bgAfkReportedCount
= 0;
15456 m_bgAfkReportedTimer
= currTime
+5*MINUTE
;
15460 void Player::UpdateContestedPvP(uint32 diff
)
15462 if(!m_contestedPvPTimer
||isInCombat())
15464 if(m_contestedPvPTimer
<= diff
)
15466 ResetContestedPvP();
15469 m_contestedPvPTimer
-= diff
;
15472 void Player::UpdatePvPFlag(time_t currTime
)
15476 if(pvpInfo
.endTimer
== 0 || currTime
< (pvpInfo
.endTimer
+ 300))
15482 void Player::UpdateDuelFlag(time_t currTime
)
15484 if(!duel
|| duel
->startTimer
== 0 ||currTime
< duel
->startTimer
+ 3)
15487 SetUInt32Value(PLAYER_DUEL_TEAM
, 1);
15488 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 2);
15490 duel
->startTimer
= 0;
15491 duel
->startTime
= currTime
;
15492 duel
->opponent
->duel
->startTimer
= 0;
15493 duel
->opponent
->duel
->startTime
= currTime
;
15496 void Player::RemovePet(Pet
* pet
, PetSaveMode mode
, bool returnreagent
)
15501 if(returnreagent
&& (pet
|| m_temporaryUnsummonedPetNumber
))
15503 //returning of reagents only for players, so best done here
15504 uint32 spellId
= pet
? pet
->GetUInt32Value(UNIT_CREATED_BY_SPELL
) : m_oldpetspell
;
15505 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellId
);
15509 for(uint32 i
= 0; i
< 7; ++i
)
15511 if(spellInfo
->Reagent
[i
] > 0)
15513 ItemPosCountVec dest
; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
15514 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, spellInfo
->Reagent
[i
], spellInfo
->ReagentCount
[i
] );
15515 if( msg
== EQUIP_ERR_OK
)
15517 Item
* item
= StoreNewItem( dest
, spellInfo
->Reagent
[i
], true);
15519 SendNewItem(item
,spellInfo
->ReagentCount
[i
],true,false);
15524 m_temporaryUnsummonedPetNumber
= 0;
15527 if(!pet
|| pet
->GetOwnerGUID()!=GetGUID())
15530 // only if current pet in slot
15531 switch(pet
->getPetType())
15537 m_guardianPets
.erase(pet
->GetGUID());
15540 if(GetPetGUID()==pet
->GetGUID())
15549 switch(pet
->GetEntry())
15551 //warlock pets except imp are removed(?) when logging out
15556 mode
= PET_SAVE_NOT_IN_SLOT
;
15561 pet
->SavePetToDB(mode
);
15563 pet
->CleanupsBeforeDelete();
15564 pet
->AddObjectToRemoveList();
15565 pet
->m_removed
= true;
15567 if(pet
->isControlled())
15569 WorldPacket
data(SMSG_PET_SPELLS
, 8);
15571 GetSession()->SendPacket(&data
);
15574 SetGroupUpdateFlag(GROUP_UPDATE_PET
);
15578 void Player::RemoveMiniPet()
15580 if(Pet
* pet
= GetMiniPet())
15582 pet
->Remove(PET_SAVE_AS_DELETED
);
15587 Pet
* Player::GetMiniPet()
15591 return ObjectAccessor::GetPet(m_miniPet
);
15594 void Player::RemoveGuardians()
15596 while(!m_guardianPets
.empty())
15598 uint64 guid
= *m_guardianPets
.begin();
15599 if(Pet
* pet
= ObjectAccessor::GetPet(guid
))
15600 pet
->Remove(PET_SAVE_AS_DELETED
);
15602 m_guardianPets
.erase(guid
);
15606 bool Player::HasGuardianWithEntry(uint32 entry
)
15608 // pet guid middle part is entry (and creature also)
15609 // and in guardian list must be guardians with same entry _always_
15610 for(GuardianPetList::const_iterator itr
= m_guardianPets
.begin(); itr
!= m_guardianPets
.end(); ++itr
)
15611 if(GUID_ENPART(*itr
)==entry
)
15617 void Player::Uncharm()
15619 Unit
* charm
= GetCharm();
15623 charm
->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM
);
15624 charm
->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS
);
15627 void Player::BuildPlayerChat(WorldPacket
*data
, uint8 msgtype
, std::string text
, uint32 language
) const
15629 *data
<< (uint8
)msgtype
;
15630 *data
<< (uint32
)language
;
15631 *data
<< (uint64
)GetGUID();
15632 *data
<< (uint32
)language
; //language 2.1.0 ?
15633 *data
<< (uint64
)GetGUID();
15634 *data
<< (uint32
)(text
.length()+1);
15636 *data
<< (uint8
)chatTag();
15639 void Player::Say(const std::string text
, const uint32 language
)
15641 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
15642 BuildPlayerChat(&data
, CHAT_MSG_SAY
, text
, language
);
15643 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_SAY
),true);
15646 void Player::Yell(const std::string text
, const uint32 language
)
15648 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
15649 BuildPlayerChat(&data
, CHAT_MSG_YELL
, text
, language
);
15650 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_YELL
),true);
15653 void Player::TextEmote(const std::string text
)
15655 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
15656 BuildPlayerChat(&data
, CHAT_MSG_EMOTE
, text
, LANG_UNIVERSAL
);
15657 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE
),true, !sWorld
.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT
) );
15660 void Player::Whisper(std::string text
, uint32 language
,uint64 receiver
)
15662 if (language
!= LANG_ADDON
) // if not addon data
15663 language
= LANG_UNIVERSAL
; // whispers should always be readable
15665 Player
*rPlayer
= objmgr
.GetPlayer(receiver
);
15667 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
15668 if(!rPlayer
->isDND() || isGameMaster())
15670 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
15671 BuildPlayerChat(&data
, CHAT_MSG_WHISPER
, text
, language
);
15672 rPlayer
->GetSession()->SendPacket(&data
);
15674 data
.Initialize(SMSG_MESSAGECHAT
, 200);
15675 rPlayer
->BuildPlayerChat(&data
, CHAT_MSG_REPLY
, text
, language
);
15676 GetSession()->SendPacket(&data
);
15680 // announce to player that player he is whispering to is dnd and cannot receive his message
15681 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND
, rPlayer
->GetName(), rPlayer
->dndMsg
.c_str());
15684 if(!isAcceptWhispers())
15686 SetAcceptWhispers(true);
15687 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON
);
15690 // announce to player that player he is whispering to is afk
15691 if(rPlayer
->isAFK())
15692 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK
, rPlayer
->GetName(), rPlayer
->afkMsg
.c_str());
15694 // if player whisper someone, auto turn of dnd to be able to receive an answer
15695 if(isDND() && !rPlayer
->isGameMaster())
15699 void Player::PetSpellInitialize()
15701 Pet
* pet
= GetPet();
15707 sLog
.outDebug("Pet Spells Groups");
15709 CreatureInfo
const *cinfo
= pet
->GetCreatureInfo();
15711 if(pet
->isControlled() && (pet
->getPetType() == HUNTER_PET
|| cinfo
&& cinfo
->type
== CREATURE_TYPE_DEMON
&& getClass() == CLASS_WARLOCK
))
15713 for(PetSpellMap::iterator itr
= pet
->m_spells
.begin();itr
!= pet
->m_spells
.end();itr
++)
15715 if(itr
->second
->state
== PETSPELL_REMOVED
)
15721 // first line + actionbar + spellcount + spells + last adds
15722 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);
15724 CharmInfo
*charmInfo
= pet
->GetCharmInfo();
15727 data
<< (uint64
)pet
->GetGUID() << uint32(0x00000000) << uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState()) << uint16(0);
15729 for(uint32 i
= 0; i
< 10; i
++) //40
15731 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
15734 data
<< uint8(addlist
); //1
15736 if(addlist
&& pet
->isControlled())
15738 for (PetSpellMap::iterator itr
= pet
->m_spells
.begin(); itr
!= pet
->m_spells
.end(); ++itr
)
15740 if(itr
->second
->state
== PETSPELL_REMOVED
)
15743 data
<< uint16(itr
->first
);
15744 data
<< uint16(itr
->second
->active
); // pet spell active state isn't boolean
15748 //data << uint8(0x01) << uint32(0x6010) << uint32(0x01) << uint32(0x05) << uint16(0x00); //15
15749 uint8 count
= 3; //1+8+8+8=25
15751 // if count = 0, then end of packet...
15753 // uint32 value is spell id...
15754 // uint64 value is constant 0, unknown...
15755 data
<< uint32(0x6010) << uint64(0); // if count = 1, 2 or 3
15756 //data << uint32(0x5fd1) << uint64(0); // if count = 2
15757 data
<< uint32(0x8e8c) << uint64(0); // if count = 3
15758 data
<< uint32(0x8e8b) << uint64(0); // if count = 3
15760 GetSession()->SendPacket(&data
);
15764 void Player::PossessSpellInitialize()
15766 Unit
* charm
= GetCharm();
15771 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
15775 sLog
.outError("Player::PossessSpellInitialize(): charm ("I64FMTD
") has no charminfo!", charm
->GetGUID());
15780 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);// first line + actionbar + spellcount + spells + last adds
15783 data
<< (uint64
)charm
->GetGUID() << uint32(0x00000000) << uint8(0) << uint8(0) << uint16(0);
15785 for(uint32 i
= 0; i
< 10; i
++) //40
15787 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
15790 data
<< uint8(addlist
); //1
15794 data
<< uint32(0x6010) << uint64(0); // if count = 1, 2 or 3
15795 data
<< uint32(0x8e8c) << uint64(0); // if count = 3
15796 data
<< uint32(0x8e8b) << uint64(0); // if count = 3
15798 GetSession()->SendPacket(&data
);
15801 void Player::CharmSpellInitialize()
15803 Unit
* charm
= GetCharm();
15808 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
15811 sLog
.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD
") has no charminfo!", charm
->GetGUID());
15817 if(charm
->GetTypeId() != TYPEID_PLAYER
)
15819 CreatureInfo
const *cinfo
= ((Creature
*)charm
)->GetCreatureInfo();
15821 if(cinfo
&& cinfo
->type
== CREATURE_TYPE_DEMON
&& getClass() == CLASS_WARLOCK
)
15823 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
15825 if(charmInfo
->GetCharmSpell(i
)->spellId
)
15831 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);// first line + actionbar + spellcount + spells + last adds
15833 data
<< (uint64
)charm
->GetGUID() << uint32(0x00000000);
15835 if(charm
->GetTypeId() != TYPEID_PLAYER
)
15836 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState());
15838 data
<< uint8(0) << uint8(0);
15842 for(uint32 i
= 0; i
< 10; i
++) //40
15844 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
15847 data
<< uint8(addlist
); //1
15851 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
15853 CharmSpellEntry
*cspell
= charmInfo
->GetCharmSpell(i
);
15854 if(cspell
->spellId
)
15856 data
<< uint16(cspell
->spellId
);
15857 data
<< uint16(cspell
->active
);
15864 data
<< uint32(0x6010) << uint64(0); // if count = 1, 2 or 3
15865 data
<< uint32(0x8e8c) << uint64(0); // if count = 3
15866 data
<< uint32(0x8e8b) << uint64(0); // if count = 3
15868 GetSession()->SendPacket(&data
);
15871 int32
Player::GetTotalFlatMods(uint32 spellId
, SpellModOp op
)
15873 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellId
);
15874 if (!spellInfo
) return 0;
15876 for (SpellModList::iterator itr
= m_spellMods
[op
].begin(); itr
!= m_spellMods
[op
].end(); ++itr
)
15878 SpellModifier
*mod
= *itr
;
15880 if(!IsAffectedBySpellmod(spellInfo
,mod
))
15883 if (mod
->type
== SPELLMOD_FLAT
)
15884 total
+= mod
->value
;
15889 int32
Player::GetTotalPctMods(uint32 spellId
, SpellModOp op
)
15891 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellId
);
15892 if (!spellInfo
) return 0;
15894 for (SpellModList::iterator itr
= m_spellMods
[op
].begin(); itr
!= m_spellMods
[op
].end(); ++itr
)
15896 SpellModifier
*mod
= *itr
;
15898 if(!IsAffectedBySpellmod(spellInfo
,mod
))
15901 if (mod
->type
== SPELLMOD_PCT
)
15902 total
+= mod
->value
;
15907 bool Player::IsAffectedBySpellmod(SpellEntry
const *spellInfo
, SpellModifier
*mod
, Spell
const* spell
)
15909 if (!mod
|| !spellInfo
)
15912 if(mod
->charges
== -1 && mod
->lastAffected
) // marked as expired but locked until spell casting finish
15914 // prevent apply to any spell except spell that trigger expire
15917 if(mod
->lastAffected
!= spell
)
15920 else if(mod
->lastAffected
!= FindCurrentSpellBySpellId(spellInfo
->Id
))
15924 return spellmgr
.IsAffectedBySpell(spellInfo
,mod
->spellId
,mod
->effectId
,mod
->mask
);
15927 void Player::AddSpellMod(SpellModifier
* mod
, bool apply
)
15929 uint16 Opcode
= (mod
->type
== SPELLMOD_FLAT
) ? SMSG_SET_FLAT_SPELL_MODIFIER
: SMSG_SET_PCT_SPELL_MODIFIER
;
15931 for(int eff
=0;eff
<64;++eff
)
15933 uint64 _mask
= uint64(1) << eff
;
15934 if ( mod
->mask
& _mask
)
15937 for (SpellModList::iterator itr
= m_spellMods
[mod
->op
].begin(); itr
!= m_spellMods
[mod
->op
].end(); ++itr
)
15939 if ((*itr
)->type
== mod
->type
&& (*itr
)->mask
& _mask
)
15940 val
+= (*itr
)->value
;
15942 val
+= apply
? mod
->value
: -(mod
->value
);
15943 WorldPacket
data(Opcode
, (1+1+4));
15944 data
<< uint8(eff
);
15945 data
<< uint8(mod
->op
);
15946 data
<< int32(val
);
15947 SendDirectMessage(&data
);
15952 m_spellMods
[mod
->op
].push_back(mod
);
15955 if (mod
->charges
== -1)
15956 --m_SpellModRemoveCount
;
15957 m_spellMods
[mod
->op
].remove(mod
);
15962 void Player::RemoveSpellMods(Spell
const* spell
)
15964 if(!spell
|| (m_SpellModRemoveCount
== 0))
15967 for(int i
=0;i
<MAX_SPELLMOD
;++i
)
15969 for (SpellModList::iterator itr
= m_spellMods
[i
].begin(); itr
!= m_spellMods
[i
].end();)
15971 SpellModifier
*mod
= *itr
;
15974 if (mod
&& mod
->charges
== -1 && (mod
->lastAffected
== spell
|| mod
->lastAffected
==NULL
))
15976 RemoveAurasDueToSpell(mod
->spellId
);
15977 if (m_spellMods
[i
].empty())
15980 itr
= m_spellMods
[i
].begin();
15986 // send Proficiency
15987 void Player::SendProficiency(uint8 pr1
, uint32 pr2
)
15989 WorldPacket
data(SMSG_SET_PROFICIENCY
, 8);
15990 data
<< pr1
<< pr2
;
15991 GetSession()->SendPacket (&data
);
15994 void Player::RemovePetitionsAndSigns(uint64 guid
, uint32 type
)
15996 QueryResult
*result
= NULL
;
15998 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
16000 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16003 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.
16004 { // and SendPetitionQueryOpcode reads data from the DB
16005 Field
*fields
= result
->Fetch();
16006 uint64 ownerguid
= MAKE_NEW_GUID(fields
[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
16007 uint64 petitionguid
= MAKE_NEW_GUID(fields
[1].GetUInt32(), 0, HIGHGUID_ITEM
);
16009 // send update if charter owner in game
16010 Player
* owner
= objmgr
.GetPlayer(ownerguid
);
16012 owner
->GetSession()->SendPetitionQueryOpcode(petitionguid
);
16014 } while ( result
->NextRow() );
16019 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
16021 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16024 CharacterDatabase
.BeginTransaction();
16027 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid
));
16028 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid
));
16032 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16033 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16035 CharacterDatabase
.CommitTransaction();
16038 void Player::SetRestBonus (float rest_bonus_new
)
16040 // Prevent resting on max level
16041 if(getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
16042 rest_bonus_new
= 0;
16044 if(rest_bonus_new
< 0)
16045 rest_bonus_new
= 0;
16047 float rest_bonus_max
= (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)*1.5/2;
16049 if(rest_bonus_new
> rest_bonus_max
)
16050 m_rest_bonus
= rest_bonus_max
;
16052 m_rest_bonus
= rest_bonus_new
;
16054 // update data for client
16055 if(m_rest_bonus
>10)
16056 SetByteValue(PLAYER_BYTES_2
, 3, 0x01); // Set Reststate = Rested
16057 else if(m_rest_bonus
<=1)
16058 SetByteValue(PLAYER_BYTES_2
, 3, 0x02); // Set Reststate = Normal
16061 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE
, uint32(m_rest_bonus
));
16064 void Player::HandleStealthedUnitsDetection()
16066 std::list
<Unit
*> stealthedUnits
;
16068 CellPair
p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16070 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
16071 cell
.SetNoCreate();
16073 MaNGOS::AnyStealthedCheck u_check
;
16074 MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
> searcher(stealthedUnits
, u_check
);
16076 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, WorldTypeMapContainer
> world_unit_searcher(searcher
);
16077 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, GridTypeMapContainer
> grid_unit_searcher(searcher
);
16079 CellLock
<GridReadGuard
> cell_lock(cell
, p
);
16080 cell_lock
->Visit(cell_lock
, world_unit_searcher
, *MapManager::Instance().GetMap(GetMapId(), this));
16081 cell_lock
->Visit(cell_lock
, grid_unit_searcher
, *MapManager::Instance().GetMap(GetMapId(), this));
16083 for (std::list
<Unit
*>::iterator i
= stealthedUnits
.begin(); i
!= stealthedUnits
.end();)
16087 i
= stealthedUnits
.erase(i
);
16091 if ((*i
)->isVisibleForOrDetect(this,true))
16094 (*i
)->SendUpdateToPlayer(this);
16095 m_clientGUIDs
.insert((*i
)->GetGUID());
16097 #ifdef MANGOS_DEBUG
16098 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
16099 sLog
.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i
)->GetGUIDLow(),(*i
)->GetTypeId(),GetGUIDLow(),GetDistance(*i
));
16102 // target aura duration for caster show only if target exist at caster client
16103 // send data at target visibility change (adding to client)
16104 if((*i
)!=this && (*i
)->isType(TYPEMASK_UNIT
))
16105 SendAuraDurationsForTarget(*i
);
16107 i
= stealthedUnits
.erase(i
);
16115 bool Player::ActivateTaxiPathTo(std::vector
<uint32
> const& nodes
, uint32 mount_id
, Creature
* npc
)
16117 if(nodes
.size() < 2)
16120 // not let cheating with start flight mounted
16123 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16124 data
<< uint32(ERR_TAXIPLAYERALREADYMOUNTED
);
16125 GetSession()->SendPacket(&data
);
16129 if( m_ShapeShiftFormSpellId
&& m_form
!= FORM_BATTLESTANCE
&& m_form
!= FORM_BERSERKERSTANCE
&& m_form
!= FORM_DEFENSIVESTANCE
&& m_form
!= FORM_SHADOW
)
16131 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16132 data
<< uint32(ERR_TAXIPLAYERSHAPESHIFTED
);
16133 GetSession()->SendPacket(&data
);
16137 // 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
16138 if(GetSession()->isLogingOut() ||
16139 (!m_currentSpells
[CURRENT_GENERIC_SPELL
] ||
16140 m_currentSpells
[CURRENT_GENERIC_SPELL
]->m_spellInfo
->Effect
[0] != SPELL_EFFECT_SEND_TAXI
)&&
16141 IsNonMeleeSpellCasted(false) ||
16144 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16145 data
<< uint32(ERR_TAXIPLAYERBUSY
);
16146 GetSession()->SendPacket(&data
);
16150 if(HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_DISABLE_MOVE
))
16153 uint32 sourcenode
= nodes
[0];
16155 // starting node too far away (cheat?)
16156 TaxiNodesEntry
const* node
= sTaxiNodesStore
.LookupEntry(sourcenode
);
16157 if( !node
|| node
->map_id
!= GetMapId() ||
16158 (node
->x
- GetPositionX())*(node
->x
- GetPositionX())+
16159 (node
->y
- GetPositionY())*(node
->y
- GetPositionY())+
16160 (node
->z
- GetPositionZ())*(node
->z
- GetPositionZ()) >
16161 (2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
) )
16163 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16164 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
16165 GetSession()->SendPacket(&data
);
16169 // Prepare to flight start now
16171 // stop combat at start taxi flight if any
16174 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16177 // clean not finished taxi path if any
16178 m_taxi
.ClearTaxiDestinations();
16180 // 0 element current node
16181 m_taxi
.AddTaxiDestination(sourcenode
);
16183 // fill destinations path tail
16184 uint32 sourcepath
= 0;
16185 uint32 totalcost
= 0;
16187 uint32 prevnode
= sourcenode
;
16188 uint32 lastnode
= 0;
16190 for(uint32 i
= 1; i
< nodes
.size(); ++i
)
16194 lastnode
= nodes
[i
];
16195 objmgr
.GetTaxiPath(prevnode
, lastnode
, path
, cost
);
16199 m_taxi
.ClearTaxiDestinations();
16205 if(prevnode
== sourcenode
)
16208 m_taxi
.AddTaxiDestination(lastnode
);
16210 prevnode
= lastnode
;
16213 if(!mount_id
) // if not provide then attempt use default.
16214 mount_id
= objmgr
.GetTaxiMount(sourcenode
, GetTeam());
16216 if (mount_id
== 0 || sourcepath
== 0)
16218 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16219 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
16220 GetSession()->SendPacket(&data
);
16221 m_taxi
.ClearTaxiDestinations();
16225 uint32 money
= GetMoney();
16229 totalcost
= (uint32
)ceil(totalcost
*GetReputationPriceDiscount(npc
));
16232 if(money
< totalcost
)
16234 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16235 data
<< uint32(ERR_TAXINOTENOUGHMONEY
);
16236 GetSession()->SendPacket(&data
);
16237 m_taxi
.ClearTaxiDestinations();
16241 //Checks and preparations done, DO FLIGHT
16242 ModifyMoney(-(int32
)totalcost
);
16244 // prevent stealth flight
16245 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH
);
16247 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16248 data
<< uint32(ERR_TAXIOK
);
16249 GetSession()->SendPacket(&data
);
16251 sLog
.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16253 GetSession()->SendDoFlight(mount_id
, sourcepath
);
16258 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask
, uint32 unTimeMs
)
16260 // last check 2.0.10
16261 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+m_spells
.size()*8);
16263 data
<< uint8(0x0); // flags (0x1, 0x2)
16264 time_t curTime
= time(NULL
);
16265 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
16267 if (itr
->second
->state
== PLAYERSPELL_REMOVED
)
16269 uint32 unSpellId
= itr
->first
;
16270 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(unSpellId
);
16277 // Not send cooldown for this spells
16278 if (spellInfo
->Attributes
& SPELL_ATTR_DISABLED_WHILE_ACTIVE
)
16281 if((idSchoolMask
& GetSpellSchoolMask(spellInfo
)) && GetSpellCooldownDelay(unSpellId
) < unTimeMs
)
16284 data
<< unTimeMs
; // in m.secs
16285 AddSpellCooldown(unSpellId
, 0, curTime
+ unTimeMs
/1000);
16288 GetSession()->SendPacket(&data
);
16291 void Player::InitDataForForm(bool reapplyMods
)
16293 SpellShapeshiftEntry
const* ssEntry
= sSpellShapeshiftStore
.LookupEntry(m_form
);
16294 if(ssEntry
&& ssEntry
->attackSpeed
)
16296 SetAttackTime(BASE_ATTACK
,ssEntry
->attackSpeed
);
16297 SetAttackTime(OFF_ATTACK
,ssEntry
->attackSpeed
);
16298 SetAttackTime(RANGED_ATTACK
, BASE_ATTACK_TIME
);
16301 SetRegularAttackTime();
16307 if(getPowerType()!=POWER_ENERGY
)
16308 setPowerType(POWER_ENERGY
);
16312 case FORM_DIREBEAR
:
16314 if(getPowerType()!=POWER_RAGE
)
16315 setPowerType(POWER_RAGE
);
16318 default: // 0, for example
16320 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(getClass());
16321 if(cEntry
&& cEntry
->powerType
< MAX_POWERS
&& uint32(getPowerType()) != cEntry
->powerType
)
16322 setPowerType(Powers(cEntry
->powerType
));
16327 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
16329 UpdateEquipSpellsAtFormChange();
16331 UpdateAttackPowerAndDamage();
16332 UpdateAttackPowerAndDamage(true);
16335 // Return true is the bought item has a max count to force refresh of window by caller
16336 bool Player::BuyItemFromVendor(uint64 vendorguid
, uint32 item
, uint8 count
, uint64 bagguid
, uint8 slot
)
16338 // cheating attempt
16339 if(count
< 1) count
= 1;
16344 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
16347 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, NULL
, item
, 0);
16351 Creature
*pCreature
= ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid
,UNIT_NPC_FLAG_VENDOR
);
16354 sLog
.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid
)) );
16355 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR
, NULL
, item
, 0);
16359 VendorItemData
const* vItems
= pCreature
->GetVendorItems();
16360 if(!vItems
|| vItems
->Empty())
16362 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
16366 size_t vendor_slot
= vItems
->FindItemSlot(item
);
16367 if(vendor_slot
>= vItems
->GetItemCount())
16369 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
16373 VendorItem
const* crItem
= vItems
->m_items
[vendor_slot
];
16375 // check current item amount if it limited
16376 if( crItem
->maxcount
!= 0 )
16378 if(pCreature
->GetVendorItemCurrentCount(crItem
) < pProto
->BuyCount
* count
)
16380 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD
, pCreature
, item
, 0);
16385 if( uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
16387 SendBuyError( BUY_ERR_REPUTATION_REQUIRE
, pCreature
, item
, 0);
16391 if(crItem
->ExtendedCost
)
16393 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
16396 sLog
.outError("Item %u have wrong ExtendedCost field value %u", pProto
->ItemId
, crItem
->ExtendedCost
);
16400 // honor points price
16401 if(GetHonorPoints() < (iece
->reqhonorpoints
* count
))
16403 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS
, NULL
, NULL
);
16407 // arena points price
16408 if(GetArenaPoints() < (iece
->reqarenapoints
* count
))
16410 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS
, NULL
, NULL
);
16415 for (uint8 i
= 0; i
< 5; ++i
)
16417 if(iece
->reqitem
[i
] && !HasItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
)))
16419 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS
, NULL
, NULL
);
16424 // check for personal arena rating requirement
16425 if( GetMaxPersonalArenaRatingRequirement() < iece
->reqpersonalarenarating
)
16427 // probably not the proper equip err
16428 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK
,NULL
,NULL
);
16433 uint32 price
= pProto
->BuyPrice
* count
;
16435 // reputation discount
16436 price
= uint32(floor(price
* GetReputationPriceDiscount(pCreature
)));
16438 if( GetMoney() < price
)
16440 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, pCreature
, item
, 0);
16444 uint8 bag
= 0; // init for case invalid bagGUID
16446 if (bagguid
!= NULL_BAG
&& slot
!= NULL_SLOT
)
16449 if( bagguid
== GetGUID() )
16451 bag
= INVENTORY_SLOT_BAG_0
;
16455 for (int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
;i
++)
16457 pBag
= (Bag
*)GetItemByPos(INVENTORY_SLOT_BAG_0
,i
);
16460 if( bagguid
== pBag
->GetGUID() )
16470 if( IsInventoryPos( bag
, slot
) || (bagguid
== NULL_BAG
&& slot
== NULL_SLOT
) )
16472 ItemPosCountVec dest
;
16473 uint8 msg
= CanStoreNewItem( bag
, slot
, dest
, item
, pProto
->BuyCount
* count
);
16474 if( msg
!= EQUIP_ERR_OK
)
16476 SendEquipError( msg
, NULL
, NULL
);
16480 ModifyMoney( -(int32
)price
);
16481 if(crItem
->ExtendedCost
) // case for new honor system
16483 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
16484 if(iece
->reqhonorpoints
)
16485 ModifyHonorPoints( - int32(iece
->reqhonorpoints
* count
));
16486 if(iece
->reqarenapoints
)
16487 ModifyArenaPoints( - int32(iece
->reqarenapoints
* count
));
16488 for (uint8 i
= 0; i
< 5; ++i
)
16490 if(iece
->reqitem
[i
])
16491 DestroyItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
), true);
16495 if(Item
*it
= StoreNewItem( dest
, item
, true ))
16497 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
16499 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
16500 data
<< pCreature
->GetGUID();
16501 data
<< (uint32
)(vendor_slot
+1); // numbered from 1 at client
16502 data
<< (uint32
)(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
16503 data
<< (uint32
)count
;
16504 GetSession()->SendPacket(&data
);
16506 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
16509 else if( IsEquipmentPos( bag
, slot
) )
16512 uint8 msg
= CanEquipNewItem( slot
, dest
, item
, pProto
->BuyCount
* count
, false );
16513 if( msg
!= EQUIP_ERR_OK
)
16515 SendEquipError( msg
, NULL
, NULL
);
16519 ModifyMoney( -(int32
)price
);
16520 if(crItem
->ExtendedCost
) // case for new honor system
16522 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
16523 if(iece
->reqhonorpoints
)
16524 ModifyHonorPoints( - int32(iece
->reqhonorpoints
));
16525 if(iece
->reqarenapoints
)
16526 ModifyArenaPoints( - int32(iece
->reqarenapoints
));
16527 for (uint8 i
= 0; i
< 5; ++i
)
16529 if(iece
->reqitem
[i
])
16530 DestroyItemCount(iece
->reqitem
[i
], iece
->reqitemcount
[i
], true);
16534 if(Item
*it
= EquipNewItem( dest
, item
, pProto
->BuyCount
* count
, true ))
16536 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
16538 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
16539 data
<< pCreature
->GetGUID();
16540 data
<< (uint32
)(vendor_slot
+1); // numbered from 1 at client
16541 data
<< (uint32
)(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
16542 data
<< (uint32
)count
;
16543 GetSession()->SendPacket(&data
);
16545 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
16547 AutoUnequipOffhandIfNeed();
16552 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
, NULL
, NULL
);
16556 return crItem
->maxcount
!=0;
16559 uint32
Player::GetMaxPersonalArenaRatingRequirement()
16561 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
16562 // the personal rating of the arena team must match the required limit as well
16563 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
16564 uint32 max_personal_rating
= 0;
16565 for(int i
= 0; i
< MAX_ARENA_SLOT
; ++i
)
16567 if(ArenaTeam
* at
= objmgr
.GetArenaTeamById(GetArenaTeamId(i
)))
16569 uint32 p_rating
= GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ (i
* 6) + 5);
16570 uint32 t_rating
= at
->GetRating();
16571 p_rating
= p_rating
<t_rating
? p_rating
: t_rating
;
16572 if(max_personal_rating
< p_rating
)
16573 max_personal_rating
= p_rating
;
16576 return max_personal_rating
;
16579 void Player::UpdateHomebindTime(uint32 time
)
16581 // GMs never get homebind timer online
16582 if (m_InstanceValid
|| isGameMaster())
16584 if(m_HomebindTimer
) // instance valid, but timer not reset
16587 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
16590 GetSession()->SendPacket(&data
);
16592 // instance is valid, reset homebind timer
16593 m_HomebindTimer
= 0;
16595 else if (m_HomebindTimer
> 0)
16597 if (time
>= m_HomebindTimer
)
16599 // teleport to homebind location
16600 TeleportTo(m_homebindMapId
, m_homebindX
, m_homebindY
, m_homebindZ
, GetOrientation());
16603 m_HomebindTimer
-= time
;
16607 // instance is invalid, start homebind timer
16608 m_HomebindTimer
= 60000;
16609 // send message to player
16610 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
16611 data
<< m_HomebindTimer
;
16613 GetSession()->SendPacket(&data
);
16614 sLog
.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
16618 void Player::UpdatePvP(bool state
, bool ovrride
)
16620 if(!state
|| ovrride
)
16623 if(Pet
* pet
= GetPet())
16624 pet
->SetPvP(state
);
16625 if(Unit
* charmed
= GetCharm())
16626 charmed
->SetPvP(state
);
16628 pvpInfo
.endTimer
= 0;
16632 if(pvpInfo
.endTimer
!= 0)
16633 pvpInfo
.endTimer
= time(NULL
);
16638 if(Pet
* pet
= GetPet())
16639 pet
->SetPvP(state
);
16640 if(Unit
* charmed
= GetCharm())
16641 charmed
->SetPvP(state
);
16646 void Player::AddSpellCooldown(uint32 spellid
, uint32 itemid
, time_t end_time
)
16650 sc
.itemid
= itemid
;
16651 m_spellCooldowns
[spellid
] = sc
;
16654 void Player::SendCooldownEvent(SpellEntry
const *spellInfo
)
16656 if ( !(spellInfo
->Attributes
& SPELL_ATTR_DISABLED_WHILE_ACTIVE
) )
16659 // Get spell cooldwn
16660 int32 cooldown
= GetSpellRecoveryTime(spellInfo
);
16662 ApplySpellMod(spellInfo
->Id
, SPELLMOD_COOLDOWN
, cooldown
);
16666 AddSpellCooldown(spellInfo
->Id
, 0, time(NULL
) + cooldown
/ 1000);
16668 WorldPacket
data(SMSG_COOLDOWN_EVENT
, (4+8));
16669 data
<< spellInfo
->Id
;
16671 SendDirectMessage(&data
);
16673 //slot to be excluded while counting
16674 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition
, int8 slot
)
16676 if(!enchantmentcondition
)
16679 SpellItemEnchantmentConditionEntry
const *Condition
= sSpellItemEnchantmentConditionStore
.LookupEntry(enchantmentcondition
);
16684 uint8 curcount
[4] = {0, 0, 0, 0};
16686 //counting current equipped gem colors
16687 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
16691 Item
*pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
16692 if(pItem2
&& pItem2
->GetProto()->Socket
[0].Color
)
16694 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
16696 uint32 enchant_id
= pItem2
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
16700 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
16704 uint32 gemid
= enchantEntry
->GemID
;
16708 ItemPrototype
const* gemProto
= sItemStorage
.LookupEntry
<ItemPrototype
>(gemid
);
16712 GemPropertiesEntry
const* gemProperty
= sGemPropertiesStore
.LookupEntry(gemProto
->GemProperties
);
16716 uint8 GemColor
= gemProperty
->color
;
16718 for(uint8 b
= 0, tmpcolormask
= 1; b
< 4; b
++, tmpcolormask
<<= 1)
16720 if(tmpcolormask
& GemColor
)
16727 bool activate
= true;
16729 for(int i
= 0; i
< 5; i
++)
16731 if(!Condition
->Color
[i
])
16734 uint32 _cur_gem
= curcount
[Condition
->Color
[i
] - 1];
16736 // if have <CompareColor> use them as count, else use <value> from Condition
16737 uint32 _cmp_gem
= Condition
->CompareColor
[i
] ? curcount
[Condition
->CompareColor
[i
] - 1]: Condition
->Value
[i
];
16739 switch(Condition
->Comparator
[i
])
16741 case 2: // requires less <color> than (<value> || <comparecolor>) gems
16742 activate
&= (_cur_gem
< _cmp_gem
) ? true : false;
16744 case 3: // requires more <color> than (<value> || <comparecolor>) gems
16745 activate
&= (_cur_gem
> _cmp_gem
) ? true : false;
16747 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
16748 activate
&= (_cur_gem
>= _cmp_gem
) ? true : false;
16753 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");
16758 void Player::CorrectMetaGemEnchants(uint8 exceptslot
, bool apply
)
16760 //cycle all equipped items
16761 for(uint32 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
16763 //enchants for the slot being socketed are handled by Player::ApplyItemMods
16764 if(slot
== exceptslot
)
16767 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
16769 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
)
16772 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
16774 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
16778 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
16782 uint32 condition
= enchantEntry
->EnchantmentCondition
;
16785 //was enchant active with/without item?
16786 bool wasactive
= EnchantmentFitsRequirements(condition
, apply
? exceptslot
: -1);
16787 //should it now be?
16788 if(wasactive
^ EnchantmentFitsRequirements(condition
, apply
? -1 : exceptslot
))
16790 // ignore item gem conditions
16791 //if state changed, (dis)apply enchant
16792 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
),!wasactive
,true,true);
16799 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
16800 void Player::ToggleMetaGemsActive(uint8 exceptslot
, bool apply
)
16802 //cycle all equipped items
16803 for(int slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
16805 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
16806 if(slot
== exceptslot
)
16809 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
16811 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
) //if item has no sockets or no item is equipped go to next item
16814 //cycle all (gem)enchants
16815 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
16817 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
16818 if(!enchant_id
) //if no enchant go to next enchant(slot)
16821 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
16825 //only metagems to be (de)activated, so only enchants with condition
16826 uint32 condition
= enchantEntry
->EnchantmentCondition
;
16828 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
), apply
);
16833 void Player::LeaveBattleground(bool teleportToEntryPoint
)
16835 if(BattleGround
*bg
= GetBattleGround())
16837 bool need_debuf
= bg
->isBattleGround() && (bg
->GetStatus() == STATUS_IN_PROGRESS
) && sWorld
.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER
);
16839 bg
->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint
, true);
16841 // call after remove to be sure that player resurrected for correct cast
16843 CastSpell(this, 26013, true); // Deserter
16847 bool Player::CanJoinToBattleground() const
16849 // check Deserter debuff
16850 if(GetDummyAura(26013))
16856 bool Player::CanReportAfkDueToLimit()
16858 // a player can complain about 15 people per 5 minutes
16859 if(m_bgAfkReportedCount
>= 15)
16861 ++m_bgAfkReportedCount
;
16865 ///This player has been blamed to be inactive in a battleground
16866 void Player::ReportedAfkBy(Player
* reporter
)
16868 BattleGround
*bg
= GetBattleGround();
16869 if(!bg
|| bg
!= reporter
->GetBattleGround() || GetTeam() != reporter
->GetTeam())
16872 // check if player has 'Idle' or 'Inactive' debuff
16873 if(m_bgAfkReporter
.find(reporter
->GetGUIDLow())==m_bgAfkReporter
.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter
->CanReportAfkDueToLimit())
16875 m_bgAfkReporter
.insert(reporter
->GetGUIDLow());
16876 // 3 players have to complain to apply debuff
16877 if(m_bgAfkReporter
.size() >= 3)
16879 // cast 'Idle' spell
16880 CastSpell(this, 43680, true);
16881 m_bgAfkReporter
.clear();
16886 bool Player::IsVisibleInGridForPlayer( Player
* pl
) const
16888 // gamemaster in GM mode see all, including ghosts
16889 if(pl
->isGameMaster() && GetSession()->GetSecurity() <= pl
->GetSession()->GetSecurity())
16892 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
16893 if (InBattleGround())
16895 if (!(isAlive() || m_deathTimer
> 0) && !IsFriendlyTo(pl
) )
16900 // Live player see live player or dead player with not realized corpse
16901 if(pl
->isAlive() || pl
->m_deathTimer
> 0)
16903 return isAlive() || m_deathTimer
> 0;
16906 // Ghost see other friendly ghosts, that's for sure
16907 if(!(isAlive() || m_deathTimer
> 0) && IsFriendlyTo(pl
))
16910 // Dead player see live players near own corpse
16913 Corpse
*corpse
= pl
->GetCorpse();
16916 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
16917 if(corpse
->IsWithinDistInMap(this,(20+25)*sWorld
.getRate(RATE_CREATURE_AGGRO
)))
16922 // and not see any other
16926 bool Player::IsVisibleGloballyFor( Player
* u
) const
16931 // Always can see self
16935 // Visible units, always are visible for all players
16936 if (GetVisibility() == VISIBILITY_ON
)
16939 // GMs are visible for higher gms (or players are visible for gms)
16940 if (u
->GetSession()->GetSecurity() > SEC_PLAYER
)
16941 return GetSession()->GetSecurity() <= u
->GetSession()->GetSecurity();
16943 // non faction visibility non-breakable for non-GMs
16944 if (GetVisibility() == VISIBILITY_OFF
)
16947 // non-gm stealth/invisibility not hide from global player lists
16951 void Player::UpdateVisibilityOf(WorldObject
* target
)
16953 if(HaveAtClient(target
))
16955 if(!target
->isVisibleForInState(this,true))
16957 target
->DestroyForPlayer(this);
16958 m_clientGUIDs
.erase(target
->GetGUID());
16960 #ifdef MANGOS_DEBUG
16961 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
16962 sLog
.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
16968 if(target
->isVisibleForInState(this,false))
16970 target
->SendUpdateToPlayer(this);
16971 if(target
->GetTypeId()!=TYPEID_GAMEOBJECT
||!((GameObject
*)target
)->IsTransport())
16972 m_clientGUIDs
.insert(target
->GetGUID());
16974 #ifdef MANGOS_DEBUG
16975 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
16976 sLog
.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
16979 // target aura duration for caster show only if target exist at caster client
16980 // send data at target visibility change (adding to client)
16981 if(target
!=this && target
->isType(TYPEMASK_UNIT
))
16982 SendAuraDurationsForTarget((Unit
*)target
);
16984 if(target
->GetTypeId()==TYPEID_UNIT
&& ((Creature
*)target
)->isAlive())
16985 ((Creature
*)target
)->SendMonsterMoveWithSpeedToCurrentDestination(this);
16991 inline void UpdateVisibilityOf_helper(std::set
<uint64
>& s64
, T
* target
)
16993 s64
.insert(target
->GetGUID());
16997 inline void UpdateVisibilityOf_helper(std::set
<uint64
>& s64
, GameObject
* target
)
16999 if(!target
->IsTransport())
17000 s64
.insert(target
->GetGUID());
17004 void Player::UpdateVisibilityOf(T
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
)
17006 if(HaveAtClient(target
))
17008 if(!target
->isVisibleForInState(this,true))
17010 target
->BuildOutOfRangeUpdateBlock(&data
);
17011 m_clientGUIDs
.erase(target
->GetGUID());
17013 #ifdef MANGOS_DEBUG
17014 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17015 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
));
17021 if(target
->isVisibleForInState(this,false))
17023 visibleNow
.insert(target
);
17024 target
->BuildUpdate(data_updates
);
17025 target
->BuildCreateUpdateBlockForPlayer(&data
, this);
17026 UpdateVisibilityOf_helper(m_clientGUIDs
,target
);
17028 #ifdef MANGOS_DEBUG
17029 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17030 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
));
17036 template void Player::UpdateVisibilityOf(Player
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17037 template void Player::UpdateVisibilityOf(Creature
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17038 template void Player::UpdateVisibilityOf(Corpse
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17039 template void Player::UpdateVisibilityOf(GameObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17040 template void Player::UpdateVisibilityOf(DynamicObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17042 void Player::InitPrimaryProffesions()
17044 SetFreePrimaryProffesions(sWorld
.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL
));
17047 void Player::SendComboPoints()
17049 Unit
*combotarget
= ObjectAccessor::GetUnit(*this, m_comboTarget
);
17052 WorldPacket
data(SMSG_UPDATE_COMBO_POINTS
, combotarget
->GetPackGUID().size()+1);
17053 data
.append(combotarget
->GetPackGUID());
17054 data
<< uint8(m_comboPoints
);
17055 GetSession()->SendPacket(&data
);
17059 void Player::AddComboPoints(Unit
* target
, int8 count
)
17064 // without combo points lost (duration checked in aura)
17065 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
17067 if(target
->GetGUID() == m_comboTarget
)
17069 m_comboPoints
+= count
;
17074 if(Unit
* target
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
17075 target
->RemoveComboPointHolder(GetGUIDLow());
17077 m_comboTarget
= target
->GetGUID();
17078 m_comboPoints
= count
;
17080 target
->AddComboPointHolder(GetGUIDLow());
17083 if (m_comboPoints
> 5) m_comboPoints
= 5;
17084 if (m_comboPoints
< 0) m_comboPoints
= 0;
17089 void Player::ClearComboPoints()
17094 // without combopoints lost (duration checked in aura)
17095 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
17101 if(Unit
* target
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
17102 target
->RemoveComboPointHolder(GetGUIDLow());
17107 void Player::SetGroup(Group
*group
, int8 subgroup
)
17109 if(group
== NULL
) m_group
.unlink();
17112 // never use SetGroup without a subgroup unless you specify NULL for group
17113 assert(subgroup
>= 0);
17114 m_group
.link(group
, this);
17115 m_group
.setSubGroup((uint8
)subgroup
);
17119 void Player::SendInitialPacketsBeforeAddToMap()
17121 WorldPacket
data(SMSG_SET_REST_START
, 4);
17122 data
<< uint32(0); // unknown, may be rest state time or expirience
17123 GetSession()->SendPacket(&data
);
17126 data
.Initialize(SMSG_BINDPOINTUPDATE
, 5*4);
17127 data
<< m_homebindX
<< m_homebindY
<< m_homebindZ
;
17128 data
<< (uint32
) m_homebindMapId
;
17129 data
<< (uint32
) m_homebindZoneId
;
17130 GetSession()->SendPacket(&data
);
17132 // SMSG_SET_PROFICIENCY
17133 // SMSG_UPDATE_AURA_DURATION
17136 data
.Initialize(SMSG_TUTORIAL_FLAGS
, 8*4);
17137 for (int i
= 0; i
< 8; ++i
)
17138 data
<< uint32( GetTutorialInt(i
) );
17139 GetSession()->SendPacket(&data
);
17141 SendInitialSpells();
17143 data
.Initialize(SMSG_SEND_UNLEARN_SPELLS
, 4);
17144 data
<< uint32(0); // count, for(count) uint32;
17145 GetSession()->SendPacket(&data
);
17147 SendInitialActionButtons();
17148 SendInitialReputations();
17149 UpdateZone(GetZoneId());
17150 SendInitWorldStates();
17152 // SMSG_SET_AURA_SINGLE
17154 data
.Initialize(SMSG_LOGIN_SETTIMESPEED
, 8);
17155 data
<< uint32(secsToTimeBitFields(sWorld
.GetGameTime()));
17156 data
<< (float)0.01666667f
; // game speed
17157 GetSession()->SendPacket( &data
);
17159 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17160 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
) || isInFlight())
17161 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2
);
17164 void Player::SendInitialPacketsAfterAddToMap()
17166 CastSpell(this, 836, true); // LOGINEFFECT
17168 // set some aura effects that send packet to player client after add player to map
17169 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17170 // same auras state lost at far teleport, send it one more time in this case also
17171 static const AuraType auratypes
[] =
17173 SPELL_AURA_MOD_FEAR
, SPELL_AURA_TRANSFORM
, SPELL_AURA_WATER_WALK
,
17174 SPELL_AURA_FEATHER_FALL
, SPELL_AURA_HOVER
, SPELL_AURA_SAFE_FALL
,
17175 SPELL_AURA_FLY
, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
, SPELL_AURA_NONE
17177 for(AuraType
const* itr
= &auratypes
[0]; itr
&& itr
[0] != SPELL_AURA_NONE
; ++itr
)
17179 Unit::AuraList
const& auraList
= GetAurasByType(*itr
);
17180 if(!auraList
.empty())
17181 auraList
.front()->ApplyModifier(true,true);
17184 if(HasAuraType(SPELL_AURA_MOD_STUN
))
17185 SetMovement(MOVE_ROOT
);
17187 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17188 if(HasAuraType(SPELL_AURA_MOD_ROOT
))
17190 WorldPacket
data(SMSG_FORCE_MOVE_ROOT
, 10);
17191 data
.append(GetPackGUID());
17193 SendMessageToSet(&data
,true);
17196 SendEnchantmentDurations(); // must be after add to map
17197 SendItemDurations(); // must be after add to map
17200 void Player::SendUpdateToOutOfRangeGroupMembers()
17202 if (m_groupUpdateMask
== GROUP_UPDATE_FLAG_NONE
)
17204 if(Group
* group
= GetGroup())
17205 group
->UpdatePlayerOutOfRange(this);
17207 m_groupUpdateMask
= GROUP_UPDATE_FLAG_NONE
;
17208 m_auraUpdateMask
= 0;
17209 if(Pet
*pet
= GetPet())
17210 pet
->ResetAuraUpdateMask();
17213 void Player::SendTransferAborted(uint32 mapid
, uint16 reason
)
17215 WorldPacket
data(SMSG_TRANSFER_ABORTED
, 4+2);
17216 data
<< uint32(mapid
);
17217 data
<< uint16(reason
); // transfer abort reason
17218 GetSession()->SendPacket(&data
);
17221 void Player::SendInstanceResetWarning(uint32 mapid
, uint32 time
)
17223 // type of warning, based on the time remaining until reset
17226 type
= RAID_INSTANCE_WELCOME
;
17227 else if(time
> 900 && time
<= 3600)
17228 type
= RAID_INSTANCE_WARNING_HOURS
;
17229 else if(time
> 300 && time
<= 900)
17230 type
= RAID_INSTANCE_WARNING_MIN
;
17232 type
= RAID_INSTANCE_WARNING_MIN_SOON
;
17233 WorldPacket
data(SMSG_RAID_INSTANCE_MESSAGE
, 4+4+4);
17234 data
<< uint32(type
);
17235 data
<< uint32(mapid
);
17236 data
<< uint32(time
);
17237 GetSession()->SendPacket(&data
);
17240 void Player::ApplyEquipCooldown( Item
* pItem
)
17242 for(int i
= 0; i
<5; ++i
)
17244 _Spell
const& spellData
= pItem
->GetProto()->Spells
[i
];
17247 if( !spellData
.SpellId
)
17250 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
17251 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
)
17254 AddSpellCooldown(spellData
.SpellId
, pItem
->GetEntry(), time(NULL
) + 30);
17256 WorldPacket
data(SMSG_ITEM_COOLDOWN
, 12);
17257 data
<< pItem
->GetGUID();
17258 data
<< uint32(spellData
.SpellId
);
17259 GetSession()->SendPacket(&data
);
17263 void Player::resetSpells()
17265 // not need after this call
17266 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS
))
17268 m_atLoginFlags
= m_atLoginFlags
& ~AT_LOGIN_RESET_SPELLS
;
17269 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS
), GetGUIDLow());
17272 // make full copy of map (spells removed and marked as deleted at another spell remove
17273 // and we can't use original map for safe iterative with visit each spell at loop end
17274 PlayerSpellMap smap
= GetSpellMap();
17276 for(PlayerSpellMap::const_iterator iter
= smap
.begin();iter
!= smap
.end(); ++iter
)
17277 removeSpell(iter
->first
); // only iter->first can be accessed, object by iter->second can be deleted already
17279 learnDefaultSpells();
17280 learnQuestRewardedSpells();
17283 void Player::learnDefaultSpells(bool loading
)
17285 // learn default race/class spells
17286 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(),getClass());
17287 std::list
<CreateSpellPair
>::const_iterator spell_itr
;
17288 for (spell_itr
= info
->spell
.begin(); spell_itr
!=info
->spell
.end(); ++spell_itr
)
17290 uint16 tspell
= spell_itr
->first
;
17293 sLog
.outDebug("PLAYER: Adding initial spell, id = %u",tspell
);
17294 if(loading
|| !spell_itr
->second
) // not care about passive spells or loading case
17295 addSpell(tspell
,spell_itr
->second
);
17296 else // but send in normal spell in game learn case
17297 learnSpell(tspell
);
17302 void Player::learnQuestRewardedSpells(Quest
const* quest
)
17304 uint32 spell_id
= quest
->GetRewSpellCast();
17306 // skip quests without rewarded spell
17310 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
17314 // check learned spells state
17315 bool found
= false;
17316 for(int i
=0; i
< 3; ++i
)
17318 if(spellInfo
->Effect
[i
] == SPELL_EFFECT_LEARN_SPELL
&& !HasSpell(spellInfo
->EffectTriggerSpell
[i
]))
17325 // skip quests with not teaching spell or already known spell
17329 // prevent learn non first rank unknown profession and second specialization for same profession)
17330 uint32 learned_0
= spellInfo
->EffectTriggerSpell
[0];
17331 if( spellmgr
.GetSpellRank(learned_0
) > 1 && !HasSpell(learned_0
) )
17333 // not have first rank learned (unlearned prof?)
17334 uint32 first_spell
= spellmgr
.GetFirstSpellInChain(learned_0
);
17335 if( !HasSpell(first_spell
) )
17338 SpellEntry
const *learnedInfo
= sSpellStore
.LookupEntry(learned_0
);
17343 if(learnedInfo
->Effect
[0]==SPELL_EFFECT_TRADE_SKILL
&& learnedInfo
->Effect
[1]==0)
17345 // search other specialization for same prof
17346 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
17348 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->first
==learned_0
)
17351 SpellEntry
const *itrInfo
= sSpellStore
.LookupEntry(itr
->first
);
17355 // compare only specializations
17356 if(itrInfo
->Effect
[0]!=SPELL_EFFECT_TRADE_SKILL
|| itrInfo
->Effect
[1]!=0)
17359 // compare same chain spells
17360 if(spellmgr
.GetFirstSpellInChain(itr
->first
) != first_spell
)
17363 // now we have 2 specialization, learn possible only if found is lesser specialization rank
17364 if(!spellmgr
.IsHighRankOfSpell(learned_0
,itr
->first
))
17370 CastSpell( this, spell_id
, true);
17373 void Player::learnQuestRewardedSpells()
17375 // learn spells received from quest completing
17376 for(QuestStatusMap::const_iterator itr
= mQuestStatus
.begin(); itr
!= mQuestStatus
.end(); ++itr
)
17378 // skip no rewarded quests
17379 if(!itr
->second
.m_rewarded
)
17382 Quest
const* quest
= objmgr
.GetQuestTemplate(itr
->first
);
17386 learnQuestRewardedSpells(quest
);
17390 void Player::learnSkillRewardedSpells(uint32 skill_id
)
17392 uint32 raceMask
= getRaceMask();
17393 uint32 classMask
= getClassMask();
17394 for (uint32 j
=0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
17396 SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
);
17397 if (!pAbility
|| pAbility
->skillId
!=skill_id
|| pAbility
->learnOnGetSkill
!= ABILITY_LEARNED_ON_GET_PROFESSION_SKILL
)
17399 // Check race if set
17400 if (pAbility
->racemask
&& !(pAbility
->racemask
& raceMask
))
17402 // Check class if set
17403 if (pAbility
->classmask
&& !(pAbility
->classmask
& classMask
))
17406 if (SpellEntry
const* spellentry
= sSpellStore
.LookupEntry(pAbility
->spellId
))
17408 // Ok need learn spell
17409 learnSpell(pAbility
->spellId
);
17414 void Player::learnSkillRewardedSpells()
17416 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
17418 if(!GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
17421 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
17423 learnSkillRewardedSpells(pskill
);
17427 void Player::SendAuraDurationsForTarget(Unit
* target
)
17429 for(Unit::AuraMap::const_iterator itr
= target
->GetAuras().begin(); itr
!= target
->GetAuras().end(); ++itr
)
17431 Aura
* aura
= itr
->second
;
17432 if(aura
->GetAuraSlot() >= MAX_AURAS
|| aura
->IsPassive() || aura
->GetCasterGUID()!=GetGUID())
17435 aura
->SendAuraDurationForCaster(this);
17439 void Player::SetDailyQuestStatus( uint32 quest_id
)
17441 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
17443 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
17445 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
17446 m_lastDailyQuestTime
= time(NULL
); // last daily quest time
17447 m_DailyQuestChanged
= true;
17453 void Player::ResetDailyQuestStatus()
17455 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
17456 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
17458 // DB data deleted in caller
17459 m_DailyQuestChanged
= false;
17460 m_lastDailyQuestTime
= 0;
17463 BattleGround
* Player::GetBattleGround() const
17465 if(GetBattleGroundId()==0)
17468 return sBattleGroundMgr
.GetBattleGround(GetBattleGroundId());
17471 bool Player::InArena() const
17473 BattleGround
*bg
= GetBattleGround();
17474 if(!bg
|| !bg
->isArena())
17480 bool Player::GetBGAccessByLevel(uint32 bgTypeId
) const
17482 BattleGround
*bg
= sBattleGroundMgr
.GetBattleGround(bgTypeId
);
17486 if(getLevel() < bg
->GetMinLevel() || getLevel() > bg
->GetMaxLevel())
17492 uint32
Player::GetMinLevelForBattleGroundQueueId(uint32 queue_id
)
17500 return 10*(queue_id
+1);
17503 uint32
Player::GetMaxLevelForBattleGroundQueueId(uint32 queue_id
)
17506 return 255; // hardcoded max level
17508 return 10*(queue_id
+2)-1;
17511 uint32
Player::GetBattleGroundQueueIdFromLevel() const
17513 uint32 level
= getLevel();
17516 else if (level
> 69)
17519 return level
/10 - 1; // 20..29 -> 1, 30-39 -> 2, ...
17522 float Player::GetReputationPriceDiscount( Creature
const* pCreature
) const
17524 FactionTemplateEntry
const* vendor_faction
= pCreature
->getFactionTemplateEntry();
17525 if(!vendor_faction
)
17528 ReputationRank rank
= GetReputationRank(vendor_faction
->faction
);
17529 if(rank
<= REP_NEUTRAL
)
17532 return 1.0f
- 0.05f
* (rank
- REP_NEUTRAL
);
17535 bool Player::IsSpellFitByClassAndRace( uint32 spell_id
) const
17537 uint32 racemask
= getRaceMask();
17538 uint32 classmask
= getClassMask();
17540 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
17541 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
17543 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
17545 // skip wrong race skills
17546 if( _spell_idx
->second
->racemask
&& (_spell_idx
->second
->racemask
& racemask
) == 0)
17549 // skip wrong class skills
17550 if( _spell_idx
->second
->classmask
&& (_spell_idx
->second
->classmask
& classmask
) == 0)
17556 bool Player::HasQuestForGO(int32 GOId
)
17558 for( QuestStatusMap::iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
17560 QuestStatusData qs
=i
->second
;
17561 if (qs
.m_status
== QUEST_STATUS_INCOMPLETE
)
17563 Quest
const* qinfo
= objmgr
.GetQuestTemplate(i
->first
);
17567 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
17570 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
17572 if (qinfo
->ReqCreatureOrGOId
[j
]>=0) //skip non GO case
17575 if((-1)*GOId
== qinfo
->ReqCreatureOrGOId
[j
] && qs
.m_creatureOrGOcount
[j
] < qinfo
->ReqCreatureOrGOCount
[j
])
17583 void Player::UpdateForQuestsGO()
17585 if(m_clientGUIDs
.empty())
17589 WorldPacket packet
;
17590 for(ClientGUIDs::iterator itr
=m_clientGUIDs
.begin(); itr
!=m_clientGUIDs
.end(); ++itr
)
17592 if(IS_GAMEOBJECT_GUID(*itr
))
17594 GameObject
*obj
= HashMapHolder
<GameObject
>::Find(*itr
);
17596 obj
->BuildValuesUpdateBlockForPlayer(&udata
,this);
17599 udata
.BuildPacket(&packet
);
17600 GetSession()->SendPacket(&packet
);
17603 void Player::SummonIfPossible(bool agree
)
17607 m_summon_expire
= 0;
17611 // expire and auto declined
17612 if(m_summon_expire
< time(NULL
))
17615 // stop taxi flight at summon
17618 GetMotionMaster()->MovementExpired();
17619 m_taxi
.ClearTaxiDestinations();
17622 // drop flag at summon
17623 if(BattleGround
*bg
= GetBattleGround())
17624 bg
->EventPlayerDroppedFlag(this);
17626 m_summon_expire
= 0;
17628 TeleportTo(m_summon_mapid
, m_summon_x
, m_summon_y
, m_summon_z
,GetOrientation());
17631 void Player::RemoveItemDurations( Item
*item
)
17633 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); ++itr
)
17637 m_itemDuration
.erase(itr
);
17643 void Player::AddItemDurations( Item
*item
)
17645 if(item
->GetUInt32Value(ITEM_FIELD_DURATION
))
17647 m_itemDuration
.push_back(item
);
17648 item
->SendTimeUpdate(this);
17652 void Player::AutoUnequipOffhandIfNeed()
17654 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
17658 Item
*mainItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_MAINHAND
);
17660 if(!mainItem
|| mainItem
->GetProto()->InventoryType
!= INVTYPE_2HWEAPON
)
17663 ItemPosCountVec off_dest
;
17664 uint8 off_msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false );
17665 if( off_msg
== EQUIP_ERR_OK
)
17667 RemoveItem(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
, true);
17668 StoreItem( off_dest
, offItem
, true );
17672 sLog
.outError("Player::EquipItem: Can's store offhand item at 2hand item equip for player (GUID: %u).",GetGUIDLow());
17676 bool Player::HasItemFitToSpellReqirements(SpellEntry
const* spellInfo
, Item
const* ignoreItem
)
17678 if(spellInfo
->EquippedItemClass
< 0)
17681 // scan other equipped items for same requirements (mostly 2 daggers/etc)
17682 // for optimize check 2 used cases only
17683 switch(spellInfo
->EquippedItemClass
)
17685 case ITEM_CLASS_WEAPON
:
17687 for(int i
= EQUIPMENT_SLOT_MAINHAND
; i
< EQUIPMENT_SLOT_TABARD
; ++i
)
17688 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
17689 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
17693 case ITEM_CLASS_ARMOR
:
17695 // tabard not have dependent spells
17696 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_MAINHAND
; ++i
)
17697 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
17698 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
17701 // shields can be equipped to offhand slot
17702 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
))
17703 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
17706 // ranged slot can have some armor subclasses
17707 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_RANGED
))
17708 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
17714 sLog
.outError("HasItemFitToSpellReqirements: Not handeled spell reqirement for item class %u",spellInfo
->EquippedItemClass
);
17721 void Player::RemoveItemDependentAurasAndCasts( Item
* pItem
)
17723 AuraMap
& auras
= GetAuras();
17724 for(AuraMap::iterator itr
= auras
.begin(); itr
!= auras
.end(); )
17726 Aura
* aura
= itr
->second
;
17728 // skip passive (passive item dependent spells work in another way) and not self applied auras
17729 SpellEntry
const* spellInfo
= aura
->GetSpellProto();
17730 if(aura
->IsPassive() || aura
->GetCasterGUID()!=GetGUID())
17736 // skip if not item dependent or have alternative item
17737 if(HasItemFitToSpellReqirements(spellInfo
,pItem
))
17743 // no alt item, remove aura, restart check
17744 RemoveAurasDueToSpell(aura
->GetId());
17745 itr
= auras
.begin();
17748 // currently casted spells can be dependent from item
17749 for (uint32 i
= 0; i
< CURRENT_MAX_SPELL
; i
++)
17751 if( m_currentSpells
[i
] && m_currentSpells
[i
]->getState()!=SPELL_STATE_DELAYED
&&
17752 !HasItemFitToSpellReqirements(m_currentSpells
[i
]->m_spellInfo
,pItem
) )
17757 uint32
Player::GetResurrectionSpellId()
17759 // search priceless resurrection possabilities
17761 uint32 spell_id
= 0;
17762 AuraList
const& dummyAuras
= GetAurasByType(SPELL_AURA_DUMMY
);
17763 for(AuraList::const_iterator itr
= dummyAuras
.begin(); itr
!= dummyAuras
.end(); ++itr
)
17765 // Soulstone Resurrection // prio: 3 (max, non death persistent)
17766 if( prio
< 2 && (*itr
)->GetSpellProto()->SpellVisual
== 99 && (*itr
)->GetSpellProto()->SpellIconID
== 92 )
17768 switch((*itr
)->GetId())
17770 case 20707: spell_id
= 3026; break; // rank 1
17771 case 20762: spell_id
= 20758; break; // rank 2
17772 case 20763: spell_id
= 20759; break; // rank 3
17773 case 20764: spell_id
= 20760; break; // rank 4
17774 case 20765: spell_id
= 20761; break; // rank 5
17775 case 27239: spell_id
= 27240; break; // rank 6
17777 sLog
.outError("Unhandled spell %%u: S.Resurrection",(*itr
)->GetId());
17783 // Twisting Nether // prio: 2 (max)
17784 else if((*itr
)->GetId()==23701 && roll_chance_i(10))
17791 // Reincarnation (passive spell) // prio: 1
17792 if(prio
< 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
17798 bool Player::RewardPlayerAndGroupAtKill(Unit
* pVictim
)
17800 bool PvP
= pVictim
->isCharmedOwnedByPlayerOrPlayer();
17802 // prepare data for near group iteration (PvP and !PvP cases)
17804 bool honored_kill
= false;
17806 if(Group
*pGroup
= GetGroup())
17809 uint32 sum_level
= 0;
17810 Player
* member_with_max_level
= NULL
;
17811 Player
* not_gray_member_with_max_level
= NULL
;
17813 pGroup
->GetDataForXPAtKill(pVictim
,count
,sum_level
,member_with_max_level
,not_gray_member_with_max_level
);
17815 if(member_with_max_level
)
17817 /// not get Xp in PvP or no not gray players in group
17818 xp
= (PvP
|| !not_gray_member_with_max_level
) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level
, pVictim
);
17820 /// skip in check PvP case (for speed, not used)
17821 bool is_raid
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsRaid() && pGroup
->isRaidGroup();
17822 bool is_dungeon
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsDungeon();
17823 float group_rate
= MaNGOS::XP::xp_in_group_rate(count
,is_raid
);
17825 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
17827 Player
* pGroupGuy
= itr
->getSource();
17831 if(!pGroupGuy
->IsAtGroupRewardDistance(pVictim
))
17832 continue; // member (alive or dead) or his corpse at req. distance
17834 // honor can be in PvP and !PvP (racial leader) cases (for alive)
17835 if(pGroupGuy
->isAlive() && pGroupGuy
->RewardHonor(pVictim
,count
) && pGroupGuy
==this)
17836 honored_kill
= true;
17838 // xp and reputation only in !PvP case
17841 float rate
= group_rate
* float(pGroupGuy
->getLevel()) / sum_level
;
17843 // if is in dungeon then all receive full reputation at kill
17844 // rewarded any alive/dead/near_corpse group member
17845 pGroupGuy
->RewardReputation(pVictim
,is_dungeon
? 1.0f
: rate
);
17847 // XP updated only for alive group member
17848 if(pGroupGuy
->isAlive() && not_gray_member_with_max_level
&&
17849 pGroupGuy
->getLevel() <= not_gray_member_with_max_level
->getLevel())
17851 uint32 itr_xp
= (member_with_max_level
== not_gray_member_with_max_level
) ? uint32(xp
*rate
) : uint32((xp
*rate
/2)+1);
17853 pGroupGuy
->GiveXP(itr_xp
, pVictim
);
17854 if(Pet
* pet
= pGroupGuy
->GetPet())
17855 pet
->GivePetXP(itr_xp
/2);
17858 // quest objectives updated only for alive group member or dead but with not released body
17859 if(pGroupGuy
->isAlive()|| !pGroupGuy
->GetCorpse())
17861 // normal creature (not pet/etc) can be only in !PvP case
17862 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
17863 pGroupGuy
->KilledMonster(pVictim
->GetEntry(), pVictim
->GetGUID());
17869 else // if (!pGroup)
17871 xp
= PvP
? 0 : MaNGOS::XP::Gain(this, pVictim
);
17873 // honor can be in PvP and !PvP (racial leader) cases
17874 if(RewardHonor(pVictim
,1))
17875 honored_kill
= true;
17877 // xp and reputation only in !PvP case
17880 RewardReputation(pVictim
,1);
17881 GiveXP(xp
, pVictim
);
17883 if(Pet
* pet
= GetPet())
17884 pet
->GivePetXP(xp
);
17886 // normal creature (not pet/etc) can be only in !PvP case
17887 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
17888 KilledMonster(pVictim
->GetEntry(),pVictim
->GetGUID());
17891 return xp
|| honored_kill
;
17894 bool Player::IsAtGroupRewardDistance(WorldObject
const* pRewardSource
) const
17896 if(pRewardSource
->GetDistance(this) <= sWorld
.getConfig(CONFIG_GROUP_XP_DISTANCE
))
17902 Corpse
* corpse
= GetCorpse();
17906 return pRewardSource
->GetDistance(corpse
) <= sWorld
.getConfig(CONFIG_GROUP_XP_DISTANCE
);
17909 uint32
Player::GetBaseWeaponSkillValue (WeaponAttackType attType
) const
17911 Item
* item
= GetWeaponForAttack(attType
,true);
17913 // unarmmed only with base attack
17914 if(attType
!= BASE_ATTACK
&& !item
)
17917 // weapon skill or (unarmed for base attack)
17918 uint32 skill
= item
? item
->GetSkill() : SKILL_UNARMED
;
17919 return GetBaseSkillValue(skill
);
17922 void Player::ResurectUsingRequestData()
17924 ResurrectPlayer(0.0f
,false);
17926 if(GetMaxHealth() > m_resurrectHealth
)
17927 SetHealth( m_resurrectHealth
);
17929 SetHealth( GetMaxHealth() );
17931 if(GetMaxPower(POWER_MANA
) > m_resurrectMana
)
17932 SetPower(POWER_MANA
, m_resurrectMana
);
17934 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
) );
17936 SetPower(POWER_RAGE
, 0 );
17938 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
) );
17940 SpawnCorpseBones();
17942 TeleportTo(m_resurrectMap
, m_resurrectX
, m_resurrectY
, m_resurrectZ
, GetOrientation());
17945 void Player::SetClientControl(Unit
* target
, uint8 allowMove
)
17947 WorldPacket
data(SMSG_CLIENT_CONTROL_UPDATE
, target
->GetPackGUID().size()+1);
17948 data
.append(target
->GetPackGUID());
17949 data
<< uint8(allowMove
);
17950 GetSession()->SendPacket(&data
);
17953 void Player::UpdateZoneDependentAuras( uint32 newZone
)
17955 // remove new continent flight forms
17956 if( !isGameMaster() &&
17957 GetVirtualMapForMapAndZone(GetMapId(),newZone
) != 530)
17959 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
);
17960 RemoveSpellsCausingAura(SPELL_AURA_FLY
);
17963 // Some spells applied at enter into zone (with subzones)
17965 // NOTE: these are removed by RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
17966 if ( newZone
== 2367 ) // Old Hillsbrad Foothills
17968 uint32 spellid
= 0;
17970 if( GetTeam() == HORDE
)
17971 spellid
= getGender() == GENDER_FEMALE
? 35481 : 35480;
17972 // and some alliance races
17973 else if( getRace() == RACE_NIGHTELF
|| getRace() == RACE_DRAENEI
)
17974 spellid
= getGender() == GENDER_FEMALE
? 35483 : 35482;
17976 if(spellid
&& !HasAura(spellid
,0) )
17977 CastSpell(this,spellid
,true);
17981 void Player::UpdateAreaDependentAuras( uint32 newArea
)
17983 // remove auras from spells with area limitations
17984 for(AuraMap::iterator iter
= m_Auras
.begin(); iter
!= m_Auras
.end();)
17986 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
17987 if(!IsSpellAllowedInLocation(iter
->second
->GetSpellProto(),GetMapId(),m_zoneUpdateId
,newArea
))
17993 // unmount if enter in this subzone
17995 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED
);
17996 // Dragonmaw Illusion
17997 else if( newArea
== 3759 || newArea
== 3966 || newArea
== 3939 )
17999 if( GetDummyAura(40214) )
18001 if( !HasAura(40216,0) )
18002 CastSpell(this,40216,true);
18003 if( !HasAura(42016,0) )
18004 CastSpell(this,42016,true);
18009 uint32
Player::GetCorpseReclaimDelay(bool pvp
) const
18011 if( pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18012 !pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18014 return copseReclaimDelay
[0];
18017 time_t now
= time(NULL
);
18018 // 0..2 full period
18019 uint32 count
= (now
< m_deathExpireTime
) ? (m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
: 0;
18020 return copseReclaimDelay
[count
];
18023 void Player::UpdateCorpseReclaimDelay()
18025 bool pvp
= m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
;
18027 if( pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18028 !pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18031 time_t now
= time(NULL
);
18032 if(now
< m_deathExpireTime
)
18034 // full and partly periods 1..3
18035 uint32 count
= (m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
+1;
18036 if(count
< MAX_DEATH_COUNT
)
18037 m_deathExpireTime
= now
+(count
+1)*DEATH_EXPIRE_STEP
;
18039 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
;
18042 m_deathExpireTime
= now
+DEATH_EXPIRE_STEP
;
18045 void Player::SendCorpseReclaimDelay(bool load
)
18047 Corpse
* corpse
= GetCorpse();
18054 if(corpse
->GetGhostTime() > m_deathExpireTime
)
18057 bool pvp
= corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
;
18060 if( pvp
&& sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18061 !pvp
&& sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18063 count
= (m_deathExpireTime
-corpse
->GetGhostTime())/DEATH_EXPIRE_STEP
;
18064 if(count
>=MAX_DEATH_COUNT
)
18065 count
= MAX_DEATH_COUNT
-1;
18070 time_t expected_time
= corpse
->GetGhostTime()+copseReclaimDelay
[count
];
18072 time_t now
= time(NULL
);
18073 if(now
>= expected_time
)
18076 delay
= expected_time
-now
;
18079 delay
= GetCorpseReclaimDelay(corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
);
18081 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
18082 WorldPacket
data(SMSG_CORPSE_RECLAIM_DELAY
, 4);
18083 data
<< uint32(delay
*1000);
18084 GetSession()->SendPacket( &data
);
18087 Player
* Player::GetNextRandomRaidMember(float radius
)
18089 Group
*pGroup
= GetGroup();
18093 std::vector
<Player
*> nearMembers
;
18094 nearMembers
.reserve(pGroup
->GetMembersCount());
18096 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
18098 Player
* Target
= itr
->getSource();
18100 // IsHostileTo check duel and controlled by enemy
18101 if( Target
&& Target
!= this && IsWithinDistInMap(Target
, radius
) &&
18102 !Target
->HasInvisibilityAura() && !IsHostileTo(Target
) )
18103 nearMembers
.push_back(Target
);
18106 if (nearMembers
.empty())
18109 uint32 randTarget
= urand(0,nearMembers
.size()-1);
18110 return nearMembers
[randTarget
];
18113 void Player::UpdateUnderwaterState( Map
* m
, float x
, float y
, float z
)
18115 float water_z
= m
->GetWaterLevel(x
,y
);
18116 float height_z
= m
->GetHeight(x
,y
,z
, false); // use .map base surface height
18117 uint8 flag1
= m
->GetTerrainType(x
,y
);
18119 //!Underwater check, not in water if underground or above water level
18120 if (height_z
<= INVALID_HEIGHT
|| z
< (height_z
-2) || z
> (water_z
- 2) )
18121 m_isunderwater
&= 0x7A;
18122 else if ((z
< (water_z
- 2)) && (flag1
& 0x01))
18123 m_isunderwater
|= 0x01;
18125 //!in lava check, anywhere under lava level
18126 if ((height_z
<= INVALID_HEIGHT
|| z
< (height_z
- 0)) && (flag1
== 0x00) && IsInWater())
18127 m_isunderwater
|= 0x80;
18130 void Player::SetCanParry( bool value
)
18132 if(m_canParry
==value
)
18135 m_canParry
= value
;
18136 UpdateParryPercentage();
18139 void Player::SetCanBlock( bool value
)
18141 if(m_canBlock
==value
)
18144 m_canBlock
= value
;
18145 UpdateBlockPercentage();
18148 bool ItemPosCount::isContainedIn(ItemPosCountVec
const& vec
) const
18150 for(ItemPosCountVec::const_iterator itr
= vec
.begin(); itr
!= vec
.end();++itr
)
18151 if(itr
->pos
== this->pos
)
18157 bool Player::isAllowUseBattleGroundObject()
18159 return ( //InBattleGround() && // in battleground - not need, check in other cases
18160 !IsMounted() && // not mounted
18161 !HasStealthAura() && // not stealthed
18162 !HasInvisibilityAura() && // not invisible
18163 !HasAura(SPELL_RECENTLY_DROPPED_FLAG
, 0) && // can't pickup
18164 isAlive() // live player