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
<< uint32(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( const 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 reagents 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
, const std::string
& name
, uint8 race
, uint8 class_
, uint8 gender
, uint8 skin
, uint8 face
, uint8 hairStyle
, uint8 hairColor
, uint8 facialHair
, uint8 outfitId
)
481 //FIXME: outfitId not used in player creating
483 Object::_Create(guidlow
, 0, HIGHGUID_PLAYER
);
487 PlayerInfo
const* info
= objmgr
.GetPlayerInfo(race
, class_
);
490 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
494 for (int i
= 0; i
< PLAYER_SLOTS_COUNT
; i
++)
500 SetMapId(info
->mapId
);
501 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
);
503 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(class_
);
506 sLog
.outError("Class %u not found in DBC (Wrong DBC files?)",class_
);
510 uint8 powertype
= cEntry
->powerType
;
518 unitfield
= 0x00000000;
521 unitfield
= 0x00110000;
524 sLog
.outError("Invalid default powertype %u for player (class %u)",powertype
,class_
);
528 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, DEFAULT_WORLD_OBJECT_SIZE
);
529 SetFloatValue(UNIT_FIELD_COMBATREACH
, 1.5f
);
534 SetDisplayId(info
->displayId_f
);
535 SetNativeDisplayId(info
->displayId_f
);
538 SetDisplayId(info
->displayId_m
);
539 SetNativeDisplayId(info
->displayId_m
);
542 sLog
.outError("Invalid gender %u for player",gender
);
547 setFactionForRace(m_race
);
549 uint32 RaceClassGender
= ( race
) | ( class_
<< 8 ) | ( gender
<< 16 );
551 SetUInt32Value(UNIT_FIELD_BYTES_0
, ( RaceClassGender
| ( powertype
<< 24 ) ) );
552 SetUInt32Value(UNIT_FIELD_BYTES_1
, unitfield
);
553 SetByteValue(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_UNK3
| UNIT_BYTE2_FLAG_UNK5
);
554 SetUInt32Value(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
);
555 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
); // fix cast time showed in spell tooltip on client
557 //-1 is default value
558 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX
, uint32(-1));
560 SetUInt32Value(PLAYER_BYTES
, (skin
| (face
<< 8) | (hairStyle
<< 16) | (hairColor
<< 24)));
561 SetUInt32Value(PLAYER_BYTES_2
, (facialHair
| (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
562 SetByteValue(PLAYER_BYTES_3
, 0, gender
);
564 SetUInt32Value( PLAYER_GUILDID
, 0 );
565 SetUInt32Value( PLAYER_GUILDRANK
, 0 );
566 SetUInt32Value( PLAYER_GUILD_TIMESTAMP
, 0 );
568 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES
, 0 ); // 0=disabled
569 SetUInt32Value( PLAYER_CHOSEN_TITLE
, 0 );
570 SetUInt32Value( PLAYER_FIELD_KILLS
, 0 );
571 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 0 );
572 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION
, 0 );
573 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0 );
575 // set starting level
576 if (GetSession()->GetSecurity() >= SEC_MODERATOR
)
577 SetUInt32Value (UNIT_FIELD_LEVEL
, sWorld
.getConfig(CONFIG_START_GM_LEVEL
));
579 SetUInt32Value (UNIT_FIELD_LEVEL
, sWorld
.getConfig(CONFIG_START_PLAYER_LEVEL
));
581 SetUInt32Value (PLAYER_FIELD_COINAGE
, sWorld
.getConfig(CONFIG_START_PLAYER_MONEY
));
582 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_START_HONOR_POINTS
));
583 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_START_ARENA_POINTS
));
586 m_Last_tick
= time(NULL
);
587 m_Played_time
[0] = 0;
588 m_Played_time
[1] = 0;
590 // base stats and related field values
592 InitTaxiNodesForLevel();
593 InitTalentForLevel();
594 InitPrimaryProffesions(); // to max set before any spell added
596 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
597 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
598 SetHealth(GetMaxHealth());
599 if (getPowerType()==POWER_MANA
)
601 UpdateMaxPower(POWER_MANA
); // Update max Mana (for add bonus from intellect)
602 SetPower(POWER_MANA
,GetMaxPower(POWER_MANA
));
606 learnDefaultSpells(true);
608 // original action bar
609 std::list
<uint16
>::const_iterator action_itr
[4];
610 for(int i
=0; i
<4; i
++)
611 action_itr
[i
] = info
->action
[i
].begin();
613 for (; action_itr
[0]!=info
->action
[0].end() && action_itr
[1]!=info
->action
[1].end();)
616 for(int i
=0; i
<4 ;i
++)
617 taction
[i
] = (*action_itr
[i
]);
619 addActionButton((uint8
)taction
[0], taction
[1], (uint8
)taction
[2], (uint8
)taction
[3]);
621 for(int i
=0; i
<4 ;i
++)
626 CharStartOutfitEntry
const* oEntry
= NULL
;
627 for (uint32 i
= 1; i
< sCharStartOutfitStore
.GetNumRows(); ++i
)
629 if(CharStartOutfitEntry
const* entry
= sCharStartOutfitStore
.LookupEntry(i
))
631 if(entry
->RaceClassGender
== RaceClassGender
)
641 for(int j
= 0; j
< MAX_OUTFIT_ITEMS
; ++j
)
643 if(oEntry
->ItemId
[j
] <= 0)
646 uint32 item_id
= oEntry
->ItemId
[j
];
648 ItemPrototype
const* iProto
= objmgr
.GetItemPrototype(item_id
);
651 sLog
.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id
,getRace(),getClass());
655 uint32 count
= iProto
->Stackable
; // max stack by default (mostly 1)
656 if(iProto
->Class
==ITEM_CLASS_CONSUMABLE
&& iProto
->SubClass
==ITEM_SUBCLASS_FOOD
)
658 switch(iProto
->Spells
[0].SpellCategory
)
661 if(iProto
->Stackable
> 4)
665 if(iProto
->Stackable
> 2)
671 StoreNewItemInBestSlots(item_id
, count
);
675 for (PlayerCreateInfoItems::const_iterator item_id_itr
= info
->item
.begin(); item_id_itr
!=info
->item
.end(); ++item_id_itr
++)
676 StoreNewItemInBestSlots(item_id_itr
->item_id
, item_id_itr
->item_amount
);
678 // bags and main-hand weapon must equipped at this moment
679 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
680 // or ammo not equipped in special bag
681 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
683 if(Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
686 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
687 uint8 msg
= CanEquipItem( NULL_SLOT
, eDest
, pItem
, false );
688 if( msg
== EQUIP_ERR_OK
)
690 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
691 EquipItem( eDest
, pItem
, true);
693 // move other items to more appropriate slots (ammo not equipped in special bag)
696 ItemPosCountVec sDest
;
697 msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, sDest
, pItem
, false );
698 if( msg
== EQUIP_ERR_OK
)
700 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
701 pItem
= StoreItem( sDest
, pItem
, true);
704 // if this is ammo then use it
705 uint8 msg
= CanUseAmmo( pItem
->GetProto()->ItemId
);
706 if( msg
== EQUIP_ERR_OK
)
707 SetAmmo( pItem
->GetProto()->ItemId
);
711 // all item positions resolved
716 bool Player::StoreNewItemInBestSlots(uint32 titem_id
, uint32 titem_amount
)
718 sLog
.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id
, titem_amount
);
720 // attempt equip by one
721 while(titem_amount
> 0)
724 uint8 msg
= CanEquipNewItem( NULL_SLOT
, eDest
, titem_id
, false );
725 if( msg
!= EQUIP_ERR_OK
)
728 EquipNewItem( eDest
, titem_id
, true);
729 AutoUnequipOffhandIfNeed();
733 if(titem_amount
== 0)
734 return true; // equipped
737 ItemPosCountVec sDest
;
738 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
739 uint8 msg
= CanStoreNewItem( INVENTORY_SLOT_BAG_0
, NULL_SLOT
, sDest
, titem_id
, titem_amount
);
740 if( msg
== EQUIP_ERR_OK
)
742 StoreNewItem( sDest
, titem_id
, true, Item::GenerateItemRandomPropertyId(titem_id
) );
743 return true; // stored
746 // item can't be added
747 sLog
.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id
,getRace(),getClass(),msg
);
751 void Player::StartMirrorTimer(MirrorTimerType Type
, uint32 MaxValue
)
753 uint32 BreathRegen
= (uint32
)-1;
755 WorldPacket
data(SMSG_START_MIRROR_TIMER
, (21));
756 data
<< (uint32
)Type
;
761 data
<< (uint32
)0; // spell id
762 GetSession()->SendPacket(&data
);
765 void Player::ModifyMirrorTimer(MirrorTimerType Type
, uint32 MaxValue
, uint32 CurrentValue
, uint32 Regen
)
767 if(Type
==BREATH_TIMER
)
768 m_breathTimer
= ((MaxValue
+ 1000) - CurrentValue
) / Regen
;
770 WorldPacket
data(SMSG_START_MIRROR_TIMER
, (21));
771 data
<< (uint32
)Type
;
772 data
<< CurrentValue
;
776 data
<< (uint32
)0; // spell id
777 GetSession()->SendPacket( &data
);
780 void Player::StopMirrorTimer(MirrorTimerType Type
)
782 if(Type
==BREATH_TIMER
)
785 WorldPacket
data(SMSG_STOP_MIRROR_TIMER
, 4);
786 data
<< (uint32
)Type
;
787 GetSession()->SendPacket( &data
);
790 void Player::EnvironmentalDamage(uint64 guid
, EnviromentalDamage type
, uint32 damage
)
792 WorldPacket
data(SMSG_ENVIRONMENTALDAMAGELOG
, (21));
793 data
<< (uint64
)guid
;
794 data
<< (uint8
)(type
!=DAMAGE_FALL_TO_VOID
? type
: DAMAGE_FALL
);
795 data
<< (uint32
)damage
;
798 SendMessageToSet(&data
, true);
800 DealDamage(this, damage
, NULL
, SELF_DAMAGE
, SPELL_SCHOOL_MASK_NORMAL
, NULL
, false);
802 if(type
==DAMAGE_FALL
&& !isAlive()) // DealDamage not apply item durability loss at self damage
804 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
805 DurabilityLossAll(0.10f
,false);
806 // durability lost message
807 WorldPacket
data(SMSG_DURABILITY_DAMAGE_DEATH
, 0);
808 GetSession()->SendPacket(&data
);
812 void Player::HandleDrowning()
817 //if player is GM, have waterbreath, is dead or if breathing is disabled then return
818 if(waterbreath
|| isGameMaster() || !isAlive() || GetSession()->GetSecurity() >= sWorld
.getConfig(CONFIG_DISABLE_BREATHING
))
820 StopMirrorTimer(BREATH_TIMER
);
825 uint32 UnderWaterTime
= 1*MINUTE
*1000; // default length 1 min
827 AuraList
const& mModWaterBreathing
= GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING
);
828 for(AuraList::const_iterator i
= mModWaterBreathing
.begin(); i
!= mModWaterBreathing
.end(); ++i
)
829 UnderWaterTime
= uint32(UnderWaterTime
* (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
);
831 if ((m_isunderwater
& 0x01) && !(m_isunderwater
& 0x80) && isAlive())
833 //single trigger timer
834 if (!(m_isunderwater
& 0x02))
836 m_isunderwater
|= 0x02;
837 m_breathTimer
= UnderWaterTime
+ 1000;
839 //single trigger "Breathbar"
840 if ( m_breathTimer
<= UnderWaterTime
&& !(m_isunderwater
& 0x04))
842 m_isunderwater
|= 0x04;
843 StartMirrorTimer(BREATH_TIMER
, UnderWaterTime
);
845 //continuous trigger drowning "Damage"
846 if ((m_breathTimer
== 0) && (m_isunderwater
& 0x01))
848 //TODO: Check this formula
849 uint64 guid
= GetGUID();
850 uint32 damage
= GetMaxHealth() / 5 + urand(0, getLevel()-1);
852 EnvironmentalDamage(guid
, DAMAGE_DROWNING
,damage
);
853 m_breathTimer
= 2000;
856 //single trigger retract bar
857 else if (!(m_isunderwater
& 0x01) && !(m_isunderwater
& 0x08) && (m_isunderwater
& 0x02) && (m_breathTimer
> 0) && isAlive())
859 m_isunderwater
= 0x08;
861 uint32 BreathRegen
= 10;
862 ModifyMirrorTimer(BREATH_TIMER
, UnderWaterTime
, m_breathTimer
,BreathRegen
);
863 m_isunderwater
= 0x10;
866 else if ((m_breathTimer
< 50) && !(m_isunderwater
& 0x01) && (m_isunderwater
== 0x10))
868 StopMirrorTimer(BREATH_TIMER
);
873 void Player::HandleLava()
875 bool ValidArea
= false;
877 if ((m_isunderwater
& 0x80) && isAlive())
879 //Single trigger Set BreathTimer
880 if (!(m_isunderwater
& 0x80))
882 m_isunderwater
|= 0x04;
883 m_breathTimer
= 1000;
885 //Reset BreathTimer and still in the lava
888 uint64 guid
= GetGUID();
889 uint32 damage
= urand(600, 700); // TODO: Get more detailed information about lava damage
890 uint32 dmgZone
= GetZoneId(); // TODO: Find correct "lava dealing zone" flag in Area Table
892 // Deal lava damage only in lava zones.
908 if (dmgZone
/ 5 & 0x408)
912 // if is valid area and is not gamemaster then deal damage
913 if ( ValidArea
&& !isGameMaster() )
914 EnvironmentalDamage(guid
, DAMAGE_LAVA
, damage
);
916 m_breathTimer
= 1000;
920 //Death timer disabled and WaterFlags reset
921 else if (m_deathState
== DEAD
)
928 ///The player sobers by 256 every 10 seconds
929 void Player::HandleSobering()
933 uint32 drunk
= (m_drunk
<= 256) ? 0 : (m_drunk
- 256);
934 SetDrunkValue(drunk
);
937 DrunkenState
Player::GetDrunkenstateByValue(uint16 value
)
940 return DRUNKEN_SMASHED
;
942 return DRUNKEN_DRUNK
;
944 return DRUNKEN_TIPSY
;
945 return DRUNKEN_SOBER
;
948 void Player::SetDrunkValue(uint16 newDrunkenValue
, uint32 itemId
)
950 uint32 oldDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
952 m_drunk
= newDrunkenValue
;
953 SetUInt32Value(PLAYER_BYTES_3
,(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFF0001) | (m_drunk
& 0xFFFE));
955 uint32 newDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
957 // special drunk invisibility detection
958 if(newDrunkenState
>= DRUNKEN_DRUNK
)
959 m_detectInvisibilityMask
|= (1<<6);
961 m_detectInvisibilityMask
&= ~(1<<6);
963 if(newDrunkenState
== oldDrunkenState
)
966 WorldPacket
data(SMSG_CROSSED_INEBRIATION_THRESHOLD
, (8+4+4));
967 data
<< uint64(GetGUID());
968 data
<< uint32(newDrunkenState
);
969 data
<< uint32(itemId
);
971 SendMessageToSet(&data
, true);
974 void Player::Update( uint32 p_time
)
980 if(m_nextMailDelivereTime
&& m_nextMailDelivereTime
<= time(NULL
))
985 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
986 m_nextMailDelivereTime
= 0;
989 Unit::Update( p_time
);
991 // update player only attacks
992 if(uint32 ranged_att
= getAttackTimer(RANGED_ATTACK
))
994 setAttackTimer(RANGED_ATTACK
, (p_time
>= ranged_att
? 0 : ranged_att
- p_time
) );
997 if(uint32 off_att
= getAttackTimer(OFF_ATTACK
))
999 setAttackTimer(OFF_ATTACK
, (p_time
>= off_att
? 0 : off_att
- p_time
) );
1002 time_t now
= time (NULL
);
1006 UpdateContestedPvP(p_time
);
1008 UpdateDuelFlag(now
);
1010 CheckDuelDistance(now
);
1012 UpdateAfkReport(now
);
1014 CheckExploreSystem();
1016 // Update items that have just a limited lifetime
1017 if (now
>m_Last_tick
)
1018 UpdateItemDuration(uint32(now
- m_Last_tick
));
1020 if (!m_timedquests
.empty())
1022 std::set
<uint32
>::iterator iter
= m_timedquests
.begin();
1023 while (iter
!= m_timedquests
.end())
1025 QuestStatusData
& q_status
= mQuestStatus
[*iter
];
1026 if( q_status
.m_timer
<= p_time
)
1028 uint32 quest_id
= *iter
;
1029 ++iter
; // current iter will be removed in FailTimedQuest
1030 FailTimedQuest( quest_id
);
1034 q_status
.m_timer
-= p_time
;
1035 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
1041 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING
))
1043 Unit
*pVictim
= getVictim();
1044 if( !IsNonMeleeSpellCasted(false) && pVictim
)
1046 // default combat reach 10
1047 // TODO add weapon,skill check
1049 float pldistance
= ATTACK_DISTANCE
;
1051 if (isAttackReady(BASE_ATTACK
))
1053 if(!IsWithinDistInMap(pVictim
, pldistance
))
1055 setAttackTimer(BASE_ATTACK
,100);
1056 if(m_swingErrorMsg
!= 1) // send single time (client auto repeat)
1058 SendAttackSwingNotInRange();
1059 m_swingErrorMsg
= 1;
1062 //120 degrees of radiant range
1063 else if( !HasInArc( 2*M_PI
/3, pVictim
))
1065 setAttackTimer(BASE_ATTACK
,100);
1066 if(m_swingErrorMsg
!= 2) // send single time (client auto repeat)
1068 SendAttackSwingBadFacingAttack();
1069 m_swingErrorMsg
= 2;
1074 m_swingErrorMsg
= 0; // reset swing error state
1076 // prevent base and off attack in same time, delay attack at 0.2 sec
1077 if(haveOffhandWeapon())
1079 uint32 off_att
= getAttackTimer(OFF_ATTACK
);
1080 if(off_att
< ATTACK_DISPLAY_DELAY
)
1081 setAttackTimer(OFF_ATTACK
,ATTACK_DISPLAY_DELAY
);
1083 AttackerStateUpdate(pVictim
, BASE_ATTACK
);
1084 resetAttackTimer(BASE_ATTACK
);
1088 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK
))
1090 if(!IsWithinDistInMap(pVictim
, pldistance
))
1092 setAttackTimer(OFF_ATTACK
,100);
1094 else if( !HasInArc( 2*M_PI
/3, pVictim
))
1096 setAttackTimer(OFF_ATTACK
,100);
1100 // prevent base and off attack in same time, delay attack at 0.2 sec
1101 uint32 base_att
= getAttackTimer(BASE_ATTACK
);
1102 if(base_att
< ATTACK_DISPLAY_DELAY
)
1103 setAttackTimer(BASE_ATTACK
,ATTACK_DISPLAY_DELAY
);
1105 AttackerStateUpdate(pVictim
, OFF_ATTACK
);
1106 resetAttackTimer(OFF_ATTACK
);
1110 Unit
*owner
= pVictim
->GetOwner();
1111 Unit
*u
= owner
? owner
: pVictim
;
1112 if(u
->IsPvP() && (!duel
|| duel
->opponent
!= u
))
1115 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT
);
1120 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
))
1122 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1124 int time_inn
= time(NULL
)-GetTimeInnEnter();
1125 if (time_inn
>= 10) //freeze update
1127 float bubble
= 0.125*sWorld
.getRate(RATE_REST_INGAME
);
1128 //speed collect rest bonus (section/in hour)
1129 SetRestBonus( GetRestBonus()+ time_inn
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
1130 UpdateInnerTime(time(NULL
));
1135 if(m_regenTimer
> 0)
1137 if(p_time
>= m_regenTimer
)
1140 m_regenTimer
-= p_time
;
1143 if (m_weaponChangeTimer
> 0)
1145 if(p_time
>= m_weaponChangeTimer
)
1146 m_weaponChangeTimer
= 0;
1148 m_weaponChangeTimer
-= p_time
;
1151 if (m_zoneUpdateTimer
> 0)
1153 if(p_time
>= m_zoneUpdateTimer
)
1155 uint32 newzone
= GetZoneId();
1156 if( m_zoneUpdateId
!= newzone
)
1157 UpdateZone(newzone
); // also update area
1160 // use area updates as well
1161 // needed for free far all arenas for example
1162 uint32 newarea
= GetAreaId();
1163 if( m_areaUpdateId
!= newarea
)
1164 UpdateArea(newarea
);
1166 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
1170 m_zoneUpdateTimer
-= p_time
;
1178 if (m_deathState
== JUST_DIED
)
1185 if(p_time
>= m_nextSave
)
1187 // m_nextSave reseted in SaveToDB call
1189 sLog
.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1193 m_nextSave
-= p_time
;
1198 if(m_breathTimer
> 0)
1200 if(p_time
>= m_breathTimer
)
1203 m_breathTimer
-= p_time
;
1207 //Handle Water/drowning
1213 //Handle detect stealth players
1214 if (m_DetectInvTimer
> 0)
1216 if (p_time
>= m_DetectInvTimer
)
1218 m_DetectInvTimer
= 3000;
1219 HandleStealthedUnitsDetection();
1222 m_DetectInvTimer
-= p_time
;
1226 if (now
> m_Last_tick
)
1228 uint32 elapsed
= uint32(now
- m_Last_tick
);
1229 m_Played_time
[0] += elapsed
; // Total played time
1230 m_Played_time
[1] += elapsed
; // Level played time
1236 m_drunkTimer
+= p_time
;
1238 if (m_drunkTimer
> 10000)
1242 // not auto-free ghost from body in instances
1243 if(m_deathTimer
> 0 && !GetBaseMap()->Instanceable())
1245 if(p_time
>= m_deathTimer
)
1252 m_deathTimer
-= p_time
;
1255 UpdateEnchantTime(p_time
);
1256 UpdateHomebindTime(p_time
);
1259 SendUpdateToOutOfRangeGroupMembers();
1261 Pet
* pet
= GetPet();
1262 if(pet
&& !IsWithinDistInMap(pet
, OWNER_MAX_DISTANCE
))
1264 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
, true);
1269 void Player::setDeathState(DeathState s
)
1271 uint32 ressSpellId
= 0;
1273 bool cur
= isAlive();
1275 if(s
== JUST_DIED
&& cur
)
1277 // drunken state is cleared on death
1279 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1282 clearResurrectRequestData();
1284 // remove form before other mods to prevent incorrect stats calculation
1285 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId
);
1287 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1288 RemovePet(NULL
, PET_SAVE_NOT_IN_SLOT
, true);
1290 // remove uncontrolled pets
1294 // save value before aura remove in Unit::setDeathState
1295 ressSpellId
= GetUInt32Value(PLAYER_SELF_RES_SPELL
);
1299 ressSpellId
= GetResurrectionSpellId();
1301 Unit::setDeathState(s
);
1303 // restore resurrection spell id for player after aura remove
1304 if(s
== JUST_DIED
&& cur
&& ressSpellId
)
1305 SetUInt32Value(PLAYER_SELF_RES_SPELL
, ressSpellId
);
1307 if(isAlive() && !cur
)
1309 //clear aura case after resurrection by another way (spells will be applied before next death)
1310 SetUInt32Value(PLAYER_SELF_RES_SPELL
, 0);
1312 // restore default warrior stance
1313 if(getClass()== CLASS_WARRIOR
)
1314 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
1318 void Player::BuildEnumData( QueryResult
* result
, WorldPacket
* p_data
)
1320 *p_data
<< GetGUID();
1323 *p_data
<< getRace();
1324 uint8 pClass
= getClass();
1326 *p_data
<< getGender();
1328 uint32 bytes
= GetUInt32Value(PLAYER_BYTES
);
1329 *p_data
<< uint8(bytes
);
1330 *p_data
<< uint8(bytes
>> 8);
1331 *p_data
<< uint8(bytes
>> 16);
1332 *p_data
<< uint8(bytes
>> 24);
1334 bytes
= GetUInt32Value(PLAYER_BYTES_2
);
1335 *p_data
<< uint8(bytes
);
1337 *p_data
<< uint8(getLevel()); // player level
1338 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1339 uint32 zoneId
= MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY());
1340 sLog
.outDebug("Player::BuildEnumData: m:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId
);
1342 *p_data
<< GetMapId();
1344 *p_data
<< GetPositionX();
1345 *p_data
<< GetPositionY();
1346 *p_data
<< GetPositionZ();
1348 *p_data
<< (result
? result
->Fetch()[13].GetUInt32() : 0);
1350 uint32 char_flags
= 0;
1351 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
1352 char_flags
|= CHARACTER_FLAG_HIDE_HELM
;
1353 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
1354 char_flags
|= CHARACTER_FLAG_HIDE_CLOAK
;
1355 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
))
1356 char_flags
|= CHARACTER_FLAG_GHOST
;
1357 if(HasAtLoginFlag(AT_LOGIN_RENAME
))
1358 char_flags
|= CHARACTER_FLAG_RENAME
;
1359 // always send the flag if declined names aren't used
1360 // to let the client select a default method of declining the name
1361 if(!sWorld
.getConfig(CONFIG_DECLINED_NAMES_USED
) || (result
&& result
->Fetch()[14].GetCppString() != ""))
1362 char_flags
|= CHARACTER_FLAG_DECLINED
;
1364 *p_data
<< (uint32
)char_flags
; // character flags
1366 *p_data
<< (uint8
)1; // unknown
1370 uint32 petDisplayId
= 0;
1371 uint32 petLevel
= 0;
1372 uint32 petFamily
= 0;
1374 // show pet at selection character in character list only for non-ghost character
1375 if(result
&& isAlive() && (pClass
== CLASS_WARLOCK
|| pClass
== CLASS_HUNTER
))
1377 Field
* fields
= result
->Fetch();
1379 uint32 entry
= fields
[10].GetUInt32();
1380 CreatureInfo
const* cInfo
= sCreatureStorage
.LookupEntry
<CreatureInfo
>(entry
);
1383 petDisplayId
= fields
[11].GetUInt32();
1384 petLevel
= fields
[12].GetUInt32();
1385 petFamily
= cInfo
->family
;
1389 *p_data
<< (uint32
)petDisplayId
;
1390 *p_data
<< (uint32
)petLevel
;
1391 *p_data
<< (uint32
)petFamily
;
1394 /*ItemPrototype const *items[EQUIPMENT_SLOT_END];
1395 for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
1398 QueryResult *result = CharacterDatabase.PQuery("SELECT slot,item_template FROM character_inventory WHERE guid = '%u' AND bag = 0",GetGUIDLow());
1403 Field *fields = result->Fetch();
1404 uint8 slot = fields[0].GetUInt8() & 255;
1405 uint32 item_id = fields[1].GetUInt32();
1406 if( slot >= EQUIPMENT_SLOT_END )
1409 items[slot] = objmgr.GetItemPrototype(item_id);
1412 sLog.outError( "Player::BuildEnumData: Player %s have unknown item (id: #%u) in inventory, skipped.", GetName(),item_id );
1415 } while (result->NextRow());
1419 for (uint8 slot
= 0; slot
< EQUIPMENT_SLOT_END
; slot
++)
1421 uint32 visualbase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
1422 uint32 item_id
= GetUInt32Value(visualbase
);
1423 const ItemPrototype
* proto
= objmgr
.GetItemPrototype(item_id
);
1424 SpellItemEnchantmentEntry
const *enchant
= NULL
;
1426 for(uint8 enchantSlot
= PERM_ENCHANTMENT_SLOT
; enchantSlot
<=TEMP_ENCHANTMENT_SLOT
; enchantSlot
++)
1428 uint32 enchantId
= GetUInt32Value(visualbase
+1+enchantSlot
);
1429 if(enchant
= sSpellItemEnchantmentStore
.LookupEntry(enchantId
))
1435 *p_data
<< (uint32
)proto
->DisplayInfoID
;
1436 *p_data
<< (uint8
)proto
->InventoryType
;
1437 *p_data
<< (uint32
)(enchant
?enchant
->aura_id
:0);
1441 *p_data
<< (uint32
)0;
1442 *p_data
<< (uint8
)0;
1443 *p_data
<< (uint32
)0; // enchant?
1446 *p_data
<< (uint32
)0; // first bag display id
1447 *p_data
<< (uint8
)0; // first bag inventory type
1448 *p_data
<< (uint32
)0; // enchant?
1451 bool Player::ToggleAFK()
1453 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1455 bool state
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1457 // afk player not allowed in battleground
1458 if(state
&& InBattleGround())
1459 LeaveBattleground();
1464 bool Player::ToggleDND()
1466 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1468 return HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1471 uint8
Player::chatTag() const
1488 bool Player::TeleportTo(uint32 mapid
, float x
, float y
, float z
, float orientation
, uint32 options
)
1490 if(!MapManager::IsValidMapCoord(mapid
, x
, y
, z
, orientation
))
1492 sLog
.outError("TeleportTo: invalid map %d or absent instance template.", mapid
);
1496 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1497 Pet
* pet
= GetPet();
1499 MapEntry
const* mEntry
= sMapStore
.LookupEntry(mapid
);
1501 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1502 if(!InBattleGround() && mEntry
->IsBattleGround() && !GetSession()->GetSecurity())
1505 // client without expansion support
1506 if(GetSession()->Expansion() < mEntry
->Expansion())
1508 sLog
.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid
);
1511 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1513 SendTransferAborted(mapid
, TRANSFER_ABORT_INSUF_EXPAN_LVL1
);
1515 return false; // normal client can't teleport to this map...
1519 sLog
.outDebug("Player %s will teleported to map %u", GetName(), mapid
);
1522 // if we were on a transport, leave
1523 if (!(options
& TELE_TO_NOT_LEAVE_TRANSPORT
) && m_transport
)
1525 m_transport
->RemovePassenger(this);
1527 m_movementInfo
.t_x
= 0.0f
;
1528 m_movementInfo
.t_y
= 0.0f
;
1529 m_movementInfo
.t_z
= 0.0f
;
1530 m_movementInfo
.t_o
= 0.0f
;
1531 m_movementInfo
.t_time
= 0;
1534 SetSemaphoreTeleport(true);
1536 // The player was ported to another map and looses the duel immediately.
1537 // We have to perform this check before the teleport, otherwise the
1538 // ObjectAccessor won't find the flag.
1539 if (duel
&& GetMapId()!=mapid
)
1541 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER
));
1543 DuelComplete(DUEL_FLED
);
1546 // reset movement flags at teleport, because player will continue move with these flags after teleport
1547 SetUnitMovementFlags(0);
1549 if ((GetMapId() == mapid
) && (!m_transport
))
1551 // prepare zone change detect
1552 uint32 old_zone
= GetZoneId();
1555 if(!GetSession()->PlayerLogout())
1558 BuildTeleportAckMsg(&data
, x
, y
, z
, orientation
);
1559 GetSession()->SendPacket(&data
);
1560 SetPosition( x
, y
, z
, orientation
, true);
1563 // this will be used instead of the current location in SaveToDB
1564 m_teleport_dest
= WorldLocation(mapid
, x
, y
, z
, orientation
);
1565 SetFallInformation(0, z
);
1567 //BuildHeartBeatMsg(&data);
1568 //SendMessageToSet(&data, true);
1569 if (!(options
& TELE_TO_NOT_UNSUMMON_PET
))
1571 //same map, only remove pet if out of range
1572 if(pet
&& !IsWithinDistInMap(pet
, OWNER_MAX_DISTANCE
))
1574 if(pet
->isControlled() && !pet
->isTemporarySummoned() )
1575 m_temporaryUnsummonedPetNumber
= pet
->GetCharmInfo()->GetPetNumber();
1577 m_temporaryUnsummonedPetNumber
= 0;
1579 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
);
1583 if(!(options
& TELE_TO_NOT_LEAVE_COMBAT
))
1586 if (!(options
& TELE_TO_NOT_UNSUMMON_PET
))
1589 if(pet
&& m_temporaryUnsummonedPetNumber
)
1591 Pet
* NewPet
= new Pet
;
1592 if(!NewPet
->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber
, true))
1595 m_temporaryUnsummonedPetNumber
= 0;
1599 if(!GetSession()->PlayerLogout())
1601 // don't reset teleport semaphore while logging out, otherwise m_teleport_dest won't be used in Player::SaveToDB
1602 SetSemaphoreTeleport(false);
1604 UpdateZone(GetZoneId());
1608 if(old_zone
!= GetZoneId())
1611 if(pvpInfo
.inHostileArea
)
1612 CastSpell(this, 2479, true);
1617 // far teleport to another map
1618 Map
* oldmap
= IsInWorld() ? GetMap() : NULL
;
1619 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1621 // Check enter rights before map getting to avoid creating instance copy for player
1622 // this check not dependent from map instance copy and same for all instance copies of selected map
1623 if (!MapManager::Instance().CanPlayerEnter(mapid
, this))
1625 SetSemaphoreTeleport(false);
1629 // If the map is not created, assume it is possible to enter it.
1630 // It will be created in the WorldPortAck.
1631 Map
*map
= MapManager::Instance().FindMap(mapid
);
1632 if (!map
|| map
->CanEnter(this))
1638 ResetContestedPvP();
1640 // remove player from battleground on far teleport (when changing maps)
1641 if(BattleGround
const* bg
= GetBattleGround())
1643 // Note: at battleground join battleground id set before teleport
1644 // and we already will found "current" battleground
1645 // just need check that this is targeted map or leave
1646 if(bg
->GetMapId() != mapid
)
1647 LeaveBattleground(false); // don't teleport to entry point
1650 // remove pet on map change
1653 //leaving map -> delete pet right away (doing this later will cause problems)
1654 if(pet
->isControlled() && !pet
->isTemporarySummoned())
1655 m_temporaryUnsummonedPetNumber
= pet
->GetCharmInfo()->GetPetNumber();
1657 m_temporaryUnsummonedPetNumber
= 0;
1659 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
);
1662 // remove all dyn objects
1663 RemoveAllDynObjects();
1665 // stop spellcasting
1666 // not attempt interrupt teleportation spell at caster teleport
1667 if(!(options
& TELE_TO_SPELL
))
1668 if(IsNonMeleeSpellCasted(true))
1669 InterruptNonMeleeSpells(true);
1671 if(!GetSession()->PlayerLogout())
1673 // send transfer packets
1674 WorldPacket
data(SMSG_TRANSFER_PENDING
, (4+4+4));
1675 data
<< uint32(mapid
);
1678 data
<< m_transport
->GetEntry() << GetMapId();
1680 GetSession()->SendPacket(&data
);
1682 data
.Initialize(SMSG_NEW_WORLD
, (20));
1685 data
<< (uint32
)mapid
<< m_movementInfo
.t_x
<< m_movementInfo
.t_y
<< m_movementInfo
.t_z
<< m_movementInfo
.t_o
;
1689 data
<< (uint32
)mapid
<< (float)x
<< (float)y
<< (float)z
<< (float)orientation
;
1691 GetSession()->SendPacket( &data
);
1692 SendSavedInstances();
1694 // remove from old map now
1695 if(oldmap
) oldmap
->Remove(this, false);
1698 // new final coordinates
1702 float final_o
= orientation
;
1706 final_x
+= m_movementInfo
.t_x
;
1707 final_y
+= m_movementInfo
.t_y
;
1708 final_z
+= m_movementInfo
.t_z
;
1709 final_o
+= m_movementInfo
.t_o
;
1712 m_teleport_dest
= WorldLocation(mapid
, final_x
, final_y
, final_z
, final_o
);
1713 SetFallInformation(0, final_z
);
1714 // if the player is saved before worldportack (at logout for example)
1715 // this will be used instead of the current location in SaveToDB
1717 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP
);
1719 // move packet sent by client always after far teleport
1720 // SetPosition(final_x, final_y, final_z, final_o, true);
1723 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1731 void Player::AddToWorld()
1733 ///- Do not add/remove the player from the object storage
1734 ///- It will crash when updating the ObjectAccessor
1735 ///- The player should only be added when logging in
1738 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; i
++)
1741 m_items
[i
]->AddToWorld();
1745 void Player::RemoveFromWorld()
1750 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1752 UnsummonAllTotems();
1757 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; i
++)
1760 m_items
[i
]->RemoveFromWorld();
1763 ///- Do not add/remove the player from the object storage
1764 ///- It will crash when updating the ObjectAccessor
1765 ///- The player should only be removed when logging out
1766 Unit::RemoveFromWorld();
1769 void Player::RewardRage( uint32 damage
, uint32 weaponSpeedHitFactor
, bool attacker
)
1773 float rageconversion
= ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1777 addRage
= ((damage
/rageconversion
*7.5 + weaponSpeedHitFactor
)/2);
1779 // talent who gave more rage on attack
1780 addRage
*= 1.0f
+ GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT
) / 100.0f
;
1784 addRage
= damage
/rageconversion
*2.5;
1786 // Berserker Rage effect
1787 if(HasAura(18499,0))
1791 addRage
*= sWorld
.getRate(RATE_POWER_RAGE_INCOME
);
1793 ModifyPower(POWER_RAGE
, uint32(addRage
*10));
1796 void Player::RegenerateAll()
1798 if (m_regenTimer
!= 0)
1800 uint32 regenDelay
= 2000;
1802 // Not in combat or they have regeneration
1803 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) ||
1804 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
) || IsPolymorphed() )
1807 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN
))
1808 Regenerate(POWER_RAGE
);
1811 Regenerate( POWER_ENERGY
);
1813 Regenerate( POWER_MANA
);
1815 m_regenTimer
= regenDelay
;
1818 void Player::Regenerate(Powers power
)
1820 uint32 curValue
= GetPower(power
);
1821 uint32 maxValue
= GetMaxPower(power
);
1823 float addvalue
= 0.0f
;
1829 bool recentCast
= IsUnderLastManaUseEffect();
1830 float ManaIncreaseRate
= sWorld
.getRate(RATE_POWER_MANA
);
1833 // Mangos Updates Mana in intervals of 2s, which is correct
1834 addvalue
= GetFloatValue(PLAYER_FIELD_MOD_MANA_REGEN_INTERRUPT
) * ManaIncreaseRate
* 2.00f
;
1838 addvalue
= GetFloatValue(PLAYER_FIELD_MOD_MANA_REGEN
) * ManaIncreaseRate
* 2.00f
;
1841 case POWER_RAGE
: // Regenerate rage
1843 float RageDecreaseRate
= sWorld
.getRate(RATE_POWER_RAGE_LOSS
);
1844 addvalue
= 30 * RageDecreaseRate
; // 3 rage by tick
1846 case POWER_ENERGY
: // Regenerate energy (rogue)
1850 case POWER_HAPPINESS
:
1854 // Mana regen calculated in Player::UpdateManaRegen()
1855 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1856 if(power
!= POWER_MANA
)
1858 AuraList
const& ModPowerRegenPCTAuras
= GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT
);
1859 for(AuraList::const_iterator i
= ModPowerRegenPCTAuras
.begin(); i
!= ModPowerRegenPCTAuras
.end(); ++i
)
1860 if ((*i
)->GetModifier()->m_miscvalue
== power
)
1861 addvalue
*= ((*i
)->GetModifier()->m_amount
+ 100) / 100.0f
;
1864 if (power
!= POWER_RAGE
)
1866 curValue
+= uint32(addvalue
);
1867 if (curValue
> maxValue
)
1868 curValue
= maxValue
;
1872 if(curValue
<= uint32(addvalue
))
1875 curValue
-= uint32(addvalue
);
1877 SetPower(power
, curValue
);
1880 void Player::RegenerateHealth()
1882 uint32 curValue
= GetHealth();
1883 uint32 maxValue
= GetMaxHealth();
1885 if (curValue
>= maxValue
) return;
1887 float HealthIncreaseRate
= sWorld
.getRate(RATE_HEALTH
);
1889 float addvalue
= 0.0f
;
1892 if ( IsPolymorphed() )
1893 addvalue
= GetMaxHealth()/3;
1894 // normal regen case (maybe partly in combat case)
1895 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) )
1897 addvalue
= OCTRegenHPPerSpirit()* HealthIncreaseRate
;
1900 AuraList
const& mModHealthRegenPct
= GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT
);
1901 for(AuraList::const_iterator i
= mModHealthRegenPct
.begin(); i
!= mModHealthRegenPct
.end(); ++i
)
1902 addvalue
*= (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
;
1904 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
))
1905 addvalue
*= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) / 100.0f
;
1911 // always regeneration bonus (including combat)
1912 addvalue
+= GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
);
1917 ModifyHealth(int32(addvalue
));
1920 bool Player::CanInteractWithNPCs(bool alive
) const
1922 if(alive
&& !isAlive())
1930 bool Player::IsUnderWater() const
1932 return IsInWater() &&
1933 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
1936 void Player::SetInWater(bool apply
)
1938 if(m_isInWater
==apply
)
1941 //define player in water by opcodes
1942 //move player's guid into HateOfflineList of those mobs
1943 //which can't swim and move guid back into ThreatList when
1945 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
1946 m_isInWater
= apply
;
1948 // remove auras that need water/land
1949 RemoveAurasWithInterruptFlags(apply
? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER
: AURA_INTERRUPT_FLAG_NOT_UNDERWATER
);
1951 getHostilRefManager().updateThreatTables();
1954 void Player::SetGameMaster(bool on
)
1958 m_ExtraFlags
|= PLAYER_EXTRA_GM_ON
;
1960 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
1962 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_FFA_PVP
);
1963 ResetContestedPvP();
1965 getHostilRefManager().setOnlineOfflineState(false);
1970 m_ExtraFlags
&= ~ PLAYER_EXTRA_GM_ON
;
1971 setFactionForRace(getRace());
1972 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
1974 // restore FFA PvP Server state
1975 if(sWorld
.IsFFAPvPRealm())
1976 SetFlag(PLAYER_FLAGS
,PLAYER_FLAGS_FFA_PVP
);
1978 // restore FFA PvP area state, remove not allowed for GM mounts
1979 UpdateArea(m_areaUpdateId
);
1981 getHostilRefManager().setOnlineOfflineState(true);
1984 ObjectAccessor::UpdateVisibilityForPlayer(this);
1987 void Player::SetGMVisible(bool on
)
1991 m_ExtraFlags
&= ~PLAYER_EXTRA_GM_INVISIBLE
; //remove flag
1993 // Reapply stealth/invisibility if active or show if not any
1994 if(HasAuraType(SPELL_AURA_MOD_STEALTH
))
1995 SetVisibility(VISIBILITY_GROUP_STEALTH
);
1996 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY
))
1997 SetVisibility(VISIBILITY_GROUP_INVISIBILITY
);
1999 SetVisibility(VISIBILITY_ON
);
2003 m_ExtraFlags
|= PLAYER_EXTRA_GM_INVISIBLE
; //add flag
2005 SetAcceptWhispers(false);
2006 SetGameMaster(true);
2008 SetVisibility(VISIBILITY_OFF
);
2012 bool Player::IsGroupVisibleFor(Player
* p
) const
2014 switch(sWorld
.getConfig(CONFIG_GROUP_VISIBILITY
))
2016 default: return IsInSameGroupWith(p
);
2017 case 1: return IsInSameRaidWith(p
);
2018 case 2: return GetTeam()==p
->GetTeam();
2022 bool Player::IsInSameGroupWith(Player
const* p
) const
2024 return p
==this || GetGroup() != NULL
&&
2025 GetGroup() == p
->GetGroup() &&
2026 GetGroup()->SameSubGroup((Player
*)this, (Player
*)p
);
2029 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2030 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2031 void Player::UninviteFromGroup()
2033 Group
* group
= GetGroupInvite();
2037 group
->RemoveInvite(this);
2039 if(group
->GetMembersCount() <= 1) // group has just 1 member => disband
2041 if(group
->IsCreated())
2043 group
->Disband(true);
2044 objmgr
.RemoveGroup(group
);
2047 group
->RemoveAllInvites();
2053 void Player::RemoveFromGroup(Group
* group
, uint64 guid
)
2057 if (group
->RemoveMember(guid
, 0) <= 1)
2059 // group->Disband(); already disbanded in RemoveMember
2060 objmgr
.RemoveGroup(group
);
2062 // removemember sets the player's group pointer to NULL
2067 void Player::SendLogXPGain(uint32 GivenXP
, Unit
* victim
, uint32 RestXP
)
2069 WorldPacket
data(SMSG_LOG_XPGAIN
, 21);
2070 data
<< uint64(victim
? victim
->GetGUID() : 0); // guid
2071 data
<< uint32(GivenXP
+RestXP
); // given experience
2072 data
<< uint8(victim
? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2075 data
<< uint32(GivenXP
); // experience without rested bonus
2076 data
<< float(1); // 1 - none 0 - 100% group bonus output
2078 data
<< uint8(0); // new 2.4.0
2079 GetSession()->SendPacket(&data
);
2082 void Player::GiveXP(uint32 xp
, Unit
* victim
)
2090 uint32 level
= getLevel();
2092 // XP to money conversion processed in Player::RewardQuest
2093 if(level
>= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
2096 // handle SPELL_AURA_MOD_XP_PCT auras
2097 Unit::AuraList
const& ModXPPctAuras
= GetAurasByType(SPELL_AURA_MOD_XP_PCT
);
2098 for(Unit::AuraList::const_iterator i
= ModXPPctAuras
.begin();i
!= ModXPPctAuras
.end(); ++i
)
2099 xp
= uint32(xp
*(1.0f
+ (*i
)->GetModifier()->m_amount
/ 100.0f
));
2101 // XP resting bonus for kill
2102 uint32 rested_bonus_xp
= victim
? GetXPRestBonus(xp
) : 0;
2104 SendLogXPGain(xp
,victim
,rested_bonus_xp
);
2106 uint32 curXP
= GetUInt32Value(PLAYER_XP
);
2107 uint32 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2108 uint32 newXP
= curXP
+ xp
+ rested_bonus_xp
;
2110 while( newXP
>= nextLvlXP
&& level
< sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
2114 if ( level
< sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
2115 GiveLevel(level
+ 1);
2118 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2121 SetUInt32Value(PLAYER_XP
, newXP
);
2124 // Update player to next level
2125 // Current player experience not update (must be update by caller)
2126 void Player::GiveLevel(uint32 level
)
2128 if ( level
== getLevel() )
2131 PlayerLevelInfo info
;
2132 objmgr
.GetPlayerLevelInfo(getRace(),getClass(),level
,&info
);
2134 PlayerClassLevelInfo classInfo
;
2135 objmgr
.GetPlayerClassLevelInfo(getClass(),level
,&classInfo
);
2137 // send levelup info to client
2138 WorldPacket
data(SMSG_LEVELUP_INFO
, (4+4+MAX_POWERS
*4+MAX_STATS
*4));
2139 data
<< uint32(level
);
2140 data
<< uint32(int32(classInfo
.basehealth
) - int32(GetCreateHealth()));
2141 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2142 data
<< uint32(int32(classInfo
.basemana
) - int32(GetCreateMana()));
2148 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
) // Stats loop (0-4)
2149 data
<< uint32(int32(info
.stats
[i
]) - GetCreateStat(Stats(i
)));
2151 GetSession()->SendPacket(&data
);
2153 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, MaNGOS::XP::xp_to_level(level
));
2155 //update level, max level of skills
2156 if(getLevel()!= level
)
2157 m_Played_time
[1] = 0; // Level Played Time reset
2159 UpdateSkillsForLevel ();
2161 // save base values (bonuses already included in stored stats
2162 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2163 SetCreateStat(Stats(i
), info
.stats
[i
]);
2165 SetCreateHealth(classInfo
.basehealth
);
2166 SetCreateMana(classInfo
.basemana
);
2168 InitTalentForLevel();
2169 InitTaxiNodesForLevel();
2173 // set current level health and mana/energy to maximum after applying all mods.
2174 SetHealth(GetMaxHealth());
2175 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2176 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2177 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2178 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2179 SetPower(POWER_FOCUS
, 0);
2180 SetPower(POWER_HAPPINESS
, 0);
2182 // give level to summoned pet
2183 Pet
* pet
= GetPet();
2184 if(pet
&& pet
->getPetType()==SUMMON_PET
)
2185 pet
->GivePetLevel(level
);
2188 void Player::InitTalentForLevel()
2190 uint32 level
= getLevel();
2191 // talents base at level diff ( talents = level - 9 but some can be used already)
2194 // Remove all talent points
2195 if(m_usedTalentCount
> 0) // Free any used talents
2198 SetFreeTalentPoints(0);
2203 uint32 talentPointsForLevel
= uint32((level
-9)*sWorld
.getRate(RATE_TALENT
));
2204 // if used more that have then reset
2205 if(m_usedTalentCount
> talentPointsForLevel
)
2207 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR
)
2210 SetFreeTalentPoints(0);
2212 // else update amount of free points
2214 SetFreeTalentPoints(talentPointsForLevel
-m_usedTalentCount
);
2218 void Player::InitStatsForLevel(bool reapplyMods
)
2220 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2221 _RemoveAllStatBonuses();
2223 PlayerClassLevelInfo classInfo
;
2224 objmgr
.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo
);
2226 PlayerLevelInfo info
;
2227 objmgr
.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info
);
2229 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL
, sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) );
2230 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, MaNGOS::XP::xp_to_level(getLevel()));
2232 UpdateSkillsForLevel ();
2234 // set default cast time multiplier
2235 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
);
2237 // reset size before reapply auras
2238 SetFloatValue(OBJECT_FIELD_SCALE_X
,1.0f
);
2240 // save base values (bonuses already included in stored stats
2241 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2242 SetCreateStat(Stats(i
), info
.stats
[i
]);
2244 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2245 SetStat(Stats(i
), info
.stats
[i
]);
2247 SetCreateHealth(classInfo
.basehealth
);
2250 SetCreateMana(classInfo
.basemana
);
2252 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2256 //reset rating fields values
2257 for(uint16 index
= PLAYER_FIELD_COMBAT_RATING_1
; index
< PLAYER_FIELD_COMBAT_RATING_1
+ MAX_COMBAT_RATING
; ++index
)
2258 SetUInt32Value(index
, 0);
2260 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS
,0);
2261 for (int i
= 0; i
< 7; i
++)
2263 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG
+i
, 0);
2264 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS
+i
, 0);
2265 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT
+i
, 1.00f
);
2268 //reset attack power, damage and attack speed fields
2269 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
, 2000.0f
);
2270 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
+ 1, 2000.0f
); // offhand attack time
2271 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME
, 2000.0f
);
2273 SetFloatValue(UNIT_FIELD_MINDAMAGE
, 0.0f
);
2274 SetFloatValue(UNIT_FIELD_MAXDAMAGE
, 0.0f
);
2275 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
, 0.0f
);
2276 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
, 0.0f
);
2277 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
, 0.0f
);
2278 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
, 0.0f
);
2280 SetUInt32Value(UNIT_FIELD_ATTACK_POWER
, 0 );
2281 SetUInt32Value(UNIT_FIELD_ATTACK_POWER_MODS
, 0 );
2282 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER
,0.0f
);
2283 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER
, 0 );
2284 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS
,0 );
2285 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER
,0.0f
);
2287 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2288 SetFloatValue(PLAYER_CRIT_PERCENTAGE
,0.0f
);
2289 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE
,0.0f
);
2290 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE
,0.0f
);
2292 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2293 for (uint8 i
= 0; i
< 7; ++i
)
2294 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1
+i
, 0.0f
);
2296 SetFloatValue(PLAYER_PARRY_PERCENTAGE
, 0.0f
);
2297 SetFloatValue(PLAYER_BLOCK_PERCENTAGE
, 0.0f
);
2298 SetUInt32Value(PLAYER_SHIELD_BLOCK
, 0);
2301 SetFloatValue(PLAYER_DODGE_PERCENTAGE
, 0.0f
);
2303 // set armor (resistance 0) to original value (create_agility*2)
2304 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2305 SetResistanceBuffMods(SpellSchools(0), true, 0.0f
);
2306 SetResistanceBuffMods(SpellSchools(0), false, 0.0f
);
2307 // set other resistance to original value (0)
2308 for (int i
= 1; i
< MAX_SPELL_SCHOOL
; i
++)
2310 SetResistance(SpellSchools(i
), 0);
2311 SetResistanceBuffMods(SpellSchools(i
), true, 0.0f
);
2312 SetResistanceBuffMods(SpellSchools(i
), false, 0.0f
);
2315 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE
,0);
2316 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE
,0);
2317 for(int i
= 0; i
< MAX_SPELL_SCHOOL
; ++i
)
2319 SetFloatValue(UNIT_FIELD_POWER_COST_MODIFIER
+i
,0.0f
);
2320 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER
+i
,0.0f
);
2322 // Init data for form but skip reapply item mods for form
2323 InitDataForForm(reapplyMods
);
2326 for (int i
= POWER_MANA
; i
< MAX_POWERS
; i
++)
2327 SetMaxPower(Powers(i
), uint32(GetCreatePowers(Powers(i
))));
2329 SetMaxHealth(classInfo
.basehealth
); // stamina bonus will applied later
2331 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2332 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID
, 0);
2334 // cleanup unit flags (will be re-applied if need at aura load).
2335 RemoveFlag( UNIT_FIELD_FLAGS
,
2336 UNIT_FLAG_NON_ATTACKABLE
| UNIT_FLAG_DISABLE_MOVE
| UNIT_FLAG_NOT_ATTACKABLE_1
|
2337 UNIT_FLAG_PET_IN_COMBAT
| UNIT_FLAG_SILENCED
| UNIT_FLAG_PACIFIED
|
2338 UNIT_FLAG_DISABLE_ROTATE
| UNIT_FLAG_IN_COMBAT
| UNIT_FLAG_DISARMED
|
2339 UNIT_FLAG_CONFUSED
| UNIT_FLAG_FLEEING
| UNIT_FLAG_NOT_SELECTABLE
|
2340 UNIT_FLAG_SKINNABLE
| UNIT_FLAG_MOUNT
| UNIT_FLAG_TAXI_FLIGHT
);
2341 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
); // must be set
2343 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2344 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
| PLAYER_FLAGS_DND
| PLAYER_FLAGS_GM
| PLAYER_FLAGS_GHOST
| PLAYER_FLAGS_FFA_PVP
);
2346 SetByteValue(UNIT_FIELD_BYTES_1
, 2, 0x00); // one form stealth modified bytes
2348 // restore if need some important flags
2349 SetUInt32Value(PLAYER_FIELD_BYTES2
, 0 ); // flags empty by default
2351 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2352 _ApplyAllStatBonuses();
2354 // set current level health and mana/energy to maximum after applying all mods.
2355 SetHealth(GetMaxHealth());
2356 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2357 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2358 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2359 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2360 SetPower(POWER_FOCUS
, 0);
2361 SetPower(POWER_HAPPINESS
, 0);
2364 void Player::SendInitialSpells()
2366 uint16 spellCount
= 0;
2368 WorldPacket
data(SMSG_INITIAL_SPELLS
, (1+2+4*m_spells
.size()+2+m_spellCooldowns
.size()*(2+2+2+4+4)));
2371 size_t countPos
= data
.wpos();
2372 data
<< uint16(spellCount
); // spell count placeholder
2374 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2376 if(itr
->second
->state
== PLAYERSPELL_REMOVED
)
2379 if(!itr
->second
->active
|| itr
->second
->disabled
)
2382 data
<< uint16(itr
->first
);
2383 data
<< uint16(0); // it's not slot id
2388 data
.put
<uint16
>(countPos
,spellCount
); // write real count value
2390 uint16 spellCooldowns
= m_spellCooldowns
.size();
2391 data
<< uint16(spellCooldowns
);
2392 for(SpellCooldowns::const_iterator itr
=m_spellCooldowns
.begin(); itr
!=m_spellCooldowns
.end(); ++itr
)
2394 SpellEntry
const *sEntry
= sSpellStore
.LookupEntry(itr
->first
);
2398 data
<< uint16(itr
->first
);
2400 time_t cooldown
= 0;
2401 time_t curTime
= time(NULL
);
2402 if(itr
->second
.end
> curTime
)
2403 cooldown
= (itr
->second
.end
-curTime
)*1000;
2405 data
<< uint16(itr
->second
.itemid
); // cast item id
2406 data
<< uint16(sEntry
->Category
); // spell category
2407 if(sEntry
->Category
) // may be wrong, but anyway better than nothing...
2409 data
<< uint32(0); // cooldown
2410 data
<< uint32(cooldown
); // category cooldown
2414 data
<< uint32(cooldown
); // cooldown
2415 data
<< uint32(0); // category cooldown
2419 GetSession()->SendPacket(&data
);
2421 sLog
.outDetail( "CHARACTER: Sent Initial Spells" );
2424 void Player::RemoveMail(uint32 id
)
2426 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
2428 if ((*itr
)->messageID
== id
)
2430 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2437 void Player::SendMailResult(uint32 mailId
, uint32 mailAction
, uint32 mailError
, uint32 equipError
, uint32 item_guid
, uint32 item_count
)
2439 WorldPacket
data(SMSG_SEND_MAIL_RESULT
, (4+4+4+(mailError
== MAIL_ERR_BAG_FULL
?4:(mailAction
== MAIL_ITEM_TAKEN
?4+4:0))));
2440 data
<< (uint32
) mailId
;
2441 data
<< (uint32
) mailAction
;
2442 data
<< (uint32
) mailError
;
2443 if ( mailError
== MAIL_ERR_BAG_FULL
)
2444 data
<< (uint32
) equipError
;
2445 else if( mailAction
== MAIL_ITEM_TAKEN
)
2447 data
<< (uint32
) item_guid
; // item guid low?
2448 data
<< (uint32
) item_count
; // item count?
2450 GetSession()->SendPacket(&data
);
2453 void Player::SendNewMail()
2455 // deliver undelivered mail
2456 WorldPacket
data(SMSG_RECEIVED_MAIL
, 4);
2458 GetSession()->SendPacket(&data
);
2461 void Player::UpdateNextMailTimeAndUnreads()
2463 // calculate next delivery time (min. from non-delivered mails
2464 // and recalculate unReadMail
2465 time_t cTime
= time(NULL
);
2466 m_nextMailDelivereTime
= 0;
2468 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
2470 if((*itr
)->deliver_time
> cTime
)
2472 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> (*itr
)->deliver_time
)
2473 m_nextMailDelivereTime
= (*itr
)->deliver_time
;
2475 else if(((*itr
)->checked
& MAIL_CHECK_MASK_READ
) == 0)
2480 void Player::AddNewMailDeliverTime(time_t deliver_time
)
2482 if(deliver_time
<= time(NULL
)) // ready now
2487 else // not ready and no have ready mails
2489 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> deliver_time
)
2490 m_nextMailDelivereTime
= deliver_time
;
2494 bool Player::addSpell(uint32 spell_id
, bool active
, bool learning
, bool loading
, uint16 slot_id
, bool disabled
)
2496 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
2499 // do character spell book cleanup (all characters)
2500 if(loading
&& !learning
) // spell load case
2502 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id
);
2503 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2506 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id
);
2511 if(!SpellMgr::IsSpellValid(spellInfo
,this,false))
2513 // do character spell book cleanup (all characters)
2514 if(loading
&& !learning
) // spell load case
2516 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id
);
2517 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2520 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id
);
2525 PlayerSpellState state
= learning
? PLAYERSPELL_NEW
: PLAYERSPELL_UNCHANGED
;
2527 bool disabled_case
= false;
2528 bool superceded_old
= false;
2530 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2531 if (itr
!= m_spells
.end())
2533 // update active state for known spell
2534 if(itr
->second
->active
!= active
&& itr
->second
->state
!= PLAYERSPELL_REMOVED
&& !itr
->second
->disabled
)
2536 itr
->second
->active
= active
;
2538 // loading && !learning == explicitly load from DB and then exist in it already and set correctly
2539 if(loading
&& !learning
)
2540 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2541 else if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2542 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2546 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
2547 data
<< uint16(spell_id
);
2548 GetSession()->SendPacket(&data
);
2550 return active
; // learn (show in spell book if active now)
2553 if(itr
->second
->disabled
!= disabled
&& itr
->second
->state
!= PLAYERSPELL_REMOVED
)
2555 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2556 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2557 itr
->second
->disabled
= disabled
;
2562 disabled_case
= true;
2564 else switch(itr
->second
->state
)
2566 case PLAYERSPELL_UNCHANGED
: // known saved spell
2568 case PLAYERSPELL_REMOVED
: // re-learning removed not saved spell
2571 m_spells
.erase(itr
);
2572 state
= PLAYERSPELL_CHANGED
;
2573 break; // need re-add
2575 default: // known not saved yet spell (new or modified)
2577 // can be in case spell loading but learned at some previous spell loading
2578 if(loading
&& !learning
)
2579 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2586 if(!disabled_case
) // skip new spell adding if spell already known (disabled spells case)
2588 // talent: unlearn all other talent ranks (high and low)
2589 if(TalentSpellPos
const* talentPos
= GetTalentSpellPos(spell_id
))
2591 if(TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry( talentPos
->talent_id
))
2593 for(int i
=0; i
<5; ++i
)
2595 // skip learning spell and no rank spell case
2596 uint32 rankSpellId
= talentInfo
->RankID
[i
];
2597 if(!rankSpellId
|| rankSpellId
==spell_id
)
2600 // skip unknown ranks
2601 if(!HasSpell(rankSpellId
))
2604 removeSpell(rankSpellId
);
2608 // non talent spell: learn low ranks (recursive call)
2609 else if(uint32 prev_spell
= spellmgr
.GetPrevSpellInChain(spell_id
))
2611 if(loading
) // at spells loading, no output, but allow save
2612 addSpell(prev_spell
,active
,true,loading
,SPELL_WITHOUT_SLOT_ID
,disabled
);
2613 else // at normal learning
2614 learnSpell(prev_spell
);
2617 PlayerSpell
*newspell
= new PlayerSpell
;
2618 newspell
->active
= active
;
2619 newspell
->state
= state
;
2620 newspell
->disabled
= disabled
;
2622 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2623 if(newspell
->active
&& !newspell
->disabled
&& !SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
2625 for( PlayerSpellMap::iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2627 if(itr
->second
->state
== PLAYERSPELL_REMOVED
) continue;
2628 SpellEntry
const *i_spellInfo
= sSpellStore
.LookupEntry(itr
->first
);
2629 if(!i_spellInfo
) continue;
2631 if( spellmgr
.IsRankSpellDueToSpell(spellInfo
,itr
->first
) )
2633 if(itr
->second
->active
)
2635 if(spellmgr
.IsHighRankOfSpell(spell_id
,itr
->first
))
2637 if(!loading
) // not send spell (re-/over-)learn packets at loading
2639 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2640 data
<< uint16(itr
->first
);
2641 data
<< uint16(spell_id
);
2642 GetSession()->SendPacket( &data
);
2645 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2646 itr
->second
->active
= false;
2647 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2648 superceded_old
= true; // new spell replace old in action bars and spell book.
2650 else if(spellmgr
.IsHighRankOfSpell(itr
->first
,spell_id
))
2652 if(!loading
) // not send spell (re-/over-)learn packets at loading
2654 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2655 data
<< uint16(spell_id
);
2656 data
<< uint16(itr
->first
);
2657 GetSession()->SendPacket( &data
);
2660 // mark new spell as disable (not learned yet for client and will not learned)
2661 newspell
->active
= false;
2662 if(newspell
->state
!= PLAYERSPELL_NEW
)
2663 newspell
->state
= PLAYERSPELL_CHANGED
;
2670 uint16 tmpslot
=slot_id
;
2672 if (tmpslot
== SPELL_WITHOUT_SLOT_ID
)
2675 PlayerSpellMap::iterator itr
;
2676 for (itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2678 if(itr
->second
->state
== PLAYERSPELL_REMOVED
)
2680 if (itr
->second
->slotId
> maxid
)
2681 maxid
= itr
->second
->slotId
;
2683 tmpslot
= maxid
+ 1;
2686 newspell
->slotId
= tmpslot
;
2687 m_spells
[spell_id
] = newspell
;
2689 // return false if spell disabled
2690 if (newspell
->disabled
)
2694 uint32 talentCost
= GetTalentSpellCost(spell_id
);
2696 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2697 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2698 if( talentCost
> 0 && IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_LEARN_SPELL
) )
2700 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2701 CastSpell(this, spell_id
, true);
2703 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2704 else if (IsPassiveSpell(spell_id
))
2706 // if spell doesn't require a stance or the player is in the required stance
2707 if( ( !spellInfo
->Stances
&&
2708 spell_id
!= 5420 && spell_id
!= 5419 && spell_id
!= 7376 &&
2709 spell_id
!= 7381 && spell_id
!= 21156 && spell_id
!= 21009 &&
2710 spell_id
!= 21178 && spell_id
!= 33948 && spell_id
!= 40121 ) ||
2711 m_form
!= 0 && (spellInfo
->Stances
& (1<<(m_form
-1))) ||
2712 (spell_id
== 5420 && m_form
== FORM_TREE
) ||
2713 (spell_id
== 5419 && m_form
== FORM_TRAVEL
) ||
2714 (spell_id
== 7376 && m_form
== FORM_DEFENSIVESTANCE
) ||
2715 (spell_id
== 7381 && m_form
== FORM_BERSERKERSTANCE
) ||
2716 (spell_id
== 21156 && m_form
== FORM_BATTLESTANCE
)||
2717 (spell_id
== 21178 && (m_form
== FORM_BEAR
|| m_form
== FORM_DIREBEAR
) ) ||
2718 (spell_id
== 33948 && m_form
== FORM_FLIGHT
) ||
2719 (spell_id
== 40121 && m_form
== FORM_FLIGHT_EPIC
) )
2720 //Check CasterAuraStates
2721 if (!spellInfo
->CasterAuraState
|| HasAuraState(AuraState(spellInfo
->CasterAuraState
)))
2722 CastSpell(this, spell_id
, true);
2724 else if( IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_SKILL_STEP
) )
2726 CastSpell(this, spell_id
, true);
2730 // update used talent points count
2731 m_usedTalentCount
+= talentCost
;
2733 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2734 if(uint32 freeProfs
= GetFreePrimaryProffesionPoints())
2736 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
2737 SetFreePrimaryProffesions(freeProfs
-1);
2740 // add dependent skills
2741 uint16 maxskill
= GetMaxSkillValueForLevel();
2743 SpellLearnSkillNode
const* spellLearnSkill
= spellmgr
.GetSpellLearnSkill(spell_id
);
2747 uint32 skill_value
= GetPureSkillValue(spellLearnSkill
->skill
);
2748 uint32 skill_max_value
= GetPureMaxSkillValue(spellLearnSkill
->skill
);
2750 if(skill_value
< spellLearnSkill
->value
)
2751 skill_value
= spellLearnSkill
->value
;
2753 uint32 new_skill_max_value
= spellLearnSkill
->maxvalue
== 0 ? maxskill
: spellLearnSkill
->maxvalue
;
2755 if(skill_max_value
< new_skill_max_value
)
2756 skill_max_value
= new_skill_max_value
;
2758 SetSkill(spellLearnSkill
->skill
,skill_value
,skill_max_value
);
2762 // not ranked skills
2763 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
2764 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
2766 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
2768 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
2772 if(HasSkill(pSkill
->id
))
2775 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
2776 // poison special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2777 pSkill
->id
==SKILL_POISONS
&& _spell_idx
->second
->max_value
==0 ||
2778 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2779 pSkill
->id
==SKILL_LOCKPICKING
&& _spell_idx
->second
->max_value
==0 )
2781 switch(GetSkillRangeType(pSkill
,_spell_idx
->second
->racemask
!=0))
2783 case SKILL_RANGE_LANGUAGE
:
2784 SetSkill(pSkill
->id
, 300, 300 );
2786 case SKILL_RANGE_LEVEL
:
2787 SetSkill(pSkill
->id
, 1, GetMaxSkillValueForLevel() );
2789 case SKILL_RANGE_MONO
:
2790 SetSkill(pSkill
->id
, 1, 1 );
2799 // learn dependent spells
2800 SpellLearnSpellMap::const_iterator spell_begin
= spellmgr
.GetBeginSpellLearnSpell(spell_id
);
2801 SpellLearnSpellMap::const_iterator spell_end
= spellmgr
.GetEndSpellLearnSpell(spell_id
);
2803 for(SpellLearnSpellMap::const_iterator itr
= spell_begin
; itr
!= spell_end
; ++itr
)
2805 if(!itr
->second
.autoLearned
)
2807 if(loading
) // at spells loading, no output, but allow save
2808 addSpell(itr
->second
.spell
,true,true,loading
);
2809 else // at normal learning
2810 learnSpell(itr
->second
.spell
);
2814 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2815 return active
&& !disabled
&& !superceded_old
;
2818 void Player::learnSpell(uint32 spell_id
)
2820 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2822 bool disabled
= (itr
!= m_spells
.end()) ? itr
->second
->disabled
: false;
2823 bool active
= disabled
? itr
->second
->active
: true;
2825 bool learning
= addSpell(spell_id
,active
);
2827 // learn all disabled higher ranks (recursive)
2828 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
2829 for(SpellChainMapNext::const_iterator i
= nextMap
.lower_bound(spell_id
); i
!= nextMap
.upper_bound(spell_id
); ++i
)
2831 PlayerSpellMap::iterator iter
= m_spells
.find(i
->second
);
2832 if (disabled
&& iter
!= m_spells
.end() && iter
->second
->disabled
)
2833 learnSpell(i
->second
);
2836 // prevent duplicated entires in spell book
2840 WorldPacket
data(SMSG_LEARNED_SPELL
, 4);
2841 data
<< uint32(spell_id
);
2842 GetSession()->SendPacket(&data
);
2845 void Player::removeSpell(uint32 spell_id
, bool disabled
)
2847 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2848 if (itr
== m_spells
.end())
2851 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| disabled
&& itr
->second
->disabled
)
2854 // unlearn non talent higher ranks (recursive)
2855 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
2856 for(SpellChainMapNext::const_iterator itr2
= nextMap
.lower_bound(spell_id
); itr2
!= nextMap
.upper_bound(spell_id
); ++itr2
)
2857 if(HasSpell(itr2
->second
) && !GetTalentSpellPos(itr2
->second
))
2858 removeSpell(itr2
->second
,disabled
);
2861 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
2862 data
<< uint16(spell_id
);
2863 GetSession()->SendPacket(&data
);
2867 itr
->second
->disabled
= disabled
;
2868 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2869 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2873 if(itr
->second
->state
== PLAYERSPELL_NEW
)
2876 m_spells
.erase(itr
);
2879 itr
->second
->state
= PLAYERSPELL_REMOVED
;
2882 RemoveAurasDueToSpell(spell_id
);
2885 if(PetAura
const* petSpell
= spellmgr
.GetPetAura(spell_id
))
2886 RemovePetAura(petSpell
);
2888 // free talent points
2889 uint32 talentCosts
= GetTalentSpellCost(spell_id
);
2892 if(talentCosts
< m_usedTalentCount
)
2893 m_usedTalentCount
-= talentCosts
;
2895 m_usedTalentCount
= 0;
2898 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
2899 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
2901 uint32 freeProfs
= GetFreePrimaryProffesionPoints()+1;
2902 if(freeProfs
<= sWorld
.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL
))
2903 SetFreePrimaryProffesions(freeProfs
);
2906 // remove dependent skill
2907 SpellLearnSkillNode
const* spellLearnSkill
= spellmgr
.GetSpellLearnSkill(spell_id
);
2910 uint32 prev_spell
= spellmgr
.GetPrevSpellInChain(spell_id
);
2911 if(!prev_spell
) // first rank, remove skill
2912 SetSkill(spellLearnSkill
->skill
,0,0);
2915 // search prev. skill setting by spell ranks chain
2916 SpellLearnSkillNode
const* prevSkill
= spellmgr
.GetSpellLearnSkill(prev_spell
);
2917 while(!prevSkill
&& prev_spell
)
2919 prev_spell
= spellmgr
.GetPrevSpellInChain(prev_spell
);
2920 prevSkill
= spellmgr
.GetSpellLearnSkill(spellmgr
.GetFirstSpellInChain(prev_spell
));
2923 if(!prevSkill
) // not found prev skill setting, remove skill
2924 SetSkill(spellLearnSkill
->skill
,0,0);
2925 else // set to prev. skill setting values
2927 uint32 skill_value
= GetPureSkillValue(prevSkill
->skill
);
2928 uint32 skill_max_value
= GetPureMaxSkillValue(prevSkill
->skill
);
2930 if(skill_value
> prevSkill
->value
)
2931 skill_value
= prevSkill
->value
;
2933 uint32 new_skill_max_value
= prevSkill
->maxvalue
== 0 ? GetMaxSkillValueForLevel() : prevSkill
->maxvalue
;
2935 if(skill_max_value
> new_skill_max_value
)
2936 skill_max_value
= new_skill_max_value
;
2938 SetSkill(prevSkill
->skill
,skill_value
,skill_max_value
);
2945 // not ranked skills
2946 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
2947 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
2949 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
2951 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
2955 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
2956 // poison special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2957 pSkill
->id
==SKILL_POISONS
&& _spell_idx
->second
->max_value
==0 ||
2958 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2959 pSkill
->id
==SKILL_LOCKPICKING
&& _spell_idx
->second
->max_value
==0 )
2961 // not reset skills for professions and racial abilities
2962 if( (pSkill
->categoryId
==SKILL_CATEGORY_SECONDARY
|| pSkill
->categoryId
==SKILL_CATEGORY_PROFESSION
) &&
2963 (IsProfessionSkill(pSkill
->id
) || _spell_idx
->second
->racemask
!=0) )
2966 SetSkill(pSkill
->id
, 0, 0 );
2971 // remove dependent spells
2972 SpellLearnSpellMap::const_iterator spell_begin
= spellmgr
.GetBeginSpellLearnSpell(spell_id
);
2973 SpellLearnSpellMap::const_iterator spell_end
= spellmgr
.GetEndSpellLearnSpell(spell_id
);
2975 for(SpellLearnSpellMap::const_iterator itr2
= spell_begin
; itr2
!= spell_end
; ++itr2
)
2976 removeSpell(itr2
->second
.spell
, disabled
);
2979 void Player::RemoveArenaSpellCooldowns()
2981 // remove cooldowns on spells that has < 15 min CD
2982 SpellCooldowns::iterator itr
, next
;
2983 // iterate spell cooldowns
2984 for(itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); itr
= next
)
2988 SpellEntry
const * entry
= sSpellStore
.LookupEntry(itr
->first
);
2989 // check if spellentry is present and if the cooldown is less than 15 mins
2991 entry
->RecoveryTime
<= 15 * MINUTE
* 1000 &&
2992 entry
->CategoryRecoveryTime
<= 15 * MINUTE
* 1000 )
2995 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, (4+8));
2996 data
<< uint32(itr
->first
);
2998 GetSession()->SendPacket(&data
);
3000 m_spellCooldowns
.erase(itr
);
3005 void Player::RemoveAllSpellCooldown()
3007 if(!m_spellCooldowns
.empty())
3009 for(SpellCooldowns::const_iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); ++itr
)
3011 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, (4+8));
3012 data
<< uint32(itr
->first
);
3013 data
<< uint64(GetGUID());
3014 GetSession()->SendPacket(&data
);
3016 m_spellCooldowns
.clear();
3020 void Player::_LoadSpellCooldowns(QueryResult
*result
)
3022 m_spellCooldowns
.clear();
3024 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3028 time_t curTime
= time(NULL
);
3032 Field
*fields
= result
->Fetch();
3034 uint32 spell_id
= fields
[0].GetUInt32();
3035 uint32 item_id
= fields
[1].GetUInt32();
3036 time_t db_time
= (time_t)fields
[2].GetUInt64();
3038 if(!sSpellStore
.LookupEntry(spell_id
))
3040 sLog
.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id
);
3044 // skip outdated cooldown
3045 if(db_time
<= curTime
)
3048 AddSpellCooldown(spell_id
, item_id
, db_time
);
3050 sLog
.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id
, item_id
, uint32(db_time
-curTime
));
3052 while( result
->NextRow() );
3058 void Player::_SaveSpellCooldowns()
3060 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3062 time_t curTime
= time(NULL
);
3064 // remove outdated and save active
3065 for(SpellCooldowns::iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end();)
3067 if(itr
->second
.end
<= curTime
)
3068 m_spellCooldowns
.erase(itr
++);
3071 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
));
3077 uint32
Player::resetTalentsCost() const
3079 // The first time reset costs 1 gold
3080 if(m_resetTalentsCost
< 1*GOLD
)
3083 else if(m_resetTalentsCost
< 5*GOLD
)
3085 // After that it increases in increments of 5 gold
3086 else if(m_resetTalentsCost
< 10*GOLD
)
3090 uint32 months
= (sWorld
.GetGameTime() - m_resetTalentsTime
)/MONTH
;
3093 // This cost will be reduced by a rate of 5 gold per month
3094 int32 new_cost
= int32(m_resetTalentsCost
) - 5*GOLD
*months
;
3095 // to a minimum of 10 gold.
3096 return (new_cost
< 10*GOLD
? 10*GOLD
: new_cost
);
3100 // After that it increases in increments of 5 gold
3101 int32 new_cost
= m_resetTalentsCost
+ 5*GOLD
;
3102 // until it hits a cap of 50 gold.
3103 if(new_cost
> 50*GOLD
)
3110 bool Player::resetTalents(bool no_cost
)
3112 // not need after this call
3113 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS
))
3115 m_atLoginFlags
= m_atLoginFlags
& ~AT_LOGIN_RESET_TALENTS
;
3116 CharacterDatabase
.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS
), GetGUIDLow());
3119 uint32 level
= getLevel();
3120 uint32 talentPointsForLevel
= level
< 10 ? 0 : uint32((level
-9)*sWorld
.getRate(RATE_TALENT
));
3122 if (m_usedTalentCount
== 0)
3124 SetFreeTalentPoints(talentPointsForLevel
);
3132 cost
= resetTalentsCost();
3134 if (GetMoney() < cost
)
3136 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, 0, 0, 0);
3141 for (unsigned int i
= 0; i
< sTalentStore
.GetNumRows(); i
++)
3143 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry(i
);
3145 if (!talentInfo
) continue;
3147 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentInfo
->TalentTab
);
3152 // unlearn only talents for character class
3153 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3154 // to prevent unexpected lost normal learned spell skip another class talents
3155 if( (getClassMask() & talentTabInfo
->ClassMask
) == 0 )
3158 for (int j
= 0; j
< 5; j
++)
3160 for(PlayerSpellMap::iterator itr
= GetSpellMap().begin(); itr
!= GetSpellMap().end();)
3162 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->second
->disabled
)
3168 // remove learned spells (all ranks)
3169 uint32 itrFirstId
= spellmgr
.GetFirstSpellInChain(itr
->first
);
3171 // unlearn if first rank is talent or learned by talent
3172 if (itrFirstId
== talentInfo
->RankID
[j
] || spellmgr
.IsSpellLearnToSpell(talentInfo
->RankID
[j
],itrFirstId
))
3174 removeSpell(itr
->first
,!IsPassiveSpell(itr
->first
));
3175 itr
= GetSpellMap().begin();
3184 SetFreeTalentPoints(talentPointsForLevel
);
3188 ModifyMoney(-(int32
)cost
);
3190 m_resetTalentsCost
= cost
;
3191 m_resetTalentsTime
= time(NULL
);
3194 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3195 RemovePet(NULL
,PET_SAVE_NOT_IN_SLOT
, true);
3200 bool Player::_removeSpell(uint16 spell_id
)
3202 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
3203 if (itr
!= m_spells
.end())
3206 m_spells
.erase(itr
);
3212 Mail
* Player::GetMail(uint32 id
)
3214 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
3216 if ((*itr
)->messageID
== id
)
3224 void Player::_SetCreateBits(UpdateMask
*updateMask
, Player
*target
) const
3228 Object::_SetCreateBits(updateMask
, target
);
3232 for(uint16 index
= 0; index
< m_valuesCount
; index
++)
3234 if(GetUInt32Value(index
) != 0 && updateVisualBits
.GetBit(index
))
3235 updateMask
->SetBit(index
);
3240 void Player::_SetUpdateBits(UpdateMask
*updateMask
, Player
*target
) const
3244 Object::_SetUpdateBits(updateMask
, target
);
3248 Object::_SetUpdateBits(updateMask
, target
);
3249 *updateMask
&= updateVisualBits
;
3253 void Player::InitVisibleBits()
3255 updateVisualBits
.SetCount(PLAYER_END
);
3257 // TODO: really implement OWNER_ONLY and GROUP_ONLY. Flags can be found in UpdateFields.h
3259 updateVisualBits
.SetBit(OBJECT_FIELD_GUID
);
3260 updateVisualBits
.SetBit(OBJECT_FIELD_TYPE
);
3261 updateVisualBits
.SetBit(OBJECT_FIELD_SCALE_X
);
3263 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
);
3264 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+1);
3266 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
);
3267 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+1);
3269 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
);
3270 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+1);
3272 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
);
3273 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+1);
3275 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
);
3276 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+1);
3278 updateVisualBits
.SetBit(UNIT_FIELD_HEALTH
);
3279 updateVisualBits
.SetBit(UNIT_FIELD_POWER1
);
3280 updateVisualBits
.SetBit(UNIT_FIELD_POWER2
);
3281 updateVisualBits
.SetBit(UNIT_FIELD_POWER3
);
3282 updateVisualBits
.SetBit(UNIT_FIELD_POWER4
);
3283 updateVisualBits
.SetBit(UNIT_FIELD_POWER5
);
3285 updateVisualBits
.SetBit(UNIT_FIELD_MAXHEALTH
);
3286 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER1
);
3287 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER2
);
3288 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER3
);
3289 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER4
);
3290 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER5
);
3292 updateVisualBits
.SetBit(UNIT_FIELD_LEVEL
);
3293 updateVisualBits
.SetBit(UNIT_FIELD_FACTIONTEMPLATE
);
3294 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_0
);
3295 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS
);
3296 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS_2
);
3297 for(uint16 i
= UNIT_FIELD_AURA
; i
< UNIT_FIELD_AURASTATE
; ++i
)
3298 updateVisualBits
.SetBit(i
);
3299 updateVisualBits
.SetBit(UNIT_FIELD_AURASTATE
);
3300 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
);
3301 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 1);
3302 updateVisualBits
.SetBit(UNIT_FIELD_BOUNDINGRADIUS
);
3303 updateVisualBits
.SetBit(UNIT_FIELD_COMBATREACH
);
3304 updateVisualBits
.SetBit(UNIT_FIELD_DISPLAYID
);
3305 updateVisualBits
.SetBit(UNIT_FIELD_NATIVEDISPLAYID
);
3306 updateVisualBits
.SetBit(UNIT_FIELD_MOUNTDISPLAYID
);
3307 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_1
);
3308 updateVisualBits
.SetBit(UNIT_FIELD_PETNUMBER
);
3309 updateVisualBits
.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP
);
3310 updateVisualBits
.SetBit(UNIT_DYNAMIC_FLAGS
);
3311 updateVisualBits
.SetBit(UNIT_CHANNEL_SPELL
);
3312 updateVisualBits
.SetBit(UNIT_MOD_CAST_SPEED
);
3313 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_2
);
3315 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
);
3316 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+1);
3317 updateVisualBits
.SetBit(PLAYER_FLAGS
);
3318 updateVisualBits
.SetBit(PLAYER_GUILDID
);
3319 updateVisualBits
.SetBit(PLAYER_GUILDRANK
);
3320 updateVisualBits
.SetBit(PLAYER_BYTES
);
3321 updateVisualBits
.SetBit(PLAYER_BYTES_2
);
3322 updateVisualBits
.SetBit(PLAYER_BYTES_3
);
3323 updateVisualBits
.SetBit(PLAYER_DUEL_TEAM
);
3324 updateVisualBits
.SetBit(PLAYER_GUILD_TIMESTAMP
);
3326 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3327 for(uint16 i
= PLAYER_QUEST_LOG_1_1
; i
< PLAYER_QUEST_LOG_25_2
; i
+=4)
3328 updateVisualBits
.SetBit(i
);
3330 //Players visible items are not inventory stuff
3331 //431) = 884 (0x374) = main weapon
3332 for(uint16 i
= 0; i
< EQUIPMENT_SLOT_END
; i
++)
3335 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (i
*MAX_VISIBLE_ITEM_OFFSET
) + 0);
3336 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (i
*MAX_VISIBLE_ITEM_OFFSET
) + 1);
3338 uint16 visual_base
= PLAYER_VISIBLE_ITEM_1_0
+ (i
*MAX_VISIBLE_ITEM_OFFSET
);
3341 updateVisualBits
.SetBit(visual_base
+ 0);
3343 // item enchantment IDs
3344 for(uint8 j
= 0; j
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++j
)
3345 updateVisualBits
.SetBit(visual_base
+ 1 + j
);
3347 // random properties
3348 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 0 + (i
*MAX_VISIBLE_ITEM_OFFSET
));
3349 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (i
*MAX_VISIBLE_ITEM_OFFSET
));
3352 updateVisualBits
.SetBit(PLAYER_CHOSEN_TITLE
);
3355 void Player::BuildCreateUpdateBlockForPlayer( UpdateData
*data
, Player
*target
) const
3357 for(int i
= 0; i
< EQUIPMENT_SLOT_END
; i
++)
3359 if(m_items
[i
] == NULL
)
3362 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3368 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
3370 if(m_items
[i
] == NULL
)
3373 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3375 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
3377 if(m_items
[i
] == NULL
)
3380 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3384 Unit::BuildCreateUpdateBlockForPlayer( data
, target
);
3387 void Player::DestroyForPlayer( Player
*target
) const
3389 Unit::DestroyForPlayer( target
);
3391 for(int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
3393 if(m_items
[i
] == NULL
)
3396 m_items
[i
]->DestroyForPlayer( target
);
3401 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
3403 if(m_items
[i
] == NULL
)
3406 m_items
[i
]->DestroyForPlayer( target
);
3408 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
3410 if(m_items
[i
] == NULL
)
3413 m_items
[i
]->DestroyForPlayer( target
);
3418 bool Player::HasSpell(uint32 spell
) const
3420 PlayerSpellMap::const_iterator itr
= m_spells
.find((uint16
)spell
);
3421 return (itr
!= m_spells
.end() && itr
->second
->state
!= PLAYERSPELL_REMOVED
&& !itr
->second
->disabled
);
3424 TrainerSpellState
Player::GetTrainerSpellState(TrainerSpell
const* trainer_spell
) const
3427 return TRAINER_SPELL_RED
;
3429 if (!trainer_spell
->spell
)
3430 return TRAINER_SPELL_RED
;
3433 if(HasSpell(trainer_spell
->spell
))
3434 return TRAINER_SPELL_GRAY
;
3436 // check race/class requirement
3437 if(!IsSpellFitByClassAndRace(trainer_spell
->spell
))
3438 return TRAINER_SPELL_RED
;
3440 // check level requirement
3441 if(getLevel() < trainer_spell
->reqlevel
)
3442 return TRAINER_SPELL_RED
;
3444 if(SpellChainNode
const* spell_chain
= spellmgr
.GetSpellChainNode(trainer_spell
->spell
))
3446 // check prev.rank requirement
3447 if(spell_chain
->prev
&& !HasSpell(spell_chain
->prev
))
3448 return TRAINER_SPELL_RED
;
3450 // check additional spell requirement
3451 if(spell_chain
->req
&& !HasSpell(spell_chain
->req
))
3452 return TRAINER_SPELL_RED
;
3455 // check skill requirement
3456 if(trainer_spell
->reqskill
&& GetBaseSkillValue(trainer_spell
->reqskill
) < trainer_spell
->reqskillvalue
)
3457 return TRAINER_SPELL_RED
;
3459 // exist, already checked at loading
3460 SpellEntry
const* spell
= sSpellStore
.LookupEntry(trainer_spell
->spell
);
3462 // secondary prof. or not prof. spell
3463 uint32 skill
= spell
->EffectMiscValue
[1];
3465 if(spell
->Effect
[1] != SPELL_EFFECT_SKILL
|| !IsPrimaryProfessionSkill(skill
))
3466 return TRAINER_SPELL_GREEN
;
3468 // check primary prof. limit
3469 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell
->Id
) && GetFreePrimaryProffesionPoints() == 0)
3470 return TRAINER_SPELL_RED
;
3472 return TRAINER_SPELL_GREEN
;
3475 void Player::DeleteFromDB(uint64 playerguid
, uint32 accountId
, bool updateRealmChars
)
3477 uint32 guid
= GUID_LOPART(playerguid
);
3479 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3480 // bones will be deleted by corpse/bones deleting thread shortly
3481 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid
);
3483 // remove from guild
3484 uint32 guildId
= GetGuildIdFromDB(playerguid
);
3487 Guild
* guild
= objmgr
.GetGuildById(guildId
);
3489 guild
->DelMember(guid
);
3492 // the player was uninvited already on logout so just remove from group
3493 QueryResult
*resultGroup
= CharacterDatabase
.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid
);
3496 uint64 leaderGuid
= MAKE_NEW_GUID((*resultGroup
)[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
3498 Group
* group
= objmgr
.GetGroupByLeader(leaderGuid
);
3501 RemoveFromGroup(group
, playerguid
);
3505 // remove signs from petitions (also remove petitions if owner);
3506 RemovePetitionsAndSigns(playerguid
, 10);
3508 // return back all mails with COD and Item 0 1 2 3 4 5 6
3509 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
);
3514 Field
*fields
= resultMail
->Fetch();
3516 uint32 mail_id
= fields
[0].GetUInt32();
3517 uint16 mailTemplateId
= fields
[1].GetUInt16();
3518 uint32 sender
= fields
[2].GetUInt32();
3519 std::string subject
= fields
[3].GetCppString();
3520 uint32 itemTextId
= fields
[4].GetUInt32();
3521 uint32 money
= fields
[5].GetUInt32();
3522 bool has_items
= fields
[6].GetBool();
3524 //we can return mail now
3525 //so firstly delete the old one
3526 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id
);
3531 QueryResult
*resultItems
= CharacterDatabase
.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", mail_id
);
3536 Field
*fields2
= resultItems
->Fetch();
3538 uint32 item_guidlow
= fields2
[0].GetUInt32();
3539 uint32 item_template
= fields2
[1].GetUInt32();
3541 ItemPrototype
const* itemProto
= objmgr
.GetItemPrototype(item_template
);
3544 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow
);
3548 Item
*pItem
= NewItemOrBag(itemProto
);
3549 if(!pItem
->LoadFromDB(item_guidlow
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
)))
3551 pItem
->FSetState(ITEM_REMOVED
);
3552 pItem
->SaveToDB(); // it also deletes item object !
3556 mi
.AddItem(item_guidlow
, item_template
, pItem
);
3558 while (resultItems
->NextRow());
3564 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id
);
3566 uint32 pl_account
= objmgr
.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
3568 WorldSession::SendReturnToSender(MAIL_NORMAL
, pl_account
, guid
, sender
, subject
, itemTextId
, &mi
, money
, mailTemplateId
);
3570 while (resultMail
->NextRow());
3575 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3576 // Get guids of character's pets, will deleted in transaction
3577 QueryResult
*resultPets
= CharacterDatabase
.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid
);
3579 // NOW we can finally clear other DB data related to character
3580 CharacterDatabase
.BeginTransaction();
3585 Field
*fields3
= resultPets
->Fetch();
3586 uint32 petguidlow
= fields3
[0].GetUInt32();
3587 Pet::DeleteFromDB(petguidlow
);
3588 } while (resultPets
->NextRow());
3592 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",guid
);
3593 CharacterDatabase
.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid
);
3594 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid
);
3595 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid
);
3596 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid
);
3597 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid
);
3598 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid
);
3599 CharacterDatabase
.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid
);
3600 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid
);
3601 CharacterDatabase
.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid
);
3602 CharacterDatabase
.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid
);
3603 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid
);
3604 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid
);
3605 CharacterDatabase
.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid
);
3606 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid
);
3607 CharacterDatabase
.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid
,guid
);
3608 CharacterDatabase
.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid
);
3609 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid
);
3610 CharacterDatabase
.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid
);
3611 CharacterDatabase
.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid
);
3612 CharacterDatabase
.CommitTransaction();
3614 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3615 if(updateRealmChars
) sWorld
.UpdateRealmCharCount(accountId
);
3618 void Player::SetMovement(PlayerMovementType pType
)
3623 case MOVE_ROOT
: data
.Initialize(SMSG_FORCE_MOVE_ROOT
, GetPackGUID().size()+4); break;
3624 case MOVE_UNROOT
: data
.Initialize(SMSG_FORCE_MOVE_UNROOT
, GetPackGUID().size()+4); break;
3625 case MOVE_WATER_WALK
: data
.Initialize(SMSG_MOVE_WATER_WALK
, GetPackGUID().size()+4); break;
3626 case MOVE_LAND_WALK
: data
.Initialize(SMSG_MOVE_LAND_WALK
, GetPackGUID().size()+4); break;
3628 sLog
.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType
);
3631 data
.append(GetPackGUID());
3633 GetSession()->SendPacket( &data
);
3637 - a resurrectable corpse must not be loaded for the player (only bones)
3638 - the player must be in world
3640 void Player::BuildPlayerRepop()
3642 if(getRace() == RACE_NIGHTELF
)
3643 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)
3644 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3646 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3647 // there must be SMSG.STOP_MIRROR_TIMER
3648 // there we must send 888 opcode
3650 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3653 sLog
.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3657 // create a corpse and place it at the player's location
3659 Corpse
*corpse
= GetCorpse();
3662 sLog
.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3665 GetMap()->Add(corpse
);
3667 // convert player body to ghost
3670 SetMovement(MOVE_WATER_WALK
);
3671 if(!GetSession()->isLogingOut())
3672 SetMovement(MOVE_UNROOT
);
3674 // BG - remove insignia related
3675 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_SKINNABLE
);
3677 SendCorpseReclaimDelay();
3679 // to prevent cheating
3680 corpse
->ResetGhostTime();
3682 StopMirrorTimers(); //disable timers(bars)
3684 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, (float)1.0); //see radius of death player?
3686 SetByteValue(UNIT_FIELD_BYTES_1
, 3, PLAYER_STATE_FLAG_ALWAYS_STAND
);
3689 void Player::SendDelayResponse(const uint32 ml_seconds
)
3691 //FIXME: is this delay time arg really need? 50msec by default in code
3692 WorldPacket
data( SMSG_QUERY_TIME_RESPONSE
, 4+4 );
3693 data
<< (uint32
)time(NULL
);
3695 GetSession()->SendPacket( &data
);
3698 void Player::ResurrectPlayer(float restore_percent
, bool applySickness
)
3700 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // remove spirit healer position
3705 GetSession()->SendPacket(&data
);
3707 // speed change, land walk
3709 // remove death flag + set aura
3710 SetByteValue(UNIT_FIELD_BYTES_1
, 3, 0x00);
3711 if(getRace() == RACE_NIGHTELF
)
3712 RemoveAurasDueToSpell(20584); // speed bonuses
3713 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3715 setDeathState(ALIVE
);
3717 SetMovement(MOVE_LAND_WALK
);
3718 SetMovement(MOVE_UNROOT
);
3722 // set health/powers (0- will be set in caller)
3723 if(restore_percent
>0.0f
)
3725 SetHealth(uint32(GetMaxHealth()*restore_percent
));
3726 SetPower(POWER_MANA
, uint32(GetMaxPower(POWER_MANA
)*restore_percent
));
3727 SetPower(POWER_RAGE
, 0);
3728 SetPower(POWER_ENERGY
, uint32(GetMaxPower(POWER_ENERGY
)*restore_percent
));
3731 // update visibility
3732 ObjectAccessor::UpdateVisibilityForPlayer(this);
3734 // some items limited to specific map
3735 DestroyZoneLimitedItem( true, GetZoneId());
3740 //Characters from level 1-10 are not affected by resurrection sickness.
3741 //Characters from level 11-19 will suffer from one minute of sickness
3742 //for each level they are above 10.
3743 //Characters level 20 and up suffer from ten minutes of sickness.
3744 int32 startLevel
= sWorld
.getConfig(CONFIG_DEATH_SICKNESS_LEVEL
);
3746 if(int32(getLevel()) >= startLevel
)
3748 // set resurrection sickness
3749 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,true);
3751 // not full duration
3752 if(int32(getLevel()) < startLevel
+9)
3754 int32 delta
= (int32(getLevel()) - startLevel
+ 1)*MINUTE
;
3756 for(int i
=0; i
< 3; ++i
)
3758 if(Aura
* Aur
= GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,i
))
3760 Aur
->SetAuraDuration(delta
*1000);
3761 Aur
->UpdateAuraDuration();
3768 void Player::KillPlayer()
3770 SetMovement(MOVE_ROOT
);
3772 StopMirrorTimers(); //disable timers(bars)
3774 setDeathState(CORPSE
);
3775 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
3777 SetFlag(UNIT_DYNAMIC_FLAGS
, 0x00);
3778 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, !sMapStore
.LookupEntry(GetMapId())->Instanceable());
3780 // 6 minutes until repop at graveyard
3781 m_deathTimer
= 6*MINUTE
*1000;
3783 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
3785 // don't create corpse at this moment, player might be falling
3787 // update visibility
3788 ObjectAccessor::UpdateObjectVisibility(this);
3791 void Player::CreateCorpse()
3793 // prevent existence 2 corpse for player
3796 uint32 _uf
, _pb
, _pb2
, _cfb1
, _cfb2
;
3798 Corpse
*corpse
= new Corpse( (m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
) ? CORPSE_RESURRECTABLE_PVP
: CORPSE_RESURRECTABLE_PVE
);
3801 if(!corpse
->Create(objmgr
.GenerateLowGuid(HIGHGUID_CORPSE
), this, GetMapId(), GetPositionX(),
3802 GetPositionY(), GetPositionZ(), GetOrientation()))
3808 _uf
= GetUInt32Value(UNIT_FIELD_BYTES_0
);
3809 _pb
= GetUInt32Value(PLAYER_BYTES
);
3810 _pb2
= GetUInt32Value(PLAYER_BYTES_2
);
3812 uint8 race
= (uint8
)(_uf
);
3813 uint8 skin
= (uint8
)(_pb
);
3814 uint8 face
= (uint8
)(_pb
>> 8);
3815 uint8 hairstyle
= (uint8
)(_pb
>> 16);
3816 uint8 haircolor
= (uint8
)(_pb
>> 24);
3817 uint8 facialhair
= (uint8
)(_pb2
);
3819 _cfb1
= ((0x00) | (race
<< 8) | (getGender() << 16) | (skin
<< 24));
3820 _cfb2
= ((face
) | (hairstyle
<< 8) | (haircolor
<< 16) | (facialhair
<< 24));
3822 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_1
, _cfb1
);
3823 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_2
, _cfb2
);
3825 uint32 flags
= CORPSE_FLAG_UNK2
;
3826 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
3827 flags
|= CORPSE_FLAG_HIDE_HELM
;
3828 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
3829 flags
|= CORPSE_FLAG_HIDE_CLOAK
;
3830 if(InBattleGround())
3831 flags
|= CORPSE_FLAG_LOOTABLE
; // to be able to remove insignia
3832 corpse
->SetUInt32Value( CORPSE_FIELD_FLAGS
, flags
);
3834 corpse
->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID
, GetNativeDisplayId() );
3836 corpse
->SetUInt32Value( CORPSE_FIELD_GUILD
, GetGuildId() );
3839 uint16 iIventoryType
;
3841 for (int i
= 0; i
< EQUIPMENT_SLOT_END
; i
++)
3845 iDisplayID
= m_items
[i
]->GetProto()->DisplayInfoID
;
3846 iIventoryType
= (uint16
)m_items
[i
]->GetProto()->InventoryType
;
3848 _cfi
= (uint16(iDisplayID
)) | (iIventoryType
)<< 24;
3849 corpse
->SetUInt32Value(CORPSE_FIELD_ITEM
+ i
,_cfi
);
3853 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
3854 const MapEntry
*entry
= sMapStore
.LookupEntry(corpse
->GetMapId());
3856 if(entry
->map_type
!= MAP_BATTLEGROUND
)
3859 // register for player, but not show
3860 ObjectAccessor::Instance().AddCorpse(corpse
);
3863 void Player::SpawnCorpseBones()
3865 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
3866 SaveToDB(); // prevent loading as ghost without corpse
3869 Corpse
* Player::GetCorpse() const
3871 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
3874 void Player::DurabilityLossAll(double percent
, bool inventory
)
3876 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
3877 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3878 DurabilityLoss(pItem
,percent
);
3882 // bags not have durability
3883 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3885 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
3886 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3887 DurabilityLoss(pItem
,percent
);
3889 // keys not have durability
3890 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3892 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
3893 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3894 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
3895 if(Item
* pItem
= GetItemByPos( i
, j
))
3896 DurabilityLoss(pItem
,percent
);
3900 void Player::DurabilityLoss(Item
* item
, double percent
)
3905 uint32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
3910 uint32 pDurabilityLoss
= uint32(pMaxDurability
*percent
);
3912 if(pDurabilityLoss
< 1 )
3913 pDurabilityLoss
= 1;
3915 DurabilityPointsLoss(item
,pDurabilityLoss
);
3918 void Player::DurabilityPointsLossAll(int32 points
, bool inventory
)
3920 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
3921 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3922 DurabilityPointsLoss(pItem
,points
);
3926 // bags not have durability
3927 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3929 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
3930 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3931 DurabilityPointsLoss(pItem
,points
);
3933 // keys not have durability
3934 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3936 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
3937 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
3938 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
3939 if(Item
* pItem
= GetItemByPos( i
, j
))
3940 DurabilityPointsLoss(pItem
,points
);
3944 void Player::DurabilityPointsLoss(Item
* item
, int32 points
)
3946 int32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
3947 int32 pOldDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
3948 int32 pNewDurability
= pOldDurability
- points
;
3950 if (pNewDurability
< 0)
3952 else if (pNewDurability
> pMaxDurability
)
3953 pNewDurability
= pMaxDurability
;
3955 if (pOldDurability
!= pNewDurability
)
3957 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
3958 if ( pNewDurability
== 0 && pOldDurability
> 0 && item
->IsEquipped())
3959 _ApplyItemMods(item
,item
->GetSlot(), false);
3961 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, pNewDurability
);
3963 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
3964 if ( pNewDurability
> 0 && pOldDurability
== 0 && item
->IsEquipped())
3965 _ApplyItemMods(item
,item
->GetSlot(), true);
3967 item
->SetState(ITEM_CHANGED
, this);
3971 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot
)
3973 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
))
3974 DurabilityPointsLoss(pItem
,1);
3977 uint32
Player::DurabilityRepairAll(bool cost
, float discountMod
, bool guildBank
)
3979 uint32 TotalCost
= 0;
3980 // equipped, backpack, bags itself
3981 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
3982 TotalCost
+= DurabilityRepair(( (INVENTORY_SLOT_BAG_0
<< 8) | i
),cost
,discountMod
, guildBank
);
3984 // bank, buyback and keys not repaired
3986 // items in inventory bags
3987 for(int j
= INVENTORY_SLOT_BAG_START
; j
< INVENTORY_SLOT_BAG_END
; j
++)
3988 for(int i
= 0; i
< MAX_BAG_SIZE
; i
++)
3989 TotalCost
+= DurabilityRepair(( (j
<< 8) | i
),cost
,discountMod
, guildBank
);
3993 uint32
Player::DurabilityRepair(uint16 pos
, bool cost
, float discountMod
, bool guildBank
)
3995 Item
* item
= GetItemByPos(pos
);
3997 uint32 TotalCost
= 0;
4001 uint32 maxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4005 uint32 curDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4009 uint32 LostDurability
= maxDurability
- curDurability
;
4010 if(LostDurability
>0)
4012 ItemPrototype
const *ditemProto
= item
->GetProto();
4014 DurabilityCostsEntry
const *dcost
= sDurabilityCostsStore
.LookupEntry(ditemProto
->ItemLevel
);
4017 sLog
.outError("ERROR: RepairDurability: Wrong item lvl %u", ditemProto
->ItemLevel
);
4021 uint32 dQualitymodEntryId
= (ditemProto
->Quality
+1)*2;
4022 DurabilityQualityEntry
const *dQualitymodEntry
= sDurabilityQualityStore
.LookupEntry(dQualitymodEntryId
);
4023 if(!dQualitymodEntry
)
4025 sLog
.outError("ERROR: RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId
);
4029 uint32 dmultiplier
= dcost
->multiplier
[ItemSubClassToDurabilityMultiplierId(ditemProto
->Class
,ditemProto
->SubClass
)];
4030 uint32 costs
= uint32(LostDurability
*dmultiplier
*double(dQualitymodEntry
->quality_mod
));
4032 costs
= uint32(costs
* discountMod
);
4034 if (costs
==0) //fix for ITEM_QUALITY_ARTIFACT
4039 if (GetGuildId()==0)
4041 DEBUG_LOG("You are not member of a guild");
4045 Guild
*pGuild
= objmgr
.GetGuildById(GetGuildId());
4049 if (!pGuild
->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR
))
4051 DEBUG_LOG("You do not have rights to withdraw for repairs");
4055 if (pGuild
->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs
)
4057 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4061 if (pGuild
->GetGuildBankMoney() < costs
)
4063 DEBUG_LOG("There is not enough money in bank");
4067 pGuild
->MemberMoneyWithdraw(costs
, GetGUIDLow());
4070 else if (GetMoney() < costs
)
4072 DEBUG_LOG("You do not have enough money");
4076 ModifyMoney( -int32(costs
) );
4080 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, maxDurability
);
4081 item
->SetState(ITEM_CHANGED
, this);
4083 // reapply mods for total broken and repaired item if equipped
4084 if(IsEquipmentPos(pos
) && !curDurability
)
4085 _ApplyItemMods(item
,pos
& 255, true);
4089 void Player::RepopAtGraveyard()
4091 // note: this can be called also when the player is alive
4092 // for example from WorldSession::HandleMovementOpcodes
4094 AreaTableEntry
const *zone
= GetAreaEntryByAreaID(GetAreaId());
4096 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4097 if(!isAlive() && zone
&& zone
->flags
& AREA_FLAG_NEED_FLY
|| GetTransport())
4099 ResurrectPlayer(0.5f
);
4103 WorldSafeLocsEntry
const *ClosestGrave
= NULL
;
4105 // Special handle for battleground maps
4106 BattleGround
*bg
= sBattleGroundMgr
.GetBattleGround(GetBattleGroundId());
4108 if(bg
&& (bg
->GetTypeID() == BATTLEGROUND_AB
|| bg
->GetTypeID() == BATTLEGROUND_EY
))
4109 ClosestGrave
= bg
->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetTeam());
4111 ClosestGrave
= objmgr
.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4113 // stop countdown until repop
4116 // if no grave found, stay at the current location
4117 // and don't show spirit healer location
4120 TeleportTo(ClosestGrave
->map_id
, ClosestGrave
->x
, ClosestGrave
->y
, ClosestGrave
->z
, GetOrientation());
4121 if(isDead()) // not send if alive, because it used in TeleportTo()
4123 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // show spirit healer position on minimap
4124 data
<< ClosestGrave
->map_id
;
4125 data
<< ClosestGrave
->x
;
4126 data
<< ClosestGrave
->y
;
4127 data
<< ClosestGrave
->z
;
4128 GetSession()->SendPacket(&data
);
4133 void Player::JoinedChannel(Channel
*c
)
4135 m_channels
.push_back(c
);
4138 void Player::LeftChannel(Channel
*c
)
4140 m_channels
.remove(c
);
4143 void Player::CleanupChannels()
4145 while(!m_channels
.empty())
4147 Channel
* ch
= *m_channels
.begin();
4148 m_channels
.erase(m_channels
.begin()); // remove from player's channel list
4149 ch
->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4150 if (ChannelMgr
* cMgr
= channelMgr(GetTeam()))
4151 cMgr
->LeftChannel(ch
->GetName()); // deleted channel if empty
4154 sLog
.outDebug("Player: channels cleaned up!");
4157 void Player::UpdateLocalChannels(uint32 newZone
)
4159 if(m_channels
.empty())
4162 AreaTableEntry
const* current_zone
= GetAreaEntryByAreaID(newZone
);
4166 ChannelMgr
* cMgr
= channelMgr(GetTeam());
4170 std::string current_zone_name
= current_zone
->area_name
[GetSession()->GetSessionDbcLocale()];
4172 for(JoinedChannelsList::iterator i
= m_channels
.begin(), next
; i
!= m_channels
.end(); i
= next
)
4176 // skip non built-in channels
4177 if(!(*i
)->IsConstant())
4180 ChatChannelsEntry
const* ch
= GetChannelEntryFor((*i
)->GetChannelId());
4184 if((ch
->flags
& 4) == 4) // global channel without zone name in pattern
4188 char new_channel_name_buf
[100];
4189 snprintf(new_channel_name_buf
,100,ch
->pattern
[m_session
->GetSessionDbcLocale()],current_zone_name
.c_str());
4190 Channel
* new_channel
= cMgr
->GetJoinChannel(new_channel_name_buf
,ch
->ChannelID
);
4192 if((*i
)!=new_channel
)
4194 new_channel
->Join(GetGUID(),""); // will output Changed Channel: N. Name
4196 // leave old channel
4197 (*i
)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4198 std::string name
= (*i
)->GetName(); // store name, (*i)erase in LeftChannel
4199 LeftChannel(*i
); // remove from player's channel list
4200 cMgr
->LeftChannel(name
); // delete if empty
4203 sLog
.outDebug("Player: channels cleaned up!");
4206 void Player::LeaveLFGChannel()
4208 for(JoinedChannelsList::iterator i
= m_channels
.begin(); i
!= m_channels
.end(); ++i
)
4212 (*i
)->Leave(GetGUID());
4218 void Player::UpdateDefense()
4220 uint32 defense_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_DEFENSE
);
4222 if(UpdateSkill(SKILL_DEFENSE
,defense_skill_gain
))
4224 // update dependent from defense skill part
4225 UpdateDefenseBonusesMod();
4229 void Player::HandleBaseModValue(BaseModGroup modGroup
, BaseModType modType
, float amount
, bool apply
)
4231 if(modGroup
>= BASEMOD_END
|| modType
>= MOD_END
)
4233 sLog
.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4242 m_auraBaseMod
[modGroup
][modType
] += apply
? amount
: -amount
;
4245 if(amount
<= -100.0f
)
4248 val
= (100.0f
+ amount
) / 100.0f
;
4249 m_auraBaseMod
[modGroup
][modType
] *= apply
? val
: (1.0f
/val
);
4253 if(!CanModifyStats())
4258 case CRIT_PERCENTAGE
: UpdateCritPercentage(BASE_ATTACK
); break;
4259 case RANGED_CRIT_PERCENTAGE
: UpdateCritPercentage(RANGED_ATTACK
); break;
4260 case OFFHAND_CRIT_PERCENTAGE
: UpdateCritPercentage(OFF_ATTACK
); break;
4261 case SHIELD_BLOCK_VALUE
: UpdateShieldBlockValue(); break;
4266 float Player::GetBaseModValue(BaseModGroup modGroup
, BaseModType modType
) const
4268 if(modGroup
>= BASEMOD_END
|| modType
> MOD_END
)
4270 sLog
.outError("ERROR: trial to access non existed BaseModGroup or wrong BaseModType!");
4274 if(modType
== PCT_MOD
&& m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4277 return m_auraBaseMod
[modGroup
][modType
];
4280 float Player::GetTotalBaseModValue(BaseModGroup modGroup
) const
4282 if(modGroup
>= BASEMOD_END
)
4284 sLog
.outError("ERROR: wrong BaseModGroup in GetTotalBaseModValue()!");
4288 if(m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4291 return m_auraBaseMod
[modGroup
][FLAT_MOD
] * m_auraBaseMod
[modGroup
][PCT_MOD
];
4294 uint32
Player::GetShieldBlockValue() const
4296 BaseModGroup modGroup
= SHIELD_BLOCK_VALUE
;
4298 float value
= GetTotalBaseModValue(modGroup
) + GetStat(STAT_STRENGTH
)/20 - 1;
4300 value
= (value
< 0) ? 0 : value
;
4302 return uint32(value
);
4305 float Player::GetMeleeCritFromAgility()
4307 uint32 level
= getLevel();
4308 uint32 pclass
= getClass();
4310 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4312 GtChanceToMeleeCritBaseEntry
const *critBase
= sGtChanceToMeleeCritBaseStore
.LookupEntry(pclass
-1);
4313 GtChanceToMeleeCritEntry
const *critRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4314 if (critBase
==NULL
|| critRatio
==NULL
)
4317 float crit
=critBase
->base
+ GetStat(STAT_AGILITY
)*critRatio
->ratio
;
4321 float Player::GetDodgeFromAgility()
4323 // Table for base dodge values
4324 float dodge_base
[MAX_CLASSES
] = {
4326 0.00652f
, // Paladin
4333 0.02011f
, // Warlock
4337 // Crit/agility to dodge/agility coefficient multipliers
4338 float crit_to_dodge
[MAX_CLASSES
] = {
4352 uint32 level
= getLevel();
4353 uint32 pclass
= getClass();
4355 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4357 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4358 GtChanceToMeleeCritEntry
const *dodgeRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4359 if (dodgeRatio
==NULL
|| pclass
> MAX_CLASSES
)
4362 float dodge
=dodge_base
[pclass
-1] + GetStat(STAT_AGILITY
) * dodgeRatio
->ratio
* crit_to_dodge
[pclass
-1];
4363 return dodge
*100.0f
;
4366 float Player::GetSpellCritFromIntellect()
4368 uint32 level
= getLevel();
4369 uint32 pclass
= getClass();
4371 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4373 GtChanceToSpellCritBaseEntry
const *critBase
= sGtChanceToSpellCritBaseStore
.LookupEntry(pclass
-1);
4374 GtChanceToSpellCritEntry
const *critRatio
= sGtChanceToSpellCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4375 if (critBase
==NULL
|| critRatio
==NULL
)
4378 float crit
=critBase
->base
+ GetStat(STAT_INTELLECT
)*critRatio
->ratio
;
4382 float Player::GetRatingCoefficient(CombatRating cr
) const
4384 uint32 level
= getLevel();
4386 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4388 GtCombatRatingsEntry
const *Rating
= sGtCombatRatingsStore
.LookupEntry(cr
*GT_MAX_LEVEL
+level
-1);
4390 return 1.0f
; // By default use minimum coefficient (not must be called)
4392 return Rating
->ratio
;
4395 float Player::GetRatingBonusValue(CombatRating cr
) const
4397 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
)) / GetRatingCoefficient(cr
);
4400 uint32
Player::GetMeleeCritDamageReduction(uint32 damage
) const
4402 float melee
= GetRatingBonusValue(CR_CRIT_TAKEN_MELEE
)*2.0f
;
4403 if (melee
>25.0f
) melee
= 25.0f
;
4404 return uint32 (melee
* damage
/100.0f
);
4407 uint32
Player::GetRangedCritDamageReduction(uint32 damage
) const
4409 float ranged
= GetRatingBonusValue(CR_CRIT_TAKEN_RANGED
)*2.0f
;
4410 if (ranged
>25.0f
) ranged
=25.0f
;
4411 return uint32 (ranged
* damage
/100.0f
);
4414 uint32
Player::GetSpellCritDamageReduction(uint32 damage
) const
4416 float spell
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
)*2.0f
;
4417 // In wow script resilience limited to 25%
4420 return uint32 (spell
* damage
/ 100.0f
);
4423 uint32
Player::GetDotDamageReduction(uint32 damage
) const
4425 float spellDot
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
);
4426 // Dot resilience not limited (limit it by 100%)
4427 if (spellDot
> 100.0f
)
4429 return uint32 (spellDot
* damage
/ 100.0f
);
4432 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType
) const
4437 return GetUInt32Value(PLAYER_EXPERTISE
) / 4.0f
;
4439 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE
) / 4.0f
;
4446 float Player::OCTRegenHPPerSpirit()
4448 uint32 level
= getLevel();
4449 uint32 pclass
= getClass();
4451 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4453 GtOCTRegenHPEntry
const *baseRatio
= sGtOCTRegenHPStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4454 GtRegenHPPerSptEntry
const *moreRatio
= sGtRegenHPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4455 if (baseRatio
==NULL
|| moreRatio
==NULL
)
4458 // Formula from PaperDollFrame script
4459 float spirit
= GetStat(STAT_SPIRIT
);
4460 float baseSpirit
= spirit
;
4461 if (baseSpirit
>50) baseSpirit
= 50;
4462 float moreSpirit
= spirit
- baseSpirit
;
4463 float regen
= baseSpirit
* baseRatio
->ratio
+ moreSpirit
* moreRatio
->ratio
;
4467 float Player::OCTRegenMPPerSpirit()
4469 uint32 level
= getLevel();
4470 uint32 pclass
= getClass();
4472 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4474 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4475 GtRegenMPPerSptEntry
const *moreRatio
= sGtRegenMPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4476 if (moreRatio
==NULL
)
4479 // Formula get from PaperDollFrame script
4480 float spirit
= GetStat(STAT_SPIRIT
);
4481 float regen
= spirit
* moreRatio
->ratio
;
4485 void Player::ApplyRatingMod(CombatRating cr
, int32 value
, bool apply
)
4487 ApplyModUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
, value
, apply
);
4489 float RatingCoeffecient
= GetRatingCoefficient(cr
);
4490 float RatingChange
= 0.0f
;
4492 bool affectStats
= CanModifyStats();
4496 case CR_WEAPON_SKILL
: // Implemented in Unit::RollMeleeOutcomeAgainst
4497 case CR_DEFENSE_SKILL
:
4498 UpdateDefenseBonusesMod();
4501 UpdateDodgePercentage();
4504 UpdateParryPercentage();
4507 UpdateBlockPercentage();
4510 RatingChange
= value
/ RatingCoeffecient
;
4511 m_modMeleeHitChance
+= apply
? RatingChange
: -RatingChange
;
4514 RatingChange
= value
/ RatingCoeffecient
;
4515 m_modRangedHitChance
+= apply
? RatingChange
: -RatingChange
;
4518 RatingChange
= value
/ RatingCoeffecient
;
4519 m_modSpellHitChance
+= apply
? RatingChange
: -RatingChange
;
4524 UpdateCritPercentage(BASE_ATTACK
);
4525 UpdateCritPercentage(OFF_ATTACK
);
4528 case CR_CRIT_RANGED
:
4530 UpdateCritPercentage(RANGED_ATTACK
);
4534 UpdateAllSpellCritChances();
4536 case CR_HIT_TAKEN_MELEE
: // Implemented in Unit::MeleeMissChanceCalc
4537 case CR_HIT_TAKEN_RANGED
:
4539 case CR_HIT_TAKEN_SPELL
: // Implemented in Unit::MagicSpellHitResult
4541 case CR_CRIT_TAKEN_MELEE
: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4542 case CR_CRIT_TAKEN_RANGED
:
4544 case CR_CRIT_TAKEN_SPELL
: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4546 case CR_HASTE_MELEE
:
4547 RatingChange
= value
/ RatingCoeffecient
;
4548 ApplyAttackTimePercentMod(BASE_ATTACK
,RatingChange
,apply
);
4549 ApplyAttackTimePercentMod(OFF_ATTACK
,RatingChange
,apply
);
4551 case CR_HASTE_RANGED
:
4552 RatingChange
= value
/ RatingCoeffecient
;
4553 ApplyAttackTimePercentMod(RANGED_ATTACK
, RatingChange
, apply
);
4555 case CR_HASTE_SPELL
:
4556 RatingChange
= value
/ RatingCoeffecient
;
4557 ApplyCastTimePercentMod(RatingChange
,apply
);
4559 case CR_WEAPON_SKILL_MAINHAND
: // Implemented in Unit::RollMeleeOutcomeAgainst
4560 case CR_WEAPON_SKILL_OFFHAND
:
4561 case CR_WEAPON_SKILL_RANGED
:
4566 UpdateExpertise(BASE_ATTACK
);
4567 UpdateExpertise(OFF_ATTACK
);
4573 void Player::SetRegularAttackTime()
4575 for(int i
= 0; i
< MAX_ATTACK
; ++i
)
4577 Item
*tmpitem
= GetWeaponForAttack(WeaponAttackType(i
));
4578 if(tmpitem
&& !tmpitem
->IsBroken())
4580 ItemPrototype
const *proto
= tmpitem
->GetProto();
4582 SetAttackTime(WeaponAttackType(i
), proto
->Delay
);
4584 SetAttackTime(WeaponAttackType(i
), BASE_ATTACK_TIME
);
4589 //skill+step, checking for max value
4590 bool Player::UpdateSkill(uint32 skill_id
, uint32 step
)
4596 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4597 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill_id
)
4600 if(i
>=PLAYER_MAX_SKILLS
)
4603 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4604 uint32 value
= SKILL_VALUE(data
);
4605 uint32 max
= SKILL_MAX(data
);
4607 if ((!max
) || (!value
) || (value
>= max
))
4610 if (value
*512 < max
*urand(0,512))
4612 uint32 new_value
= value
+step
;
4616 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,max
));
4623 inline int SkillGainChance(uint32 SkillValue
, uint32 GrayLevel
, uint32 GreenLevel
, uint32 YellowLevel
)
4625 if ( SkillValue
>= GrayLevel
)
4626 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREY
)*10;
4627 if ( SkillValue
>= GreenLevel
)
4628 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREEN
)*10;
4629 if ( SkillValue
>= YellowLevel
)
4630 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_YELLOW
)*10;
4631 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_ORANGE
)*10;
4634 bool Player::UpdateCraftSkill(uint32 spellid
)
4636 sLog
.outDebug("UpdateCraftSkill spellid %d", spellid
);
4638 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spellid
);
4639 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spellid
);
4641 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
4643 if(_spell_idx
->second
->skillId
)
4645 uint32 SkillValue
= GetPureSkillValue(_spell_idx
->second
->skillId
);
4647 // Alchemy Discoveries here
4648 SpellEntry
const* spellEntry
= sSpellStore
.LookupEntry(spellid
);
4649 if(spellEntry
&& spellEntry
->Mechanic
==MECHANIC_DISCOVERY
)
4651 if(uint32 discoveredSpell
= GetSkillDiscoverySpell(_spell_idx
->second
->skillId
, spellid
, this))
4652 learnSpell(discoveredSpell
);
4655 uint32 craft_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_CRAFTING
);
4657 return UpdateSkillPro(_spell_idx
->second
->skillId
, SkillGainChance(SkillValue
,
4658 _spell_idx
->second
->max_value
,
4659 (_spell_idx
->second
->max_value
+ _spell_idx
->second
->min_value
)/2,
4660 _spell_idx
->second
->min_value
),
4667 bool Player::UpdateGatherSkill(uint32 SkillId
, uint32 SkillValue
, uint32 RedLevel
, uint32 Multiplicator
)
4669 sLog
.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId
, SkillValue
, RedLevel
);
4671 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
4673 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4676 case SKILL_HERBALISM
:
4677 case SKILL_LOCKPICKING
:
4678 case SKILL_JEWELCRAFTING
:
4679 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4680 case SKILL_SKINNING
:
4681 if( sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)==0)
4682 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4684 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)), gathering_skill_gain
);
4686 if (sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)==0)
4687 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4689 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)),gathering_skill_gain
);
4694 bool Player::UpdateFishingSkill()
4696 sLog
.outDebug("UpdateFishingSkill");
4698 uint32 SkillValue
= GetPureSkillValue(SKILL_FISHING
);
4700 int32 chance
= SkillValue
< 75 ? 100 : 2500/(SkillValue
-50);
4702 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
4704 return UpdateSkillPro(SKILL_FISHING
,chance
*10,gathering_skill_gain
);
4707 bool Player::UpdateSkillPro(uint16 SkillId
, int32 Chance
, uint32 step
)
4709 sLog
.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId
, Chance
/10.0);
4713 if(Chance
<= 0) // speedup in 0 chance case
4715 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
4720 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4721 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i
))) == SkillId
) break;
4722 if ( i
>= PLAYER_MAX_SKILLS
)
4725 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4726 uint16 SkillValue
= SKILL_VALUE(data
);
4727 uint16 MaxValue
= SKILL_MAX(data
);
4729 if ( !MaxValue
|| !SkillValue
|| SkillValue
>= MaxValue
)
4732 int32 Roll
= irand(1,1000);
4734 if ( Roll
<= Chance
)
4736 uint32 new_value
= SkillValue
+step
;
4737 if(new_value
> MaxValue
)
4738 new_value
= MaxValue
;
4740 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,MaxValue
));
4741 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance
/10.0);
4745 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
4749 void Player::UpdateWeaponSkill (WeaponAttackType attType
)
4751 // no skill gain in pvp
4752 Unit
*pVictim
= getVictim();
4753 if(pVictim
&& pVictim
->GetTypeId() == TYPEID_PLAYER
)
4757 return; // always maximized SKILL_FERAL_COMBAT in fact
4759 if(m_form
== FORM_TREE
)
4760 return; // use weapon but not skill up
4762 uint32 weapon_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_WEAPON
);
4768 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
4771 UpdateSkill(SKILL_UNARMED
,weapon_skill_gain
);
4772 else if(tmpitem
->GetProto()->SubClass
!= ITEM_SUBCLASS_WEAPON_FISHING_POLE
)
4773 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
4779 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
4781 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
4785 UpdateAllCritPercentages();
4788 void Player::UpdateCombatSkills(Unit
*pVictim
, WeaponAttackType attType
, MeleeHitOutcome outcome
, bool defence
)
4792 case MELEE_HIT_CRIT
:
4793 case MELEE_HIT_DODGE
:
4794 case MELEE_HIT_PARRY
:
4795 case MELEE_HIT_BLOCK
:
4796 case MELEE_HIT_BLOCK_CRIT
:
4803 uint32 plevel
= getLevel(); // if defense than pVictim == attacker
4804 uint32 greylevel
= MaNGOS::XP::GetGrayLevel(plevel
);
4805 uint32 moblevel
= pVictim
->getLevelForTarget(this);
4806 if(moblevel
< greylevel
)
4809 if (moblevel
> plevel
+ 5)
4810 moblevel
= plevel
+ 5;
4812 uint32 lvldif
= moblevel
- greylevel
;
4816 uint32 skilldif
= 5 * plevel
- (defence
? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType
));
4820 float chance
= float(3 * lvldif
* skilldif
) / plevel
;
4823 if(getClass() == CLASS_WARRIOR
|| getClass() == CLASS_ROGUE
)
4824 chance
*= 0.1f
* GetStat(STAT_INTELLECT
);
4827 chance
= chance
< 1.0f
? 1.0f
: chance
; //minimum chance to increase skill is 1%
4829 if(roll_chance_f(chance
))
4834 UpdateWeaponSkill(attType
);
4840 void Player::ModifySkillBonus(uint32 skillid
,int32 val
, bool talent
)
4842 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4843 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skillid
)
4845 uint32 bonus_val
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
4846 int16 temp_bonus
= SKILL_TEMP_BONUS(bonus_val
);
4847 int16 perm_bonus
= SKILL_PERM_BONUS(bonus_val
);
4849 if(talent
) // permanent bonus stored in high part
4850 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
,perm_bonus
+val
));
4851 else // temporary/item bonus stored in low part
4852 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
+val
,perm_bonus
));
4857 void Player::UpdateSkillsForLevel()
4859 uint16 maxconfskill
= sWorld
.GetConfigMaxSkillValue();
4860 uint32 maxSkill
= GetMaxSkillValueForLevel();
4862 bool alwaysMaxSkill
= sWorld
.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL
);
4864 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4865 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
4867 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
4869 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(pskill
);
4873 if(GetSkillRangeType(pSkill
,false) != SKILL_RANGE_LEVEL
)
4876 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4877 uint32 max
= SKILL_MAX(data
);
4878 uint32 val
= SKILL_VALUE(data
);
4880 /// update only level dependent max skill values
4883 /// miximize skill always
4885 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(maxSkill
,maxSkill
));
4886 /// update max skill value if current max skill not maximized
4887 else if(max
!= maxconfskill
)
4888 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(val
,maxSkill
));
4893 void Player::UpdateSkillsToMaxSkillsForLevel()
4895 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4896 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
4898 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
4899 if( IsProfessionSkill(pskill
) || pskill
== SKILL_RIDING
)
4901 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4903 uint32 max
= SKILL_MAX(data
);
4906 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(max
,max
));
4908 if(pskill
== SKILL_DEFENSE
)
4909 UpdateDefenseBonusesMod();
4913 // This functions sets a skill line value (and adds if doesn't exist yet)
4914 // To "remove" a skill line, set it's values to zero
4915 void Player::SetSkill(uint32 id
, uint16 currVal
, uint16 maxVal
)
4921 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4922 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == id
) break;
4924 if(i
<PLAYER_MAX_SKILLS
) //has skill
4927 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
4930 // clear skill fields
4931 SetUInt32Value(PLAYER_SKILL_INDEX(i
),0);
4932 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),0);
4933 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
4935 // remove spells that depend on this skill when removing the skill
4936 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(), next
= m_spells
.begin(); itr
!= m_spells
.end(); itr
= next
)
4939 if(itr
->second
->state
== PLAYERSPELL_REMOVED
)
4942 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(itr
->first
);
4943 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(itr
->first
);
4945 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
4947 if (_spell_idx
->second
->skillId
== id
)
4949 // this may remove more than one spell (dependents)
4950 removeSpell(itr
->first
);
4951 next
= m_spells
.begin();
4958 else if(currVal
) //add
4960 for (i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
4961 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
4963 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
4966 sLog
.outError("Skill not found in SkillLineStore: skill #%u", id
);
4969 // enable unlearn button for primary professions only
4970 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
4971 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
4973 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
4974 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
4976 // apply skill bonuses
4977 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
4979 // temporary bonuses
4980 AuraList
const& mModSkill
= GetAurasByType(SPELL_AURA_MOD_SKILL
);
4981 for(AuraList::const_iterator i
= mModSkill
.begin(); i
!= mModSkill
.end(); ++i
)
4982 if ((*i
)->GetModifier()->m_miscvalue
== int32(id
))
4983 (*i
)->ApplyModifier(true);
4985 // permanent bonuses
4986 AuraList
const& mModSkillTalent
= GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT
);
4987 for(AuraList::const_iterator i
= mModSkillTalent
.begin(); i
!= mModSkillTalent
.end(); ++i
)
4988 if ((*i
)->GetModifier()->m_miscvalue
== int32(id
))
4989 (*i
)->ApplyModifier(true);
4991 // Learn all spells for skill
4992 learnSkillRewardedSpells(id
);
4998 bool Player::HasSkill(uint32 skill
) const
5000 if(!skill
)return false;
5001 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5003 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5011 uint16
Player::GetSkillValue(uint32 skill
) const
5016 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5018 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5020 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5022 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5023 result
+= SKILL_TEMP_BONUS(bonus
);
5024 result
+= SKILL_PERM_BONUS(bonus
);
5025 return result
< 0 ? 0 : result
;
5031 uint16
Player::GetMaxSkillValue(uint32 skill
) const
5034 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5036 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5038 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5040 int32 result
= int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5041 result
+= SKILL_TEMP_BONUS(bonus
);
5042 result
+= SKILL_PERM_BONUS(bonus
);
5043 return result
< 0 ? 0 : result
;
5049 uint16
Player::GetPureMaxSkillValue(uint32 skill
) const
5052 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5054 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5056 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5062 uint16
Player::GetBaseSkillValue(uint32 skill
) const
5065 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5067 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5069 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5070 result
+= SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5071 return result
< 0 ? 0 : result
;
5077 uint16
Player::GetPureSkillValue(uint32 skill
) const
5080 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5082 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5084 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5090 int16
Player::GetSkillTempBonusValue(uint32 skill
) const
5095 for (int i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
5097 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5099 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5106 void Player::SendInitialActionButtons()
5108 sLog
.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5110 WorldPacket
data(SMSG_ACTION_BUTTONS
, (MAX_ACTION_BUTTONS
*4));
5111 for(int button
= 0; button
< MAX_ACTION_BUTTONS
; ++button
)
5113 ActionButtonList::const_iterator itr
= m_actionButtons
.find(button
);
5114 if(itr
!= m_actionButtons
.end() && itr
->second
.uState
!= ACTIONBUTTON_DELETED
)
5116 data
<< uint16(itr
->second
.action
);
5117 data
<< uint8(itr
->second
.misc
);
5118 data
<< uint8(itr
->second
.type
);
5126 GetSession()->SendPacket( &data
);
5127 sLog
.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5130 void Player::addActionButton(const uint8 button
, const uint16 action
, const uint8 type
, const uint8 misc
)
5132 if(button
>= MAX_ACTION_BUTTONS
)
5134 sLog
.outError( "Action %u not added into button %u for player %s: button must be < 132", action
, button
, GetName() );
5138 // check cheating with adding non-known spells to action bar
5139 if(type
==ACTION_BUTTON_SPELL
)
5141 if(!sSpellStore
.LookupEntry(action
))
5143 sLog
.outError( "Action %u not added into button %u for player %s: spell not exist", action
, button
, GetName() );
5147 if(!HasSpell(action
))
5149 sLog
.outError( "Action %u not added into button %u for player %s: player don't known this spell", action
, button
, GetName() );
5154 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5156 if (buttonItr
==m_actionButtons
.end())
5157 { // just add new button
5158 m_actionButtons
[button
] = ActionButton(action
,type
,misc
);
5161 { // change state of current button
5162 ActionButtonUpdateState uState
= buttonItr
->second
.uState
;
5163 buttonItr
->second
= ActionButton(action
,type
,misc
);
5164 if (uState
!= ACTIONBUTTON_NEW
) buttonItr
->second
.uState
= ACTIONBUTTON_CHANGED
;
5167 sLog
.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action
, button
);
5170 void Player::removeActionButton(uint8 button
)
5172 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5173 if (buttonItr
==m_actionButtons
.end())
5176 if(buttonItr
->second
.uState
==ACTIONBUTTON_NEW
)
5177 m_actionButtons
.erase(buttonItr
); // new and not saved
5179 buttonItr
->second
.uState
= ACTIONBUTTON_DELETED
; // saved, will deleted at next save
5181 sLog
.outDetail( "Action Button '%u' Removed from Player '%u'", button
, GetGUIDLow() );
5184 void Player::SetDontMove(bool dontMove
)
5186 m_dontMove
= dontMove
;
5189 bool Player::SetPosition(float x
, float y
, float z
, float orientation
, bool teleport
)
5191 // prevent crash when a bad coord is sent by the client
5192 if(!MaNGOS::IsValidMapCoord(x
,y
,z
,orientation
))
5194 sLog
.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x
,y
,z
,orientation
,teleport
,GetGUIDLow());
5200 const float old_x
= GetPositionX();
5201 const float old_y
= GetPositionY();
5202 const float old_z
= GetPositionZ();
5203 const float old_r
= GetOrientation();
5205 if( teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
|| old_r
!= orientation
)
5207 if (teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
)
5208 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE
| AURA_INTERRUPT_FLAG_TURNING
);
5210 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING
);
5212 // move and update visible state if need
5213 m
->PlayerRelocation(this, x
, y
, z
, orientation
);
5215 // reread after Map::Relocation
5222 if(GetGroup() && (old_x
!= x
|| old_y
!= y
))
5223 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION
);
5226 // code block for underwater state update
5227 UpdateUnderwaterState(m
, x
, y
, z
);
5229 CheckExploreSystem();
5234 void Player::SaveRecallPosition()
5236 m_recallMap
= GetMapId();
5237 m_recallX
= GetPositionX();
5238 m_recallY
= GetPositionY();
5239 m_recallZ
= GetPositionZ();
5240 m_recallO
= GetOrientation();
5243 void Player::SendMessageToSet(WorldPacket
*data
, bool self
)
5245 GetMap()->MessageBroadcast(this, data
, self
);
5248 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
)
5250 GetMap()->MessageDistBroadcast(this, data
, dist
, self
);
5253 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
, bool own_team_only
)
5255 GetMap()->MessageDistBroadcast(this, data
, dist
, self
,own_team_only
);
5258 void Player::SendDirectMessage(WorldPacket
*data
)
5260 GetSession()->SendPacket(data
);
5263 void Player::CheckExploreSystem()
5271 uint16 areaFlag
=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY());
5272 if(areaFlag
==0xffff)
5274 int offset
= areaFlag
/ 32;
5278 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
);
5282 uint32 val
= (uint32
)(1 << (areaFlag
% 32));
5283 uint32 currFields
= GetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
);
5285 if( !(currFields
& val
) )
5287 SetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
, (uint32
)(currFields
| val
));
5289 AreaTableEntry
const *p
= GetAreaEntryByAreaFlagAndMap(areaFlag
,GetMapId());
5292 sLog
.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5294 else if(p
->area_level
> 0)
5296 uint32 area
= p
->ID
;
5297 if (getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
5299 SendExplorationExperience(area
,0);
5303 int32 diff
= int32(getLevel()) - p
->area_level
;
5307 XP
= uint32(objmgr
.GetBaseXP(getLevel()+5)*sWorld
.getRate(RATE_XP_EXPLORE
));
5311 int32 exploration_percent
= (100-((diff
-5)*5));
5312 if (exploration_percent
> 100)
5313 exploration_percent
= 100;
5314 else if (exploration_percent
< 0)
5315 exploration_percent
= 0;
5317 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*exploration_percent
/100*sWorld
.getRate(RATE_XP_EXPLORE
));
5321 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*sWorld
.getRate(RATE_XP_EXPLORE
));
5325 SendExplorationExperience(area
,XP
);
5327 sLog
.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area
);
5332 uint32
Player::TeamForRace(uint8 race
)
5334 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5337 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5341 switch(rEntry
->TeamID
)
5343 case 7: return ALLIANCE
;
5344 case 1: return HORDE
;
5347 sLog
.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race
),rEntry
->TeamID
);
5351 uint32
Player::getFactionForRace(uint8 race
)
5353 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5356 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5360 return rEntry
->FactionID
;
5363 void Player::setFactionForRace(uint8 race
)
5365 m_team
= TeamForRace(race
);
5366 setFaction( getFactionForRace(race
) );
5369 void Player::UpdateReputation() const
5371 sLog
.outDetail( "WORLD: Player::UpdateReputation" );
5373 for(FactionStateList::const_iterator itr
= m_factions
.begin(); itr
!= m_factions
.end(); ++itr
)
5375 SendFactionState(&(itr
->second
));
5379 void Player::SendFactionState(FactionState
const* faction
) const
5381 if(faction
->Flags
& FACTION_FLAG_VISIBLE
) //If faction is visible then update it
5383 WorldPacket
data(SMSG_SET_FACTION_STANDING
, (16)); // last check 2.4.0
5384 data
<< (float) 0; // unk 2.4.0
5385 data
<< (uint32
) 1; // count
5387 data
<< (uint32
) faction
->ReputationListID
;
5388 data
<< (uint32
) faction
->Standing
;
5390 GetSession()->SendPacket(&data
);
5394 void Player::SendInitialReputations()
5396 WorldPacket
data(SMSG_INITIALIZE_FACTIONS
, (4+128*5));
5397 data
<< uint32 (0x00000080);
5401 for (FactionStateList::const_iterator itr
= m_factions
.begin(); itr
!= m_factions
.end(); ++itr
)
5403 // fill in absent fields
5404 for (; a
!= itr
->first
; a
++)
5406 data
<< uint8 (0x00);
5407 data
<< uint32 (0x00000000);
5410 // fill in encountered data
5411 data
<< uint8 (itr
->second
.Flags
);
5412 data
<< uint32 (itr
->second
.Standing
);
5417 // fill in absent fields
5418 for (; a
!= 128; a
++)
5420 data
<< uint8 (0x00);
5421 data
<< uint32 (0x00000000);
5424 GetSession()->SendPacket(&data
);
5427 FactionState
const* Player::GetFactionState( FactionEntry
const* factionEntry
) const
5429 FactionStateList::const_iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5430 if (itr
!= m_factions
.end())
5431 return &itr
->second
;
5436 void Player::SetFactionAtWar(FactionState
* faction
, bool atWar
)
5438 // not allow declare war to own faction
5439 if(atWar
&& (faction
->Flags
& FACTION_FLAG_PEACE_FORCED
) )
5443 if(((faction
->Flags
& FACTION_FLAG_AT_WAR
) != 0) == atWar
)
5447 faction
->Flags
|= FACTION_FLAG_AT_WAR
;
5449 faction
->Flags
&= ~FACTION_FLAG_AT_WAR
;
5451 faction
->Changed
= true;
5454 void Player::SetFactionInactive(FactionState
* faction
, bool inactive
)
5456 // always invisible or hidden faction can't be inactive
5457 if(inactive
&& ((faction
->Flags
& (FACTION_FLAG_INVISIBLE_FORCED
|FACTION_FLAG_HIDDEN
)) || !(faction
->Flags
& FACTION_FLAG_VISIBLE
) ) )
5461 if(((faction
->Flags
& FACTION_FLAG_INACTIVE
) != 0) == inactive
)
5465 faction
->Flags
|= FACTION_FLAG_INACTIVE
;
5467 faction
->Flags
&= ~FACTION_FLAG_INACTIVE
;
5469 faction
->Changed
= true;
5472 void Player::SetFactionVisibleForFactionTemplateId(uint32 FactionTemplateId
)
5474 FactionTemplateEntry
const*factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5476 if(!factionTemplateEntry
)
5479 SetFactionVisibleForFactionId(factionTemplateEntry
->faction
);
5482 void Player::SetFactionVisibleForFactionId(uint32 FactionId
)
5484 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(FactionId
);
5488 if(factionEntry
->reputationListID
< 0)
5491 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5492 if (itr
== m_factions
.end())
5495 SetFactionVisible(&itr
->second
);
5498 void Player::SetFactionVisible(FactionState
* faction
)
5500 // always invisible or hidden faction can't be make visible
5501 if(faction
->Flags
& (FACTION_FLAG_INVISIBLE_FORCED
|FACTION_FLAG_HIDDEN
))
5505 if(faction
->Flags
& FACTION_FLAG_VISIBLE
)
5508 faction
->Flags
|= FACTION_FLAG_VISIBLE
;
5509 faction
->Changed
= true;
5511 if(!m_session
->PlayerLoading())
5513 // make faction visible in reputation list at client
5514 WorldPacket
data(SMSG_SET_FACTION_VISIBLE
, 4);
5515 data
<< faction
->ReputationListID
;
5516 GetSession()->SendPacket(&data
);
5520 void Player::SetInitialFactions()
5522 for(unsigned int i
= 1; i
< sFactionStore
.GetNumRows(); i
++)
5524 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(i
);
5526 if( factionEntry
&& (factionEntry
->reputationListID
>= 0))
5528 FactionState newFaction
;
5529 newFaction
.ID
= factionEntry
->ID
;
5530 newFaction
.ReputationListID
= factionEntry
->reputationListID
;
5531 newFaction
.Standing
= 0;
5532 newFaction
.Flags
= GetDefaultReputationFlags(factionEntry
);
5533 newFaction
.Changed
= true;
5535 m_factions
[newFaction
.ReputationListID
] = newFaction
;
5540 uint32
Player::GetDefaultReputationFlags(const FactionEntry
*factionEntry
) const
5545 uint32 raceMask
= getRaceMask();
5546 uint32 classMask
= getClassMask();
5547 for (int i
=0; i
< 4; i
++)
5549 if( (factionEntry
->BaseRepRaceMask
[i
] & raceMask
) &&
5550 (factionEntry
->BaseRepClassMask
[i
]==0 ||
5551 (factionEntry
->BaseRepClassMask
[i
] & classMask
) ) )
5552 return factionEntry
->ReputationFlags
[i
];
5557 int32
Player::GetBaseReputation(const FactionEntry
*factionEntry
) const
5562 uint32 raceMask
= getRaceMask();
5563 uint32 classMask
= getClassMask();
5564 for (int i
=0; i
< 4; i
++)
5566 if( (factionEntry
->BaseRepRaceMask
[i
] & raceMask
) &&
5567 (factionEntry
->BaseRepClassMask
[i
]==0 ||
5568 (factionEntry
->BaseRepClassMask
[i
] & classMask
) ) )
5569 return factionEntry
->BaseRepValue
[i
];
5572 // in faction.dbc exist factions with (RepListId >=0, listed in character reputation list) with all BaseRepRaceMask[i]==0
5576 int32
Player::GetReputation(uint32 faction_id
) const
5578 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(faction_id
);
5582 sLog
.outError("Player::GetReputation: Can't get reputation of %s for unknown faction (faction template id) #%u.",GetName(), faction_id
);
5586 return GetReputation(factionEntry
);
5589 int32
Player::GetReputation(const FactionEntry
*factionEntry
) const
5591 // Faction without recorded reputation. Just ignore.
5595 FactionStateList::const_iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5596 if (itr
!= m_factions
.end())
5597 return GetBaseReputation(factionEntry
) + itr
->second
.Standing
;
5602 ReputationRank
Player::GetReputationRank(uint32 faction
) const
5604 FactionEntry
const*factionEntry
= sFactionStore
.LookupEntry(faction
);
5606 return MIN_REPUTATION_RANK
;
5608 return GetReputationRank(factionEntry
);
5611 ReputationRank
Player::ReputationToRank(int32 standing
) const
5613 int32 Limit
= Reputation_Cap
+ 1;
5614 for (int i
= MAX_REPUTATION_RANK
-1; i
>= MIN_REPUTATION_RANK
; --i
)
5616 Limit
-= ReputationRank_Length
[i
];
5617 if (standing
>= Limit
)
5618 return ReputationRank(i
);
5620 return MIN_REPUTATION_RANK
;
5623 ReputationRank
Player::GetReputationRank(const FactionEntry
*factionEntry
) const
5625 int32 Reputation
= GetReputation(factionEntry
);
5626 return ReputationToRank(Reputation
);
5629 ReputationRank
Player::GetBaseReputationRank(const FactionEntry
*factionEntry
) const
5631 int32 Reputation
= GetBaseReputation(factionEntry
);
5632 return ReputationToRank(Reputation
);
5635 bool Player::ModifyFactionReputation(uint32 FactionTemplateId
, int32 DeltaReputation
)
5637 FactionTemplateEntry
const* factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5639 if(!factionTemplateEntry
)
5641 sLog
.outError("Player::ModifyFactionReputation: Can't update reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId
);
5645 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(factionTemplateEntry
->faction
);
5647 // Faction without recorded reputation. Just ignore.
5651 return ModifyFactionReputation(factionEntry
, DeltaReputation
);
5654 bool Player::ModifyFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5656 SimpleFactionsList
const* flist
= GetFactionTeamList(factionEntry
->ID
);
5660 for (SimpleFactionsList::const_iterator itr
= flist
->begin();itr
!= flist
->end();++itr
)
5662 FactionEntry
const *factionEntryCalc
= sFactionStore
.LookupEntry(*itr
);
5663 if(factionEntryCalc
)
5664 res
= ModifyOneFactionReputation(factionEntryCalc
, standing
);
5669 return ModifyOneFactionReputation(factionEntry
, standing
);
5672 bool Player::ModifyOneFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5674 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5675 if (itr
!= m_factions
.end())
5677 int32 BaseRep
= GetBaseReputation(factionEntry
);
5678 int32 new_rep
= BaseRep
+ itr
->second
.Standing
+ standing
;
5680 if (new_rep
> Reputation_Cap
)
5681 new_rep
= Reputation_Cap
;
5683 if (new_rep
< Reputation_Bottom
)
5684 new_rep
= Reputation_Bottom
;
5686 if(ReputationToRank(new_rep
) <= REP_HOSTILE
)
5687 SetFactionAtWar(&itr
->second
,true);
5689 itr
->second
.Standing
= new_rep
- BaseRep
;
5690 itr
->second
.Changed
= true;
5692 SetFactionVisible(&itr
->second
);
5694 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
5696 if(uint32 questid
= GetQuestSlotQuestId(i
))
5698 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
5699 if( qInfo
&& qInfo
->GetRepObjectiveFaction() == factionEntry
->ID
)
5701 QuestStatusData
& q_status
= mQuestStatus
[questid
];
5702 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
5704 if(GetReputation(factionEntry
) >= qInfo
->GetRepObjectiveValue())
5705 if ( CanCompleteQuest( questid
) )
5706 CompleteQuest( questid
);
5708 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
5710 if(GetReputation(factionEntry
) < qInfo
->GetRepObjectiveValue())
5711 IncompleteQuest( questid
);
5717 SendFactionState(&(itr
->second
));
5724 bool Player::SetFactionReputation(uint32 FactionTemplateId
, int32 standing
)
5726 FactionTemplateEntry
const* factionTemplateEntry
= sFactionTemplateStore
.LookupEntry(FactionTemplateId
);
5728 if(!factionTemplateEntry
)
5730 sLog
.outError("Player::SetFactionReputation: Can't set reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId
);
5734 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(factionTemplateEntry
->faction
);
5736 // Faction without recorded reputation. Just ignore.
5740 return SetFactionReputation(factionEntry
, standing
);
5743 bool Player::SetFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5745 SimpleFactionsList
const* flist
= GetFactionTeamList(factionEntry
->ID
);
5749 for (SimpleFactionsList::const_iterator itr
= flist
->begin();itr
!= flist
->end();++itr
)
5751 FactionEntry
const *factionEntryCalc
= sFactionStore
.LookupEntry(*itr
);
5752 if(factionEntryCalc
)
5753 res
= SetOneFactionReputation(factionEntryCalc
, standing
);
5758 return SetOneFactionReputation(factionEntry
, standing
);
5761 bool Player::SetOneFactionReputation(FactionEntry
const* factionEntry
, int32 standing
)
5763 FactionStateList::iterator itr
= m_factions
.find(factionEntry
->reputationListID
);
5764 if (itr
!= m_factions
.end())
5766 if (standing
> Reputation_Cap
)
5767 standing
= Reputation_Cap
;
5769 if (standing
< Reputation_Bottom
)
5770 standing
= Reputation_Bottom
;
5772 int32 BaseRep
= GetBaseReputation(factionEntry
);
5773 itr
->second
.Standing
= standing
- BaseRep
;
5774 itr
->second
.Changed
= true;
5776 SetFactionVisible(&itr
->second
);
5778 if(ReputationToRank(standing
) <= REP_HOSTILE
)
5779 SetFactionAtWar(&itr
->second
,true);
5781 SendFactionState(&(itr
->second
));
5787 //Calculate total reputation percent player gain with quest/creature level
5788 int32
Player::CalculateReputationGain(uint32 creatureOrQuestLevel
, int32 rep
, bool for_quest
)
5790 // for grey creature kill received 20%, in other case 100.
5791 int32 percent
= (!for_quest
&& (creatureOrQuestLevel
<= MaNGOS::XP::GetGrayLevel(getLevel()))) ? 20 : 100;
5793 int32 repMod
= GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN
);
5795 percent
+= rep
> 0 ? repMod
: -repMod
;
5800 return int32(sWorld
.getRate(RATE_REPUTATION_GAIN
)*rep
*percent
/100);
5803 //Calculates how many reputation points player gains in victim's enemy factions
5804 void Player::RewardReputation(Unit
*pVictim
, float rate
)
5806 if(!pVictim
|| pVictim
->GetTypeId() == TYPEID_PLAYER
)
5809 ReputationOnKillEntry
const* Rep
= objmgr
.GetReputationOnKilEntry(((Creature
*)pVictim
)->GetCreatureInfo()->Entry
);
5814 if(Rep
->repfaction1
&& (!Rep
->team_dependent
|| GetTeam()==ALLIANCE
))
5816 int32 donerep1
= CalculateReputationGain(pVictim
->getLevel(),Rep
->repvalue1
,false);
5817 donerep1
= int32(donerep1
*rate
);
5818 FactionEntry
const *factionEntry1
= sFactionStore
.LookupEntry(Rep
->repfaction1
);
5819 uint32 current_reputation_rank1
= GetReputationRank(factionEntry1
);
5820 if(factionEntry1
&& current_reputation_rank1
<= Rep
->reputation_max_cap1
)
5821 ModifyFactionReputation(factionEntry1
, donerep1
);
5823 // Wiki: Team factions value divided by 2
5824 if(Rep
->is_teamaward1
)
5826 FactionEntry
const *team1_factionEntry
= sFactionStore
.LookupEntry(factionEntry1
->team
);
5827 if(team1_factionEntry
)
5828 ModifyFactionReputation(team1_factionEntry
, donerep1
/ 2);
5832 if(Rep
->repfaction2
&& (!Rep
->team_dependent
|| GetTeam()==HORDE
))
5834 int32 donerep2
= CalculateReputationGain(pVictim
->getLevel(),Rep
->repvalue2
,false);
5835 donerep2
= int32(donerep2
*rate
);
5836 FactionEntry
const *factionEntry2
= sFactionStore
.LookupEntry(Rep
->repfaction2
);
5837 uint32 current_reputation_rank2
= GetReputationRank(factionEntry2
);
5838 if(factionEntry2
&& current_reputation_rank2
<= Rep
->reputation_max_cap2
)
5839 ModifyFactionReputation(factionEntry2
, donerep2
);
5841 // Wiki: Team factions value divided by 2
5842 if(Rep
->is_teamaward2
)
5844 FactionEntry
const *team2_factionEntry
= sFactionStore
.LookupEntry(factionEntry2
->team
);
5845 if(team2_factionEntry
)
5846 ModifyFactionReputation(team2_factionEntry
, donerep2
/ 2);
5851 //Calculate how many reputation points player gain with the quest
5852 void Player::RewardReputation(Quest
const *pQuest
)
5854 // quest reputation reward/loss
5855 for(int i
= 0; i
< QUEST_REPUTATIONS_COUNT
; ++i
)
5857 if(pQuest
->RewRepFaction
[i
] && pQuest
->RewRepValue
[i
] )
5859 int32 rep
= CalculateReputationGain(pQuest
->GetQuestLevel(),pQuest
->RewRepValue
[i
],true);
5860 FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(pQuest
->RewRepFaction
[i
]);
5862 ModifyFactionReputation(factionEntry
, rep
);
5866 // TODO: implement reputation spillover
5869 void Player::UpdateArenaFields(void)
5871 /* arena calcs go here */
5874 void Player::UpdateHonorFields()
5876 /// called when rewarding honor and at each save
5877 uint64 now
= time(NULL
);
5878 uint64 today
= uint64(time(NULL
) / DAY
) * DAY
;
5880 if(m_lastHonorUpdateTime
< today
)
5882 uint64 yesterday
= today
- DAY
;
5884 uint16 kills_today
= PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS
));
5886 // update yesterday's contribution
5887 if(m_lastHonorUpdateTime
>= yesterday
)
5889 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
));
5891 // this is the first update today, reset today's contribution
5892 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, 0);
5893 SetUInt32Value(PLAYER_FIELD_KILLS
, MAKE_PAIR32(0,kills_today
));
5897 // no honor/kills yesterday or today, reset
5898 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0);
5899 SetUInt32Value(PLAYER_FIELD_KILLS
, 0);
5903 m_lastHonorUpdateTime
= now
;
5906 ///Calculate the amount of honor gained based on the victim
5907 ///and the size of the group for which the honor is divided
5908 ///An exact honor value can also be given (overriding the calcs)
5909 bool Player::RewardHonor(Unit
*uVictim
, uint32 groupsize
, float honor
)
5911 // do not reward honor in arenas, but enable onkill spellproc
5914 if(!uVictim
|| uVictim
== this || uVictim
->GetTypeId() != TYPEID_PLAYER
)
5917 if( GetBGTeam() == ((Player
*)uVictim
)->GetBGTeam() )
5923 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5924 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE
))
5927 uint64 victim_guid
= 0;
5928 uint32 victim_rank
= 0;
5930 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5931 UpdateHonorFields();
5935 if(!uVictim
|| uVictim
== this || uVictim
->HasAuraType(SPELL_AURA_NO_PVP_CREDIT
))
5938 victim_guid
= uVictim
->GetGUID();
5940 if( uVictim
->GetTypeId() == TYPEID_PLAYER
)
5942 Player
*pVictim
= (Player
*)uVictim
;
5944 if( GetTeam() == pVictim
->GetTeam() && !sWorld
.IsFFAPvPRealm() )
5947 float f
= 1; //need for total kills (?? need more info)
5949 uint32 k_level
= getLevel();
5950 uint32 v_level
= pVictim
->getLevel();
5953 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
5955 // [1..14] Alliance honor titles and player name
5956 // [15..28] Horde honor titles and player name
5957 // [29..38] Other title and player name
5959 uint32 victim_title
= pVictim
->GetUInt32Value(PLAYER_CHOSEN_TITLE
);
5960 // Get Killer titles, CharTitlesEntry::bit_index
5962 // title[1..14] -> rank[5..18]
5963 // title[15..28] -> rank[5..18]
5964 // title[other] -> 0
5965 if (victim_title
== 0)
5966 victim_guid
= 0; // Don't show HK: <rank> message, only log.
5967 else if (victim_title
< 15)
5968 victim_rank
= victim_title
+ 4;
5969 else if (victim_title
< 29)
5970 victim_rank
= victim_title
- 14 + 4;
5972 victim_guid
= 0; // Don't show HK: <rank> message, only log.
5977 else if( k_level
<= 39 )
5978 k_grey
= k_level
- 5 - k_level
/10;
5980 k_grey
= k_level
- 1 - k_level
/5;
5985 float diff_level
= (k_level
== k_grey
) ? 1 : ((float(v_level
) - float(k_grey
)) / (float(k_level
) - float(k_grey
)));
5987 int32 v_rank
=1; //need more info
5989 honor
= ((f
* diff_level
* (190 + v_rank
*10))/6);
5990 honor
*= ((float)k_level
) / 70.0f
; //factor of dependence on levels of the killer
5992 // count the number of playerkills in one day
5993 ApplyModUInt32Value(PLAYER_FIELD_KILLS
, 1, true);
5994 // and those in a lifetime
5995 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 1, true);
5999 Creature
*cVictim
= (Creature
*)uVictim
;
6001 if (!cVictim
->isRacialLeader())
6004 honor
= 100; // ??? need more info
6005 victim_rank
= 19; // HK: Leader
6009 if (uVictim
!= NULL
)
6011 honor
*= sWorld
.getRate(RATE_HONOR
);
6016 honor
*= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6019 // honor - for show honor points in log
6020 // victim_guid - for show victim name in log
6021 // victim_rank [1..4] HK: <dishonored rank>
6022 // victim_rank [5..19] HK: <alliance\horde rank>
6023 // victim_rank [0,20+] HK: <>
6024 WorldPacket
data(SMSG_PVP_CREDIT
,4+8+4);
6025 data
<< (uint32
) honor
;
6026 data
<< (uint64
) victim_guid
;
6027 data
<< (uint32
) victim_rank
;
6029 GetSession()->SendPacket(&data
);
6032 ModifyHonorPoints(int32(honor
));
6034 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, uint32(honor
), true);
6038 void Player::ModifyHonorPoints( int32 value
)
6042 if (GetHonorPoints() > sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
))
6043 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) + value
);
6045 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() > uint32(-value
) ? GetHonorPoints() + value
: 0);
6048 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() < sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) - value
? GetHonorPoints() + value
: sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
));
6051 void Player::ModifyArenaPoints( int32 value
)
6055 if (GetArenaPoints() > sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
))
6056 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) + value
);
6058 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() > uint32(-value
) ? GetArenaPoints() + value
: 0);
6061 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() < sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) - value
? GetArenaPoints() + value
: sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
));
6064 uint32
Player::GetGuildIdFromDB(uint64 guid
)
6066 std::ostringstream ss
;
6067 ss
<<"SELECT guildid FROM guild_member WHERE guid='"<<guid
<<"'";
6068 QueryResult
*result
= CharacterDatabase
.Query( ss
.str().c_str() );
6071 uint32 v
= result
->Fetch()[0].GetUInt32();
6079 uint32
Player::GetRankFromDB(uint64 guid
)
6081 std::ostringstream ss
;
6082 ss
<<"SELECT rank FROM guild_member WHERE guid='"<<guid
<<"'";
6083 QueryResult
*result
= CharacterDatabase
.Query( ss
.str().c_str() );
6086 uint32 v
= result
->Fetch()[0].GetUInt32();
6094 uint32
Player::GetArenaTeamIdFromDB(uint64 guid
, uint8 type
)
6096 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid='%u' AND type='%u' LIMIT 1", GUID_LOPART(guid
), type
);
6100 uint32 id
= (*result
)[0].GetUInt32();
6105 uint32
Player::GetZoneIdFromDB(uint64 guid
)
6107 std::ostringstream ss
;
6109 ss
<<"SELECT zone FROM characters WHERE guid='"<<GUID_LOPART(guid
)<<"'";
6110 QueryResult
*result
= CharacterDatabase
.Query( ss
.str().c_str() );
6113 Field
* fields
= result
->Fetch();
6114 uint32 zone
= fields
[0].GetUInt32();
6119 // stored zone is zero, use generic and slow zone detection
6121 ss
<<"SELECT map,position_x,position_y FROM characters WHERE guid='"<<GUID_LOPART(guid
)<<"'";
6122 result
= CharacterDatabase
.Query(ss
.str().c_str());
6125 fields
= result
->Fetch();
6126 uint32 map
= fields
[0].GetUInt32();
6127 float posx
= fields
[1].GetFloat();
6128 float posy
= fields
[2].GetFloat();
6131 zone
= MapManager::Instance().GetZoneId(map
,posx
,posy
);
6134 ss
<< "UPDATE characters SET zone='"<<zone
<<"' WHERE guid='"<<GUID_LOPART(guid
)<<"'";
6135 CharacterDatabase
.Execute(ss
.str().c_str());
6141 void Player::UpdateArea(uint32 newArea
)
6143 // FFA_PVP flags are area and not zone id dependent
6144 // so apply them accordingly
6145 m_areaUpdateId
= newArea
;
6147 AreaTableEntry
const* area
= GetAreaEntryByAreaID(newArea
);
6149 if(area
&& (area
->flags
& AREA_FLAG_ARENA
))
6152 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_FFA_PVP
);
6156 // remove ffa flag only if not ffapvp realm
6157 // removal in sanctuaries and capitals is handled in zone update
6158 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_FFA_PVP
) && !sWorld
.IsFFAPvPRealm())
6159 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_FFA_PVP
);
6162 UpdateAreaDependentAuras(newArea
);
6165 void Player::UpdateZone(uint32 newZone
)
6167 m_zoneUpdateId
= newZone
;
6168 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
6170 // zone changed, so area changed as well, update it
6171 UpdateArea(GetAreaId());
6173 AreaTableEntry
const* zone
= GetAreaEntryByAreaID(newZone
);
6177 if (sWorld
.getConfig(CONFIG_WEATHER
))
6179 Weather
*wth
= sWorld
.FindWeather(zone
->ID
);
6182 wth
->SendWeatherUpdateToPlayer(this);
6186 if(!sWorld
.AddWeather(zone
->ID
))
6188 // send fine weather packet to remove old zone's weather
6189 Weather::SendFineWeatherUpdateToPlayer(this);
6194 pvpInfo
.inHostileArea
=
6195 GetTeam() == ALLIANCE
&& zone
->team
== AREATEAM_HORDE
||
6196 GetTeam() == HORDE
&& zone
->team
== AREATEAM_ALLY
||
6197 sWorld
.IsPvPRealm() && zone
->team
== AREATEAM_NONE
||
6198 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6200 if(pvpInfo
.inHostileArea
) // in hostile area
6202 if(!IsPvP() || pvpInfo
.endTimer
!= 0)
6203 UpdatePvP(true, true);
6205 else // in friendly area
6207 if(IsPvP() && !HasFlag(PLAYER_FLAGS
,PLAYER_FLAGS_IN_PVP
) && pvpInfo
.endTimer
== 0)
6208 pvpInfo
.endTimer
= time(0); // start toggle-off
6211 if(zone
->flags
& AREA_FLAG_SANCTUARY
) // in sanctuary
6213 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_SANCTUARY
);
6214 if(sWorld
.IsFFAPvPRealm())
6215 RemoveFlag(PLAYER_FLAGS
,PLAYER_FLAGS_FFA_PVP
);
6219 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_SANCTUARY
);
6222 if(zone
->flags
& AREA_FLAG_CAPITAL
) // in capital city
6224 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6225 SetRestType(REST_TYPE_IN_CITY
);
6226 InnEnter(time(0),GetMapId(),0,0,0);
6228 if(sWorld
.IsFFAPvPRealm())
6229 RemoveFlag(PLAYER_FLAGS
,PLAYER_FLAGS_FFA_PVP
);
6231 else // anywhere else
6233 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6235 if(GetRestType()==REST_TYPE_IN_TAVERN
) // has been in tavern. Is still in?
6237 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6239 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6240 SetRestType(REST_TYPE_NO
);
6242 if(sWorld
.IsFFAPvPRealm())
6243 SetFlag(PLAYER_FLAGS
,PLAYER_FLAGS_FFA_PVP
);
6246 else // not in tavern (leave city then)
6248 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6249 SetRestType(REST_TYPE_NO
);
6251 // Set player to FFA PVP when not in rested environment.
6252 if(sWorld
.IsFFAPvPRealm())
6253 SetFlag(PLAYER_FLAGS
,PLAYER_FLAGS_FFA_PVP
);
6258 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6259 // if player resurrected at teleport this will be applied in resurrect code
6261 DestroyZoneLimitedItem( true, newZone
);
6263 // recent client version not send leave/join channel packets for built-in local channels
6264 UpdateLocalChannels( newZone
);
6268 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE
);
6270 UpdateZoneDependentAuras(newZone
);
6273 //If players are too far way of duel flag... then player loose the duel
6274 void Player::CheckDuelDistance(time_t currTime
)
6279 uint64 duelFlagGUID
= GetUInt64Value(PLAYER_DUEL_ARBITER
);
6280 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, duelFlagGUID
);
6284 if(duel
->outOfBound
== 0)
6286 if(!IsWithinDistInMap(obj
, 50))
6288 duel
->outOfBound
= currTime
;
6290 WorldPacket
data(SMSG_DUEL_OUTOFBOUNDS
, 0);
6291 GetSession()->SendPacket(&data
);
6296 if(IsWithinDistInMap(obj
, 40))
6298 duel
->outOfBound
= 0;
6300 WorldPacket
data(SMSG_DUEL_INBOUNDS
, 0);
6301 GetSession()->SendPacket(&data
);
6303 else if(currTime
>= (duel
->outOfBound
+10))
6305 DuelComplete(DUEL_FLED
);
6310 void Player::DuelComplete(DuelCompleteType type
)
6312 // duel not requested
6316 WorldPacket
data(SMSG_DUEL_COMPLETE
, (1));
6317 data
<< (uint8
)((type
!= DUEL_INTERUPTED
) ? 1 : 0);
6318 GetSession()->SendPacket(&data
);
6319 duel
->opponent
->GetSession()->SendPacket(&data
);
6321 if(type
!= DUEL_INTERUPTED
)
6323 data
.Initialize(SMSG_DUEL_WINNER
, (1+20)); // we guess size
6324 data
<< (uint8
)((type
==DUEL_WON
) ? 0 : 1); // 0 = just won; 1 = fled
6325 data
<< duel
->opponent
->GetName();
6327 SendMessageToSet(&data
,true);
6330 // cool-down duel spell
6331 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6338 GetSession()->SendPacket(&data);
6339 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6340 data<<duel->opponent->GetGUID();
6344 duel->opponent->GetSession()->SendPacket(&data);*/
6346 //Remove Duel Flag object
6347 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER
));
6349 duel
->initiator
->RemoveGameObject(obj
,true);
6352 std::vector
<uint32
> auras2remove
;
6353 AuraMap
const& vAuras
= duel
->opponent
->GetAuras();
6354 for (AuraMap::const_iterator i
= vAuras
.begin(); i
!= vAuras
.end(); ++i
)
6356 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6357 auras2remove
.push_back(i
->second
->GetId());
6360 for(size_t i
=0; i
<auras2remove
.size(); i
++)
6361 duel
->opponent
->RemoveAurasDueToSpell(auras2remove
[i
]);
6363 auras2remove
.clear();
6364 AuraMap
const& auras
= GetAuras();
6365 for (AuraMap::const_iterator i
= auras
.begin(); i
!= auras
.end(); ++i
)
6367 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == duel
->opponent
->GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6368 auras2remove
.push_back(i
->second
->GetId());
6370 for(size_t i
=0; i
<auras2remove
.size(); i
++)
6371 RemoveAurasDueToSpell(auras2remove
[i
]);
6373 // cleanup combo points
6374 if(GetComboTarget()==duel
->opponent
->GetGUID())
6376 else if(GetComboTarget()==duel
->opponent
->GetPetGUID())
6379 if(duel
->opponent
->GetComboTarget()==GetGUID())
6380 duel
->opponent
->ClearComboPoints();
6381 else if(duel
->opponent
->GetComboTarget()==GetPetGUID())
6382 duel
->opponent
->ClearComboPoints();
6385 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6386 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6387 duel
->opponent
->SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6388 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6390 delete duel
->opponent
->duel
;
6391 duel
->opponent
->duel
= NULL
;
6396 //---------------------------------------------------------//
6398 void Player::_ApplyItemMods(Item
*item
, uint8 slot
,bool apply
)
6400 if(slot
>= INVENTORY_SLOT_BAG_END
|| !item
)
6403 // not apply/remove mods for broken item
6404 if(item
->IsBroken())
6407 ItemPrototype
const *proto
= item
->GetProto();
6412 sLog
.outDetail("applying mods for item %u ",item
->GetGUIDLow());
6414 uint32 attacktype
= Player::GetAttackBySlot(slot
);
6415 if(attacktype
< MAX_ATTACK
)
6416 _ApplyWeaponDependentAuraMods(item
,WeaponAttackType(attacktype
),apply
);
6418 _ApplyItemBonuses(proto
,slot
,apply
);
6420 if( slot
==EQUIPMENT_SLOT_RANGED
)
6421 _ApplyAmmoBonuses();
6423 ApplyItemEquipSpell(item
,apply
);
6424 ApplyEnchantment(item
, apply
);
6426 if(proto
->Socket
[0].Color
) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6427 CorrectMetaGemEnchants(slot
, apply
);
6429 sLog
.outDebug("_ApplyItemMods complete.");
6432 void Player::_ApplyItemBonuses(ItemPrototype
const *proto
,uint8 slot
,bool apply
)
6434 if(slot
>= INVENTORY_SLOT_BAG_END
|| !proto
)
6437 for (int i
= 0; i
< 10; i
++)
6439 float val
= float (proto
->ItemStat
[i
].ItemStatValue
);
6444 switch (proto
->ItemStat
[i
].ItemStatType
)
6447 HandleStatModifier(UNIT_MOD_MANA
, BASE_VALUE
, float(val
), apply
);
6449 case ITEM_MOD_HEALTH
: // modify HP
6450 HandleStatModifier(UNIT_MOD_HEALTH
, BASE_VALUE
, float(val
), apply
);
6452 case ITEM_MOD_AGILITY
: // modify agility
6453 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, BASE_VALUE
, float(val
), apply
);
6454 ApplyStatBuffMod(STAT_AGILITY
, float(val
), apply
);
6456 case ITEM_MOD_STRENGTH
: //modify strength
6457 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, BASE_VALUE
, float(val
), apply
);
6458 ApplyStatBuffMod(STAT_STRENGTH
, float(val
), apply
);
6460 case ITEM_MOD_INTELLECT
: //modify intellect
6461 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, BASE_VALUE
, float(val
), apply
);
6462 ApplyStatBuffMod(STAT_INTELLECT
, float(val
), apply
);
6464 case ITEM_MOD_SPIRIT
: //modify spirit
6465 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, BASE_VALUE
, float(val
), apply
);
6466 ApplyStatBuffMod(STAT_SPIRIT
, float(val
), apply
);
6468 case ITEM_MOD_STAMINA
: //modify stamina
6469 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, BASE_VALUE
, float(val
), apply
);
6470 ApplyStatBuffMod(STAT_STAMINA
, float(val
), apply
);
6472 case ITEM_MOD_DEFENSE_SKILL_RATING
:
6473 ApplyRatingMod(CR_DEFENSE_SKILL
, int32(val
), apply
);
6475 case ITEM_MOD_DODGE_RATING
:
6476 ApplyRatingMod(CR_DODGE
, int32(val
), apply
);
6478 case ITEM_MOD_PARRY_RATING
:
6479 ApplyRatingMod(CR_PARRY
, int32(val
), apply
);
6481 case ITEM_MOD_BLOCK_RATING
:
6482 ApplyRatingMod(CR_BLOCK
, int32(val
), apply
);
6484 case ITEM_MOD_HIT_MELEE_RATING
:
6485 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6487 case ITEM_MOD_HIT_RANGED_RATING
:
6488 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6490 case ITEM_MOD_HIT_SPELL_RATING
:
6491 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6493 case ITEM_MOD_CRIT_MELEE_RATING
:
6494 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6496 case ITEM_MOD_CRIT_RANGED_RATING
:
6497 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6499 case ITEM_MOD_CRIT_SPELL_RATING
:
6500 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6502 case ITEM_MOD_HIT_TAKEN_MELEE_RATING
:
6503 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6505 case ITEM_MOD_HIT_TAKEN_RANGED_RATING
:
6506 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6508 case ITEM_MOD_HIT_TAKEN_SPELL_RATING
:
6509 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6511 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING
:
6512 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6514 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING
:
6515 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6517 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING
:
6518 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6520 case ITEM_MOD_HASTE_MELEE_RATING
:
6521 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6523 case ITEM_MOD_HASTE_RANGED_RATING
:
6524 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6526 case ITEM_MOD_HASTE_SPELL_RATING
:
6527 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6529 case ITEM_MOD_HIT_RATING
:
6530 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6531 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6532 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6534 case ITEM_MOD_CRIT_RATING
:
6535 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6536 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6537 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6539 case ITEM_MOD_HIT_TAKEN_RATING
:
6540 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6541 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6542 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6544 case ITEM_MOD_CRIT_TAKEN_RATING
:
6545 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6546 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6547 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6549 case ITEM_MOD_RESILIENCE_RATING
:
6550 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6551 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6552 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6554 case ITEM_MOD_HASTE_RATING
:
6555 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6556 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6557 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6559 case ITEM_MOD_EXPERTISE_RATING
:
6560 ApplyRatingMod(CR_EXPERTISE
, int32(val
), apply
);
6566 HandleStatModifier(UNIT_MOD_ARMOR
, BASE_VALUE
, float(proto
->Armor
), apply
);
6569 HandleBaseModValue(SHIELD_BLOCK_VALUE
, FLAT_MOD
, float(proto
->Block
), apply
);
6572 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY
, BASE_VALUE
, float(proto
->HolyRes
), apply
);
6575 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE
, BASE_VALUE
, float(proto
->FireRes
), apply
);
6577 if (proto
->NatureRes
)
6578 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE
, BASE_VALUE
, float(proto
->NatureRes
), apply
);
6580 if (proto
->FrostRes
)
6581 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST
, BASE_VALUE
, float(proto
->FrostRes
), apply
);
6583 if (proto
->ShadowRes
)
6584 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW
, BASE_VALUE
, float(proto
->ShadowRes
), apply
);
6586 if (proto
->ArcaneRes
)
6587 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE
, BASE_VALUE
, float(proto
->ArcaneRes
), apply
);
6589 WeaponAttackType attType
= BASE_ATTACK
;
6590 float damage
= 0.0f
;
6592 if( slot
== EQUIPMENT_SLOT_RANGED
&& (
6593 proto
->InventoryType
== INVTYPE_RANGED
|| proto
->InventoryType
== INVTYPE_THROWN
||
6594 proto
->InventoryType
== INVTYPE_RANGEDRIGHT
))
6596 attType
= RANGED_ATTACK
;
6598 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6600 attType
= OFF_ATTACK
;
6603 if (proto
->Damage
[0].DamageMin
> 0 )
6605 damage
= apply
? proto
->Damage
[0].DamageMin
: BASE_MINDAMAGE
;
6606 SetBaseWeaponDamage(attType
, MINDAMAGE
, damage
);
6607 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6610 if (proto
->Damage
[0].DamageMax
> 0 )
6612 damage
= apply
? proto
->Damage
[0].DamageMax
: BASE_MAXDAMAGE
;
6613 SetBaseWeaponDamage(attType
, MAXDAMAGE
, damage
);
6616 if(!IsUseEquipedWeapon(slot
==EQUIPMENT_SLOT_MAINHAND
))
6621 if(slot
== EQUIPMENT_SLOT_RANGED
)
6622 SetAttackTime(RANGED_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6623 else if(slot
==EQUIPMENT_SLOT_MAINHAND
)
6624 SetAttackTime(BASE_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6625 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6626 SetAttackTime(OFF_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6629 if(CanModifyStats() && (damage
|| proto
->Delay
))
6630 UpdateDamagePhysical(attType
);
6633 void Player::_ApplyWeaponDependentAuraMods(Item
*item
,WeaponAttackType attackType
,bool apply
)
6635 AuraList
const& auraCritList
= GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT
);
6636 for(AuraList::const_iterator itr
= auraCritList
.begin(); itr
!=auraCritList
.end();++itr
)
6637 _ApplyWeaponDependentAuraCritMod(item
,attackType
,*itr
,apply
);
6639 AuraList
const& auraDamageFlatList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE
);
6640 for(AuraList::const_iterator itr
= auraDamageFlatList
.begin(); itr
!=auraDamageFlatList
.end();++itr
)
6641 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6643 AuraList
const& auraDamagePCTList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
);
6644 for(AuraList::const_iterator itr
= auraDamagePCTList
.begin(); itr
!=auraDamagePCTList
.end();++itr
)
6645 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6648 void Player::_ApplyWeaponDependentAuraCritMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6650 // generic not weapon specific case processes in aura code
6651 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6654 BaseModGroup mod
= BASEMOD_END
;
6657 case BASE_ATTACK
: mod
= CRIT_PERCENTAGE
; break;
6658 case OFF_ATTACK
: mod
= OFFHAND_CRIT_PERCENTAGE
;break;
6659 case RANGED_ATTACK
: mod
= RANGED_CRIT_PERCENTAGE
; break;
6663 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6665 HandleBaseModValue(mod
, FLAT_MOD
, float (aura
->GetModifier()->m_amount
), apply
);
6669 void Player::_ApplyWeaponDependentAuraDamageMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6671 // ignore spell mods for not wands
6672 Modifier
const* modifier
= aura
->GetModifier();
6673 if((modifier
->m_miscvalue
& SPELL_SCHOOL_MASK_NORMAL
)==0 && (getClassMask() & CLASSMASK_WAND_USERS
)==0)
6676 // generic not weapon specific case processes in aura code
6677 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6680 UnitMods unitMod
= UNIT_MOD_END
;
6683 case BASE_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_MAINHAND
; break;
6684 case OFF_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_OFFHAND
; break;
6685 case RANGED_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_RANGED
; break;
6689 UnitModifierType unitModType
= TOTAL_VALUE
;
6690 switch(modifier
->m_auraname
)
6692 case SPELL_AURA_MOD_DAMAGE_DONE
: unitModType
= TOTAL_VALUE
; break;
6693 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
: unitModType
= TOTAL_PCT
; break;
6697 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6699 HandleStatModifier(unitMod
, unitModType
, float(modifier
->m_amount
),apply
);
6703 void Player::ApplyItemEquipSpell(Item
*item
, bool apply
, bool form_change
)
6708 ItemPrototype
const *proto
= item
->GetProto();
6712 for (int i
= 0; i
< 5; i
++)
6714 _Spell
const& spellData
= proto
->Spells
[i
];
6717 if(!spellData
.SpellId
)
6720 // wrong triggering type
6721 if(apply
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_EQUIP
)
6724 // check if it is valid spell
6725 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellData
.SpellId
);
6729 ApplyEquipSpell(spellproto
,item
,apply
,form_change
);
6733 void Player::ApplyEquipSpell(SpellEntry
const* spellInfo
, Item
* item
, bool apply
, bool form_change
)
6737 // Cannot be used in this stance/form
6738 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
)!=0)
6741 if(form_change
) // check aura active state from other form
6744 for (int k
=0; k
< 3; ++k
)
6746 spellEffectPair spair
= spellEffectPair(spellInfo
->Id
, k
);
6747 for (AuraMap::iterator iter
= m_Auras
.lower_bound(spair
); iter
!= m_Auras
.upper_bound(spair
); ++iter
)
6749 if(!item
|| iter
->second
->GetCastItemGUID() == item
->GetGUID())
6759 if(found
) // and skip re-cast already active aura at form change
6763 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item
? "item" : "itemset"), spellInfo
->Id
);
6765 CastSpell(this,spellInfo
,true,item
);
6769 if(form_change
) // check aura compatibility
6771 // Cannot be used in this stance/form
6772 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
)==0)
6773 return; // and remove only not compatible at form change
6777 RemoveAurasDueToItemSpell(item
,spellInfo
->Id
); // un-apply all spells , not only at-equipped
6779 RemoveAurasDueToSpell(spellInfo
->Id
); // un-apply spell (item set case)
6783 void Player::UpdateEquipSpellsAtFormChange()
6785 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6787 if(m_items
[i
] && !m_items
[i
]->IsBroken())
6789 ApplyItemEquipSpell(m_items
[i
],false,true); // remove spells that not fit to form
6790 ApplyItemEquipSpell(m_items
[i
],true,true); // add spells that fit form but not active
6794 // item set bonuses not dependent from item broken state
6795 for(size_t setindex
= 0; setindex
< ItemSetEff
.size(); ++setindex
)
6797 ItemSetEffect
* eff
= ItemSetEff
[setindex
];
6801 for(uint32 y
=0;y
<8; ++y
)
6803 SpellEntry
const* spellInfo
= eff
->spells
[y
];
6807 ApplyEquipSpell(spellInfo
,NULL
,false,true); // remove spells that not fit to form
6808 ApplyEquipSpell(spellInfo
,NULL
,true,true); // add spells that fit form but not active
6813 void Player::CastItemCombatSpell(Item
*item
,Unit
* Target
, WeaponAttackType attType
)
6815 if(!item
|| item
->IsBroken())
6818 ItemPrototype
const *proto
= item
->GetProto();
6822 if (!Target
|| Target
== this )
6825 for (int i
= 0; i
< 5; i
++)
6827 _Spell
const& spellData
= proto
->Spells
[i
];
6830 if(!spellData
.SpellId
)
6833 // wrong triggering type
6834 if(spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_CHANCE_ON_HIT
)
6837 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
6840 sLog
.outError("WORLD: unknown Item spellid %i", spellData
.SpellId
);
6844 // not allow proc extra attack spell at extra attack
6845 if( m_extraAttacks
&& IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_ADD_EXTRA_ATTACKS
) )
6848 float chance
= spellInfo
->procChance
;
6850 if(spellData
.SpellPPMRate
)
6852 uint32 WeaponSpeed
= GetAttackTime(attType
);
6853 chance
= GetPPMProcChance(WeaponSpeed
, spellData
.SpellPPMRate
);
6855 else if(chance
> 100.0f
)
6857 chance
= GetWeaponProcChance();
6860 if (roll_chance_f(chance
))
6861 CastSpell(Target
, spellInfo
->Id
, true, item
);
6864 // item combat enchantments
6865 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
6867 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
6868 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
6869 if(!pEnchant
) continue;
6870 for (int s
=0;s
<3;s
++)
6872 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
)
6875 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
6878 sLog
.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
6882 float chance
= pEnchant
->amount
[s
] != 0 ? float(pEnchant
->amount
[s
]) : GetWeaponProcChance();
6883 if (roll_chance_f(chance
))
6885 if(IsPositiveSpell(pEnchant
->spellid
[s
]))
6886 CastSpell(this, pEnchant
->spellid
[s
], true, item
);
6888 CastSpell(Target
, pEnchant
->spellid
[s
], true, item
);
6894 void Player::_RemoveAllItemMods()
6896 sLog
.outDebug("_RemoveAllItemMods start.");
6898 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6902 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6906 // item set bonuses not dependent from item broken state
6908 RemoveItemsSetItem(this,proto
);
6910 if(m_items
[i
]->IsBroken())
6913 ApplyItemEquipSpell(m_items
[i
],false);
6914 ApplyEnchantment(m_items
[i
], false);
6918 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6922 if(m_items
[i
]->IsBroken())
6924 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6928 uint32 attacktype
= Player::GetAttackBySlot(i
);
6929 if(attacktype
< MAX_ATTACK
)
6930 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),false);
6932 _ApplyItemBonuses(proto
,i
, false);
6934 if( i
== EQUIPMENT_SLOT_RANGED
)
6935 _ApplyAmmoBonuses();
6939 sLog
.outDebug("_RemoveAllItemMods complete.");
6942 void Player::_ApplyAllItemMods()
6944 sLog
.outDebug("_ApplyAllItemMods start.");
6946 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6950 if(m_items
[i
]->IsBroken())
6953 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6957 uint32 attacktype
= Player::GetAttackBySlot(i
);
6958 if(attacktype
< MAX_ATTACK
)
6959 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),true);
6961 _ApplyItemBonuses(proto
,i
, true);
6963 if( i
== EQUIPMENT_SLOT_RANGED
)
6964 _ApplyAmmoBonuses();
6968 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6972 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6976 // item set bonuses not dependent from item broken state
6978 AddItemsSetItem(this,m_items
[i
]);
6980 if(m_items
[i
]->IsBroken())
6983 ApplyItemEquipSpell(m_items
[i
],true);
6984 ApplyEnchantment(m_items
[i
], true);
6988 sLog
.outDebug("_ApplyAllItemMods complete.");
6991 void Player::_ApplyAmmoBonuses()
6994 uint32 ammo_id
= GetUInt32Value(PLAYER_AMMO_ID
);
6998 float currentAmmoDPS
;
7000 ItemPrototype
const *ammo_proto
= objmgr
.GetItemPrototype( ammo_id
);
7001 if( !ammo_proto
|| ammo_proto
->Class
!=ITEM_CLASS_PROJECTILE
|| !CheckAmmoCompatibility(ammo_proto
))
7002 currentAmmoDPS
= 0.0f
;
7004 currentAmmoDPS
= ammo_proto
->Damage
[0].DamageMin
;
7006 if(currentAmmoDPS
== GetAmmoDPS())
7009 m_ammoDPS
= currentAmmoDPS
;
7011 if(CanModifyStats())
7012 UpdateDamagePhysical(RANGED_ATTACK
);
7015 bool Player::CheckAmmoCompatibility(const ItemPrototype
*ammo_proto
) const
7020 // check ranged weapon
7021 Item
*weapon
= GetWeaponForAttack( RANGED_ATTACK
);
7022 if(!weapon
|| weapon
->IsBroken() )
7025 ItemPrototype
const* weapon_proto
= weapon
->GetProto();
7026 if(!weapon_proto
|| weapon_proto
->Class
!=ITEM_CLASS_WEAPON
)
7029 // check ammo ws. weapon compatibility
7030 switch(weapon_proto
->SubClass
)
7032 case ITEM_SUBCLASS_WEAPON_BOW
:
7033 case ITEM_SUBCLASS_WEAPON_CROSSBOW
:
7034 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_ARROW
)
7037 case ITEM_SUBCLASS_WEAPON_GUN
:
7038 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_BULLET
)
7048 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7049 Called by remove insignia spell effect */
7050 void Player::RemovedInsignia(Player
* looterPlr
)
7052 if (!GetBattleGroundId())
7055 // If not released spirit, do it !
7056 if(m_deathTimer
> 0)
7063 Corpse
*corpse
= GetCorpse();
7067 // We have to convert player corpse to bones, not to be able to resurrect there
7068 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7069 Corpse
*bones
= ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
7073 // Now we must make bones lootable, and send player loot
7074 bones
->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS
, CORPSE_DYNFLAG_LOOTABLE
);
7076 // We store the level of our player in the gold field
7077 // We retrieve this information at Player::SendLoot()
7078 bones
->loot
.gold
= getLevel();
7079 bones
->lootRecipient
= looterPlr
;
7080 looterPlr
->SendLoot(bones
->GetGUID(), LOOT_INSIGNIA
);
7089 void Player::SendLootRelease( uint64 guid
)
7091 WorldPacket
data( SMSG_LOOT_RELEASE_RESPONSE
, (8+1) );
7092 data
<< uint64(guid
) << uint8(1);
7093 SendDirectMessage( &data
);
7096 void Player::SendLoot(uint64 guid
, LootType loot_type
)
7099 PermissionTypes permission
= ALL_PERMISSION
;
7101 sLog
.outDebug("Player::SendLoot");
7102 if (IS_GAMEOBJECT_GUID(guid
))
7104 sLog
.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7106 ObjectAccessor::GetGameObject(*this, guid
);
7108 // not check distance for GO in case owned GO (fishing bobber case, for example)
7109 // And permit out of range GO with no owner in case fishing hole
7110 if (!go
|| (loot_type
!= LOOT_FISHINGHOLE
&& (loot_type
!= LOOT_FISHING
|| go
->GetOwnerGUID() != GetGUID()) && !go
->IsWithinDistInMap(this,INTERACTION_DISTANCE
)))
7112 SendLootRelease(guid
);
7118 if(go
->getLootState() == GO_READY
)
7120 uint32 lootid
= go
->GetLootId();
7124 sLog
.outDebug(" if(lootid)");
7126 loot
->FillLoot(lootid
, LootTemplates_Gameobject
, this);
7129 if(loot_type
== LOOT_FISHING
)
7130 go
->getFishLoot(loot
);
7132 go
->SetLootState(GO_ACTIVATED
);
7135 else if (IS_ITEM_GUID(guid
))
7137 Item
*item
= GetItemByGuid( guid
);
7141 SendLootRelease(guid
);
7145 if(loot_type
== LOOT_DISENCHANTING
)
7149 if(!item
->m_lootGenerated
)
7151 item
->m_lootGenerated
= true;
7153 loot
->FillLoot(item
->GetProto()->DisenchantID
, LootTemplates_Disenchant
, this);
7156 else if(loot_type
== LOOT_PROSPECTING
)
7160 if(!item
->m_lootGenerated
)
7162 item
->m_lootGenerated
= true;
7164 loot
->FillLoot(item
->GetEntry(), LootTemplates_Prospecting
, this);
7171 if(!item
->m_lootGenerated
)
7173 item
->m_lootGenerated
= true;
7175 loot
->FillLoot(item
->GetEntry(), LootTemplates_Item
, this);
7177 loot
->generateMoneyLoot(item
->GetProto()->MinMoneyLoot
,item
->GetProto()->MaxMoneyLoot
);
7181 else if (IS_CORPSE_GUID(guid
)) // remove insignia
7183 Corpse
*bones
= ObjectAccessor::GetCorpse(*this, guid
);
7185 if (!bones
|| !((loot_type
== LOOT_CORPSE
) || (loot_type
== LOOT_INSIGNIA
)) || (bones
->GetType() != CORPSE_BONES
) )
7187 SendLootRelease(guid
);
7191 loot
= &bones
->loot
;
7193 if (!bones
->lootForBody
)
7195 bones
->lootForBody
= true;
7196 uint32 pLevel
= bones
->loot
.gold
;
7197 bones
->loot
.clear();
7198 // It may need a better formula
7199 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7200 bones
->loot
.gold
= (uint32
)( urand(50, 150) * 0.016f
* pow( ((float)pLevel
)/5.76f
, 2.5f
) * sWorld
.getRate(RATE_DROP_MONEY
) );
7203 if (bones
->lootRecipient
!= this)
7204 permission
= NONE_PERMISSION
;
7208 Creature
*creature
= ObjectAccessor::GetCreature(*this, guid
);
7210 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7211 if (!creature
|| creature
->isAlive()!=(loot_type
== LOOT_PICKPOCKETING
) || !creature
->IsWithinDistInMap(this,INTERACTION_DISTANCE
))
7213 SendLootRelease(guid
);
7217 if(loot_type
== LOOT_PICKPOCKETING
&& IsFriendlyTo(creature
))
7219 SendLootRelease(guid
);
7223 loot
= &creature
->loot
;
7225 if(loot_type
== LOOT_PICKPOCKETING
)
7227 if ( !creature
->lootForPickPocketed
)
7229 creature
->lootForPickPocketed
= true;
7232 if (uint32 lootid
= creature
->GetCreatureInfo()->pickpocketLootId
)
7233 loot
->FillLoot(lootid
, LootTemplates_Pickpocketing
, this);
7235 // Generate extra money for pick pocket loot
7236 const uint32 a
= urand(0, creature
->getLevel()/2);
7237 const uint32 b
= urand(0, getLevel()/2);
7238 loot
->gold
= uint32(10 * (a
+ b
) * sWorld
.getRate(RATE_DROP_MONEY
));
7243 // the player whose group may loot the corpse
7244 Player
*recipient
= creature
->GetLootRecipient();
7247 creature
->SetLootRecipient(this);
7251 if (creature
->lootForPickPocketed
)
7253 creature
->lootForPickPocketed
= false;
7257 if(!creature
->lootForBody
)
7259 creature
->lootForBody
= true;
7262 if (uint32 lootid
= creature
->GetCreatureInfo()->lootid
)
7263 loot
->FillLoot(lootid
, LootTemplates_Creature
, recipient
);
7265 loot
->generateMoneyLoot(creature
->GetCreatureInfo()->mingold
,creature
->GetCreatureInfo()->maxgold
);
7267 if(Group
* group
= recipient
->GetGroup())
7269 group
->UpdateLooterGuid(creature
,true);
7271 switch (group
->GetLootMethod())
7274 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7275 group
->GroupLoot(recipient
->GetGUID(), loot
, creature
);
7277 case NEED_BEFORE_GREED
:
7278 group
->NeedBeforeGreed(recipient
->GetGUID(), loot
, creature
);
7281 group
->MasterLoot(recipient
->GetGUID(), loot
, creature
);
7289 // possible only if creature->lootForBody && loot->empty() at spell cast check
7290 if (loot_type
== LOOT_SKINNING
)
7293 loot
->FillLoot(creature
->GetCreatureInfo()->SkinLootId
, LootTemplates_Skinning
, this);
7295 // set group rights only for loot_type != LOOT_SKINNING
7298 if(Group
* group
= GetGroup())
7300 if( group
== recipient
->GetGroup() )
7302 if(group
->GetLootMethod() == FREE_FOR_ALL
)
7303 permission
= ALL_PERMISSION
;
7304 else if(group
->GetLooterGuid() == GetGUID())
7306 if(group
->GetLootMethod() == MASTER_LOOT
)
7307 permission
= MASTER_PERMISSION
;
7309 permission
= ALL_PERMISSION
;
7312 permission
= GROUP_PERMISSION
;
7315 permission
= NONE_PERMISSION
;
7317 else if(recipient
== this)
7318 permission
= ALL_PERMISSION
;
7320 permission
= NONE_PERMISSION
;
7327 QuestItemList
*q_list
= 0;
7328 if (permission
!= NONE_PERMISSION
)
7330 QuestItemMap
const& lootPlayerQuestItems
= loot
->GetPlayerQuestItems();
7331 QuestItemMap::const_iterator itr
= lootPlayerQuestItems
.find(GetGUIDLow());
7332 if (itr
== lootPlayerQuestItems
.end())
7333 q_list
= loot
->FillQuestLoot(this);
7335 q_list
= itr
->second
;
7338 QuestItemList
*ffa_list
= 0;
7339 if (permission
!= NONE_PERMISSION
)
7341 QuestItemMap
const& lootPlayerFFAItems
= loot
->GetPlayerFFAItems();
7342 QuestItemMap::const_iterator itr
= lootPlayerFFAItems
.find(GetGUIDLow());
7343 if (itr
== lootPlayerFFAItems
.end())
7344 ffa_list
= loot
->FillFFALoot(this);
7346 ffa_list
= itr
->second
;
7349 QuestItemList
*conditional_list
= 0;
7350 if (permission
!= NONE_PERMISSION
)
7352 QuestItemMap
const& lootPlayerNonQuestNonFFAConditionalItems
= loot
->GetPlayerNonQuestNonFFAConditionalItems();
7353 QuestItemMap::const_iterator itr
= lootPlayerNonQuestNonFFAConditionalItems
.find(GetGUIDLow());
7354 if (itr
== lootPlayerNonQuestNonFFAConditionalItems
.end())
7355 conditional_list
= loot
->FillNonQuestNonFFAConditionalLoot(this);
7357 conditional_list
= itr
->second
;
7360 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING and LOOT_INSIGNIA unsupported by client, sending LOOT_SKINNING instead
7361 if(loot_type
== LOOT_PICKPOCKETING
|| loot_type
== LOOT_DISENCHANTING
|| loot_type
== LOOT_PROSPECTING
|| loot_type
== LOOT_INSIGNIA
)
7362 loot_type
= LOOT_SKINNING
;
7364 if(loot_type
== LOOT_FISHINGHOLE
)
7365 loot_type
= LOOT_FISHING
;
7367 WorldPacket
data(SMSG_LOOT_RESPONSE
, (9+50)); // we guess size
7369 data
<< uint64(guid
);
7370 data
<< uint8(loot_type
);
7371 data
<< LootView(*loot
, q_list
, ffa_list
, conditional_list
, this, permission
);
7373 SendDirectMessage(&data
);
7375 // add 'this' player as one of the players that are looting 'loot'
7376 if (permission
!= NONE_PERMISSION
)
7377 loot
->AddLooter(GetGUID());
7379 if ( loot_type
== LOOT_CORPSE
&& !IS_ITEM_GUID(guid
) )
7380 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_LOOTING
);
7383 void Player::SendNotifyLootMoneyRemoved()
7385 WorldPacket
data(SMSG_LOOT_CLEAR_MONEY
, 0);
7386 GetSession()->SendPacket( &data
);
7389 void Player::SendNotifyLootItemRemoved(uint8 lootSlot
)
7391 WorldPacket
data(SMSG_LOOT_REMOVED
, 1);
7392 data
<< uint8(lootSlot
);
7393 GetSession()->SendPacket( &data
);
7396 void Player::SendUpdateWorldState(uint32 Field
, uint32 Value
)
7398 WorldPacket
data(SMSG_UPDATE_WORLD_STATE
, 8);
7401 GetSession()->SendPacket(&data
);
7404 void Player::SendInitWorldStates()
7406 // data depends on zoneid/mapid...
7407 BattleGround
* bg
= GetBattleGround();
7408 uint16 NumberOfFields
= 0;
7409 uint32 mapid
= GetMapId();
7410 uint32 zoneid
= GetZoneId();
7411 uint32 areaid
= GetAreaId();
7412 sLog
.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid
, zoneid
);
7413 // may be exist better way to do this...
7436 NumberOfFields
= 81;
7439 NumberOfFields
= 14;
7443 NumberOfFields
= 38;
7446 NumberOfFields
= 22;
7449 NumberOfFields
= 36;
7452 NumberOfFields
= 35;
7463 NumberOfFields
= 10;
7467 WorldPacket
data(SMSG_INIT_WORLD_STATES
, (4+4+4+2+(NumberOfFields
*8)));
7468 data
<< uint32(mapid
); // mapid
7469 data
<< uint32(zoneid
); // zone id
7470 data
<< uint32(areaid
); // area id, new 2.1.0
7471 data
<< uint16(NumberOfFields
); // count of uint64 blocks
7472 data
<< uint32(0x8d8) << uint32(0x0); // 1
7473 data
<< uint32(0x8d7) << uint32(0x0); // 2
7474 data
<< uint32(0x8d6) << uint32(0x0); // 3
7475 data
<< uint32(0x8d5) << uint32(0x0); // 4
7476 data
<< uint32(0x8d4) << uint32(0x0); // 5
7477 data
<< uint32(0x8d3) << uint32(0x0); // 6
7478 if(mapid
== 530) // Outland
7480 data
<< uint32(0x9bf) << uint32(0x0); // 7
7481 data
<< uint32(0x9bd) << uint32(0xF); // 8
7482 data
<< uint32(0x9bb) << uint32(0xF); // 9
7497 data
<< uint32(0x7ae) << uint32(0x1); // 7
7498 data
<< uint32(0x532) << uint32(0x1); // 8
7499 data
<< uint32(0x531) << uint32(0x0); // 9
7500 data
<< uint32(0x52e) << uint32(0x0); // 10
7501 data
<< uint32(0x571) << uint32(0x0); // 11
7502 data
<< uint32(0x570) << uint32(0x0); // 12
7503 data
<< uint32(0x567) << uint32(0x1); // 13
7504 data
<< uint32(0x566) << uint32(0x1); // 14
7505 data
<< uint32(0x550) << uint32(0x1); // 15
7506 data
<< uint32(0x544) << uint32(0x0); // 16
7507 data
<< uint32(0x536) << uint32(0x0); // 17
7508 data
<< uint32(0x535) << uint32(0x1); // 18
7509 data
<< uint32(0x518) << uint32(0x0); // 19
7510 data
<< uint32(0x517) << uint32(0x0); // 20
7511 data
<< uint32(0x574) << uint32(0x0); // 21
7512 data
<< uint32(0x573) << uint32(0x0); // 22
7513 data
<< uint32(0x572) << uint32(0x0); // 23
7514 data
<< uint32(0x56f) << uint32(0x0); // 24
7515 data
<< uint32(0x56e) << uint32(0x0); // 25
7516 data
<< uint32(0x56d) << uint32(0x0); // 26
7517 data
<< uint32(0x56c) << uint32(0x0); // 27
7518 data
<< uint32(0x56b) << uint32(0x0); // 28
7519 data
<< uint32(0x56a) << uint32(0x1); // 29
7520 data
<< uint32(0x569) << uint32(0x1); // 30
7521 data
<< uint32(0x568) << uint32(0x1); // 13
7522 data
<< uint32(0x565) << uint32(0x0); // 32
7523 data
<< uint32(0x564) << uint32(0x0); // 33
7524 data
<< uint32(0x563) << uint32(0x0); // 34
7525 data
<< uint32(0x562) << uint32(0x0); // 35
7526 data
<< uint32(0x561) << uint32(0x0); // 36
7527 data
<< uint32(0x560) << uint32(0x0); // 37
7528 data
<< uint32(0x55f) << uint32(0x0); // 38
7529 data
<< uint32(0x55e) << uint32(0x0); // 39
7530 data
<< uint32(0x55d) << uint32(0x0); // 40
7531 data
<< uint32(0x3c6) << uint32(0x4); // 41
7532 data
<< uint32(0x3c4) << uint32(0x6); // 42
7533 data
<< uint32(0x3c2) << uint32(0x4); // 43
7534 data
<< uint32(0x516) << uint32(0x1); // 44
7535 data
<< uint32(0x515) << uint32(0x0); // 45
7536 data
<< uint32(0x3b6) << uint32(0x6); // 46
7537 data
<< uint32(0x55c) << uint32(0x0); // 47
7538 data
<< uint32(0x55b) << uint32(0x0); // 48
7539 data
<< uint32(0x55a) << uint32(0x0); // 49
7540 data
<< uint32(0x559) << uint32(0x0); // 50
7541 data
<< uint32(0x558) << uint32(0x0); // 51
7542 data
<< uint32(0x557) << uint32(0x0); // 52
7543 data
<< uint32(0x556) << uint32(0x0); // 53
7544 data
<< uint32(0x555) << uint32(0x0); // 54
7545 data
<< uint32(0x554) << uint32(0x1); // 55
7546 data
<< uint32(0x553) << uint32(0x1); // 56
7547 data
<< uint32(0x552) << uint32(0x1); // 57
7548 data
<< uint32(0x551) << uint32(0x1); // 58
7549 data
<< uint32(0x54f) << uint32(0x0); // 59
7550 data
<< uint32(0x54e) << uint32(0x0); // 60
7551 data
<< uint32(0x54d) << uint32(0x1); // 61
7552 data
<< uint32(0x54c) << uint32(0x0); // 62
7553 data
<< uint32(0x54b) << uint32(0x0); // 63
7554 data
<< uint32(0x545) << uint32(0x0); // 64
7555 data
<< uint32(0x543) << uint32(0x1); // 65
7556 data
<< uint32(0x542) << uint32(0x0); // 66
7557 data
<< uint32(0x540) << uint32(0x0); // 67
7558 data
<< uint32(0x53f) << uint32(0x0); // 68
7559 data
<< uint32(0x53e) << uint32(0x0); // 69
7560 data
<< uint32(0x53d) << uint32(0x0); // 70
7561 data
<< uint32(0x53c) << uint32(0x0); // 71
7562 data
<< uint32(0x53b) << uint32(0x0); // 72
7563 data
<< uint32(0x53a) << uint32(0x1); // 73
7564 data
<< uint32(0x539) << uint32(0x0); // 74
7565 data
<< uint32(0x538) << uint32(0x0); // 75
7566 data
<< uint32(0x537) << uint32(0x0); // 76
7567 data
<< uint32(0x534) << uint32(0x0); // 77
7568 data
<< uint32(0x533) << uint32(0x0); // 78
7569 data
<< uint32(0x530) << uint32(0x0); // 79
7570 data
<< uint32(0x52f) << uint32(0x0); // 80
7571 data
<< uint32(0x52d) << uint32(0x1); // 81
7574 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_WS
)
7575 bg
->FillInitialWorldStates(data
);
7578 data
<< uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7579 data
<< uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7580 data
<< uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7581 data
<< uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7582 data
<< uint32(0x60b) << uint32(0x2); // 11 1547 unk
7583 data
<< uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7584 data
<< uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7585 data
<< uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7589 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_AB
)
7590 bg
->FillInitialWorldStates(data
);
7593 data
<< uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7594 data
<< uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7595 data
<< uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7596 data
<< uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7597 data
<< uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7598 data
<< uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7599 data
<< uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7600 data
<< uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7601 data
<< uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7602 data
<< uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7603 data
<< uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7604 data
<< uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7605 data
<< uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7606 data
<< uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7607 data
<< uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7608 data
<< uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7609 data
<< uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7610 data
<< uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7611 data
<< uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7612 data
<< uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7613 data
<< uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7614 data
<< uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7615 data
<< uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7616 data
<< uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7617 data
<< uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7618 data
<< uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7619 data
<< uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7620 data
<< uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7621 data
<< uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7622 data
<< uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7623 data
<< uint32(0x745) << uint32(0x2); // 37 1861 unk
7624 data
<< uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7628 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_EY
)
7629 bg
->FillInitialWorldStates(data
);
7632 data
<< uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7633 data
<< uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7634 data
<< uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7635 data
<< uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7636 data
<< uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7637 data
<< uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7638 data
<< uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7639 data
<< uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7640 data
<< uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7641 data
<< uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7642 data
<< uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7643 data
<< uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7644 data
<< uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7645 data
<< uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7646 data
<< uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7647 data
<< uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7648 data
<< uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7649 data
<< uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7650 data
<< uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7651 data
<< uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7652 data
<< uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7653 data
<< uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7654 data
<< uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7655 data
<< uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7656 data
<< uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7657 data
<< uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7658 data
<< uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7659 data
<< uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7660 data
<< uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7661 data
<< uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7662 data
<< uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7663 data
<< uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7664 // and some more ... unknown
7667 case 3483: // Hellfire Peninsula
7668 data
<< uint32(0x9ba) << uint32(0x1); // 10
7669 data
<< uint32(0x9b9) << uint32(0x1); // 11
7670 data
<< uint32(0x9b5) << uint32(0x0); // 12
7671 data
<< uint32(0x9b4) << uint32(0x1); // 13
7672 data
<< uint32(0x9b3) << uint32(0x0); // 14
7673 data
<< uint32(0x9b2) << uint32(0x0); // 15
7674 data
<< uint32(0x9b1) << uint32(0x1); // 16
7675 data
<< uint32(0x9b0) << uint32(0x0); // 17
7676 data
<< uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7677 data
<< uint32(0x9ac) << uint32(0x0); // 19
7678 data
<< uint32(0x9a8) << uint32(0x0); // 20
7679 data
<< uint32(0x9a7) << uint32(0x0); // 21
7680 data
<< uint32(0x9a6) << uint32(0x1); // 22
7682 case 3519: // Terokkar Forest
7683 data
<< uint32(0xa41) << uint32(0x0); // 10
7684 data
<< uint32(0xa40) << uint32(0x14); // 11
7685 data
<< uint32(0xa3f) << uint32(0x0); // 12
7686 data
<< uint32(0xa3e) << uint32(0x0); // 13
7687 data
<< uint32(0xa3d) << uint32(0x5); // 14
7688 data
<< uint32(0xa3c) << uint32(0x0); // 15
7689 data
<< uint32(0xa87) << uint32(0x0); // 16
7690 data
<< uint32(0xa86) << uint32(0x0); // 17
7691 data
<< uint32(0xa85) << uint32(0x0); // 18
7692 data
<< uint32(0xa84) << uint32(0x0); // 19
7693 data
<< uint32(0xa83) << uint32(0x0); // 20
7694 data
<< uint32(0xa82) << uint32(0x0); // 21
7695 data
<< uint32(0xa81) << uint32(0x0); // 22
7696 data
<< uint32(0xa80) << uint32(0x0); // 23
7697 data
<< uint32(0xa7e) << uint32(0x0); // 24
7698 data
<< uint32(0xa7d) << uint32(0x0); // 25
7699 data
<< uint32(0xa7c) << uint32(0x0); // 26
7700 data
<< uint32(0xa7b) << uint32(0x0); // 27
7701 data
<< uint32(0xa7a) << uint32(0x0); // 28
7702 data
<< uint32(0xa79) << uint32(0x0); // 29
7703 data
<< uint32(0x9d0) << uint32(0x5); // 30
7704 data
<< uint32(0x9ce) << uint32(0x0); // 31
7705 data
<< uint32(0x9cd) << uint32(0x0); // 32
7706 data
<< uint32(0x9cc) << uint32(0x0); // 33
7707 data
<< uint32(0xa88) << uint32(0x0); // 34
7708 data
<< uint32(0xad0) << uint32(0x0); // 35
7709 data
<< uint32(0xacf) << uint32(0x1); // 36
7711 case 3521: // Zangarmarsh
7712 data
<< uint32(0x9e1) << uint32(0x0); // 10
7713 data
<< uint32(0x9e0) << uint32(0x0); // 11
7714 data
<< uint32(0x9df) << uint32(0x0); // 12
7715 data
<< uint32(0xa5d) << uint32(0x1); // 13
7716 data
<< uint32(0xa5c) << uint32(0x0); // 14
7717 data
<< uint32(0xa5b) << uint32(0x1); // 15
7718 data
<< uint32(0xa5a) << uint32(0x0); // 16
7719 data
<< uint32(0xa59) << uint32(0x1); // 17
7720 data
<< uint32(0xa58) << uint32(0x0); // 18
7721 data
<< uint32(0xa57) << uint32(0x0); // 19
7722 data
<< uint32(0xa56) << uint32(0x0); // 20
7723 data
<< uint32(0xa55) << uint32(0x1); // 21
7724 data
<< uint32(0xa54) << uint32(0x0); // 22
7725 data
<< uint32(0x9e7) << uint32(0x0); // 23
7726 data
<< uint32(0x9e6) << uint32(0x0); // 24
7727 data
<< uint32(0x9e5) << uint32(0x0); // 25
7728 data
<< uint32(0xa00) << uint32(0x0); // 26
7729 data
<< uint32(0x9ff) << uint32(0x1); // 27
7730 data
<< uint32(0x9fe) << uint32(0x0); // 28
7731 data
<< uint32(0x9fd) << uint32(0x0); // 29
7732 data
<< uint32(0x9fc) << uint32(0x1); // 30
7733 data
<< uint32(0x9fb) << uint32(0x0); // 31
7734 data
<< uint32(0xa62) << uint32(0x0); // 32
7735 data
<< uint32(0xa61) << uint32(0x1); // 33
7736 data
<< uint32(0xa60) << uint32(0x1); // 34
7737 data
<< uint32(0xa5f) << uint32(0x0); // 35
7739 case 3698: // Nagrand Arena
7740 data
<< uint32(0xa0f) << uint32(0x0); // 7
7741 data
<< uint32(0xa10) << uint32(0x0); // 8
7742 data
<< uint32(0xa11) << uint32(0x0); // 9
7744 case 3702: // Blade's Edge Arena
7745 data
<< uint32(0x9f0) << uint32(0x0); // 7
7746 data
<< uint32(0x9f1) << uint32(0x0); // 8
7747 data
<< uint32(0x9f3) << uint32(0x0); // 9
7749 case 3968: // Ruins of Lordaeron
7750 data
<< uint32(0xbb8) << uint32(0x0); // 7
7751 data
<< uint32(0xbb9) << uint32(0x0); // 8
7752 data
<< uint32(0xbba) << uint32(0x0); // 9
7754 case 3703: // Shattrath City
7757 data
<< uint32(0x914) << uint32(0x0); // 7
7758 data
<< uint32(0x913) << uint32(0x0); // 8
7759 data
<< uint32(0x912) << uint32(0x0); // 9
7760 data
<< uint32(0x915) << uint32(0x0); // 10
7763 GetSession()->SendPacket(&data
);
7766 uint32
Player::GetXPRestBonus(uint32 xp
)
7768 uint32 rested_bonus
= (uint32
)GetRestBonus(); // xp for each rested bonus
7770 if(rested_bonus
> xp
) // max rested_bonus == xp or (r+x) = 200% xp
7773 SetRestBonus( GetRestBonus() - rested_bonus
);
7775 sLog
.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp
+rested_bonus
,rested_bonus
,GetRestBonus());
7776 return rested_bonus
;
7779 void Player::SetBindPoint(uint64 guid
)
7781 WorldPacket
data(SMSG_BINDER_CONFIRM
, 8);
7782 data
<< uint64(guid
);
7783 GetSession()->SendPacket( &data
);
7786 void Player::SendTalentWipeConfirm(uint64 guid
)
7788 WorldPacket
data(MSG_TALENT_WIPE_CONFIRM
, (8+4));
7789 data
<< uint64(guid
);
7790 data
<< uint32(resetTalentsCost());
7791 GetSession()->SendPacket( &data
);
7794 void Player::SendPetSkillWipeConfirm()
7796 Pet
* pet
= GetPet();
7799 WorldPacket
data(SMSG_PET_UNLEARN_CONFIRM
, (8+4));
7800 data
<< pet
->GetGUID();
7801 data
<< uint32(pet
->resetTalentsCost());
7802 GetSession()->SendPacket( &data
);
7805 /*********************************************************/
7806 /*** STORAGE SYSTEM ***/
7807 /*********************************************************/
7809 void Player::SetVirtualItemSlot( uint8 i
, Item
* item
)
7814 if(!item
->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT
))
7816 uint32 charges
= item
->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
);
7820 item
->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
,charges
-1);
7821 else if(charges
<= 1)
7823 ApplyEnchantment(item
,TEMP_ENCHANTMENT_SLOT
,false);
7824 item
->ClearEnchantment(TEMP_ENCHANTMENT_SLOT
);
7829 void Player::SetSheath( uint32 sheathed
)
7833 case SHEATH_STATE_UNARMED
: // no prepared weapon
7834 SetVirtualItemSlot(0,NULL
);
7835 SetVirtualItemSlot(1,NULL
);
7836 SetVirtualItemSlot(2,NULL
);
7838 case SHEATH_STATE_MELEE
: // prepared melee weapon
7840 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK
,true));
7841 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK
,true));
7842 SetVirtualItemSlot(2,NULL
);
7844 case SHEATH_STATE_RANGED
: // prepared ranged weapon
7845 SetVirtualItemSlot(0,NULL
);
7846 SetVirtualItemSlot(1,NULL
);
7847 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK
,true));
7850 SetVirtualItemSlot(0,NULL
);
7851 SetVirtualItemSlot(1,NULL
);
7852 SetVirtualItemSlot(2,NULL
);
7855 SetByteValue(UNIT_FIELD_BYTES_2
, 0, sheathed
); // this must visualize Sheath changing for other players...
7858 uint8
Player::FindEquipSlot( ItemPrototype
const* proto
, uint32 slot
, bool swap
) const
7860 uint8 pClass
= getClass();
7863 slots
[0] = NULL_SLOT
;
7864 slots
[1] = NULL_SLOT
;
7865 slots
[2] = NULL_SLOT
;
7866 slots
[3] = NULL_SLOT
;
7867 switch( proto
->InventoryType
)
7870 slots
[0] = EQUIPMENT_SLOT_HEAD
;
7873 slots
[0] = EQUIPMENT_SLOT_NECK
;
7875 case INVTYPE_SHOULDERS
:
7876 slots
[0] = EQUIPMENT_SLOT_SHOULDERS
;
7879 slots
[0] = EQUIPMENT_SLOT_BODY
;
7882 slots
[0] = EQUIPMENT_SLOT_CHEST
;
7885 slots
[0] = EQUIPMENT_SLOT_CHEST
;
7888 slots
[0] = EQUIPMENT_SLOT_WAIST
;
7891 slots
[0] = EQUIPMENT_SLOT_LEGS
;
7894 slots
[0] = EQUIPMENT_SLOT_FEET
;
7896 case INVTYPE_WRISTS
:
7897 slots
[0] = EQUIPMENT_SLOT_WRISTS
;
7900 slots
[0] = EQUIPMENT_SLOT_HANDS
;
7902 case INVTYPE_FINGER
:
7903 slots
[0] = EQUIPMENT_SLOT_FINGER1
;
7904 slots
[1] = EQUIPMENT_SLOT_FINGER2
;
7906 case INVTYPE_TRINKET
:
7907 slots
[0] = EQUIPMENT_SLOT_TRINKET1
;
7908 slots
[1] = EQUIPMENT_SLOT_TRINKET2
;
7911 slots
[0] = EQUIPMENT_SLOT_BACK
;
7913 case INVTYPE_WEAPON
:
7915 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
7917 // suggest offhand slot only if know dual wielding
7918 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
7920 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
7922 case INVTYPE_SHIELD
:
7923 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
7925 case INVTYPE_RANGED
:
7926 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7928 case INVTYPE_2HWEAPON
:
7929 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
7931 case INVTYPE_TABARD
:
7932 slots
[0] = EQUIPMENT_SLOT_TABARD
;
7934 case INVTYPE_WEAPONMAINHAND
:
7935 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
7937 case INVTYPE_WEAPONOFFHAND
:
7938 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
7940 case INVTYPE_HOLDABLE
:
7941 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
7943 case INVTYPE_THROWN
:
7944 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7946 case INVTYPE_RANGEDRIGHT
:
7947 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7950 slots
[0] = INVENTORY_SLOT_BAG_1
;
7951 slots
[1] = INVENTORY_SLOT_BAG_2
;
7952 slots
[2] = INVENTORY_SLOT_BAG_3
;
7953 slots
[3] = INVENTORY_SLOT_BAG_4
;
7957 switch(proto
->SubClass
)
7959 case ITEM_SUBCLASS_ARMOR_LIBRAM
:
7960 if (pClass
== CLASS_PALADIN
)
7961 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7963 case ITEM_SUBCLASS_ARMOR_IDOL
:
7964 if (pClass
== CLASS_DRUID
)
7965 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7967 case ITEM_SUBCLASS_ARMOR_TOTEM
:
7968 if (pClass
== CLASS_SHAMAN
)
7969 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7971 case ITEM_SUBCLASS_ARMOR_MISC
:
7972 if (pClass
== CLASS_WARLOCK
)
7973 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7982 if( slot
!= NULL_SLOT
)
7984 if( swap
|| !GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
) )
7986 for (int i
= 0; i
< 4; i
++)
7988 if ( slots
[i
] == slot
)
7995 // search free slot at first
7996 for (int i
= 0; i
< 4; i
++)
7998 if ( slots
[i
] != NULL_SLOT
&& !GetItemByPos( INVENTORY_SLOT_BAG_0
, slots
[i
] ) )
8000 // in case 2hand equipped weapon offhand slot empty but not free
8001 if(slots
[i
]==EQUIPMENT_SLOT_OFFHAND
)
8003 Item
* mainItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_MAINHAND
);
8004 if(!mainItem
|| mainItem
->GetProto()->InventoryType
!= INVTYPE_2HWEAPON
)
8012 // if not found free and can swap return first appropriate from used
8013 for (int i
= 0; i
< 4; i
++)
8015 if ( slots
[i
] != NULL_SLOT
&& swap
)
8024 uint8
Player::CanUnequipItems( uint32 item
, uint32 count
) const
8027 uint32 tempcount
= 0;
8029 uint8 res
= EQUIP_ERR_OK
;
8031 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8033 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8034 if( pItem
&& pItem
->GetEntry() == item
)
8036 uint8 ires
= CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
, false);
8037 if(ires
==EQUIP_ERR_OK
)
8039 tempcount
+= pItem
->GetCount();
8040 if( tempcount
>= count
)
8041 return EQUIP_ERR_OK
;
8047 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8049 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8050 if( pItem
&& pItem
->GetEntry() == item
)
8052 tempcount
+= pItem
->GetCount();
8053 if( tempcount
>= count
)
8054 return EQUIP_ERR_OK
;
8057 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
8059 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8060 if( pItem
&& pItem
->GetEntry() == item
)
8062 tempcount
+= pItem
->GetCount();
8063 if( tempcount
>= count
)
8064 return EQUIP_ERR_OK
;
8068 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8070 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8073 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8075 pItem
= GetItemByPos( i
, j
);
8076 if( pItem
&& pItem
->GetEntry() == item
)
8078 tempcount
+= pItem
->GetCount();
8079 if( tempcount
>= count
)
8080 return EQUIP_ERR_OK
;
8086 // not found req. item count and have unequippable items
8090 uint32
Player::GetItemCount( uint32 item
, bool inBankAlso
, Item
* skipItem
) const
8093 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8095 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8096 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8097 count
+= pItem
->GetCount();
8099 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
8101 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8102 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8103 count
+= pItem
->GetCount();
8105 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8107 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8109 count
+= pBag
->GetItemCount(item
,skipItem
);
8112 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8114 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8116 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8117 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8118 count
+= pItem
->GetGemCountWithID(item
);
8124 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8126 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8127 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8128 count
+= pItem
->GetCount();
8130 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8132 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8134 count
+= pBag
->GetItemCount(item
,skipItem
);
8137 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8139 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8141 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8142 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8143 count
+= pItem
->GetGemCountWithID(item
);
8151 Item
* Player::GetItemByGuid( uint64 guid
) const
8153 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8155 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8156 if( pItem
&& pItem
->GetGUID() == guid
)
8159 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
8161 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8162 if( pItem
&& pItem
->GetGUID() == guid
)
8166 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8168 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8171 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8173 Item
* pItem
= pBag
->GetItemByPos( j
);
8174 if( pItem
&& pItem
->GetGUID() == guid
)
8179 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8181 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8184 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8186 Item
* pItem
= pBag
->GetItemByPos( j
);
8187 if( pItem
&& pItem
->GetGUID() == guid
)
8196 Item
* Player::GetItemByPos( uint16 pos
) const
8198 uint8 bag
= pos
>> 8;
8199 uint8 slot
= pos
& 255;
8200 return GetItemByPos( bag
, slot
);
8203 Item
* Player::GetItemByPos( uint8 bag
, uint8 slot
) const
8205 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< BANK_SLOT_BAG_END
|| slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_END
) )
8206 return m_items
[slot
];
8207 else if(bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
8208 || bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8210 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8212 return pBag
->GetItemByPos(slot
);
8217 Item
* Player::GetWeaponForAttack(WeaponAttackType attackType
, bool useable
) const
8222 case BASE_ATTACK
: slot
= EQUIPMENT_SLOT_MAINHAND
; break;
8223 case OFF_ATTACK
: slot
= EQUIPMENT_SLOT_OFFHAND
; break;
8224 case RANGED_ATTACK
: slot
= EQUIPMENT_SLOT_RANGED
; break;
8225 default: return NULL
;
8228 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, slot
);
8229 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_WEAPON
)
8235 if( item
->IsBroken() || !IsUseEquipedWeapon(attackType
==BASE_ATTACK
) )
8241 Item
* Player::GetShield(bool useable
) const
8243 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
8244 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_ARMOR
)
8250 if( item
->IsBroken())
8256 uint32
Player::GetAttackBySlot( uint8 slot
)
8260 case EQUIPMENT_SLOT_MAINHAND
: return BASE_ATTACK
;
8261 case EQUIPMENT_SLOT_OFFHAND
: return OFF_ATTACK
;
8262 case EQUIPMENT_SLOT_RANGED
: return RANGED_ATTACK
;
8263 default: return MAX_ATTACK
;
8267 bool Player::HasBankBagSlot( uint8 slot
) const
8269 uint32 maxslot
= GetByteValue(PLAYER_BYTES_2
, 2) + BANK_SLOT_BAG_START
;
8270 if( slot
< maxslot
)
8275 bool Player::IsInventoryPos( uint8 bag
, uint8 slot
)
8277 if( bag
== INVENTORY_SLOT_BAG_0
&& slot
== NULL_SLOT
)
8279 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
) )
8281 if( bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8283 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_END
) )
8288 bool Player::IsEquipmentPos( uint8 bag
, uint8 slot
)
8290 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< EQUIPMENT_SLOT_END
) )
8292 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8297 bool Player::IsBankPos( uint8 bag
, uint8 slot
)
8299 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
) )
8301 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8303 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8308 bool Player::IsBagPos( uint16 pos
)
8310 uint8 bag
= pos
>> 8;
8311 uint8 slot
= pos
& 255;
8312 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8314 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8319 bool Player::IsValidPos( uint8 bag
, uint8 slot
)
8325 if (bag
== INVENTORY_SLOT_BAG_0
)
8327 // any post selected
8328 if (slot
== NULL_SLOT
)
8332 if (slot
< EQUIPMENT_SLOT_END
)
8336 if (slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
)
8340 if (slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
)
8344 if (slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_END
)
8348 if (slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
)
8352 if (slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
8358 // bag content slots
8359 if (bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8361 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8365 // any post selected
8366 if (slot
== NULL_SLOT
)
8369 return slot
< pBag
->GetBagSize();
8372 // bank bag content slots
8373 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8375 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8379 // any post selected
8380 if (slot
== NULL_SLOT
)
8383 return slot
< pBag
->GetBagSize();
8391 bool Player::HasItemCount( uint32 item
, uint32 count
, bool inBankAlso
) const
8393 uint32 tempcount
= 0;
8394 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8396 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8397 if( pItem
&& pItem
->GetEntry() == item
)
8399 tempcount
+= pItem
->GetCount();
8400 if( tempcount
>= count
)
8404 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
8406 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8407 if( pItem
&& pItem
->GetEntry() == item
)
8409 tempcount
+= pItem
->GetCount();
8410 if( tempcount
>= count
)
8414 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8416 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8418 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8420 Item
* pItem
= GetItemByPos( i
, j
);
8421 if( pItem
&& pItem
->GetEntry() == item
)
8423 tempcount
+= pItem
->GetCount();
8424 if( tempcount
>= count
)
8433 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8435 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8436 if( pItem
&& pItem
->GetEntry() == item
)
8438 tempcount
+= pItem
->GetCount();
8439 if( tempcount
>= count
)
8443 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8445 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8447 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8449 Item
* pItem
= GetItemByPos( i
, j
);
8450 if( pItem
&& pItem
->GetEntry() == item
)
8452 tempcount
+= pItem
->GetCount();
8453 if( tempcount
>= count
)
8464 Item
* Player::GetItemOrItemWithGemEquipped( uint32 item
) const
8467 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
8469 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8470 if( pItem
&& pItem
->GetEntry() == item
)
8474 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(item
);
8475 if (pProto
&& pProto
->GemProperties
)
8477 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
8479 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8480 if( pItem
&& pItem
->GetProto()->Socket
[0].Color
)
8482 if (pItem
->GetGemCountWithID(item
) > 0 )
8491 uint8
Player::_CanTakeMoreSimilarItems(uint32 entry
, uint32 count
, Item
* pItem
, uint32
* no_space_count
) const
8493 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
8497 *no_space_count
= count
;
8498 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8502 if(pProto
->MaxCount
== 0)
8503 return EQUIP_ERR_OK
;
8505 uint32 curcount
= GetItemCount(pProto
->ItemId
,true,pItem
);
8507 if( curcount
+ count
> pProto
->MaxCount
)
8510 *no_space_count
= count
+curcount
- pProto
->MaxCount
;
8511 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8514 return EQUIP_ERR_OK
;
8517 bool Player::HasItemTotemCategory( uint32 TotemCategory
) const
8520 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8522 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8523 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8526 for(uint8 i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; ++i
)
8528 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8529 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8532 for(uint8 i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8534 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8536 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8538 pItem
= GetItemByPos( i
, j
);
8539 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8547 uint8
Player::_CanStoreItem_InSpecificSlot( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, ItemPrototype
const *pProto
, uint32
& count
, bool swap
, Item
* pSrcItem
) const
8549 Item
* pItem2
= GetItemByPos( bag
, slot
);
8551 // ignore move item (this slot will be empty at move)
8552 if(pItem2
==pSrcItem
)
8557 // empty specific slot - check item fit to slot
8558 if( !pItem2
|| swap
)
8560 if( bag
== INVENTORY_SLOT_BAG_0
)
8563 if(slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_START
+GetMaxKeyringSize() && !(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
))
8564 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8567 if(slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
|| slot
>= PLAYER_SLOT_END
)
8568 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8572 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8574 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8576 ItemPrototype
const* pBagProto
= pBag
->GetProto();
8578 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8580 if( !ItemCanGoIntoBag(pProto
,pBagProto
) )
8581 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8584 // non empty stack with space
8585 need_space
= pProto
->Stackable
;
8587 // non empty slot, check item type
8591 if(pItem2
->GetEntry() != pProto
->ItemId
)
8592 return EQUIP_ERR_ITEM_CANT_STACK
;
8595 if(pItem2
->GetCount() >= pProto
->Stackable
)
8596 return EQUIP_ERR_ITEM_CANT_STACK
;
8598 need_space
= pProto
->Stackable
- pItem2
->GetCount();
8601 if(need_space
> count
)
8604 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | slot
, need_space
);
8605 if(!newPosition
.isContainedIn(dest
))
8607 dest
.push_back(newPosition
);
8608 count
-= need_space
;
8610 return EQUIP_ERR_OK
;
8613 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
8615 // skip specific bag already processed in first called _CanStoreItem_InBag
8617 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8619 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8621 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8623 ItemPrototype
const* pBagProto
= pBag
->GetProto();
8625 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8627 // specialized bag mode or non-specilized
8628 if( non_specialized
!= (pBagProto
->Class
== ITEM_CLASS_CONTAINER
&& pBagProto
->SubClass
== ITEM_SUBCLASS_CONTAINER
) )
8629 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8631 if( !ItemCanGoIntoBag(pProto
,pBagProto
) )
8632 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8634 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8636 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8640 Item
* pItem2
= GetItemByPos( bag
, j
);
8642 // ignore move item (this slot will be empty at move)
8643 if(pItem2
==pSrcItem
)
8646 // if merge skip empty, if !merge skip non-empty
8647 if((pItem2
!=NULL
)!=merge
)
8652 if(pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->Stackable
)
8654 uint32 need_space
= pProto
->Stackable
- pItem2
->GetCount();
8655 if(need_space
> count
)
8658 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
8659 if(!newPosition
.isContainedIn(dest
))
8661 dest
.push_back(newPosition
);
8662 count
-= need_space
;
8665 return EQUIP_ERR_OK
;
8671 uint32 need_space
= pProto
->Stackable
;
8672 if(need_space
> count
)
8675 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
8676 if(!newPosition
.isContainedIn(dest
))
8678 dest
.push_back(newPosition
);
8679 count
-= need_space
;
8682 return EQUIP_ERR_OK
;
8686 return EQUIP_ERR_OK
;
8689 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
8691 for(uint32 j
= slot_begin
; j
< slot_end
; j
++)
8693 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8694 if(INVENTORY_SLOT_BAG_0
==skip_bag
&& j
==skip_slot
)
8697 Item
* pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, j
);
8699 // ignore move item (this slot will be empty at move)
8700 if(pItem2
==pSrcItem
)
8703 // if merge skip empty, if !merge skip non-empty
8704 if((pItem2
!=NULL
)!=merge
)
8709 if(pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->Stackable
)
8711 uint32 need_space
= pProto
->Stackable
- pItem2
->GetCount();
8712 if(need_space
> count
)
8714 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
8715 if(!newPosition
.isContainedIn(dest
))
8717 dest
.push_back(newPosition
);
8718 count
-= need_space
;
8721 return EQUIP_ERR_OK
;
8727 uint32 need_space
= pProto
->Stackable
;
8728 if(need_space
> count
)
8731 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
8732 if(!newPosition
.isContainedIn(dest
))
8734 dest
.push_back(newPosition
);
8735 count
-= need_space
;
8738 return EQUIP_ERR_OK
;
8742 return EQUIP_ERR_OK
;
8745 uint8
Player::_CanStoreItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, uint32 entry
, uint32 count
, Item
*pItem
, bool swap
, uint32
* no_space_count
) const
8747 sLog
.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, entry
, count
);
8749 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
8753 *no_space_count
= count
;
8754 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
:EQUIP_ERR_ITEM_NOT_FOUND
;
8757 if(pItem
&& pItem
->IsBindedNotWith(GetGUID()))
8760 *no_space_count
= count
;
8761 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
8764 // check count of items (skip for auto move for same player from bank)
8765 uint32 no_similar_count
= 0; // can't store this amount similar items
8766 uint8 res
= _CanTakeMoreSimilarItems(entry
,count
,pItem
,&no_similar_count
);
8767 if(res
!=EQUIP_ERR_OK
)
8769 if(count
==no_similar_count
)
8772 *no_space_count
= no_similar_count
;
8775 count
-= no_similar_count
;
8779 if( bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
8781 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
8782 if(res
!=EQUIP_ERR_OK
)
8785 *no_space_count
= count
+ no_similar_count
;
8791 if(no_similar_count
==0)
8792 return EQUIP_ERR_OK
;
8795 *no_space_count
= count
+ no_similar_count
;
8796 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8800 // not specific slot or have space for partly store only in specific slot
8803 if( bag
!= NULL_BAG
)
8805 // search stack in bag for merge to
8806 if( pProto
->Stackable
> 1 )
8808 if( bag
== INVENTORY_SLOT_BAG_0
) // inventory
8810 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
8811 if(res
!=EQUIP_ERR_OK
)
8814 *no_space_count
= count
+ no_similar_count
;
8820 if(no_similar_count
==0)
8821 return EQUIP_ERR_OK
;
8824 *no_space_count
= count
+ no_similar_count
;
8825 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8828 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
8829 if(res
!=EQUIP_ERR_OK
)
8832 *no_space_count
= count
+ no_similar_count
;
8838 if(no_similar_count
==0)
8839 return EQUIP_ERR_OK
;
8842 *no_space_count
= count
+ no_similar_count
;
8843 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8846 else // equipped bag
8848 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
8849 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
8850 if(res
!=EQUIP_ERR_OK
)
8851 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
8853 if(res
!=EQUIP_ERR_OK
)
8856 *no_space_count
= count
+ no_similar_count
;
8862 if(no_similar_count
==0)
8863 return EQUIP_ERR_OK
;
8866 *no_space_count
= count
+ no_similar_count
;
8867 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8872 // search free slot in bag for place to
8873 if( bag
== INVENTORY_SLOT_BAG_0
) // inventory
8875 // search free slot - keyring case
8876 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
8878 uint32 keyringSize
= GetMaxKeyringSize();
8879 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
8880 if(res
!=EQUIP_ERR_OK
)
8883 *no_space_count
= count
+ no_similar_count
;
8889 if(no_similar_count
==0)
8890 return EQUIP_ERR_OK
;
8893 *no_space_count
= count
+ no_similar_count
;
8894 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8898 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
8899 if(res
!=EQUIP_ERR_OK
)
8902 *no_space_count
= count
+ no_similar_count
;
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
;
8916 else // equipped bag
8918 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
8919 if(res
!=EQUIP_ERR_OK
)
8920 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
8922 if(res
!=EQUIP_ERR_OK
)
8925 *no_space_count
= count
+ no_similar_count
;
8931 if(no_similar_count
==0)
8932 return EQUIP_ERR_OK
;
8935 *no_space_count
= count
+ no_similar_count
;
8936 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8941 // not specific bag or have space for partly store only in specific bag
8943 // search stack for merge to
8944 if( pProto
->Stackable
> 1 )
8946 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
8947 if(res
!=EQUIP_ERR_OK
)
8950 *no_space_count
= count
+ no_similar_count
;
8956 if(no_similar_count
==0)
8957 return EQUIP_ERR_OK
;
8960 *no_space_count
= count
+ no_similar_count
;
8961 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8964 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
8965 if(res
!=EQUIP_ERR_OK
)
8968 *no_space_count
= count
+ no_similar_count
;
8974 if(no_similar_count
==0)
8975 return EQUIP_ERR_OK
;
8978 *no_space_count
= count
+ no_similar_count
;
8979 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8982 if( pProto
->BagFamily
)
8984 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8986 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
8987 if(res
!=EQUIP_ERR_OK
)
8992 if(no_similar_count
==0)
8993 return EQUIP_ERR_OK
;
8996 *no_space_count
= count
+ no_similar_count
;
8997 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9002 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9004 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
9005 if(res
!=EQUIP_ERR_OK
)
9010 if(no_similar_count
==0)
9011 return EQUIP_ERR_OK
;
9014 *no_space_count
= count
+ no_similar_count
;
9015 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9020 // search free slot - special bag case
9021 if( pProto
->BagFamily
)
9023 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9025 uint32 keyringSize
= GetMaxKeyringSize();
9026 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9027 if(res
!=EQUIP_ERR_OK
)
9030 *no_space_count
= count
+ no_similar_count
;
9036 if(no_similar_count
==0)
9037 return EQUIP_ERR_OK
;
9040 *no_space_count
= count
+ no_similar_count
;
9041 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9045 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9047 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
9048 if(res
!=EQUIP_ERR_OK
)
9053 if(no_similar_count
==0)
9054 return EQUIP_ERR_OK
;
9057 *no_space_count
= count
+ no_similar_count
;
9058 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9064 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9065 if(res
!=EQUIP_ERR_OK
)
9068 *no_space_count
= count
+ no_similar_count
;
9074 if(no_similar_count
==0)
9075 return EQUIP_ERR_OK
;
9078 *no_space_count
= count
+ no_similar_count
;
9079 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9082 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9084 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
9085 if(res
!=EQUIP_ERR_OK
)
9090 if(no_similar_count
==0)
9091 return EQUIP_ERR_OK
;
9094 *no_space_count
= count
+ no_similar_count
;
9095 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9100 *no_space_count
= count
+ no_similar_count
;
9102 return EQUIP_ERR_INVENTORY_FULL
;
9105 //////////////////////////////////////////////////////////////////////////
9106 uint8
Player::CanStoreItems( Item
**pItems
,int count
) const
9111 int inv_slot_items
[INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
];
9112 int inv_bags
[INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
][MAX_BAG_SIZE
];
9113 int inv_keys
[KEYRING_SLOT_END
-KEYRING_SLOT_START
];
9115 memset(inv_slot_items
,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
));
9116 memset(inv_bags
,0,sizeof(int)*(INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
)*MAX_BAG_SIZE
);
9117 memset(inv_keys
,0,sizeof(int)*(KEYRING_SLOT_END
-KEYRING_SLOT_START
));
9119 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
9121 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9123 if (pItem2
&& !pItem2
->IsInTrade())
9125 inv_slot_items
[i
-INVENTORY_SLOT_ITEM_START
] = pItem2
->GetCount();
9129 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
9131 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9133 if (pItem2
&& !pItem2
->IsInTrade())
9135 inv_keys
[i
-KEYRING_SLOT_START
] = pItem2
->GetCount();
9139 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9141 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
9143 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9145 pItem2
= GetItemByPos( i
, j
);
9146 if (pItem2
&& !pItem2
->IsInTrade())
9148 inv_bags
[i
-INVENTORY_SLOT_BAG_START
][j
] = pItem2
->GetCount();
9154 // check free space for all items
9155 for (int k
=0;k
<count
;k
++)
9157 Item
*pItem
= pItems
[k
];
9160 if (!pItem
) continue;
9162 sLog
.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k
+1, pItem
->GetEntry(), pItem
->GetCount());
9163 ItemPrototype
const *pProto
= pItem
->GetProto();
9167 return EQUIP_ERR_ITEM_NOT_FOUND
;
9170 if(pItem
->IsBindedNotWith(GetGUID()))
9171 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9174 ItemPrototype
const *pBagProto
;
9176 // item is 'one item only'
9177 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9178 if(res
!= EQUIP_ERR_OK
)
9181 // search stack for merge to
9182 if( pProto
->Stackable
> 1 )
9184 bool b_found
= false;
9186 for(int t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_END
; t
++)
9188 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9189 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_keys
[t
-KEYRING_SLOT_START
] + pItem
->GetCount() <= pProto
->Stackable
)
9191 inv_keys
[t
-KEYRING_SLOT_START
] += pItem
->GetCount();
9196 if (b_found
) continue;
9198 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; t
++)
9200 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9201 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] + pItem
->GetCount() <= pProto
->Stackable
)
9203 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] += pItem
->GetCount();
9208 if (b_found
) continue;
9210 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9212 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9215 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9217 pItem2
= GetItemByPos( t
, j
);
9218 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] + pItem
->GetCount() <= pProto
->Stackable
)
9220 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] += pItem
->GetCount();
9227 if (b_found
) continue;
9231 if( pProto
->BagFamily
)
9233 bool b_found
= false;
9234 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9236 uint32 keyringSize
= GetMaxKeyringSize();
9237 for(uint32 t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_START
+keyringSize
; ++t
)
9239 if( inv_keys
[t
-KEYRING_SLOT_START
] == 0 )
9241 inv_keys
[t
-KEYRING_SLOT_START
] = 1;
9248 if (b_found
) continue;
9250 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9252 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9255 pBagProto
= pBag
->GetProto();
9257 // not plain container check
9258 if( pBagProto
&& (pBagProto
->Class
!= ITEM_CLASS_CONTAINER
|| pBagProto
->SubClass
!= ITEM_SUBCLASS_CONTAINER
) &&
9259 ItemCanGoIntoBag(pProto
,pBagProto
) )
9261 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9263 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9265 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9273 if (b_found
) continue;
9277 bool b_found
= false;
9278 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; t
++)
9280 if( inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] == 0 )
9282 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] = 1;
9287 if (b_found
) continue;
9289 // search free slot in bags
9290 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9292 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9295 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9297 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9299 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9307 // no free slot found?
9309 return EQUIP_ERR_INVENTORY_FULL
;
9312 return EQUIP_ERR_OK
;
9315 //////////////////////////////////////////////////////////////////////////
9316 uint8
Player::CanEquipNewItem( uint8 slot
, uint16
&dest
, uint32 item
, bool swap
) const
9319 Item
*pItem
= Item::CreateItem( item
, 1, this );
9322 uint8 result
= CanEquipItem(slot
, dest
, pItem
, swap
);
9327 return EQUIP_ERR_ITEM_NOT_FOUND
;
9330 uint8
Player::CanEquipItem( uint8 slot
, uint16
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
9335 sLog
.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot
, pItem
->GetEntry(), pItem
->GetCount());
9336 ItemPrototype
const *pProto
= pItem
->GetProto();
9339 // May be here should be more stronger checks; STUNNED checked
9340 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9341 if (not_loading
&& hasUnitState(UNIT_STAT_STUNNED
))
9342 return EQUIP_ERR_YOU_ARE_STUNNED
;
9344 if(pItem
->IsBindedNotWith(GetGUID()))
9345 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9347 // check count of items (skip for auto move for same player from bank)
9348 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9349 if(res
!= EQUIP_ERR_OK
)
9352 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9354 // - in-progress arenas
9355 if( !pProto
->CanChangeEquipStateInCombat() )
9358 return EQUIP_ERR_NOT_IN_COMBAT
;
9360 if(BattleGround
* bg
= GetBattleGround())
9361 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
9362 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
9365 if(isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
!= 0)
9366 return EQUIP_ERR_CANT_DO_RIGHT_NOW
; // maybe exist better err
9368 if(IsNonMeleeSpellCasted(false))
9369 return EQUIP_ERR_CANT_DO_RIGHT_NOW
;
9371 uint8 eslot
= FindEquipSlot( pProto
, slot
, swap
);
9372 if( eslot
== NULL_SLOT
)
9373 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9375 uint8 msg
= CanUseItem( pItem
, not_loading
);
9376 if( msg
!= EQUIP_ERR_OK
)
9378 if( !swap
&& GetItemByPos( INVENTORY_SLOT_BAG_0
, eslot
) )
9379 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE
;
9381 // check unique-equipped on item
9382 if (pProto
->Flags
& ITEM_FLAGS_UNIQUE_EQUIPPED
)
9384 // there is an equip limit on this item
9385 Item
* tItem
= GetItemOrItemWithGemEquipped(pProto
->ItemId
);
9386 if (tItem
&& (!swap
|| tItem
->GetSlot() != eslot
) )
9387 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
9390 // check unique-equipped on gems
9391 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
9393 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
9396 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
9400 ItemPrototype
const* pGem
= objmgr
.GetItemPrototype(enchantEntry
->GemID
);
9401 if(pGem
&& (pGem
->Flags
& ITEM_FLAGS_UNIQUE_EQUIPPED
))
9403 Item
* tItem
= GetItemOrItemWithGemEquipped(enchantEntry
->GemID
);
9404 if(tItem
&& (!swap
|| tItem
->GetSlot() != eslot
))
9405 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
9409 // check unique-equipped special item classes
9410 if (pProto
->Class
== ITEM_CLASS_QUIVER
)
9412 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9414 if( Item
* pBag
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
) )
9416 if( ItemPrototype
const* pBagProto
= pBag
->GetProto() )
9418 if( pBagProto
->Class
==pProto
->Class
&& pBagProto
->SubClass
==pProto
->SubClass
&&
9419 (!swap
|| pBag
->GetSlot() != eslot
) )
9421 if(pBagProto
->SubClass
== ITEM_SUBCLASS_AMMO_POUCH
)
9422 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
;
9424 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER
;
9431 uint32 type
= pProto
->InventoryType
;
9433 if(eslot
== EQUIPMENT_SLOT_OFFHAND
)
9435 if( type
== INVTYPE_WEAPON
|| type
== INVTYPE_WEAPONOFFHAND
)
9438 return EQUIP_ERR_CANT_DUAL_WIELD
;
9441 Item
*mainItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_MAINHAND
);
9444 if(mainItem
->GetProto()->InventoryType
== INVTYPE_2HWEAPON
)
9445 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED
;
9449 // equip two-hand weapon case (with possible unequip 2 items)
9450 if( type
== INVTYPE_2HWEAPON
)
9452 if(eslot
!= EQUIPMENT_SLOT_MAINHAND
)
9453 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9455 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9456 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
9457 ItemPosCountVec off_dest
;
9458 if( offItem
&& (!not_loading
||
9459 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0
) << 8 | EQUIPMENT_SLOT_OFFHAND
,false) != EQUIP_ERR_OK
||
9460 CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false ) != EQUIP_ERR_OK
) )
9461 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_INVENTORY_FULL
;
9463 dest
= ((INVENTORY_SLOT_BAG_0
<< 8) | eslot
);
9464 return EQUIP_ERR_OK
;
9468 return EQUIP_ERR_ITEM_NOT_FOUND
;
9470 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
;
9473 uint8
Player::CanUnequipItem( uint16 pos
, bool swap
) const
9475 // Applied only to equipped items and bank bags
9476 if(!IsEquipmentPos(pos
) && !IsBagPos(pos
))
9477 return EQUIP_ERR_OK
;
9479 Item
* pItem
= GetItemByPos(pos
);
9481 // Applied only to existed equipped item
9483 return EQUIP_ERR_OK
;
9485 sLog
.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos
, pItem
->GetEntry(), pItem
->GetCount());
9487 ItemPrototype
const *pProto
= pItem
->GetProto();
9489 return EQUIP_ERR_ITEM_NOT_FOUND
;
9491 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9493 // - in-progress arenas
9494 if( !pProto
->CanChangeEquipStateInCombat() )
9497 return EQUIP_ERR_NOT_IN_COMBAT
;
9499 if(BattleGround
* bg
= GetBattleGround())
9500 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
9501 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
9504 if(!swap
&& pItem
->IsBag() && !((Bag
*)pItem
)->IsEmpty())
9505 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS
;
9507 return EQUIP_ERR_OK
;
9510 uint8
Player::CanBankItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
9513 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
9515 uint32 count
= pItem
->GetCount();
9517 sLog
.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), pItem
->GetCount());
9518 ItemPrototype
const *pProto
= pItem
->GetProto();
9520 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
9522 if( pItem
->IsBindedNotWith(GetGUID()) )
9523 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9525 // check count of items (skip for auto move for same player from bank)
9526 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9527 if(res
!= EQUIP_ERR_OK
)
9531 if( bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
9533 if( pProto
->InventoryType
== INVTYPE_BAG
)
9535 Bag
*pBag
= (Bag
*)pItem
;
9538 if( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
9540 if( !HasBankBagSlot( slot
) )
9541 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT
;
9542 if( uint8 cantuse
= CanUseItem( pItem
, not_loading
) != EQUIP_ERR_OK
)
9547 if( !pBag
->IsEmpty() )
9548 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
;
9554 if( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
9555 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
;
9558 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
9559 if(res
!=EQUIP_ERR_OK
)
9563 return EQUIP_ERR_OK
;
9566 // not specific slot or have space for partly store only in specific slot
9569 if( bag
!= NULL_BAG
)
9571 if( pProto
->InventoryType
== INVTYPE_BAG
)
9573 Bag
*pBag
= (Bag
*)pItem
;
9574 if( pBag
&& !pBag
->IsEmpty() )
9575 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
;
9578 // search stack in bag for merge to
9579 if( pProto
->Stackable
> 1 )
9581 if( bag
== INVENTORY_SLOT_BAG_0
)
9583 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9584 if(res
!=EQUIP_ERR_OK
)
9588 return EQUIP_ERR_OK
;
9592 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
9593 if(res
!=EQUIP_ERR_OK
)
9594 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
9596 if(res
!=EQUIP_ERR_OK
)
9600 return EQUIP_ERR_OK
;
9604 // search free slot in bag
9605 if( bag
== INVENTORY_SLOT_BAG_0
)
9607 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9608 if(res
!=EQUIP_ERR_OK
)
9612 return EQUIP_ERR_OK
;
9616 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
9617 if(res
!=EQUIP_ERR_OK
)
9618 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
9620 if(res
!=EQUIP_ERR_OK
)
9624 return EQUIP_ERR_OK
;
9628 // not specific bag or have space for partly store only in specific bag
9630 // search stack for merge to
9631 if( pProto
->Stackable
> 1 )
9634 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9635 if(res
!=EQUIP_ERR_OK
)
9639 return EQUIP_ERR_OK
;
9642 if( pProto
->BagFamily
)
9644 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
9646 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
9647 if(res
!=EQUIP_ERR_OK
)
9651 return EQUIP_ERR_OK
;
9655 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
9657 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
9658 if(res
!=EQUIP_ERR_OK
)
9662 return EQUIP_ERR_OK
;
9666 // search free place in special bag
9667 if( pProto
->BagFamily
)
9669 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
9671 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
9672 if(res
!=EQUIP_ERR_OK
)
9676 return EQUIP_ERR_OK
;
9680 // search free space
9681 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9682 if(res
!=EQUIP_ERR_OK
)
9686 return EQUIP_ERR_OK
;
9688 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
9690 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
9691 if(res
!=EQUIP_ERR_OK
)
9695 return EQUIP_ERR_OK
;
9697 return EQUIP_ERR_BANK_FULL
;
9700 uint8
Player::CanUseItem( Item
*pItem
, bool not_loading
) const
9704 sLog
.outDebug( "STORAGE: CanUseItem item = %u", pItem
->GetEntry());
9705 if( !isAlive() && not_loading
)
9706 return EQUIP_ERR_YOU_ARE_DEAD
;
9708 // return EQUIP_ERR_YOU_ARE_STUNNED;
9709 ItemPrototype
const *pProto
= pItem
->GetProto();
9712 if( pItem
->IsBindedNotWith(GetGUID()) )
9713 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9714 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
9715 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
9716 if( pItem
->GetSkill() != 0 )
9718 if( GetSkillValue( pItem
->GetSkill() ) == 0 )
9719 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9721 if( pProto
->RequiredSkill
!= 0 )
9723 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
9724 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9725 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
9726 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
9728 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
9729 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9730 if( pProto
->RequiredReputationFaction
&& uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
9731 return EQUIP_ERR_CANT_EQUIP_REPUTATION
;
9732 if( getLevel() < pProto
->RequiredLevel
)
9733 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
9734 return EQUIP_ERR_OK
;
9737 return EQUIP_ERR_ITEM_NOT_FOUND
;
9740 bool Player::CanUseItem( ItemPrototype
const *pProto
)
9742 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
9746 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
9748 if( pProto
->RequiredSkill
!= 0 )
9750 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
9752 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
9755 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
9757 if( getLevel() < pProto
->RequiredLevel
)
9764 uint8
Player::CanUseAmmo( uint32 item
) const
9766 sLog
.outDebug( "STORAGE: CanUseAmmo item = %u", item
);
9768 return EQUIP_ERR_YOU_ARE_DEAD
;
9770 // return EQUIP_ERR_YOU_ARE_STUNNED;
9771 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
9774 if( pProto
->InventoryType
!= INVTYPE_AMMO
)
9775 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE
;
9776 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
9777 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
9778 if( pProto
->RequiredSkill
!= 0 )
9780 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
9781 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9782 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
9783 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
9785 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
9786 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9787 /*if( GetReputation() < pProto->RequiredReputation )
9788 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9790 if( getLevel() < pProto
->RequiredLevel
)
9791 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
9794 if(GetDummyAura(46699))
9795 return EQUIP_ERR_BAG_FULL6
;
9797 return EQUIP_ERR_OK
;
9799 return EQUIP_ERR_ITEM_NOT_FOUND
;
9802 void Player::SetAmmo( uint32 item
)
9808 if( GetUInt32Value(PLAYER_AMMO_ID
) == item
)
9814 uint8 msg
= CanUseAmmo( item
);
9815 if( msg
!= EQUIP_ERR_OK
)
9817 SendEquipError( msg
, NULL
, NULL
);
9822 SetUInt32Value(PLAYER_AMMO_ID
, item
);
9824 _ApplyAmmoBonuses();
9827 void Player::RemoveAmmo()
9829 SetUInt32Value(PLAYER_AMMO_ID
, 0);
9833 if(CanModifyStats())
9834 UpdateDamagePhysical(RANGED_ATTACK
);
9837 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
9838 Item
* Player::StoreNewItem( ItemPosCountVec
const& dest
, uint32 item
, bool update
,int32 randomPropertyId
)
9841 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); ++itr
)
9842 count
+= itr
->count
;
9844 Item
*pItem
= Item::CreateItem( item
, count
, this );
9847 ItemAddedQuestCheck( item
, count
);
9848 if(randomPropertyId
)
9849 pItem
->SetItemRandomProperties(randomPropertyId
);
9850 pItem
= StoreItem( dest
, pItem
, update
);
9855 Item
* Player::StoreItem( ItemPosCountVec
const& dest
, Item
* pItem
, bool update
)
9860 Item
* lastItem
= pItem
;
9862 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); )
9864 uint16 pos
= itr
->pos
;
9865 uint32 count
= itr
->count
;
9869 if(itr
== dest
.end())
9871 lastItem
= _StoreItem(pos
,pItem
,count
,false,update
);
9875 lastItem
= _StoreItem(pos
,pItem
,count
,true,update
);
9881 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
9882 Item
* Player::_StoreItem( uint16 pos
, Item
*pItem
, uint32 count
, bool clone
, bool update
)
9887 uint8 bag
= pos
>> 8;
9888 uint8 slot
= pos
& 255;
9890 sLog
.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), count
);
9892 Item
*pItem2
= GetItemByPos( bag
, slot
);
9897 pItem
= pItem
->CloneItem(count
,this);
9899 pItem
->SetCount(count
);
9904 if( pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
9905 pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
9906 pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
) )
9907 pItem
->SetBinding( true );
9909 if( bag
== INVENTORY_SLOT_BAG_0
)
9911 m_items
[slot
] = pItem
;
9912 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), pItem
->GetGUID() );
9913 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
9914 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
9916 pItem
->SetSlot( slot
);
9917 pItem
->SetContainer( NULL
);
9919 if( IsInWorld() && update
)
9921 pItem
->AddToWorld();
9922 pItem
->SendUpdateToPlayer( this );
9925 pItem
->SetState(ITEM_CHANGED
, this);
9929 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
9932 pBag
->StoreItem( slot
, pItem
, update
);
9933 if( IsInWorld() && update
)
9935 pItem
->AddToWorld();
9936 pItem
->SendUpdateToPlayer( this );
9938 pItem
->SetState(ITEM_CHANGED
, this);
9939 pBag
->SetState(ITEM_CHANGED
, this);
9943 AddEnchantmentDurations(pItem
);
9944 AddItemDurations(pItem
);
9950 if( pItem2
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
9951 pItem2
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
9952 pItem2
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
) )
9953 pItem2
->SetBinding( true );
9955 pItem2
->SetCount( pItem2
->GetCount() + count
);
9956 if( IsInWorld() && update
)
9957 pItem2
->SendUpdateToPlayer( this );
9961 // delete item (it not in any slot currently)
9962 if( IsInWorld() && update
)
9964 pItem
->RemoveFromWorld();
9965 pItem
->DestroyForPlayer( this );
9968 RemoveEnchantmentDurations(pItem
);
9969 RemoveItemDurations(pItem
);
9971 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
9972 pItem
->SetState(ITEM_REMOVED
, this);
9974 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
9975 AddEnchantmentDurations(pItem2
);
9977 pItem2
->SetState(ITEM_CHANGED
, this);
9983 Item
* Player::EquipNewItem( uint16 pos
, uint32 item
, bool update
)
9985 Item
*pItem
= Item::CreateItem( item
, 1, this );
9988 ItemAddedQuestCheck( item
, 1 );
9989 Item
* retItem
= EquipItem( pos
, pItem
, update
);
9996 Item
* Player::EquipItem( uint16 pos
, Item
*pItem
, bool update
)
10000 AddEnchantmentDurations(pItem
);
10001 AddItemDurations(pItem
);
10003 uint8 bag
= pos
>> 8;
10004 uint8 slot
= pos
& 255;
10006 Item
*pItem2
= GetItemByPos( bag
, slot
);
10010 VisualizeItem( slot
, pItem
);
10014 ItemPrototype
const *pProto
= pItem
->GetProto();
10016 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10017 if(pProto
&& pProto
->ItemSet
)
10018 AddItemsSetItem(this,pItem
);
10020 _ApplyItemMods(pItem
, slot
, true);
10022 if(pProto
&& isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
== 0)
10024 uint32 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s
;
10026 if (getClass() == CLASS_ROGUE
)
10027 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s
;
10029 SpellEntry
const* spellProto
= sSpellStore
.LookupEntry(cooldownSpell
);
10032 sLog
.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell
);
10035 m_weaponChangeTimer
= spellProto
->StartRecoveryTime
;
10037 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+4);
10038 data
<< uint64(GetGUID());
10040 data
<< uint32(cooldownSpell
);
10042 GetSession()->SendPacket(&data
);
10047 if( IsInWorld() && update
)
10049 pItem
->AddToWorld();
10050 pItem
->SendUpdateToPlayer( this );
10053 ApplyEquipCooldown(pItem
);
10055 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
10056 UpdateExpertise(BASE_ATTACK
);
10057 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10058 UpdateExpertise(OFF_ATTACK
);
10062 pItem2
->SetCount( pItem2
->GetCount() + pItem
->GetCount() );
10063 if( IsInWorld() && update
)
10064 pItem2
->SendUpdateToPlayer( this );
10066 // delete item (it not in any slot currently)
10067 //pItem->DeleteFromDB();
10068 if( IsInWorld() && update
)
10070 pItem
->RemoveFromWorld();
10071 pItem
->DestroyForPlayer( this );
10074 RemoveEnchantmentDurations(pItem
);
10075 RemoveItemDurations(pItem
);
10077 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10078 pItem
->SetState(ITEM_REMOVED
, this);
10079 pItem2
->SetState(ITEM_CHANGED
, this);
10081 ApplyEquipCooldown(pItem2
);
10090 void Player::QuickEquipItem( uint16 pos
, Item
*pItem
)
10094 AddEnchantmentDurations(pItem
);
10095 AddItemDurations(pItem
);
10097 uint8 slot
= pos
& 255;
10098 VisualizeItem( slot
, pItem
);
10102 pItem
->AddToWorld();
10103 pItem
->SendUpdateToPlayer( this );
10108 void Player::SetVisibleItemSlot(uint8 slot
, Item
*pItem
)
10110 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10111 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10112 // entry // Size: 1
10113 // inspected enchantments // Size: 6
10115 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10116 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10121 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), pItem
->GetUInt64Value(ITEM_FIELD_CREATOR
));
10123 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
10124 SetUInt32Value(VisibleBase
+ 0, pItem
->GetEntry());
10126 for(int i
= 0; i
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++i
)
10127 SetUInt32Value(VisibleBase
+ 1 + i
, pItem
->GetEnchantmentId(EnchantmentSlot(i
)));
10129 // Use SetInt16Value to prevent set high part to FFFF for negative value
10130 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0, pItem
->GetItemRandomPropertyId());
10131 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), pItem
->GetItemSuffixFactor());
10135 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10137 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
10138 SetUInt32Value(VisibleBase
+ 0, 0);
10140 for(int i
= 0; i
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++i
)
10141 SetUInt32Value(VisibleBase
+ 1 + i
, 0);
10143 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 0 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10144 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10148 void Player::VisualizeItem( uint8 slot
, Item
*pItem
)
10153 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10154 if( pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
|| pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
|| pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
)
10155 pItem
->SetBinding( true );
10157 sLog
.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot
, pItem
->GetEntry());
10159 m_items
[slot
] = pItem
;
10160 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), pItem
->GetGUID() );
10161 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10162 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10163 pItem
->SetSlot( slot
);
10164 pItem
->SetContainer( NULL
);
10166 if( slot
< EQUIPMENT_SLOT_END
)
10167 SetVisibleItemSlot(slot
,pItem
);
10169 pItem
->SetState(ITEM_CHANGED
, this);
10172 void Player::RemoveItem( uint8 bag
, uint8 slot
, bool update
)
10174 // note: removeitem does not actually change the item
10175 // it only takes the item out of storage temporarily
10176 // note2: if removeitem is to be used for delinking
10177 // the item must be removed from the player's updatequeue
10179 Item
*pItem
= GetItemByPos( bag
, slot
);
10182 sLog
.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10184 RemoveEnchantmentDurations(pItem
);
10185 RemoveItemDurations(pItem
);
10187 if( bag
== INVENTORY_SLOT_BAG_0
)
10189 if ( slot
< INVENTORY_SLOT_BAG_END
)
10191 ItemPrototype
const *pProto
= pItem
->GetProto();
10192 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10194 if(pProto
&& pProto
->ItemSet
)
10195 RemoveItemsSetItem(this,pProto
);
10197 _ApplyItemMods(pItem
, slot
, false);
10199 // remove item dependent auras and casts (only weapon and armor slots)
10200 if(slot
< EQUIPMENT_SLOT_END
)
10201 RemoveItemDependentAurasAndCasts(pItem
);
10203 // remove held enchantments
10204 if ( slot
== EQUIPMENT_SLOT_MAINHAND
)
10206 if (pItem
->GetItemSuffixFactor())
10208 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3
);
10209 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4
);
10213 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0
);
10214 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1
);
10219 m_items
[slot
] = NULL
;
10220 SetUInt64Value((uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
*2)), 0);
10222 if ( slot
< EQUIPMENT_SLOT_END
)
10223 SetVisibleItemSlot(slot
,NULL
);
10227 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
10229 pBag
->RemoveItem(slot
, update
);
10231 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10232 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10233 pItem
->SetSlot( NULL_SLOT
);
10234 if( IsInWorld() && update
)
10235 pItem
->SendUpdateToPlayer( this );
10237 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
10238 UpdateExpertise(BASE_ATTACK
);
10239 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10240 UpdateExpertise(OFF_ATTACK
);
10244 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10245 void Player::MoveItemFromInventory(uint8 bag
, uint8 slot
, bool update
)
10247 if(Item
* it
= GetItemByPos(bag
,slot
))
10249 ItemRemovedQuestCheck(it
->GetEntry(),it
->GetCount());
10250 RemoveItem( bag
,slot
,update
);
10251 it
->RemoveFromUpdateQueueOf(this);
10252 if(it
->IsInWorld())
10254 it
->RemoveFromWorld();
10255 it
->DestroyForPlayer( this );
10260 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10261 void Player::MoveItemToInventory(ItemPosCountVec
const& dest
, Item
* pItem
, bool update
, bool in_characterInventoryDB
)
10263 // update quest counters
10264 ItemAddedQuestCheck(pItem
->GetEntry(),pItem
->GetCount());
10267 Item
* pLastItem
= StoreItem( dest
, pItem
, update
);
10269 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10270 if(pLastItem
==pItem
)
10272 // update owner for last item (this can be original item with wrong owner
10273 if(pLastItem
->GetOwnerGUID() != GetGUID())
10274 pLastItem
->SetOwnerGUID(GetGUID());
10276 // if this original item then it need create record in inventory
10277 // in case trade we already have item in other player inventory
10278 pLastItem
->SetState(in_characterInventoryDB
? ITEM_CHANGED
: ITEM_NEW
, this);
10282 void Player::DestroyItem( uint8 bag
, uint8 slot
, bool update
)
10284 Item
*pItem
= GetItemByPos( bag
, slot
);
10287 sLog
.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10289 // start from destroy contained items (only equipped bag can have its)
10290 if (pItem
->IsBag() && pItem
->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10292 for (int i
= 0; i
< MAX_BAG_SIZE
; i
++)
10293 DestroyItem(slot
,i
,update
);
10296 if(pItem
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_WRAPPED
))
10297 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem
->GetGUIDLow());
10299 RemoveEnchantmentDurations(pItem
);
10300 RemoveItemDurations(pItem
);
10302 ItemRemovedQuestCheck( pItem
->GetEntry(), pItem
->GetCount() );
10304 if( bag
== INVENTORY_SLOT_BAG_0
)
10306 SetUInt64Value((uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
*2)), 0);
10308 // equipment and equipped bags can have applied bonuses
10309 if ( slot
< INVENTORY_SLOT_BAG_END
)
10311 ItemPrototype
const *pProto
= pItem
->GetProto();
10313 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10314 if(pProto
&& pProto
->ItemSet
)
10315 RemoveItemsSetItem(this,pProto
);
10317 _ApplyItemMods(pItem
, slot
, false);
10320 if ( slot
< EQUIPMENT_SLOT_END
)
10322 // remove item dependent auras and casts (only weapon and armor slots)
10323 RemoveItemDependentAurasAndCasts(pItem
);
10325 // equipment visual show
10326 SetVisibleItemSlot(slot
,NULL
);
10329 m_items
[slot
] = NULL
;
10331 else if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
))
10332 pBag
->RemoveItem(slot
, update
);
10334 if( IsInWorld() && update
)
10336 pItem
->RemoveFromWorld();
10337 pItem
->DestroyForPlayer(this);
10340 //pItem->SetOwnerGUID(0);
10341 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10342 pItem
->SetSlot( NULL_SLOT
);
10343 pItem
->SetState(ITEM_REMOVED
, this);
10347 void Player::DestroyItemCount( uint32 item
, uint32 count
, bool update
, bool unequip_check
)
10349 sLog
.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item
, count
);
10351 ItemPrototype
const *pProto
;
10352 uint32 remcount
= 0;
10355 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
10357 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10358 if( pItem
&& pItem
->GetEntry() == item
)
10360 if( pItem
->GetCount() + remcount
<= count
)
10362 // all items in inventory can unequipped
10363 remcount
+= pItem
->GetCount();
10364 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10366 if(remcount
>=count
)
10371 pProto
= pItem
->GetProto();
10372 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10373 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10374 if( IsInWorld() & update
)
10375 pItem
->SendUpdateToPlayer( this );
10376 pItem
->SetState(ITEM_CHANGED
, this);
10381 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
10383 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10384 if( pItem
&& pItem
->GetEntry() == item
)
10386 if( pItem
->GetCount() + remcount
<= count
)
10388 // all keys can be unequipped
10389 remcount
+= pItem
->GetCount();
10390 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10392 if(remcount
>=count
)
10397 pProto
= pItem
->GetProto();
10398 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10399 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10400 if( IsInWorld() & update
)
10401 pItem
->SendUpdateToPlayer( this );
10402 pItem
->SetState(ITEM_CHANGED
, this);
10408 // in inventory bags
10409 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10411 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10413 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
10415 pItem
= pBag
->GetItemByPos(j
);
10416 if( pItem
&& pItem
->GetEntry() == item
)
10418 // all items in bags can be unequipped
10419 if( pItem
->GetCount() + remcount
<= count
)
10421 remcount
+= pItem
->GetCount();
10422 DestroyItem( i
, j
, update
);
10424 if(remcount
>=count
)
10429 pProto
= pItem
->GetProto();
10430 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10431 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10432 if( IsInWorld() && update
)
10433 pItem
->SendUpdateToPlayer( this );
10434 pItem
->SetState(ITEM_CHANGED
, this);
10442 // in equipment and bag list
10443 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10445 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10446 if( pItem
&& pItem
->GetEntry() == item
)
10448 if( pItem
->GetCount() + remcount
<= count
)
10450 if(!unequip_check
|| CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
,false) == EQUIP_ERR_OK
)
10452 remcount
+= pItem
->GetCount();
10453 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10455 if(remcount
>=count
)
10461 pProto
= pItem
->GetProto();
10462 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10463 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10464 if( IsInWorld() & update
)
10465 pItem
->SendUpdateToPlayer( this );
10466 pItem
->SetState(ITEM_CHANGED
, this);
10473 void Player::DestroyZoneLimitedItem( bool update
, uint32 new_zone
)
10475 sLog
.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone
);
10478 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
10480 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10481 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
10482 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10484 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
10486 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10487 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
10488 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10491 // in inventory bags
10492 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10494 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10497 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
10499 Item
* pItem
= pBag
->GetItemByPos(j
);
10500 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
10501 DestroyItem( i
, j
, update
);
10506 // in equipment and bag list
10507 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10509 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10510 if( pItem
&& pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
) )
10511 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10515 void Player::DestroyConjuredItems( bool update
)
10517 // used when entering arena
10518 // destroys all conjured items
10519 sLog
.outDebug( "STORAGE: DestroyConjuredItems" );
10522 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
10524 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10525 if( pItem
&& pItem
->GetProto() &&
10526 (pItem
->GetProto()->Class
== ITEM_CLASS_CONSUMABLE
) &&
10527 (pItem
->GetProto()->Flags
& ITEM_FLAGS_CONJURED
) )
10528 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10531 // in inventory bags
10532 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10534 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10537 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
10539 Item
* pItem
= pBag
->GetItemByPos(j
);
10540 if( pItem
&& pItem
->GetProto() &&
10541 (pItem
->GetProto()->Class
== ITEM_CLASS_CONSUMABLE
) &&
10542 (pItem
->GetProto()->Flags
& ITEM_FLAGS_CONJURED
) )
10543 DestroyItem( i
, j
, update
);
10548 // in equipment and bag list
10549 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10551 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
10552 if( pItem
&& pItem
->GetProto() &&
10553 (pItem
->GetProto()->Class
== ITEM_CLASS_CONSUMABLE
) &&
10554 (pItem
->GetProto()->Flags
& ITEM_FLAGS_CONJURED
) )
10555 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10559 void Player::DestroyItemCount( Item
* pItem
, uint32
&count
, bool update
)
10564 sLog
.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem
->GetGUIDLow(),pItem
->GetEntry(), count
);
10566 if( pItem
->GetCount() <= count
)
10568 count
-= pItem
->GetCount();
10570 DestroyItem( pItem
->GetBagSlot(),pItem
->GetSlot(), update
);
10574 ItemRemovedQuestCheck( pItem
->GetEntry(), count
);
10575 pItem
->SetCount( pItem
->GetCount() - count
);
10577 if( IsInWorld() & update
)
10578 pItem
->SendUpdateToPlayer( this );
10579 pItem
->SetState(ITEM_CHANGED
, this);
10583 void Player::SplitItem( uint16 src
, uint16 dst
, uint32 count
)
10585 uint8 srcbag
= src
>> 8;
10586 uint8 srcslot
= src
& 255;
10588 uint8 dstbag
= dst
>> 8;
10589 uint8 dstslot
= dst
& 255;
10591 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
10594 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
10598 // not let split all items (can be only at cheating)
10599 if(pSrcItem
->GetCount() == count
)
10601 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
10605 // not let split more existed items (can be only at cheating)
10606 if(pSrcItem
->GetCount() < count
)
10608 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT
, pSrcItem
, NULL
);
10612 if(pSrcItem
->m_lootGenerated
) // prevent split looting item (item
10614 //best error message found for attempting to split while looting
10615 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
10619 sLog
.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag
, dstslot
, pSrcItem
->GetEntry(), count
);
10620 Item
*pNewItem
= pSrcItem
->CloneItem( count
, this );
10623 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
10627 if( IsInventoryPos( dst
) )
10629 // change item amount before check (for unique max count check)
10630 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
10632 ItemPosCountVec dest
;
10633 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pNewItem
, false );
10634 if( msg
!= EQUIP_ERR_OK
)
10637 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
10638 SendEquipError( msg
, pSrcItem
, NULL
);
10643 pSrcItem
->SendUpdateToPlayer( this );
10644 pSrcItem
->SetState(ITEM_CHANGED
, this);
10645 StoreItem( dest
, pNewItem
, true);
10647 else if( IsBankPos ( dst
) )
10649 // change item amount before check (for unique max count check)
10650 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
10652 ItemPosCountVec dest
;
10653 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pNewItem
, false );
10654 if( msg
!= EQUIP_ERR_OK
)
10657 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
10658 SendEquipError( msg
, pSrcItem
, NULL
);
10663 pSrcItem
->SendUpdateToPlayer( this );
10664 pSrcItem
->SetState(ITEM_CHANGED
, this);
10665 BankItem( dest
, pNewItem
, true);
10667 else if( IsEquipmentPos ( dst
) )
10669 // change item amount before check (for unique max count check), provide space for splitted items
10670 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
10673 uint8 msg
= CanEquipItem( dstslot
, dest
, pNewItem
, false );
10674 if( msg
!= EQUIP_ERR_OK
)
10677 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
10678 SendEquipError( msg
, pSrcItem
, NULL
);
10683 pSrcItem
->SendUpdateToPlayer( this );
10684 pSrcItem
->SetState(ITEM_CHANGED
, this);
10685 EquipItem( dest
, pNewItem
, true);
10686 AutoUnequipOffhandIfNeed();
10690 void Player::SwapItem( uint16 src
, uint16 dst
)
10692 uint8 srcbag
= src
>> 8;
10693 uint8 srcslot
= src
& 255;
10695 uint8 dstbag
= dst
>> 8;
10696 uint8 dstslot
= dst
& 255;
10698 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
10699 Item
*pDstItem
= GetItemByPos( dstbag
, dstslot
);
10704 sLog
.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag
, dstslot
, pSrcItem
->GetEntry());
10708 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD
, pSrcItem
, pDstItem
);
10712 if(pSrcItem
->m_lootGenerated
) // prevent swap looting item
10714 //best error message found for attempting to swap while looting
10715 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pSrcItem
, NULL
);
10719 // check unequip potability for equipped items and bank bags
10720 if(IsEquipmentPos ( src
) || IsBagPos ( src
))
10722 // bags can be swapped with empty bag slots
10723 uint8 msg
= CanUnequipItem( src
, !IsBagPos ( src
) || IsBagPos ( dst
));
10724 if(msg
!= EQUIP_ERR_OK
)
10726 SendEquipError( msg
, pSrcItem
, pDstItem
);
10731 // prevent put equipped/bank bag in self
10732 if( IsBagPos ( src
) && srcslot
== dstbag
)
10734 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
10740 if( IsInventoryPos( dst
) )
10742 ItemPosCountVec dest
;
10743 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pSrcItem
, false );
10744 if( msg
!= EQUIP_ERR_OK
)
10746 SendEquipError( msg
, pSrcItem
, NULL
);
10750 RemoveItem(srcbag
, srcslot
, true);
10751 StoreItem( dest
, pSrcItem
, true);
10753 else if( IsBankPos ( dst
) )
10755 ItemPosCountVec dest
;
10756 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pSrcItem
, false);
10757 if( msg
!= EQUIP_ERR_OK
)
10759 SendEquipError( msg
, pSrcItem
, NULL
);
10763 RemoveItem(srcbag
, srcslot
, true);
10764 BankItem( dest
, pSrcItem
, true);
10766 else if( IsEquipmentPos ( dst
) )
10769 uint8 msg
= CanEquipItem( dstslot
, dest
, pSrcItem
, false );
10770 if( msg
!= EQUIP_ERR_OK
)
10772 SendEquipError( msg
, pSrcItem
, NULL
);
10776 RemoveItem(srcbag
, srcslot
, true);
10777 EquipItem( dest
, pSrcItem
, true);
10778 AutoUnequipOffhandIfNeed();
10781 else // if (!pDstItem)
10783 if(pDstItem
->m_lootGenerated
) // prevent swap looting item
10785 //best error message found for attempting to swap while looting
10786 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pDstItem
, NULL
);
10790 // check unequip potability for equipped items and bank bags
10791 if(IsEquipmentPos ( dst
) || IsBagPos ( dst
))
10793 // bags can be swapped with empty bag slots
10794 uint8 msg
= CanUnequipItem( dst
, !IsBagPos ( dst
) || IsBagPos ( src
) );
10795 if(msg
!= EQUIP_ERR_OK
)
10797 SendEquipError( msg
, pSrcItem
, pDstItem
);
10802 // attempt merge to / fill target item
10805 ItemPosCountVec sDest
;
10807 if( IsInventoryPos( dst
) )
10808 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
10809 else if( IsBankPos ( dst
) )
10810 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
10811 else if( IsEquipmentPos ( dst
) )
10812 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, false );
10816 // can be merge/fill
10817 if(msg
== EQUIP_ERR_OK
)
10819 if( pSrcItem
->GetCount() + pDstItem
->GetCount() <= pSrcItem
->GetProto()->Stackable
)
10821 RemoveItem(srcbag
, srcslot
, true);
10823 if( IsInventoryPos( dst
) )
10824 StoreItem( sDest
, pSrcItem
, true);
10825 else if( IsBankPos ( dst
) )
10826 BankItem( sDest
, pSrcItem
, true);
10827 else if( IsEquipmentPos ( dst
) )
10829 EquipItem( eDest
, pSrcItem
, true);
10830 AutoUnequipOffhandIfNeed();
10835 pSrcItem
->SetCount( pSrcItem
->GetCount() + pDstItem
->GetCount() - pSrcItem
->GetProto()->Stackable
);
10836 pDstItem
->SetCount( pSrcItem
->GetProto()->Stackable
);
10837 pSrcItem
->SetState(ITEM_CHANGED
, this);
10838 pDstItem
->SetState(ITEM_CHANGED
, this);
10841 pSrcItem
->SendUpdateToPlayer( this );
10842 pDstItem
->SendUpdateToPlayer( this );
10849 // impossible merge/fill, do real swap
10852 // check src->dest move possibility
10853 ItemPosCountVec sDest
;
10855 if( IsInventoryPos( dst
) )
10856 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
10857 else if( IsBankPos( dst
) )
10858 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
10859 else if( IsEquipmentPos( dst
) )
10861 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, true );
10862 if( msg
== EQUIP_ERR_OK
)
10863 msg
= CanUnequipItem( eDest
, true );
10866 if( msg
!= EQUIP_ERR_OK
)
10868 SendEquipError( msg
, pSrcItem
, pDstItem
);
10872 // check dest->src move possibility
10873 ItemPosCountVec sDest2
;
10875 if( IsInventoryPos( src
) )
10876 msg
= CanStoreItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
10877 else if( IsBankPos( src
) )
10878 msg
= CanBankItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
10879 else if( IsEquipmentPos( src
) )
10881 msg
= CanEquipItem( srcslot
, eDest2
, pDstItem
, true);
10882 if( msg
== EQUIP_ERR_OK
)
10883 msg
= CanUnequipItem( eDest2
, true);
10886 if( msg
!= EQUIP_ERR_OK
)
10888 SendEquipError( msg
, pDstItem
, pSrcItem
);
10892 // now do moves, remove...
10893 RemoveItem(dstbag
, dstslot
, false);
10894 RemoveItem(srcbag
, srcslot
, false);
10897 if( IsInventoryPos( dst
) )
10898 StoreItem(sDest
, pSrcItem
, true);
10899 else if( IsBankPos( dst
) )
10900 BankItem(sDest
, pSrcItem
, true);
10901 else if( IsEquipmentPos( dst
) )
10902 EquipItem(eDest
, pSrcItem
, true);
10905 if( IsInventoryPos( src
) )
10906 StoreItem(sDest2
, pDstItem
, true);
10907 else if( IsBankPos( src
) )
10908 BankItem(sDest2
, pDstItem
, true);
10909 else if( IsEquipmentPos( src
) )
10910 EquipItem(eDest2
, pDstItem
, true);
10912 AutoUnequipOffhandIfNeed();
10916 void Player::AddItemToBuyBackSlot( Item
*pItem
)
10920 uint32 slot
= m_currentBuybackSlot
;
10921 // if current back slot non-empty search oldest or free
10924 uint32 oldest_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
);
10925 uint32 oldest_slot
= BUYBACK_SLOT_START
;
10927 for(uint32 i
= BUYBACK_SLOT_START
+1; i
< BUYBACK_SLOT_END
; ++i
)
10936 uint32 i_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ i
- BUYBACK_SLOT_START
);
10938 if(oldest_time
> i_time
)
10940 oldest_time
= i_time
;
10946 slot
= oldest_slot
;
10949 RemoveItemFromBuyBackSlot( slot
, true );
10950 sLog
.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem
->GetEntry(), slot
);
10952 m_items
[slot
] = pItem
;
10953 time_t base
= time(NULL
);
10954 uint32 etime
= uint32(base
- m_logintime
+ (30 * 3600));
10955 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
10957 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ eslot
* 2, pItem
->GetGUID() );
10958 ItemPrototype
const *pProto
= pItem
->GetProto();
10960 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, pProto
->SellPrice
* pItem
->GetCount() );
10962 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
10963 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, (uint32
)etime
);
10965 // move to next (for non filled list is move most optimized choice)
10966 if(m_currentBuybackSlot
< BUYBACK_SLOT_END
-1)
10967 ++m_currentBuybackSlot
;
10971 Item
* Player::GetItemFromBuyBackSlot( uint32 slot
)
10973 sLog
.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot
);
10974 if( slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
10975 return m_items
[slot
];
10979 void Player::RemoveItemFromBuyBackSlot( uint32 slot
, bool del
)
10981 sLog
.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot
);
10982 if( slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
10984 Item
*pItem
= m_items
[slot
];
10987 pItem
->RemoveFromWorld();
10988 if(del
) pItem
->SetState(ITEM_REMOVED
, this);
10991 m_items
[slot
] = NULL
;
10993 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
10994 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ eslot
* 2, 0 );
10995 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
10996 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, 0 );
10998 // if current backslot is filled set to now free slot
10999 if(m_items
[m_currentBuybackSlot
])
11000 m_currentBuybackSlot
= slot
;
11004 void Player::SendEquipError( uint8 msg
, Item
* pItem
, Item
*pItem2
)
11006 sLog
.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg
);
11007 WorldPacket
data( SMSG_INVENTORY_CHANGE_FAILURE
, (msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
? 22 : 18) );
11008 data
<< uint8(msg
);
11012 data
<< uint64(pItem
? pItem
->GetGUID() : 0);
11013 data
<< uint64(pItem2
? pItem2
->GetGUID() : 0);
11014 data
<< uint8(0); // not 0 there...
11016 if(msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
)
11021 if(ItemPrototype
const* proto
= pItem
->GetProto())
11022 level
= proto
->RequiredLevel
;
11024 data
<< uint32(level
); // new 2.4.0
11027 GetSession()->SendPacket(&data
);
11030 void Player::SendBuyError( uint8 msg
, Creature
* pCreature
, uint32 item
, uint32 param
)
11032 sLog
.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11033 WorldPacket
data( SMSG_BUY_FAILED
, (8+4+4+1) );
11034 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11035 data
<< uint32(item
);
11037 data
<< uint32(param
);
11038 data
<< uint8(msg
);
11039 GetSession()->SendPacket(&data
);
11042 void Player::SendSellError( uint8 msg
, Creature
* pCreature
, uint64 guid
, uint32 param
)
11044 sLog
.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11045 WorldPacket
data( SMSG_SELL_ITEM
,(8+8+(param
?4:0)+1)); // last check 2.0.10
11046 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11047 data
<< uint64(guid
);
11049 data
<< uint32(param
);
11050 data
<< uint8(msg
);
11051 GetSession()->SendPacket(&data
);
11054 void Player::ClearTrade()
11057 acceptTrade
= false;
11058 for(int i
= 0; i
< TRADE_SLOT_COUNT
; i
++)
11059 tradeItems
[i
] = NULL_SLOT
;
11062 void Player::TradeCancel(bool sendback
)
11066 // send yellow "Trade canceled" message to both traders
11070 ws
->SendCancelTrade();
11071 ws
= pTrader
->GetSession();
11072 if(!ws
->PlayerLogout())
11073 ws
->SendCancelTrade();
11077 pTrader
->ClearTrade();
11078 // prevent loss of reference
11079 pTrader
->pTrader
= NULL
;
11084 void Player::UpdateItemDuration(uint32 time
, bool realtimeonly
)
11086 if(m_itemDuration
.empty())
11089 sLog
.outDebug("Player::UpdateItemDuration(%u,%u)", time
,realtimeonly
);
11091 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); )
11094 ++itr
; // current element can be erased in UpdateDuration
11096 if (realtimeonly
&& item
->GetProto()->Duration
< 0 || !realtimeonly
)
11097 item
->UpdateDuration(this,time
);
11101 void Player::UpdateEnchantTime(uint32 time
)
11103 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11107 if(!itr
->item
->GetEnchantmentId(itr
->slot
))
11109 next
= m_enchantDuration
.erase(itr
);
11111 else if(itr
->leftduration
<= time
)
11113 ApplyEnchantment(itr
->item
,itr
->slot
,false,false);
11114 itr
->item
->ClearEnchantment(itr
->slot
);
11115 next
= m_enchantDuration
.erase(itr
);
11117 else if(itr
->leftduration
> time
)
11119 itr
->leftduration
-= time
;
11125 void Player::AddEnchantmentDurations(Item
*item
)
11127 for(int x
=0;x
<MAX_ENCHANTMENT_SLOT
;++x
)
11129 if(!item
->GetEnchantmentId(EnchantmentSlot(x
)))
11132 uint32 duration
= item
->GetEnchantmentDuration(EnchantmentSlot(x
));
11134 AddEnchantmentDuration(item
,EnchantmentSlot(x
),duration
);
11138 void Player::RemoveEnchantmentDurations(Item
*item
)
11140 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();)
11142 if(itr
->item
== item
)
11144 // save duration in item
11145 item
->SetEnchantmentDuration(EnchantmentSlot(itr
->slot
),itr
->leftduration
);
11146 itr
= m_enchantDuration
.erase(itr
);
11153 void Player::RemoveAllEnchantments(EnchantmentSlot slot
)
11155 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11156 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11159 if(itr
->slot
==slot
)
11161 if(itr
->item
&& itr
->item
->GetEnchantmentId(slot
))
11163 // remove from stats
11164 ApplyEnchantment(itr
->item
,slot
,false,false);
11166 itr
->item
->ClearEnchantment(slot
);
11168 // remove from update list
11169 next
= m_enchantDuration
.erase(itr
);
11175 // remove enchants from inventory items
11176 // NOTE: no need to remove these from stats, since these aren't equipped
11178 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
11180 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11181 if( pItem
&& pItem
->GetEnchantmentId(slot
) )
11182 pItem
->ClearEnchantment(slot
);
11185 // in inventory bags
11186 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11188 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11191 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
11193 Item
* pItem
= pBag
->GetItemByPos(j
);
11194 if( pItem
&& pItem
->GetEnchantmentId(slot
) )
11195 pItem
->ClearEnchantment(slot
);
11201 // duration == 0 will remove item enchant
11202 void Player::AddEnchantmentDuration(Item
*item
,EnchantmentSlot slot
,uint32 duration
)
11207 if(slot
>= MAX_ENCHANTMENT_SLOT
)
11210 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
11212 if(itr
->item
== item
&& itr
->slot
== slot
)
11214 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
11215 m_enchantDuration
.erase(itr
);
11219 if(item
&& duration
> 0 )
11221 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item
->GetGUID(),slot
,uint32(duration
/1000));
11222 m_enchantDuration
.push_back(EnchantDuration(item
,slot
,duration
));
11226 void Player::ApplyEnchantment(Item
*item
,bool apply
)
11228 for(uint32 slot
= 0; slot
< MAX_ENCHANTMENT_SLOT
; ++slot
)
11229 ApplyEnchantment(item
, EnchantmentSlot(slot
), apply
);
11232 void Player::ApplyEnchantment(Item
*item
,EnchantmentSlot slot
,bool apply
, bool apply_dur
, bool ignore_condition
)
11237 if(!item
->IsEquipped())
11240 if(slot
>= MAX_ENCHANTMENT_SLOT
)
11243 uint32 enchant_id
= item
->GetEnchantmentId(slot
);
11247 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
11251 if(!ignore_condition
&& pEnchant
->EnchantmentCondition
&& !((Player
*)this)->EnchantmentFitsRequirements(pEnchant
->EnchantmentCondition
, -1))
11254 for (int s
=0; s
<3; s
++)
11256 uint32 enchant_display_type
= pEnchant
->type
[s
];
11257 uint32 enchant_amount
= pEnchant
->amount
[s
];
11258 uint32 enchant_spell_id
= pEnchant
->spellid
[s
];
11260 switch(enchant_display_type
)
11262 case ITEM_ENCHANTMENT_TYPE_NONE
:
11264 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
:
11265 // processed in Player::CastItemCombatSpell
11267 case ITEM_ENCHANTMENT_TYPE_DAMAGE
:
11268 if (item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
11269 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11270 else if (item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
11271 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11272 else if (item
->GetSlot() == EQUIPMENT_SLOT_RANGED
)
11273 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11275 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL
:
11276 if(enchant_spell_id
)
11280 int32 basepoints
= int32(enchant_amount
);
11281 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11282 if (item
->GetItemRandomPropertyId() !=0 && !enchant_amount
)
11284 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11287 // Search enchant_amount
11288 for (int k
=0; k
<3; k
++)
11290 if(item_rand
->enchant_id
[k
] == enchant_id
)
11292 basepoints
= int32((item_rand
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11298 // Cast custom spell vs all equal basepoints getted from enchant_amount
11300 CastCustomSpell(this,enchant_spell_id
,&basepoints
,&basepoints
,&basepoints
,true,item
);
11302 CastSpell(this,enchant_spell_id
,true,item
);
11305 RemoveAurasDueToItemSpell(item
,enchant_spell_id
);
11308 case ITEM_ENCHANTMENT_TYPE_RESISTANCE
:
11309 if (!enchant_amount
)
11311 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11314 for (int k
=0; k
<3; k
++)
11316 if(item_rand
->enchant_id
[k
] == enchant_id
)
11318 enchant_amount
= uint32((item_rand
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11325 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START
+ enchant_spell_id
), TOTAL_VALUE
, float(enchant_amount
), apply
);
11327 case ITEM_ENCHANTMENT_TYPE_STAT
:
11329 if (!enchant_amount
)
11331 ItemRandomSuffixEntry
const *item_rand_suffix
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11332 if(item_rand_suffix
)
11334 for (int k
=0; k
<3; k
++)
11336 if(item_rand_suffix
->enchant_id
[k
] == enchant_id
)
11338 enchant_amount
= uint32((item_rand_suffix
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11345 sLog
.outDebug("Adding %u to stat nb %u",enchant_amount
,enchant_spell_id
);
11346 switch (enchant_spell_id
)
11348 case ITEM_MOD_AGILITY
:
11349 sLog
.outDebug("+ %u AGILITY",enchant_amount
);
11350 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11351 ApplyStatBuffMod(STAT_AGILITY
, enchant_amount
, apply
);
11353 case ITEM_MOD_STRENGTH
:
11354 sLog
.outDebug("+ %u STRENGTH",enchant_amount
);
11355 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11356 ApplyStatBuffMod(STAT_STRENGTH
, enchant_amount
, apply
);
11358 case ITEM_MOD_INTELLECT
:
11359 sLog
.outDebug("+ %u INTELLECT",enchant_amount
);
11360 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11361 ApplyStatBuffMod(STAT_INTELLECT
, enchant_amount
, apply
);
11363 case ITEM_MOD_SPIRIT
:
11364 sLog
.outDebug("+ %u SPIRIT",enchant_amount
);
11365 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11366 ApplyStatBuffMod(STAT_SPIRIT
, enchant_amount
, apply
);
11368 case ITEM_MOD_STAMINA
:
11369 sLog
.outDebug("+ %u STAMINA",enchant_amount
);
11370 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11371 ApplyStatBuffMod(STAT_STAMINA
, enchant_amount
, apply
);
11373 case ITEM_MOD_DEFENSE_SKILL_RATING
:
11374 ((Player
*)this)->ApplyRatingMod(CR_DEFENSE_SKILL
, enchant_amount
, apply
);
11375 sLog
.outDebug("+ %u DEFENCE", enchant_amount
);
11377 case ITEM_MOD_DODGE_RATING
:
11378 ((Player
*)this)->ApplyRatingMod(CR_DODGE
, enchant_amount
, apply
);
11379 sLog
.outDebug("+ %u DODGE", enchant_amount
);
11381 case ITEM_MOD_PARRY_RATING
:
11382 ((Player
*)this)->ApplyRatingMod(CR_PARRY
, enchant_amount
, apply
);
11383 sLog
.outDebug("+ %u PARRY", enchant_amount
);
11385 case ITEM_MOD_BLOCK_RATING
:
11386 ((Player
*)this)->ApplyRatingMod(CR_BLOCK
, enchant_amount
, apply
);
11387 sLog
.outDebug("+ %u SHIELD_BLOCK", enchant_amount
);
11389 case ITEM_MOD_HIT_MELEE_RATING
:
11390 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
11391 sLog
.outDebug("+ %u MELEE_HIT", enchant_amount
);
11393 case ITEM_MOD_HIT_RANGED_RATING
:
11394 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
11395 sLog
.outDebug("+ %u RANGED_HIT", enchant_amount
);
11397 case ITEM_MOD_HIT_SPELL_RATING
:
11398 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
11399 sLog
.outDebug("+ %u SPELL_HIT", enchant_amount
);
11401 case ITEM_MOD_CRIT_MELEE_RATING
:
11402 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
11403 sLog
.outDebug("+ %u MELEE_CRIT", enchant_amount
);
11405 case ITEM_MOD_CRIT_RANGED_RATING
:
11406 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
11407 sLog
.outDebug("+ %u RANGED_CRIT", enchant_amount
);
11409 case ITEM_MOD_CRIT_SPELL_RATING
:
11410 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
11411 sLog
.outDebug("+ %u SPELL_CRIT", enchant_amount
);
11413 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11415 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11416 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11418 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11419 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11421 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11422 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11424 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11425 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11427 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11428 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11430 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11431 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11433 // case ITEM_MOD_HASTE_MELEE_RATING:
11434 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11436 // case ITEM_MOD_HASTE_RANGED_RATING:
11437 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11439 case ITEM_MOD_HASTE_SPELL_RATING
:
11440 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
11442 case ITEM_MOD_HIT_RATING
:
11443 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
11444 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
11445 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
11446 sLog
.outDebug("+ %u HIT", enchant_amount
);
11448 case ITEM_MOD_CRIT_RATING
:
11449 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
11450 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
11451 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
11452 sLog
.outDebug("+ %u CRITICAL", enchant_amount
);
11454 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11455 // case ITEM_MOD_HIT_TAKEN_RATING:
11456 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11457 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11458 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11460 // case ITEM_MOD_CRIT_TAKEN_RATING:
11461 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11462 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11463 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11465 case ITEM_MOD_RESILIENCE_RATING
:
11466 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, enchant_amount
, apply
);
11467 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, enchant_amount
, apply
);
11468 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, enchant_amount
, apply
);
11469 sLog
.outDebug("+ %u RESILIENCE", enchant_amount
);
11471 case ITEM_MOD_HASTE_RATING
:
11472 ((Player
*)this)->ApplyRatingMod(CR_HASTE_MELEE
, enchant_amount
, apply
);
11473 ((Player
*)this)->ApplyRatingMod(CR_HASTE_RANGED
, enchant_amount
, apply
);
11474 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
11475 sLog
.outDebug("+ %u HASTE", enchant_amount
);
11477 case ITEM_MOD_EXPERTISE_RATING
:
11478 ((Player
*)this)->ApplyRatingMod(CR_EXPERTISE
, enchant_amount
, apply
);
11479 sLog
.outDebug("+ %u EXPERTISE", enchant_amount
);
11486 case ITEM_ENCHANTMENT_TYPE_TOTEM
: // Shaman Rockbiter Weapon
11488 if(getClass() == CLASS_SHAMAN
)
11490 float addValue
= 0.0f
;
11491 if(item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
11493 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/1000.0f
);
11494 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, addValue
, apply
);
11496 else if(item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
11498 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/1000.0f
);
11499 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, addValue
, apply
);
11505 sLog
.outError("Unknown item enchantment display type: %d",enchant_display_type
);
11507 } /*switch(enchant_display_type)*/
11510 // visualize enchantment at player and equipped items
11511 if(slot
< MAX_INSPECTED_ENCHANTMENT_SLOT
)
11513 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (item
->GetSlot() * MAX_VISIBLE_ITEM_OFFSET
);
11514 SetUInt32Value(VisibleBase
+ 1 + slot
, apply
? item
->GetEnchantmentId(slot
) : 0);
11522 uint32 duration
= item
->GetEnchantmentDuration(slot
);
11524 AddEnchantmentDuration(item
,slot
,duration
);
11528 // duration == 0 will remove EnchantDuration
11529 AddEnchantmentDuration(item
,slot
,0);
11534 void Player::SendEnchantmentDurations()
11536 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
11538 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr
->item
->GetGUID(),itr
->slot
,uint32(itr
->leftduration
)/1000);
11542 void Player::SendItemDurations()
11544 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end();++itr
)
11546 (*itr
)->SendTimeUpdate(this);
11550 void Player::SendNewItem(Item
*item
, uint32 count
, bool received
, bool created
, bool broadcast
)
11552 if(!item
) // prevent crash
11555 // last check 2.0.10
11556 WorldPacket
data( SMSG_ITEM_PUSH_RESULT
, (8+4+4+4+1+4+4+4+4+4) );
11557 data
<< GetGUID(); // player GUID
11558 data
<< uint32(received
); // 0=looted, 1=from npc
11559 data
<< uint32(created
); // 0=received, 1=created
11560 data
<< uint32(1); // always 0x01 (probably meant to be count of listed items)
11561 data
<< (uint8
)item
->GetBagSlot(); // bagslot
11562 // item slot, but when added to stack: 0xFFFFFFFF
11563 data
<< (uint32
) ((item
->GetCount()==count
) ? item
->GetSlot() : -1);
11564 data
<< uint32(item
->GetEntry()); // item id
11565 data
<< uint32(item
->GetItemSuffixFactor()); // SuffixFactor
11566 data
<< uint32(item
->GetItemRandomPropertyId()); // random item property id
11567 data
<< uint32(count
); // count of items
11568 data
<< GetItemCount(item
->GetEntry()); // count of items in inventory
11570 if (broadcast
&& GetGroup())
11571 GetGroup()->BroadcastPacket(&data
);
11573 GetSession()->SendPacket(&data
);
11576 /*********************************************************/
11577 /*** QUEST SYSTEM ***/
11578 /*********************************************************/
11580 void Player::PrepareQuestMenu( uint64 guid
)
11583 QuestRelations
* pObjectQR
;
11584 QuestRelations
* pObjectQIR
;
11585 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
11588 pObject
= (Object
*)pCreature
;
11589 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
11590 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
11594 GameObject
*pGameObject
= ObjectAccessor::GetGameObject(*this, guid
);
11597 pObject
= (Object
*)pGameObject
;
11598 pObjectQR
= &objmgr
.mGOQuestRelations
;
11599 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
11605 QuestMenu
&qm
= PlayerTalkClass
->GetQuestMenu();
11608 for(QuestRelations::const_iterator i
= pObjectQIR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQIR
->upper_bound(pObject
->GetEntry()); ++i
)
11610 uint32 quest_id
= i
->second
;
11611 QuestStatus status
= GetQuestStatus( quest_id
);
11612 if ( status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus( quest_id
) )
11613 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_REWARD_REP
);
11614 else if ( status
== QUEST_STATUS_INCOMPLETE
)
11615 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_INCOMPLETE
);
11616 else if (status
== QUEST_STATUS_AVAILABLE
)
11617 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_CHAT
);
11620 for(QuestRelations::const_iterator i
= pObjectQR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++i
)
11622 uint32 quest_id
= i
->second
;
11623 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
11624 if(!pQuest
) continue;
11626 QuestStatus status
= GetQuestStatus( quest_id
);
11628 if (pQuest
->IsAutoComplete() && CanTakeQuest(pQuest
, false))
11629 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_REWARD_REP
);
11630 else if ( status
== QUEST_STATUS_NONE
&& CanTakeQuest( pQuest
, false ) )
11631 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_AVAILABLE
);
11635 void Player::SendPreparedQuest( uint64 guid
)
11637 QuestMenu
& questMenu
= PlayerTalkClass
->GetQuestMenu();
11638 if( questMenu
.Empty() )
11641 QuestMenuItem
const& qmi0
= questMenu
.GetItem( 0 );
11643 uint32 status
= qmi0
.m_qIcon
;
11645 // single element case
11646 if ( questMenu
.MenuItemCount() == 1 )
11648 // Auto open -- maybe also should verify there is no greeting
11649 uint32 quest_id
= qmi0
.m_qId
;
11650 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
11653 if( status
== DIALOG_STATUS_REWARD_REP
&& !GetQuestRewardStatus( quest_id
) )
11654 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, CanRewardQuest(pQuest
,false), true );
11655 else if( status
== DIALOG_STATUS_INCOMPLETE
)
11656 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, false, true );
11657 // Send completable on repeatable quest if player don't have quest
11658 else if( pQuest
->IsRepeatable() && !pQuest
->IsDaily() )
11659 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, CanCompleteRepeatableQuest(pQuest
), true );
11661 PlayerTalkClass
->SendQuestGiverQuestDetails( pQuest
, guid
, true );
11664 // multiply entries
11670 std::string title
= "";
11671 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
11674 uint32 textid
= pCreature
->GetNpcTextId();
11675 GossipText
* gossiptext
= objmgr
.GetGossipText(textid
);
11678 qe
._Delay
= 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
11679 qe
._Emote
= 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
11684 qe
= gossiptext
->Options
[0].Emotes
[0];
11686 if(!gossiptext
->Options
[0].Text_0
.empty())
11688 title
= gossiptext
->Options
[0].Text_0
;
11690 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
11693 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
11696 if (nl
->Text_0
[0].size() > loc_idx
&& !nl
->Text_0
[0][loc_idx
].empty())
11697 title
= nl
->Text_0
[0][loc_idx
];
11703 title
= gossiptext
->Options
[0].Text_1
;
11705 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
11708 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
11711 if (nl
->Text_1
[0].size() > loc_idx
&& !nl
->Text_1
[0][loc_idx
].empty())
11712 title
= nl
->Text_1
[0][loc_idx
];
11718 PlayerTalkClass
->SendQuestGiverQuestList( qe
, title
, guid
);
11722 bool Player::IsActiveQuest( uint32 quest_id
) const
11724 QuestStatusMap::const_iterator itr
= mQuestStatus
.find(quest_id
);
11726 return itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
;
11729 Quest
const * Player::GetNextQuest( uint64 guid
, Quest
const *pQuest
)
11732 QuestRelations
* pObjectQR
;
11733 QuestRelations
* pObjectQIR
;
11735 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
11738 pObject
= (Object
*)pCreature
;
11739 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
11740 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
11744 GameObject
*pGameObject
= ObjectAccessor::GetGameObject(*this, guid
);
11747 pObject
= (Object
*)pGameObject
;
11748 pObjectQR
= &objmgr
.mGOQuestRelations
;
11749 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
11755 uint32 nextQuestID
= pQuest
->GetNextQuestInChain();
11756 for(QuestRelations::const_iterator itr
= pObjectQR
->lower_bound(pObject
->GetEntry()); itr
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++itr
)
11758 if (itr
->second
== nextQuestID
)
11759 return objmgr
.GetQuestTemplate(nextQuestID
);
11765 bool Player::CanSeeStartQuest( Quest
const *pQuest
)
11767 if( SatisfyQuestRace( pQuest
, false ) && SatisfyQuestSkillOrClass( pQuest
, false ) &&
11768 SatisfyQuestExclusiveGroup( pQuest
, false ) && SatisfyQuestReputation( pQuest
, false ) &&
11769 SatisfyQuestPreviousQuest( pQuest
, false ) && SatisfyQuestNextChain( pQuest
, false ) &&
11770 SatisfyQuestPrevChain( pQuest
, false ) && SatisfyQuestDay( pQuest
, false ) )
11772 return getLevel() + sWorld
.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF
) >= pQuest
->GetMinLevel();
11778 bool Player::CanTakeQuest( Quest
const *pQuest
, bool msg
)
11780 return SatisfyQuestStatus( pQuest
, msg
) && SatisfyQuestExclusiveGroup( pQuest
, msg
)
11781 && SatisfyQuestRace( pQuest
, msg
) && SatisfyQuestLevel( pQuest
, msg
)
11782 && SatisfyQuestSkillOrClass( pQuest
, msg
) && SatisfyQuestReputation( pQuest
, msg
)
11783 && SatisfyQuestPreviousQuest( pQuest
, msg
) && SatisfyQuestTimed( pQuest
, msg
)
11784 && SatisfyQuestNextChain( pQuest
, msg
) && SatisfyQuestPrevChain( pQuest
, msg
)
11785 && SatisfyQuestDay( pQuest
, msg
);
11788 bool Player::CanAddQuest( Quest
const *pQuest
, bool msg
)
11790 if( !SatisfyQuestLog( msg
) )
11793 uint32 srcitem
= pQuest
->GetSrcItemId();
11796 uint32 count
= pQuest
->GetSrcItemCount();
11797 ItemPosCountVec dest
;
11798 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
11800 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
11801 if( msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
11803 else if( msg
!= EQUIP_ERR_OK
)
11805 SendEquipError( msg
, NULL
, NULL
);
11812 bool Player::CanCompleteQuest( uint32 quest_id
)
11816 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
11817 if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
11818 return false; // not allow re-complete quest
11820 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
11825 // auto complete quest
11826 if (qInfo
->IsAutoComplete() && CanTakeQuest(qInfo
, false))
11829 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
11832 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
11834 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
11836 if( qInfo
->ReqItemCount
[i
]!= 0 && q_status
.m_itemcount
[i
] < qInfo
->ReqItemCount
[i
] )
11841 if ( qInfo
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
11843 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
11845 if( qInfo
->ReqCreatureOrGOId
[i
] == 0 )
11848 if( qInfo
->ReqCreatureOrGOCount
[i
] != 0 && q_status
.m_creatureOrGOcount
[i
] < qInfo
->ReqCreatureOrGOCount
[i
] )
11853 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT
) && !q_status
.m_explored
)
11856 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && q_status
.m_timer
== 0 )
11859 if ( qInfo
->GetRewOrReqMoney() < 0 )
11861 if ( GetMoney() < uint32(-qInfo
->GetRewOrReqMoney()) )
11865 uint32 repFacId
= qInfo
->GetRepObjectiveFaction();
11866 if ( repFacId
&& GetReputation(repFacId
) < qInfo
->GetRepObjectiveValue() )
11875 bool Player::CanCompleteRepeatableQuest( Quest
const *pQuest
)
11877 // Solve problem that player don't have the quest and try complete it.
11878 // if repeatable she must be able to complete event if player don't have it.
11879 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
11880 if( !CanTakeQuest(pQuest
, false) )
11883 if (pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
11884 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
11885 if( pQuest
->ReqItemId
[i
] && pQuest
->ReqItemCount
[i
] && !HasItemCount(pQuest
->ReqItemId
[i
],pQuest
->ReqItemCount
[i
]) )
11888 if( !CanRewardQuest(pQuest
, false) )
11894 bool Player::CanRewardQuest( Quest
const *pQuest
, bool msg
)
11896 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
11897 if(!pQuest
->IsAutoComplete() && GetQuestStatus(pQuest
->GetQuestId()) != QUEST_STATUS_COMPLETE
)
11900 // daily quest can't be rewarded (25 daily quest already completed)
11901 if(!SatisfyQuestDay(pQuest
,true))
11904 // rewarded and not repeatable quest (only cheating case, then ignore without message)
11905 if(GetQuestRewardStatus(pQuest
->GetQuestId()))
11908 // prevent receive reward with quest items in bank
11909 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
11911 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
11913 if( pQuest
->ReqItemCount
[i
]!= 0 &&
11914 GetItemCount(pQuest
->ReqItemId
[i
]) < pQuest
->ReqItemCount
[i
] )
11917 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, NULL
, NULL
);
11923 // prevent receive reward with low money and GetRewOrReqMoney() < 0
11924 if(pQuest
->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest
->GetRewOrReqMoney()) )
11930 bool Player::CanRewardQuest( Quest
const *pQuest
, uint32 reward
, bool msg
)
11932 // prevent receive reward with quest items in bank or for not completed quest
11933 if(!CanRewardQuest(pQuest
,msg
))
11936 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
11938 if( pQuest
->RewChoiceItemId
[reward
] )
11940 ItemPosCountVec dest
;
11941 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] );
11942 if( res
!= EQUIP_ERR_OK
)
11944 SendEquipError( res
, NULL
, NULL
);
11950 if ( pQuest
->GetRewItemsCount() > 0 )
11952 for (uint32 i
= 0; i
< pQuest
->GetRewItemsCount(); ++i
)
11954 if( pQuest
->RewItemId
[i
] )
11956 ItemPosCountVec dest
;
11957 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] );
11958 if( res
!= EQUIP_ERR_OK
)
11960 SendEquipError( res
, NULL
, NULL
);
11970 void Player::AddQuest( Quest
const *pQuest
, Object
*questGiver
)
11972 uint16 log_slot
= FindQuestSlot( 0 );
11973 assert(log_slot
< MAX_QUEST_LOG_SIZE
);
11975 uint32 quest_id
= pQuest
->GetQuestId();
11977 // if not exist then created with set uState==NEW and rewarded=false
11978 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
11979 if (questStatusData
.uState
!= QUEST_NEW
)
11980 questStatusData
.uState
= QUEST_CHANGED
;
11982 // check for repeatable quests status reset
11983 questStatusData
.m_status
= QUEST_STATUS_INCOMPLETE
;
11984 questStatusData
.m_explored
= false;
11986 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
11988 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
11989 questStatusData
.m_itemcount
[i
] = 0;
11992 if ( pQuest
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
11994 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
11995 questStatusData
.m_creatureOrGOcount
[i
] = 0;
11998 GiveQuestSourceItem( pQuest
);
11999 AdjustQuestReqItemCount( pQuest
);
12001 if( pQuest
->GetRepObjectiveFaction() )
12002 SetFactionVisibleForFactionId(pQuest
->GetRepObjectiveFaction());
12005 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
12007 uint32 limittime
= pQuest
->GetLimitTime();
12009 // shared timed quest
12010 if(questGiver
&& questGiver
->GetTypeId()==TYPEID_PLAYER
)
12011 limittime
= ((Player
*)questGiver
)->getQuestStatusMap()[quest_id
].m_timer
/ 1000;
12013 AddTimedQuest( quest_id
);
12014 questStatusData
.m_timer
= limittime
* 1000;
12015 qtime
= static_cast<uint32
>(time(NULL
)) + limittime
;
12018 questStatusData
.m_timer
= 0;
12020 SetQuestSlot(log_slot
, quest_id
, qtime
);
12022 //starting initial quest script
12023 if(questGiver
&& pQuest
->GetQuestStartScript()!=0)
12024 sWorld
.ScriptsStart(sQuestStartScripts
, pQuest
->GetQuestStartScript(), questGiver
, this);
12026 UpdateForQuestsGO();
12029 void Player::CompleteQuest( uint32 quest_id
)
12033 SetQuestStatus( quest_id
, QUEST_STATUS_COMPLETE
);
12035 uint16 log_slot
= FindQuestSlot( quest_id
);
12036 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12037 SetQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
12039 if(Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
))
12041 if( qInfo
->HasFlag(QUEST_FLAGS_AUTO_REWARDED
) )
12042 RewardQuest(qInfo
,0,this,false);
12044 SendQuestComplete( quest_id
);
12049 void Player::IncompleteQuest( uint32 quest_id
)
12053 SetQuestStatus( quest_id
, QUEST_STATUS_INCOMPLETE
);
12055 uint16 log_slot
= FindQuestSlot( quest_id
);
12056 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12057 RemoveQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
12061 void Player::RewardQuest( Quest
const *pQuest
, uint32 reward
, Object
* questGiver
, bool announce
)
12063 uint32 quest_id
= pQuest
->GetQuestId();
12065 for (int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++ )
12067 if ( pQuest
->ReqItemId
[i
] )
12068 DestroyItemCount( pQuest
->ReqItemId
[i
], pQuest
->ReqItemCount
[i
], true);
12071 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12072 // SetTimedQuest( 0 );
12073 m_timedquests
.erase(pQuest
->GetQuestId());
12075 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
12077 if( pQuest
->RewChoiceItemId
[reward
] )
12079 ItemPosCountVec dest
;
12080 if( CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] ) == EQUIP_ERR_OK
)
12082 Item
* item
= StoreNewItem( dest
, pQuest
->RewChoiceItemId
[reward
], true);
12083 SendNewItem(item
, pQuest
->RewChoiceItemCount
[reward
], true, false);
12088 if ( pQuest
->GetRewItemsCount() > 0 )
12090 for (uint32 i
=0; i
< pQuest
->GetRewItemsCount(); ++i
)
12092 if( pQuest
->RewItemId
[i
] )
12094 ItemPosCountVec dest
;
12095 if( CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] ) == EQUIP_ERR_OK
)
12097 Item
* item
= StoreNewItem( dest
, pQuest
->RewItemId
[i
], true);
12098 SendNewItem(item
, pQuest
->RewItemCount
[i
], true, false);
12104 RewardReputation( pQuest
);
12106 if( pQuest
->GetRewSpellCast() > 0 )
12107 CastSpell( this, pQuest
->GetRewSpellCast(), true);
12108 else if( pQuest
->GetRewSpell() > 0)
12109 CastSpell( this, pQuest
->GetRewSpell(), true);
12111 uint16 log_slot
= FindQuestSlot( quest_id
);
12112 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12113 SetQuestSlot(log_slot
,0);
12115 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12117 // Not give XP in case already completed once repeatable quest
12118 uint32 XP
= q_status
.m_rewarded
? 0 : uint32(pQuest
->XPValue( this )*sWorld
.getRate(RATE_XP_QUEST
));
12120 if ( getLevel() < sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
12121 GiveXP( XP
, NULL
);
12123 ModifyMoney( int32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getRate(RATE_DROP_MONEY
)) );
12125 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12126 ModifyMoney( pQuest
->GetRewOrReqMoney() );
12129 if(pQuest
->GetRewHonorableKills())
12130 RewardHonor(NULL
, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorableKills()));
12133 if(pQuest
->GetCharTitleId())
12135 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
12136 SetTitle(titleEntry
);
12139 // Send reward mail
12140 if(pQuest
->GetRewMailTemplateId())
12142 MailMessageType mailType
;
12143 uint32 senderGuidOrEntry
;
12144 switch(questGiver
->GetTypeId())
12147 mailType
= MAIL_CREATURE
;
12148 senderGuidOrEntry
= questGiver
->GetEntry();
12150 case TYPEID_GAMEOBJECT
:
12151 mailType
= MAIL_GAMEOBJECT
;
12152 senderGuidOrEntry
= questGiver
->GetEntry();
12155 mailType
= MAIL_ITEM
;
12156 senderGuidOrEntry
= questGiver
->GetEntry();
12158 case TYPEID_PLAYER
:
12159 mailType
= MAIL_NORMAL
;
12160 senderGuidOrEntry
= questGiver
->GetGUIDLow();
12163 mailType
= MAIL_NORMAL
;
12164 senderGuidOrEntry
= GetGUIDLow();
12168 Loot questMailLoot
;
12170 questMailLoot
.FillLoot(pQuest
->GetQuestId(), LootTemplates_QuestMail
, this);
12173 MailItemsInfo mi
; // item list preparing
12175 for(size_t i
= 0; mi
.size() < MAX_MAIL_ITEMS
&& i
< questMailLoot
.items
.size(); ++i
)
12177 if(LootItem
* lootitem
= questMailLoot
.LootItemInSlot(i
,this))
12179 if(Item
* item
= Item::CreateItem(lootitem
->itemid
,lootitem
->count
,this))
12181 item
->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12182 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
12187 for(size_t i
= 0; mi
.size() < MAX_MAIL_ITEMS
&& i
< questMailLoot
.quest_items
.size(); ++i
)
12189 if(LootItem
* lootitem
= questMailLoot
.LootItemInSlot(i
+questMailLoot
.items
.size(),this))
12191 if(Item
* item
= Item::CreateItem(lootitem
->itemid
,lootitem
->count
,this))
12193 item
->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12194 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
12199 WorldSession::SendMailTo(this, mailType
, MAIL_STATIONERY_NORMAL
, senderGuidOrEntry
, GetGUIDLow(), "", 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
,pQuest
->GetRewMailDelaySecs(),pQuest
->GetRewMailTemplateId());
12202 if(pQuest
->IsDaily())
12203 SetDailyQuestStatus(quest_id
);
12205 if ( !pQuest
->IsRepeatable() )
12206 SetQuestStatus(quest_id
, QUEST_STATUS_COMPLETE
);
12208 SetQuestStatus(quest_id
, QUEST_STATUS_NONE
);
12210 q_status
.m_rewarded
= true;
12213 SendQuestReward( pQuest
, XP
, questGiver
);
12215 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12218 void Player::FailQuest( uint32 quest_id
)
12222 IncompleteQuest( quest_id
);
12224 uint16 log_slot
= FindQuestSlot( quest_id
);
12225 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12227 SetQuestSlotTimer(log_slot
, 1 );
12228 SetQuestSlotState(log_slot
,QUEST_STATE_FAIL
);
12230 SendQuestFailed( quest_id
);
12234 void Player::FailTimedQuest( uint32 quest_id
)
12238 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12240 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12241 q_status
.m_timer
= 0;
12243 IncompleteQuest( quest_id
);
12245 uint16 log_slot
= FindQuestSlot( quest_id
);
12246 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12248 SetQuestSlotTimer(log_slot
, 1 );
12249 SetQuestSlotState(log_slot
,QUEST_STATE_FAIL
);
12251 SendQuestTimerFailed( quest_id
);
12255 bool Player::SatisfyQuestSkillOrClass( Quest
const* qInfo
, bool msg
)
12257 int32 zoneOrSort
= qInfo
->GetZoneOrSort();
12258 int32 skillOrClass
= qInfo
->GetSkillOrClass();
12260 // skip zone zoneOrSort and 0 case skillOrClass
12261 if( zoneOrSort
>= 0 && skillOrClass
== 0 )
12264 int32 questSort
= -zoneOrSort
;
12265 uint8 reqSortClass
= ClassByQuestSort(questSort
);
12267 // check class sort cases in zoneOrSort
12268 if( reqSortClass
!= 0 && getClass() != reqSortClass
)
12271 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12276 if( skillOrClass
< 0 )
12278 uint8 reqClass
= -int32(skillOrClass
);
12279 if(getClass() != reqClass
)
12282 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12287 else if( skillOrClass
> 0 )
12289 uint32 reqSkill
= skillOrClass
;
12290 if( GetSkillValue( reqSkill
) < qInfo
->GetRequiredSkillValue() )
12293 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12301 bool Player::SatisfyQuestLevel( Quest
const* qInfo
, bool msg
)
12303 if( getLevel() < qInfo
->GetMinLevel() )
12306 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12312 bool Player::SatisfyQuestLog( bool msg
)
12315 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE
)
12320 WorldPacket
data( SMSG_QUESTLOG_FULL
, 0 );
12321 GetSession()->SendPacket( &data
);
12322 sLog
.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12327 bool Player::SatisfyQuestPreviousQuest( Quest
const* qInfo
, bool msg
)
12329 // No previous quest (might be first quest in a series)
12330 if( qInfo
->prevQuests
.empty())
12333 for(Quest::PrevQuests::const_iterator iter
= qInfo
->prevQuests
.begin(); iter
!= qInfo
->prevQuests
.end(); ++iter
)
12335 uint32 prevId
= abs(*iter
);
12337 QuestStatusMap::iterator i_prevstatus
= mQuestStatus
.find( prevId
);
12338 Quest
const* qPrevInfo
= objmgr
.GetQuestTemplate(prevId
);
12340 if( qPrevInfo
&& i_prevstatus
!= mQuestStatus
.end() )
12342 // If any of the positive previous quests completed, return true
12343 if( *iter
> 0 && i_prevstatus
->second
.m_rewarded
)
12345 // skip one-from-all exclusive group
12346 if(qPrevInfo
->GetExclusiveGroup() >= 0)
12349 // each-from-all exclusive group ( < 0)
12350 // can be start if only all quests in prev quest exclusive group completed and rewarded
12351 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
12352 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
12354 assert(iter
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
12356 for(; iter
!= end
; ++iter
)
12358 uint32 exclude_Id
= iter
->second
;
12360 // skip checked quest id, only state of other quests in group is interesting
12361 if(exclude_Id
== prevId
)
12364 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12366 // alternative quest from group also must be completed and rewarded(reported)
12367 if( i_exstatus
== mQuestStatus
.end() || !i_exstatus
->second
.m_rewarded
)
12370 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12376 // If any of the negative previous quests active, return true
12377 if( *iter
< 0 && (i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
12378 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
))))
12380 // skip one-from-all exclusive group
12381 if(qPrevInfo
->GetExclusiveGroup() >= 0)
12384 // each-from-all exclusive group ( < 0)
12385 // can be start if only all quests in prev quest exclusive group active
12386 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
12387 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
12389 assert(iter
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
12391 for(; iter
!= end
; ++iter
)
12393 uint32 exclude_Id
= iter
->second
;
12395 // skip checked quest id, only state of other quests in group is interesting
12396 if(exclude_Id
== prevId
)
12399 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12401 // alternative quest from group also must be active
12402 if( i_exstatus
== mQuestStatus
.end() ||
12403 i_exstatus
->second
.m_status
!= QUEST_STATUS_INCOMPLETE
&&
12404 (i_prevstatus
->second
.m_status
!= QUEST_STATUS_COMPLETE
|| GetQuestRewardStatus(prevId
)) )
12407 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12416 // Has only positive prev. quests in non-rewarded state
12417 // and negative prev. quests in non-active state
12419 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12424 bool Player::SatisfyQuestRace( Quest
const* qInfo
, bool msg
)
12426 uint32 reqraces
= qInfo
->GetRequiredRaces();
12427 if ( reqraces
== 0 )
12429 if( (reqraces
& getRaceMask()) == 0 )
12432 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE
);
12438 bool Player::SatisfyQuestReputation( Quest
const* qInfo
, bool msg
)
12440 uint32 fIdMin
= qInfo
->GetRequiredMinRepFaction(); //Min required rep
12441 if(fIdMin
&& GetReputation(fIdMin
) < qInfo
->GetRequiredMinRepValue())
12444 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12448 uint32 fIdMax
= qInfo
->GetRequiredMaxRepFaction(); //Max required rep
12449 if(fIdMax
&& GetReputation(fIdMax
) >= qInfo
->GetRequiredMaxRepValue())
12452 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12459 bool Player::SatisfyQuestStatus( Quest
const* qInfo
, bool msg
)
12461 QuestStatusMap::iterator itr
= mQuestStatus
.find( qInfo
->GetQuestId() );
12462 if ( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
)
12465 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON
);
12471 bool Player::SatisfyQuestTimed( Quest
const* qInfo
, bool msg
)
12473 if ( (find(m_timedquests
.begin(), m_timedquests
.end(), qInfo
->GetQuestId()) != m_timedquests
.end()) && qInfo
->HasFlag(QUEST_MANGOS_FLAGS_TIMED
) )
12476 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED
);
12482 bool Player::SatisfyQuestExclusiveGroup( Quest
const* qInfo
, bool msg
)
12484 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12485 if(qInfo
->GetExclusiveGroup() <= 0)
12488 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qInfo
->GetExclusiveGroup());
12489 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qInfo
->GetExclusiveGroup());
12491 assert(iter
!=end
); // always must be found if qInfo->ExclusiveGroup != 0
12493 for(; iter
!= end
; ++iter
)
12495 uint32 exclude_Id
= iter
->second
;
12497 // skip checked quest id, only state of other quests in group is interesting
12498 if(exclude_Id
== qInfo
->GetQuestId())
12501 // not allow have daily quest if daily quest from exclusive group already recently completed
12502 Quest
const* Nquest
= objmgr
.GetQuestTemplate(exclude_Id
);
12503 if( !SatisfyQuestDay(Nquest
, false) )
12506 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12510 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12512 // alternative quest already started or completed
12513 if( i_exstatus
!= mQuestStatus
.end()
12514 && (i_exstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
|| i_exstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
12517 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12524 bool Player::SatisfyQuestNextChain( Quest
const* qInfo
, bool msg
)
12526 if(!qInfo
->GetNextQuestInChain())
12529 // next quest in chain already started or completed
12530 QuestStatusMap::iterator itr
= mQuestStatus
.find( qInfo
->GetNextQuestInChain() );
12531 if( itr
!= mQuestStatus
.end()
12532 && (itr
->second
.m_status
== QUEST_STATUS_COMPLETE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
12535 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12539 // check for all quests further up the chain
12540 // only necessary if there are quest chains with more than one quest that can be skipped
12541 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12545 bool Player::SatisfyQuestPrevChain( Quest
const* qInfo
, bool msg
)
12547 // No previous quest in chain
12548 if( qInfo
->prevChainQuests
.empty())
12551 for(Quest::PrevChainQuests::const_iterator iter
= qInfo
->prevChainQuests
.begin(); iter
!= qInfo
->prevChainQuests
.end(); ++iter
)
12553 uint32 prevId
= *iter
;
12555 QuestStatusMap::iterator i_prevstatus
= mQuestStatus
.find( prevId
);
12557 if( i_prevstatus
!= mQuestStatus
.end() )
12559 // If any of the previous quests in chain active, return false
12560 if( i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
12561 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
)))
12564 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12569 // check for all quests further down the chain
12570 // only necessary if there are quest chains with more than one quest that can be skipped
12571 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12575 // No previous quest in chain active
12579 bool Player::SatisfyQuestDay( Quest
const* qInfo
, bool msg
)
12581 if(!qInfo
->IsDaily())
12584 bool have_slot
= false;
12585 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
12587 uint32 id
= GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
);
12588 if(qInfo
->GetQuestId()==id
)
12598 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING
);
12605 bool Player::GiveQuestSourceItem( Quest
const *pQuest
)
12607 uint32 srcitem
= pQuest
->GetSrcItemId();
12610 uint32 count
= pQuest
->GetSrcItemCount();
12614 ItemPosCountVec dest
;
12615 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
12616 if( msg
== EQUIP_ERR_OK
)
12618 Item
* item
= StoreNewItem(dest
, srcitem
, true);
12619 SendNewItem(item
, count
, true, false);
12622 // player already have max amount required item, just report success
12623 else if( msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
12626 SendEquipError( msg
, NULL
, NULL
);
12633 bool Player::TakeQuestSourceItem( uint32 quest_id
, bool msg
)
12635 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12638 uint32 srcitem
= qInfo
->GetSrcItemId();
12641 uint32 count
= qInfo
->GetSrcItemCount();
12645 // exist one case when destroy source quest item not possible:
12646 // non un-equippable item (equipped non-empty bag, for example)
12647 uint8 res
= CanUnequipItems(srcitem
,count
);
12648 if(res
!= EQUIP_ERR_OK
)
12651 SendEquipError( res
, NULL
, NULL
);
12655 DestroyItemCount(srcitem
, count
, true, true);
12661 bool Player::GetQuestRewardStatus( uint32 quest_id
) const
12663 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12666 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
12667 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
12668 if( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
12669 && !qInfo
->IsRepeatable() )
12670 return itr
->second
.m_rewarded
;
12677 QuestStatus
Player::GetQuestStatus( uint32 quest_id
) const
12681 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
12682 if( itr
!= mQuestStatus
.end() )
12683 return itr
->second
.m_status
;
12685 return QUEST_STATUS_NONE
;
12688 bool Player::CanShareQuest(uint32 quest_id
) const
12690 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12691 if( qInfo
&& qInfo
->HasFlag(QUEST_FLAGS_SHARABLE
) )
12693 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
12694 if( itr
!= mQuestStatus
.end() )
12695 return itr
->second
.m_status
== QUEST_STATUS_NONE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
;
12700 void Player::SetQuestStatus( uint32 quest_id
, QuestStatus status
)
12702 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12705 if( status
== QUEST_STATUS_NONE
|| status
== QUEST_STATUS_INCOMPLETE
|| status
== QUEST_STATUS_COMPLETE
)
12707 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
12708 m_timedquests
.erase(qInfo
->GetQuestId());
12711 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12713 q_status
.m_status
= status
;
12714 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12717 UpdateForQuestsGO();
12720 // not used in MaNGOS, but used in scripting code
12721 uint32
Player::GetReqKillOrCastCurrentCount(uint32 quest_id
, int32 entry
)
12723 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12727 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
12728 if ( qInfo
->ReqCreatureOrGOId
[j
] == entry
)
12729 return mQuestStatus
[quest_id
].m_creatureOrGOcount
[j
];
12734 void Player::AdjustQuestReqItemCount( Quest
const* pQuest
)
12736 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12738 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12740 uint32 reqitemcount
= pQuest
->ReqItemCount
[i
];
12741 if( reqitemcount
!= 0 )
12743 uint32 quest_id
= pQuest
->GetQuestId();
12744 uint32 curitemcount
= GetItemCount(pQuest
->ReqItemId
[i
],true);
12746 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12747 q_status
.m_itemcount
[i
] = std::min(curitemcount
, reqitemcount
);
12748 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12754 uint16
Player::FindQuestSlot( uint32 quest_id
) const
12756 for ( uint16 i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
12757 if ( GetQuestSlotQuestId(i
) == quest_id
)
12760 return MAX_QUEST_LOG_SIZE
;
12763 void Player::AreaExploredOrEventHappens( uint32 questId
)
12767 uint16 log_slot
= FindQuestSlot( questId
);
12768 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12770 QuestStatusData
& q_status
= mQuestStatus
[questId
];
12772 if(!q_status
.m_explored
)
12774 q_status
.m_explored
= true;
12775 if (q_status
.uState
!= QUEST_NEW
)
12776 q_status
.uState
= QUEST_CHANGED
;
12779 if( CanCompleteQuest( questId
) )
12780 CompleteQuest( questId
);
12784 //not used in mangosd, function for external script library
12785 void Player::GroupEventHappens( uint32 questId
, WorldObject
const* pEventObject
)
12787 if( Group
*pGroup
= GetGroup() )
12789 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
12791 Player
*pGroupGuy
= itr
->getSource();
12793 // for any leave or dead (with not released body) group member at appropriate distance
12794 if( pGroupGuy
&& pGroupGuy
->IsAtGroupRewardDistance(pEventObject
) && !pGroupGuy
->GetCorpse() )
12795 pGroupGuy
->AreaExploredOrEventHappens(questId
);
12799 AreaExploredOrEventHappens(questId
);
12802 void Player::ItemAddedQuestCheck( uint32 entry
, uint32 count
)
12804 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
12806 uint32 questid
= GetQuestSlotQuestId(i
);
12807 if ( questid
== 0 )
12810 QuestStatusData
& q_status
= mQuestStatus
[questid
];
12812 if ( q_status
.m_status
!= QUEST_STATUS_INCOMPLETE
)
12815 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
12816 if( !qInfo
|| !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12819 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
12821 uint32 reqitem
= qInfo
->ReqItemId
[j
];
12822 if ( reqitem
== entry
)
12824 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
12825 uint32 curitemcount
= q_status
.m_itemcount
[j
];
12826 if ( curitemcount
< reqitemcount
)
12828 uint32 additemcount
= ( curitemcount
+ count
<= reqitemcount
? count
: reqitemcount
- curitemcount
);
12829 q_status
.m_itemcount
[j
] += additemcount
;
12830 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12832 SendQuestUpdateAddItem( qInfo
, j
, additemcount
);
12834 if ( CanCompleteQuest( questid
) )
12835 CompleteQuest( questid
);
12840 UpdateForQuestsGO();
12843 void Player::ItemRemovedQuestCheck( uint32 entry
, uint32 count
)
12845 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
12847 uint32 questid
= GetQuestSlotQuestId(i
);
12850 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
12853 if( !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12856 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
12858 uint32 reqitem
= qInfo
->ReqItemId
[j
];
12859 if ( reqitem
== entry
)
12861 QuestStatusData
& q_status
= mQuestStatus
[questid
];
12863 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
12864 uint32 curitemcount
;
12865 if( q_status
.m_status
!= QUEST_STATUS_COMPLETE
)
12866 curitemcount
= q_status
.m_itemcount
[j
];
12868 curitemcount
= GetItemCount(entry
,true);
12869 if ( curitemcount
< reqitemcount
+ count
)
12871 uint32 remitemcount
= ( curitemcount
<= reqitemcount
? count
: count
+ reqitemcount
- curitemcount
);
12872 q_status
.m_itemcount
[j
] = curitemcount
- remitemcount
;
12873 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12875 IncompleteQuest( questid
);
12881 UpdateForQuestsGO();
12884 void Player::KilledMonster( uint32 entry
, uint64 guid
)
12886 uint32 addkillcount
= 1;
12887 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
12889 uint32 questid
= GetQuestSlotQuestId(i
);
12893 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
12896 // just if !ingroup || !noraidgroup || raidgroup
12897 QuestStatusData
& q_status
= mQuestStatus
[questid
];
12898 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
&& (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo
->GetType() == QUEST_TYPE_RAID
))
12900 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
12902 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
12904 // skip GO activate objective or none
12905 if(qInfo
->ReqCreatureOrGOId
[j
] <=0)
12908 // skip Cast at creature objective
12909 if(qInfo
->ReqSpell
[j
] !=0 )
12912 uint32 reqkill
= qInfo
->ReqCreatureOrGOId
[j
];
12914 if ( reqkill
== entry
)
12916 uint32 reqkillcount
= qInfo
->ReqCreatureOrGOCount
[j
];
12917 uint32 curkillcount
= q_status
.m_creatureOrGOcount
[j
];
12918 if ( curkillcount
< reqkillcount
)
12920 q_status
.m_creatureOrGOcount
[j
] = curkillcount
+ addkillcount
;
12921 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12923 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curkillcount
, addkillcount
);
12925 if ( CanCompleteQuest( questid
) )
12926 CompleteQuest( questid
);
12928 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
12937 void Player::CastedCreatureOrGO( uint32 entry
, uint64 guid
, uint32 spell_id
)
12939 bool isCreature
= IS_CREATURE_GUID(guid
);
12941 uint32 addCastCount
= 1;
12942 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
12944 uint32 questid
= GetQuestSlotQuestId(i
);
12948 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
12952 QuestStatusData
& q_status
= mQuestStatus
[questid
];
12954 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
12956 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
12958 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
12960 // skip kill creature objective (0) or wrong spell casts
12961 if(qInfo
->ReqSpell
[j
] != spell_id
)
12964 uint32 reqTarget
= 0;
12968 // creature activate objectives
12969 if(qInfo
->ReqCreatureOrGOId
[j
] > 0)
12970 // checked at quest_template loading
12971 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
12975 // GO activate objective
12976 if(qInfo
->ReqCreatureOrGOId
[j
] < 0)
12977 // checked at quest_template loading
12978 reqTarget
= - qInfo
->ReqCreatureOrGOId
[j
];
12981 // other not this creature/GO related objectives
12982 if( reqTarget
!= entry
)
12985 uint32 reqCastCount
= qInfo
->ReqCreatureOrGOCount
[j
];
12986 uint32 curCastCount
= q_status
.m_creatureOrGOcount
[j
];
12987 if ( curCastCount
< reqCastCount
)
12989 q_status
.m_creatureOrGOcount
[j
] = curCastCount
+ addCastCount
;
12990 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12992 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curCastCount
, addCastCount
);
12995 if ( CanCompleteQuest( questid
) )
12996 CompleteQuest( questid
);
12998 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13006 void Player::TalkedToCreature( uint32 entry
, uint64 guid
)
13008 uint32 addTalkCount
= 1;
13009 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13011 uint32 questid
= GetQuestSlotQuestId(i
);
13015 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13019 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13021 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13023 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
13025 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13027 // skip spell casts and Gameobject objectives
13028 if(qInfo
->ReqSpell
[j
] > 0 || qInfo
->ReqCreatureOrGOId
[j
] < 0)
13031 uint32 reqTarget
= 0;
13033 if(qInfo
->ReqCreatureOrGOId
[j
] > 0) // creature activate objectives
13034 // checked at quest_template loading
13035 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
13039 if ( reqTarget
== entry
)
13041 uint32 reqTalkCount
= qInfo
->ReqCreatureOrGOCount
[j
];
13042 uint32 curTalkCount
= q_status
.m_creatureOrGOcount
[j
];
13043 if ( curTalkCount
< reqTalkCount
)
13045 q_status
.m_creatureOrGOcount
[j
] = curTalkCount
+ addTalkCount
;
13046 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13048 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curTalkCount
, addTalkCount
);
13050 if ( CanCompleteQuest( questid
) )
13051 CompleteQuest( questid
);
13053 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13062 void Player::MoneyChanged( uint32 count
)
13064 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; i
++ )
13066 uint32 questid
= GetQuestSlotQuestId(i
);
13070 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13071 if( qInfo
&& qInfo
->GetRewOrReqMoney() < 0 )
13073 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13075 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13077 if(int32(count
) >= -qInfo
->GetRewOrReqMoney())
13079 if ( CanCompleteQuest( questid
) )
13080 CompleteQuest( questid
);
13083 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
13085 if(int32(count
) < -qInfo
->GetRewOrReqMoney())
13086 IncompleteQuest( questid
);
13092 bool Player::HasQuestForItem( uint32 itemid
) const
13094 for( QuestStatusMap::const_iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
13096 QuestStatusData
const& q_status
= i
->second
;
13098 if (q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13100 Quest
const* qinfo
= objmgr
.GetQuestTemplate(i
->first
);
13104 // hide quest if player is in raid-group and quest is no raid quest
13105 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
13108 // There should be no mixed ReqItem/ReqSource drop
13109 // This part for ReqItem drop
13110 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13112 if(itemid
== qinfo
->ReqItemId
[j
] && q_status
.m_itemcount
[j
] < qinfo
->ReqItemCount
[j
] )
13115 // This part - for ReqSource
13116 for (int j
= 0; j
< QUEST_SOURCE_ITEM_IDS_COUNT
; j
++)
13118 // examined item is a source item
13119 if (qinfo
->ReqSourceId
[j
] == itemid
&& qinfo
->ReqSourceRef
[j
] > 0 && qinfo
->ReqSourceRef
[j
] <= QUEST_OBJECTIVES_COUNT
)
13121 uint32 idx
= qinfo
->ReqSourceRef
[j
]-1;
13123 // total count of created ReqItems and SourceItems is less than ReqItemCount
13124 if(qinfo
->ReqItemId
[idx
] != 0 &&
13125 q_status
.m_itemcount
[idx
] * qinfo
->ReqSourceCount
[j
] + GetItemCount(itemid
,true) < qinfo
->ReqItemCount
[idx
] * qinfo
->ReqSourceCount
[j
])
13128 // total count of casted ReqCreatureOrGOs and SourceItems is less than ReqCreatureOrGOCount
13129 if (qinfo
->ReqCreatureOrGOId
[idx
] != 0)
13131 if(q_status
.m_creatureOrGOcount
[idx
] * qinfo
->ReqSourceCount
[j
] + GetItemCount(itemid
,true) < qinfo
->ReqCreatureOrGOCount
[idx
] * qinfo
->ReqSourceCount
[j
])
13134 // spell with SPELL_EFFECT_QUEST_COMPLETE or SPELL_EFFECT_SEND_EVENT (with script) case
13135 else if(qinfo
->ReqSpell
[idx
] != 0)
13137 // not casted and need more reagents/item for use.
13138 if(!q_status
.m_explored
&& GetItemCount(itemid
,true) < qinfo
->ReqSourceCount
[j
])
13148 void Player::SendQuestComplete( uint32 quest_id
)
13152 WorldPacket
data( SMSG_QUESTUPDATE_COMPLETE
, 4 );
13153 data
<< uint32(quest_id
);
13154 GetSession()->SendPacket( &data
);
13155 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id
);
13159 void Player::SendQuestReward( Quest
const *pQuest
, uint32 XP
, Object
* questGiver
)
13161 uint32 questid
= pQuest
->GetQuestId();
13162 sLog
.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid
);
13163 WorldPacket
data( SMSG_QUESTGIVER_QUEST_COMPLETE
, (4+4+4+4+4+4+pQuest
->GetRewItemsCount()*8) );
13165 data
<< uint32(0x03);
13167 if ( getLevel() < sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
13170 data
<< uint32(pQuest
->GetRewOrReqMoney());
13175 data
<< uint32(pQuest
->GetRewOrReqMoney() + int32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getRate(RATE_DROP_MONEY
)));
13177 data
<< uint32(0); // new 2.3.0, HonorPoints?
13178 data
<< uint32( pQuest
->GetRewItemsCount() ); // max is 5
13180 for (uint32 i
= 0; i
< pQuest
->GetRewItemsCount(); ++i
)
13182 if ( pQuest
->RewItemId
[i
] > 0 )
13183 data
<< pQuest
->RewItemId
[i
] << pQuest
->RewItemCount
[i
];
13185 data
<< uint32(0) << uint32(0);
13187 GetSession()->SendPacket( &data
);
13189 if (pQuest
->GetQuestCompleteScript() != 0)
13190 sWorld
.ScriptsStart(sQuestEndScripts
, pQuest
->GetQuestCompleteScript(), questGiver
, this);
13193 void Player::SendQuestFailed( uint32 quest_id
)
13197 WorldPacket
data( SMSG_QUESTGIVER_QUEST_FAILED
, 4 );
13199 GetSession()->SendPacket( &data
);
13200 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13204 void Player::SendQuestTimerFailed( uint32 quest_id
)
13208 WorldPacket
data( SMSG_QUESTUPDATE_FAILEDTIMER
, 4 );
13210 GetSession()->SendPacket( &data
);
13211 sLog
.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13215 void Player::SendCanTakeQuestResponse( uint32 msg
)
13217 WorldPacket
data( SMSG_QUESTGIVER_QUEST_INVALID
, 4 );
13218 data
<< uint32(msg
);
13219 GetSession()->SendPacket( &data
);
13220 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13223 void Player::SendPushToPartyResponse( Player
*pPlayer
, uint32 msg
)
13227 WorldPacket
data( MSG_QUEST_PUSH_RESULT
, (8+1) );
13228 data
<< uint64(pPlayer
->GetGUID());
13229 data
<< uint8(msg
); // valid values: 0-8
13230 GetSession()->SendPacket( &data
);
13231 sLog
.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13235 void Player::SendQuestUpdateAddItem( Quest
const* pQuest
, uint32 item_idx
, uint32 count
)
13237 WorldPacket
data( SMSG_QUESTUPDATE_ADD_ITEM
, (4+4) );
13238 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13239 data
<< pQuest
->ReqItemId
[item_idx
];
13241 GetSession()->SendPacket( &data
);
13244 void Player::SendQuestUpdateAddCreatureOrGo( Quest
const* pQuest
, uint64 guid
, uint32 creatureOrGO_idx
, uint32 old_count
, uint32 add_count
)
13246 assert(old_count
+ add_count
< 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13248 int32 entry
= pQuest
->ReqCreatureOrGOId
[ creatureOrGO_idx
];
13250 // client expected gameobject template id in form (id|0x80000000)
13251 entry
= (-entry
) | 0x80000000;
13253 WorldPacket
data( SMSG_QUESTUPDATE_ADD_KILL
, (4*4+8) );
13254 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13255 data
<< uint32(pQuest
->GetQuestId());
13256 data
<< uint32(entry
);
13257 data
<< uint32(old_count
+ add_count
);
13258 data
<< uint32(pQuest
->ReqCreatureOrGOCount
[ creatureOrGO_idx
]);
13259 data
<< uint64(guid
);
13260 GetSession()->SendPacket(&data
);
13262 uint16 log_slot
= FindQuestSlot( pQuest
->GetQuestId() );
13263 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13264 SetQuestSlotCounter(log_slot
,creatureOrGO_idx
,GetQuestSlotCounter(log_slot
,creatureOrGO_idx
)+add_count
);
13267 /*********************************************************/
13268 /*** LOAD SYSTEM ***/
13269 /*********************************************************/
13271 bool Player::MinimalLoadFromDB( QueryResult
*result
, uint32 guid
)
13273 bool delete_result
= true;
13276 // 0 1 2 3 4 5 6 7 8 9
13277 result
= CharacterDatabase
.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid
);
13278 if(!result
) return false;
13280 else delete_result
= false;
13282 Field
*fields
= result
->Fetch();
13284 if(!LoadValues( fields
[1].GetString()))
13286 sLog
.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid
));
13287 if(delete_result
) delete result
;
13291 // overwrite possible wrong/corrupted guid
13292 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
13294 m_name
= fields
[2].GetCppString();
13296 Relocate(fields
[3].GetFloat(),fields
[4].GetFloat(),fields
[5].GetFloat());
13297 SetMapId(fields
[6].GetUInt32());
13298 // the instance id is not needed at character enum
13300 m_Played_time
[0] = fields
[7].GetUInt32();
13301 m_Played_time
[1] = fields
[8].GetUInt32();
13303 m_atLoginFlags
= fields
[9].GetUInt32();
13305 // I don't see these used anywhere ..
13308 _LoadBoundInstances();*/
13310 if (delete_result
) delete result
;
13312 for (int i
= 0; i
< PLAYER_SLOTS_COUNT
; i
++)
13315 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
13316 m_deathState
= DEAD
;
13321 void Player::_LoadDeclinedNames(QueryResult
* result
)
13327 delete m_declinedname
;
13329 m_declinedname
= new DeclinedName
;
13330 Field
*fields
= result
->Fetch();
13331 for(int i
= 0; i
< MAX_DECLINED_NAME_CASES
; ++i
)
13332 m_declinedname
->name
[i
] = fields
[i
].GetCppString();
13337 bool Player::LoadPositionFromDB(uint32
& mapid
, float& x
,float& y
,float& z
,float& o
, bool& in_flight
, uint64 guid
)
13339 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid
));
13343 Field
*fields
= result
->Fetch();
13345 x
= fields
[0].GetFloat();
13346 y
= fields
[1].GetFloat();
13347 z
= fields
[2].GetFloat();
13348 o
= fields
[3].GetFloat();
13349 mapid
= fields
[4].GetUInt32();
13350 in_flight
= !fields
[5].GetCppString().empty();
13356 bool Player::LoadValuesArrayFromDB(Tokens
& data
, uint64 guid
)
13358 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid
));
13362 Field
*fields
= result
->Fetch();
13364 data
= StrSplit(fields
[0].GetCppString(), " ");
13371 uint32
Player::GetUInt32ValueFromArray(Tokens
const& data
, uint16 index
)
13373 if(index
>= data
.size())
13376 return (uint32
)atoi(data
[index
].c_str());
13379 float Player::GetFloatValueFromArray(Tokens
const& data
, uint16 index
)
13382 uint32 temp
= Player::GetUInt32ValueFromArray(data
,index
);
13383 memcpy(&result
, &temp
, sizeof(result
));
13388 uint32
Player::GetUInt32ValueFromDB(uint16 index
, uint64 guid
)
13391 if(!LoadValuesArrayFromDB(data
,guid
))
13394 return GetUInt32ValueFromArray(data
,index
);
13397 float Player::GetFloatValueFromDB(uint16 index
, uint64 guid
)
13400 uint32 temp
= Player::GetUInt32ValueFromDB(index
, guid
);
13401 memcpy(&result
, &temp
, sizeof(result
));
13406 bool Player::LoadFromDB( uint32 guid
, SqlQueryHolder
*holder
)
13408 //// 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
13409 //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);
13410 QueryResult
*result
= holder
->GetResult(PLAYER_LOGIN_QUERY_LOADFROM
);
13414 sLog
.outError("ERROR: Player (GUID: %u) not found in table `characters`, can't load. ",guid
);
13418 Field
*fields
= result
->Fetch();
13420 uint32 dbAccountId
= fields
[1].GetUInt32();
13422 // check if the character's account in the db and the logged in account match.
13423 // player should be able to load/delete character only with correct account!
13424 if( dbAccountId
!= GetSession()->GetAccountId() )
13426 sLog
.outError("ERROR: Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid
,GetSession()->GetAccountId(),dbAccountId
);
13431 Object::_Create( guid
, 0, HIGHGUID_PLAYER
);
13433 m_name
= fields
[3].GetCppString();
13435 // check name limitations
13436 if(!ObjectMgr::IsValidName(m_name
) || GetSession()->GetSecurity() == SEC_PLAYER
&& objmgr
.IsReservedName(m_name
))
13439 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME
),guid
);
13443 if(!LoadValues( fields
[2].GetString()))
13445 sLog
.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid
));
13450 // overwrite possible wrong/corrupted guid
13451 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
13453 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13454 for(uint8 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
13456 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), 0 );
13457 SetVisibleItemSlot(slot
,NULL
);
13461 delete m_items
[slot
];
13462 m_items
[slot
] = NULL
;
13466 // update money limits
13467 if(GetMoney() > MAX_MONEY_AMOUNT
)
13468 SetMoney(MAX_MONEY_AMOUNT
);
13470 sLog
.outDebug("Load Basic value of player %s is: ", m_name
.c_str());
13473 m_race
= fields
[4].GetUInt8();
13474 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13475 //Other way is to saves m_team into characters table.
13476 setFactionForRace(m_race
);
13479 m_class
= fields
[5].GetUInt8();
13481 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(m_race
, m_class
);
13484 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
13489 InitPrimaryProffesions(); // to max set before any spell loaded
13491 uint32 transGUID
= fields
[24].GetUInt32();
13492 Relocate(fields
[6].GetFloat(),fields
[7].GetFloat(),fields
[8].GetFloat(),fields
[10].GetFloat());
13493 SetFallInformation(0, fields
[8].GetFloat());
13494 SetMapId(fields
[9].GetUInt32());
13495 SetDifficulty(fields
[32].GetUInt32()); // may be changed in _LoadGroup
13497 _LoadGroup(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP
));
13499 // check arena teams integrity
13500 for(uint32 arena_slot
= 0; arena_slot
< MAX_ARENA_SLOT
; ++arena_slot
)
13502 uint32 arena_team_id
= GetArenaTeamId(arena_slot
);
13506 if(ArenaTeam
* at
= objmgr
.GetArenaTeamById(arena_team_id
))
13507 if(at
->HaveMember(GetGUID()))
13510 // arena team not exist or not member, cleanup fields
13511 for(int j
=0; j
< 6; ++j
)
13512 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arena_slot
* 6 + j
, 0);
13515 _LoadBoundInstances(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES
));
13517 if(!IsPositionValid())
13519 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());
13521 SetMapId(info
->mapId
);
13522 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
,0.0f
);
13526 m_movementInfo
.t_x
= 0.0f
;
13527 m_movementInfo
.t_y
= 0.0f
;
13528 m_movementInfo
.t_z
= 0.0f
;
13529 m_movementInfo
.t_o
= 0.0f
;
13532 // load the player's map here if it's not already loaded
13533 Map
*map
= GetMap();
13534 // since the player may not be bound to the map yet, make sure subsequent
13535 // getmap calls won't create new maps
13536 SetInstanceId(map
->GetInstanceId());
13538 SaveRecallPosition();
13540 if (transGUID
!= 0)
13542 m_movementInfo
.t_x
= fields
[20].GetFloat();
13543 m_movementInfo
.t_y
= fields
[21].GetFloat();
13544 m_movementInfo
.t_z
= fields
[22].GetFloat();
13545 m_movementInfo
.t_o
= fields
[23].GetFloat();
13547 if( !MaNGOS::IsValidMapCoord(
13548 GetPositionX()+m_movementInfo
.t_x
,GetPositionY()+m_movementInfo
.t_y
,
13549 GetPositionZ()+m_movementInfo
.t_z
,GetOrientation()+m_movementInfo
.t_o
) ||
13550 // transport size limited
13551 m_movementInfo
.t_x
> 50 || m_movementInfo
.t_y
> 50 || m_movementInfo
.t_z
> 50 )
13553 sLog
.outError("ERROR: Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
13554 guid
,GetPositionX()+m_movementInfo
.t_x
,GetPositionY()+m_movementInfo
.t_y
,
13555 GetPositionZ()+m_movementInfo
.t_z
,GetOrientation()+m_movementInfo
.t_o
);
13557 SetMapId(info
->mapId
);
13558 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
,0.0f
);
13560 m_movementInfo
.t_x
= 0.0f
;
13561 m_movementInfo
.t_y
= 0.0f
;
13562 m_movementInfo
.t_z
= 0.0f
;
13563 m_movementInfo
.t_o
= 0.0f
;
13569 if (transGUID
!= 0)
13571 for (MapManager::TransportSet::iterator iter
= MapManager::Instance().m_Transports
.begin(); iter
!= MapManager::Instance().m_Transports
.end(); ++iter
)
13573 if( (*iter
)->GetGUIDLow() == transGUID
)
13575 m_transport
= *iter
;
13576 m_transport
->AddPassenger(this);
13577 SetMapId(m_transport
->GetMapId());
13584 sLog
.outError("ERROR: Player (guidlow %d) have invalid transport guid (%u). Teleport to default race/class locations.",
13587 SetMapId(info
->mapId
);
13588 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
,0.0f
);
13590 m_movementInfo
.t_x
= 0.0f
;
13591 m_movementInfo
.t_y
= 0.0f
;
13592 m_movementInfo
.t_z
= 0.0f
;
13593 m_movementInfo
.t_o
= 0.0f
;
13599 time_t now
= time(NULL
);
13600 time_t logoutTime
= time_t(fields
[16].GetUInt64());
13602 // since last logout (in seconds)
13603 uint64 time_diff
= uint64(now
- logoutTime
);
13605 // set value, including drunk invisibility detection
13606 // calculate sobering. after 15 minutes logged out, the player will be sober again
13608 if(time_diff
> 15*MINUTE
)
13611 soberFactor
= 1-time_diff
/(15.0f
*MINUTE
);
13612 uint16 newDrunkenValue
= uint16(soberFactor
*(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFE));
13613 SetDrunkValue(newDrunkenValue
);
13615 m_rest_bonus
= fields
[15].GetFloat();
13616 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
13617 float bubble0
= 0.031;
13618 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
13619 float bubble1
= 0.125;
13621 if((int32
)fields
[16].GetUInt32() > 0)
13623 float bubble
= fields
[17].GetUInt32() > 0
13624 ? bubble1
*sWorld
.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY
)
13625 : bubble0
*sWorld
.getRate(RATE_REST_OFFLINE_IN_WILDERNESS
);
13627 SetRestBonus(GetRestBonus()+ time_diff
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
13630 m_cinematic
= fields
[12].GetUInt32();
13631 m_Played_time
[0]= fields
[13].GetUInt32();
13632 m_Played_time
[1]= fields
[14].GetUInt32();
13634 m_resetTalentsCost
= fields
[18].GetUInt32();
13635 m_resetTalentsTime
= time_t(fields
[19].GetUInt64());
13637 // reserve some flags
13638 uint32 old_safe_flags
= GetUInt32Value(PLAYER_FLAGS
) & ( PLAYER_FLAGS_HIDE_CLOAK
| PLAYER_FLAGS_HIDE_HELM
);
13640 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
) )
13641 SetUInt32Value(PLAYER_FLAGS
, 0 | old_safe_flags
);
13643 m_taxi
.LoadTaxiMask( fields
[11].GetString() ); // must be before InitTaxiNodesForLevel
13645 uint32 extraflags
= fields
[25].GetUInt32();
13647 m_stableSlots
= fields
[26].GetUInt32();
13648 if(m_stableSlots
> 2)
13650 sLog
.outError("Player can have not more 2 stable slots, but have in DB %u",uint32(m_stableSlots
));
13654 m_atLoginFlags
= fields
[27].GetUInt32();
13657 // Update Honor kills data
13658 m_lastHonorUpdateTime
= logoutTime
;
13659 UpdateHonorFields();
13661 m_deathExpireTime
= (time_t)fields
[30].GetUInt64();
13662 if(m_deathExpireTime
> now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
)
13663 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
-1;
13665 std::string taxi_nodes
= fields
[31].GetCppString();
13669 // clear channel spell data (if saved at channel spell casting)
13670 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT
, 0);
13671 SetUInt32Value(UNIT_CHANNEL_SPELL
,0);
13673 // clear charm/summon related fields
13676 SetCharmerGUID(NULL
);
13677 SetOwnerGUID(NULL
);
13678 SetCreatorGUID(NULL
);
13680 // reset some aura modifiers before aura apply
13682 SetUInt32Value(PLAYER_TRACK_CREATURES
, 0 );
13683 SetUInt32Value(PLAYER_TRACK_RESOURCES
, 0 );
13685 // reset skill modifiers and set correct unlearn flags
13686 for (uint32 i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
13688 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
13690 // set correct unlearn bit
13691 uint32 id
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
13694 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
13695 if(!pSkill
) continue;
13697 // enable unlearn button for primary professions only
13698 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
13699 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
13701 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
13704 // make sure the unit is considered out of combat for proper loading
13707 // make sure the unit is considered not in duel for proper loading
13708 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
13709 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
13711 // remember loaded power/health values to restore after stats initialization and modifier applying
13712 uint32 savedHealth
= GetHealth();
13713 uint32 savedPower
[MAX_POWERS
];
13714 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
13715 savedPower
[i
] = GetPower(Powers(i
));
13717 // reset stats before loading any modifiers
13718 InitStatsForLevel();
13719 InitTaxiNodesForLevel();
13721 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
13723 //mails are loaded only when needed ;-) - when player in game click on mailbox.
13726 _LoadAuras(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS
), time_diff
);
13728 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
13729 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
13730 m_deathState
= DEAD
;
13732 _LoadSpells(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS
));
13734 // after spell load
13735 InitTalentForLevel();
13736 learnSkillRewardedSpells();
13738 // after spell load, learn rewarded spell if need also
13739 _LoadQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS
));
13740 _LoadDailyQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS
));
13742 _LoadTutorials(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS
));
13744 // must be before inventory (some items required reputation check)
13745 _LoadReputation(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION
));
13747 _LoadInventory(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY
), time_diff
);
13749 // update items with duration and realtime
13750 UpdateItemDuration(time_diff
, true);
13752 _LoadActions(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS
));
13754 // unread mails and next delivery time, actual mails not loaded
13755 _LoadMailInit(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT
), holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE
));
13757 m_social
= sSocialMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST
), GetGUIDLow());
13759 if(!_LoadHomeBind(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND
)))
13762 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
13763 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
13764 if(uint32 curTitle
= GetUInt32Value(PLAYER_CHOSEN_TITLE
))
13766 if(!HasTitle(curTitle
))
13767 SetUInt32Value(PLAYER_CHOSEN_TITLE
,0);
13770 // Not finish taxi flight path
13771 if(!m_taxi
.LoadTaxiDestinationsFromString(taxi_nodes
))
13773 // problems with taxi path loading
13774 TaxiNodesEntry
const* nodeEntry
= NULL
;
13775 if(uint32 node_id
= m_taxi
.GetTaxiSource())
13776 nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
13778 if(!nodeEntry
) // don't know taxi start node, to homebind
13780 sLog
.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
13781 SetMapId(m_homebindMapId
);
13782 Relocate( m_homebindX
, m_homebindY
, m_homebindZ
,0.0f
);
13783 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
13785 else // have start node, to it
13787 sLog
.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
13788 SetMapId(nodeEntry
->map_id
);
13789 Relocate(nodeEntry
->x
, nodeEntry
->y
, nodeEntry
->z
,0.0f
);
13790 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
13792 m_taxi
.ClearTaxiDestinations();
13794 else if(uint32 node_id
= m_taxi
.GetTaxiSource())
13796 // save source node as recall coord to prevent recall and fall from sky
13797 TaxiNodesEntry
const* nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
13798 assert(nodeEntry
); // checked in m_taxi.LoadTaxiDestinationsFromString
13799 m_recallMap
= nodeEntry
->map_id
;
13800 m_recallX
= nodeEntry
->x
;
13801 m_recallY
= nodeEntry
->y
;
13802 m_recallZ
= nodeEntry
->z
;
13804 // flight will started later
13807 _LoadSpellCooldowns(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS
));
13809 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
13810 // Do now before stats re-calculation cleanup for ghost state unexpected auras
13812 RemoveAllAurasOnDeath();
13814 //apply all stat bonuses from items and auras
13815 SetCanModifyStats(true);
13818 // restore remembered power/health values (but not more max values)
13819 SetHealth(savedHealth
> GetMaxHealth() ? GetMaxHealth() : savedHealth
);
13820 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
13821 SetPower(Powers(i
),savedPower
[i
] > GetMaxPower(Powers(i
)) ? GetMaxPower(Powers(i
)) : savedPower
[i
]);
13823 sLog
.outDebug("The value of player %s after load item and aura is: ", m_name
.c_str());
13827 if(GetSession()->GetSecurity() > SEC_PLAYER
)
13829 switch(sWorld
.getConfig(CONFIG_GM_LOGIN_STATE
))
13832 case 0: break; // disable
13833 case 1: SetGameMaster(true); break; // enable
13834 case 2: // save state
13835 if(extraflags
& PLAYER_EXTRA_GM_ON
)
13836 SetGameMaster(true);
13840 switch(sWorld
.getConfig(CONFIG_GM_ACCEPT_TICKETS
))
13843 case 0: break; // disable
13844 case 1: SetAcceptTicket(true); break; // enable
13845 case 2: // save state
13846 if(extraflags
& PLAYER_EXTRA_GM_ACCEPT_TICKETS
)
13847 SetAcceptTicket(true);
13851 switch(sWorld
.getConfig(CONFIG_GM_CHAT
))
13854 case 0: break; // disable
13855 case 1: SetGMChat(true); break; // enable
13856 case 2: // save state
13857 if(extraflags
& PLAYER_EXTRA_GM_CHAT
)
13862 switch(sWorld
.getConfig(CONFIG_GM_WISPERING_TO
))
13865 case 0: break; // disable
13866 case 1: SetAcceptWhispers(true); break; // enable
13867 case 2: // save state
13868 if(extraflags
& PLAYER_EXTRA_ACCEPT_WHISPERS
)
13869 SetAcceptWhispers(true);
13874 _LoadDeclinedNames(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES
));
13879 bool Player::isAllowedToLoot(Creature
* creature
)
13881 if(Player
* recipient
= creature
->GetLootRecipient())
13883 if (recipient
== this)
13885 if( Group
* otherGroup
= recipient
->GetGroup())
13887 Group
* thisGroup
= GetGroup();
13890 return thisGroup
== otherGroup
;
13895 // prevent other players from looting if the recipient got disconnected
13896 return !creature
->hasLootRecipient();
13899 void Player::_LoadActions(QueryResult
*result
)
13901 m_actionButtons
.clear();
13903 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
13909 Field
*fields
= result
->Fetch();
13911 uint8 button
= fields
[0].GetUInt8();
13913 addActionButton(button
, fields
[1].GetUInt16(), fields
[2].GetUInt8(), fields
[3].GetUInt8());
13915 m_actionButtons
[button
].uState
= ACTIONBUTTON_UNCHANGED
;
13917 while( result
->NextRow() );
13923 void Player::_LoadAuras(QueryResult
*result
, uint32 timediff
)
13926 for (int i
= 0; i
< TOTAL_AURAS
; i
++)
13927 m_modAuras
[i
].clear();
13929 // all aura related fields
13930 for(int i
= UNIT_FIELD_AURA
; i
<= UNIT_FIELD_AURASTATE
; ++i
)
13931 SetUInt32Value(i
, 0);
13933 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
13939 Field
*fields
= result
->Fetch();
13940 uint64 caster_guid
= fields
[0].GetUInt64();
13941 uint32 spellid
= fields
[1].GetUInt32();
13942 uint32 effindex
= fields
[2].GetUInt32();
13943 uint32 stackcount
= fields
[3].GetUInt32();
13944 int32 damage
= (int32
)fields
[4].GetUInt32();
13945 int32 maxduration
= (int32
)fields
[5].GetUInt32();
13946 int32 remaintime
= (int32
)fields
[6].GetUInt32();
13947 int32 remaincharges
= (int32
)fields
[7].GetUInt32();
13949 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellid
);
13952 sLog
.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid
,effindex
);
13958 sLog
.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid
,effindex
);
13962 // negative effects should continue counting down after logout
13963 if (remaintime
!= -1 && !IsPositiveEffect(spellid
, effindex
))
13965 if(remaintime
<= int32(timediff
))
13968 remaintime
-= timediff
;
13971 // prevent wrong values of remaincharges
13972 if(spellproto
->procCharges
)
13974 if(remaincharges
<= 0 || remaincharges
> spellproto
->procCharges
)
13975 remaincharges
= spellproto
->procCharges
;
13978 remaincharges
= -1;
13980 //do not load single target auras (unless they were cast by the player)
13981 if (caster_guid
!= GetGUID() && IsSingleTargetSpell(spellproto
))
13984 for(uint32 i
=0; i
<stackcount
; i
++)
13986 Aura
* aura
= CreateAura(spellproto
, effindex
, NULL
, this, NULL
);
13988 damage
= aura
->GetModifier()->m_amount
;
13989 aura
->SetLoadedState(caster_guid
,damage
,maxduration
,remaintime
,remaincharges
);
13991 sLog
.outString("Added aura spellid %u, effect %u", spellproto
->Id
, effindex
);
13994 while( result
->NextRow() );
13999 if(m_class
== CLASS_WARRIOR
)
14000 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
14003 void Player::LoadCorpse()
14007 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14011 if(Corpse
*corpse
= GetCorpse())
14013 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, corpse
&& !sMapStore
.LookupEntry(corpse
->GetMapId())->Instanceable() );
14017 //Prevent Dead Player login without corpse
14018 ResurrectPlayer(0.5f
);
14023 void Player::_LoadInventory(QueryResult
*result
, uint32 timediff
)
14025 //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());
14026 std::map
<uint64
, Bag
*> bagMap
; // fast guid lookup for bags
14027 //NOTE: the "order by `bag`" is important because it makes sure
14028 //the bagMap is filled before items in the bags are loaded
14029 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14030 //expected to be equipped before offhand items (TODO: fixme)
14032 uint32 zone
= GetZoneId();
14036 std::list
<Item
*> problematicItems
;
14038 // prevent items from being added to the queue when stored
14039 m_itemUpdateQueueBlocked
= true;
14042 Field
*fields
= result
->Fetch();
14043 uint32 bag_guid
= fields
[1].GetUInt32();
14044 uint8 slot
= fields
[2].GetUInt8();
14045 uint32 item_guid
= fields
[3].GetUInt32();
14046 uint32 item_id
= fields
[4].GetUInt32();
14048 ItemPrototype
const * proto
= objmgr
.GetItemPrototype(item_id
);
14052 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14053 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid
);
14054 sLog
.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id
);
14058 Item
*item
= NewItemOrBag(proto
);
14060 if(!item
->LoadFromDB(item_guid
, GetGUID(), result
))
14062 sLog
.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id
);
14063 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14064 item
->FSetState(ITEM_REMOVED
);
14065 item
->SaveToDB(); // it also deletes item object !
14069 // not allow have in alive state item limited to another map/zone
14070 if(isAlive() && item
->IsLimitedToAnotherMapOrZone(GetMapId(),zone
) )
14072 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14073 item
->FSetState(ITEM_REMOVED
);
14074 item
->SaveToDB(); // it also deletes item object !
14078 // "Conjured items disappear if you are logged out for more than 15 minutes"
14079 if ((timediff
> 15*60) && (item
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_CONJURED
)))
14081 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14082 item
->FSetState(ITEM_REMOVED
);
14083 item
->SaveToDB(); // it also deletes item object !
14087 bool success
= true;
14091 // the item is not in a bag
14092 item
->SetContainer( NULL
);
14093 item
->SetSlot(slot
);
14095 if( IsInventoryPos( INVENTORY_SLOT_BAG_0
, slot
) )
14097 ItemPosCountVec dest
;
14098 if( CanStoreItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false ) == EQUIP_ERR_OK
)
14099 item
= StoreItem(dest
, item
, true);
14103 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0
, slot
) )
14106 if( CanEquipItem( slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
14107 QuickEquipItem(dest
, item
);
14111 else if( IsBankPos( INVENTORY_SLOT_BAG_0
, slot
) )
14113 ItemPosCountVec dest
;
14114 if( CanBankItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
14115 item
= BankItem(dest
, item
, true);
14122 // store bags that may contain items in them
14123 if(item
->IsBag() && IsBagPos(item
->GetPos()))
14124 bagMap
[item_guid
] = (Bag
*)item
;
14129 item
->SetSlot(NULL_SLOT
);
14130 // the item is in a bag, find the bag
14131 std::map
<uint64
, Bag
*>::iterator itr
= bagMap
.find(bag_guid
);
14132 if(itr
!= bagMap
.end())
14133 itr
->second
->StoreItem(slot
, item
, true );
14138 // item's state may have changed after stored
14140 item
->SetState(ITEM_UNCHANGED
, this);
14143 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
);
14144 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14145 problematicItems
.push_back(item
);
14147 } while (result
->NextRow());
14150 m_itemUpdateQueueBlocked
= false;
14152 // send by mail problematic items
14153 while(!problematicItems
.empty())
14156 MailItemsInfo mi
; // item list preparing
14158 for(int i
= 0; !problematicItems
.empty() && i
< MAX_MAIL_ITEMS
; ++i
)
14160 Item
* item
= problematicItems
.front();
14161 problematicItems
.pop_front();
14163 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
14166 std::string subject
= GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM
);
14168 WorldSession::SendMailTo(this, MAIL_NORMAL
, MAIL_STATIONERY_GM
, GetGUIDLow(), GetGUIDLow(), subject
, 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
);
14172 _ApplyAllItemMods();
14175 // load mailed item which should receive current player
14176 void Player::_LoadMailedItems(Mail
*mail
)
14178 QueryResult
* result
= CharacterDatabase
.PQuery("SELECT item_guid, item_template FROM mail_items WHERE mail_id='%u'", mail
->messageID
);
14184 Field
*fields
= result
->Fetch();
14185 uint32 item_guid_low
= fields
[0].GetUInt32();
14186 uint32 item_template
= fields
[1].GetUInt32();
14188 mail
->AddItem(item_guid_low
, item_template
);
14190 ItemPrototype
const *proto
= objmgr
.GetItemPrototype(item_template
);
14194 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
);
14195 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
14196 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low
);
14200 Item
*item
= NewItemOrBag(proto
);
14202 if(!item
->LoadFromDB(item_guid_low
, 0))
14204 sLog
.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail
->messageID
, item_guid_low
);
14205 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
14206 item
->FSetState(ITEM_REMOVED
);
14207 item
->SaveToDB(); // it also deletes item object !
14212 } while (result
->NextRow());
14217 void Player::_LoadMailInit(QueryResult
*resultUnread
, QueryResult
*resultDelivery
)
14219 //set a count of unread mails
14220 //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);
14223 Field
*fieldMail
= resultUnread
->Fetch();
14224 unReadMails
= fieldMail
[0].GetUInt8();
14225 delete resultUnread
;
14228 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14229 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14230 if (resultDelivery
)
14232 Field
*fieldMail
= resultDelivery
->Fetch();
14233 m_nextMailDelivereTime
= (time_t)fieldMail
[0].GetUInt64();
14234 delete resultDelivery
;
14238 void Player::_LoadMail()
14241 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14242 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());
14247 Field
*fields
= result
->Fetch();
14248 Mail
*m
= new Mail
;
14249 m
->messageID
= fields
[0].GetUInt32();
14250 m
->messageType
= fields
[1].GetUInt8();
14251 m
->sender
= fields
[2].GetUInt32();
14252 m
->receiver
= fields
[3].GetUInt32();
14253 m
->subject
= fields
[4].GetCppString();
14254 m
->itemTextId
= fields
[5].GetUInt32();
14255 bool has_items
= fields
[6].GetBool();
14256 m
->expire_time
= (time_t)fields
[7].GetUInt64();
14257 m
->deliver_time
= (time_t)fields
[8].GetUInt64();
14258 m
->money
= fields
[9].GetUInt32();
14259 m
->COD
= fields
[10].GetUInt32();
14260 m
->checked
= fields
[11].GetUInt32();
14261 m
->stationery
= fields
[12].GetUInt8();
14262 m
->mailTemplateId
= fields
[13].GetInt16();
14264 if(m
->mailTemplateId
&& !sMailTemplateStore
.LookupEntry(m
->mailTemplateId
))
14266 sLog
.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m
->messageID
, m
->mailTemplateId
);
14267 m
->mailTemplateId
= 0;
14270 m
->state
= MAIL_STATE_UNCHANGED
;
14273 _LoadMailedItems(m
);
14275 m_mail
.push_back(m
);
14276 } while( result
->NextRow() );
14279 m_mailsLoaded
= true;
14282 void Player::LoadPet()
14284 //fixme: the pet should still be loaded if the player is not in world
14285 // just not added to the map
14288 Pet
*pet
= new Pet
;
14289 if(!pet
->LoadPetFromDB(this,0,0,true))
14294 void Player::_LoadQuestStatus(QueryResult
*result
)
14296 mQuestStatus
.clear();
14300 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14301 //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());
14307 Field
*fields
= result
->Fetch();
14309 uint32 quest_id
= fields
[0].GetUInt32();
14310 // used to be new, no delete?
14311 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
14315 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
14317 uint32 qstatus
= fields
[1].GetUInt32();
14318 if(qstatus
< MAX_QUEST_STATUS
)
14319 questStatusData
.m_status
= QuestStatus(qstatus
);
14322 questStatusData
.m_status
= QUEST_STATUS_NONE
;
14323 sLog
.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id
,qstatus
);
14326 questStatusData
.m_rewarded
= ( fields
[2].GetUInt8() > 0 );
14327 questStatusData
.m_explored
= ( fields
[3].GetUInt8() > 0 );
14329 time_t quest_time
= time_t(fields
[4].GetUInt64());
14331 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && !GetQuestRewardStatus(quest_id
) && questStatusData
.m_status
!= QUEST_STATUS_NONE
)
14333 AddTimedQuest( quest_id
);
14335 if (quest_time
<= sWorld
.GetGameTime())
14336 questStatusData
.m_timer
= 1;
14338 questStatusData
.m_timer
= (quest_time
- sWorld
.GetGameTime()) * 1000;
14343 questStatusData
.m_creatureOrGOcount
[0] = fields
[5].GetUInt32();
14344 questStatusData
.m_creatureOrGOcount
[1] = fields
[6].GetUInt32();
14345 questStatusData
.m_creatureOrGOcount
[2] = fields
[7].GetUInt32();
14346 questStatusData
.m_creatureOrGOcount
[3] = fields
[8].GetUInt32();
14347 questStatusData
.m_itemcount
[0] = fields
[9].GetUInt32();
14348 questStatusData
.m_itemcount
[1] = fields
[10].GetUInt32();
14349 questStatusData
.m_itemcount
[2] = fields
[11].GetUInt32();
14350 questStatusData
.m_itemcount
[3] = fields
[12].GetUInt32();
14352 questStatusData
.uState
= QUEST_UNCHANGED
;
14354 // add to quest log
14355 if( slot
< MAX_QUEST_LOG_SIZE
&&
14356 ( questStatusData
.m_status
==QUEST_STATUS_INCOMPLETE
||
14357 questStatusData
.m_status
==QUEST_STATUS_COMPLETE
&&
14358 (!questStatusData
.m_rewarded
|| pQuest
->IsDaily()) ) )
14360 SetQuestSlot(slot
,quest_id
,quest_time
);
14362 if(questStatusData
.m_status
== QUEST_STATUS_COMPLETE
)
14363 SetQuestSlotState(slot
,QUEST_STATE_COMPLETE
);
14365 for(uint8 idx
= 0; idx
< QUEST_OBJECTIVES_COUNT
; ++idx
)
14366 if(questStatusData
.m_creatureOrGOcount
[idx
])
14367 SetQuestSlotCounter(slot
,idx
,questStatusData
.m_creatureOrGOcount
[idx
]);
14372 if(questStatusData
.m_rewarded
)
14374 // learn rewarded spell if unknown
14375 learnQuestRewardedSpells(pQuest
);
14377 // set rewarded title if any
14378 if(pQuest
->GetCharTitleId())
14380 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
14381 SetTitle(titleEntry
);
14385 sLog
.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData
.m_status
, quest_id
, GetGUIDLow());
14388 while( result
->NextRow() );
14393 // clear quest log tail
14394 for ( uint16 i
= slot
; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14398 void Player::_LoadDailyQuestStatus(QueryResult
*result
)
14400 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
14401 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
14403 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14407 uint32 quest_daily_idx
= 0;
14411 if(quest_daily_idx
>= PLAYER_MAX_DAILY_QUESTS
) // max amount with exist data in query
14413 sLog
.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
14417 Field
*fields
= result
->Fetch();
14419 uint32 quest_id
= fields
[0].GetUInt32();
14421 // save _any_ from daily quest times (it must be after last reset anyway)
14422 m_lastDailyQuestTime
= (time_t)fields
[1].GetUInt64();
14424 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
14428 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
14431 sLog
.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id
, GetGUIDLow());
14433 while( result
->NextRow() );
14438 m_DailyQuestChanged
= false;
14441 void Player::_LoadReputation(QueryResult
*result
)
14443 m_factions
.clear();
14445 // Set initial reputations (so everything is nifty before DB data load)
14446 SetInitialFactions();
14448 //QueryResult *result = CharacterDatabase.PQuery("SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'",GetGUIDLow());
14454 Field
*fields
= result
->Fetch();
14456 FactionEntry
const *factionEntry
= sFactionStore
.LookupEntry(fields
[0].GetUInt32());
14457 if( factionEntry
&& (factionEntry
->reputationListID
>= 0))
14459 FactionState
* faction
= &m_factions
[factionEntry
->reputationListID
];
14461 // update standing to current
14462 faction
->Standing
= int32(fields
[1].GetUInt32());
14464 uint32 dbFactionFlags
= fields
[2].GetUInt32();
14466 if( dbFactionFlags
& FACTION_FLAG_VISIBLE
)
14467 SetFactionVisible(faction
); // have internal checks for forced invisibility
14469 if( dbFactionFlags
& FACTION_FLAG_INACTIVE
)
14470 SetFactionInactive(faction
,true); // have internal checks for visibility requirement
14472 if( dbFactionFlags
& FACTION_FLAG_AT_WAR
) // DB at war
14473 SetFactionAtWar(faction
,true); // have internal checks for FACTION_FLAG_PEACE_FORCED
14474 else // DB not at war
14476 // allow remove if visible (and then not FACTION_FLAG_INVISIBLE_FORCED or FACTION_FLAG_HIDDEN)
14477 if( faction
->Flags
& FACTION_FLAG_VISIBLE
)
14478 SetFactionAtWar(faction
,false); // have internal checks for FACTION_FLAG_PEACE_FORCED
14481 // set atWar for hostile
14482 if(GetReputationRank(factionEntry
) <= REP_HOSTILE
)
14483 SetFactionAtWar(faction
,true);
14485 // reset changed flag if values similar to saved in DB
14486 if(faction
->Flags
==dbFactionFlags
)
14487 faction
->Changed
= false;
14490 while( result
->NextRow() );
14496 void Player::_LoadSpells(QueryResult
*result
)
14498 for (PlayerSpellMap::iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
14499 delete itr
->second
;
14502 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,slot,active FROM character_spell WHERE guid = '%u'",GetGUIDLow());
14508 Field
*fields
= result
->Fetch();
14510 addSpell(fields
[0].GetUInt16(), fields
[2].GetBool(), false, true, fields
[1].GetUInt16(), fields
[3].GetBool());
14512 while( result
->NextRow() );
14518 void Player::_LoadTutorials(QueryResult
*result
)
14520 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
14526 Field
*fields
= result
->Fetch();
14528 for (int iI
=0; iI
<8; iI
++)
14529 m_Tutorials
[iI
] = fields
[iI
].GetUInt32();
14531 while( result
->NextRow() );
14536 m_TutorialsChanged
= false;
14539 void Player::_LoadGroup(QueryResult
*result
)
14541 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
14544 uint64 leaderGuid
= MAKE_NEW_GUID((*result
)[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
14546 Group
* group
= objmgr
.GetGroupByLeader(leaderGuid
);
14549 uint8 subgroup
= group
->GetMemberGroup(GetGUID());
14550 SetGroup(group
, subgroup
);
14551 if(getLevel() >= LEVELREQUIREMENT_HEROIC
)
14553 // the group leader may change the instance difficulty while the player is offline
14554 SetDifficulty(group
->GetDifficulty());
14560 void Player::_LoadBoundInstances(QueryResult
*result
)
14562 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
14563 m_boundInstances
[i
].clear();
14565 Group
*group
= GetGroup();
14567 //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));
14572 Field
*fields
= result
->Fetch();
14573 bool perm
= fields
[1].GetBool();
14574 uint32 mapId
= fields
[2].GetUInt32();
14575 uint32 instanceId
= fields
[0].GetUInt32();
14576 uint8 difficulty
= fields
[3].GetUInt8();
14577 time_t resetTime
= (time_t)fields
[4].GetUInt64();
14578 // the resettime for normal instances is only saved when the InstanceSave is unloaded
14579 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
14580 // and in that case it is not used
14584 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
);
14585 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
14589 // since non permanent binds are always solo bind, they can always be reset
14590 InstanceSave
*save
= sInstanceSaveManager
.AddInstanceSave(mapId
, instanceId
, difficulty
, resetTime
, !perm
, true);
14591 if(save
) BindToInstance(save
, perm
, true);
14592 } while(result
->NextRow());
14597 InstancePlayerBind
* Player::GetBoundInstance(uint32 mapid
, uint8 difficulty
)
14599 // some instances only have one difficulty
14600 const MapEntry
* entry
= sMapStore
.LookupEntry(mapid
);
14601 if(!entry
|| !entry
->SupportsHeroicMode()) difficulty
= DIFFICULTY_NORMAL
;
14603 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
14604 if(itr
!= m_boundInstances
[difficulty
].end())
14605 return &itr
->second
;
14610 void Player::UnbindInstance(uint32 mapid
, uint8 difficulty
, bool unload
)
14612 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
14613 UnbindInstance(itr
, difficulty
, unload
);
14616 void Player::UnbindInstance(BoundInstancesMap::iterator
&itr
, uint8 difficulty
, bool unload
)
14618 if(itr
!= m_boundInstances
[difficulty
].end())
14620 if(!unload
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr
->second
.save
->GetInstanceId());
14621 itr
->second
.save
->RemovePlayer(this); // save can become invalid
14622 m_boundInstances
[difficulty
].erase(itr
++);
14626 InstancePlayerBind
* Player::BindToInstance(InstanceSave
*save
, bool permanent
, bool load
)
14630 InstancePlayerBind
& bind
= m_boundInstances
[save
->GetDifficulty()][save
->GetMapId()];
14633 // update the save when the group kills a boss
14634 if(permanent
!= bind
.perm
|| save
!= bind
.save
)
14635 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());
14638 if(!load
) CharacterDatabase
.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save
->GetInstanceId(), permanent
);
14640 if(bind
.save
!= save
)
14642 if(bind
.save
) bind
.save
->RemovePlayer(this);
14643 save
->AddPlayer(this);
14646 if(permanent
) save
->SetCanReset(false);
14649 bind
.perm
= permanent
;
14650 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());
14657 void Player::SendRaidInfo()
14659 WorldPacket
data(SMSG_RAID_INSTANCE_INFO
, 4);
14661 uint32 counter
= 0, i
;
14662 for(i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
14663 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
14664 if(itr
->second
.perm
) counter
++;
14667 for(i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
14669 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
14671 if(itr
->second
.perm
)
14673 InstanceSave
*save
= itr
->second
.save
;
14674 data
<< (save
->GetMapId());
14675 data
<< (uint32
)(save
->GetResetTime() - time(NULL
));
14676 data
<< save
->GetInstanceId();
14677 data
<< uint32(counter
);
14682 GetSession()->SendPacket(&data
);
14686 - called on every successful teleportation to a map
14688 void Player::SendSavedInstances()
14690 bool hasBeenSaved
= false;
14693 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
14695 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
14697 if(itr
->second
.perm
) // only permanent binds are sent
14699 hasBeenSaved
= true;
14705 //Send opcode 811. true or false means, whether you have current raid/heroic instances
14706 data
.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP
);
14707 data
<< uint32(hasBeenSaved
);
14708 GetSession()->SendPacket(&data
);
14713 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
14715 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
14717 if(itr
->second
.perm
)
14719 data
.Initialize(SMSG_UPDATE_LAST_INSTANCE
);
14720 data
<< uint32(itr
->second
.save
->GetMapId());
14721 GetSession()->SendPacket(&data
);
14727 /// convert the player's binds to the group
14728 void Player::ConvertInstancesToGroup(Player
*player
, Group
*group
, uint64 player_guid
)
14730 bool has_binds
= false;
14731 bool has_solo
= false;
14733 if(player
) { player_guid
= player
->GetGUID(); if(!group
) group
= player
->GetGroup(); }
14734 assert(player_guid
);
14736 // copy all binds to the group, when changing leader it's assumed the character
14737 // will not have any solo binds
14741 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
14743 for (BoundInstancesMap::iterator itr
= player
->m_boundInstances
[i
].begin(); itr
!= player
->m_boundInstances
[i
].end();)
14746 if(group
) group
->BindToInstance(itr
->second
.save
, itr
->second
.perm
, true);
14747 // permanent binds are not removed
14748 if(!itr
->second
.perm
)
14750 player
->UnbindInstance(itr
, i
, true); // increments itr
14759 // if the player's not online we don't know what binds it has
14760 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
));
14761 // the following should not get executed when changing leaders
14762 if(!player
|| has_solo
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid
));
14765 bool Player::_LoadHomeBind(QueryResult
*result
)
14768 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
14771 Field
*fields
= result
->Fetch();
14772 m_homebindMapId
= fields
[0].GetUInt32();
14773 m_homebindZoneId
= fields
[1].GetUInt16();
14774 m_homebindX
= fields
[2].GetFloat();
14775 m_homebindY
= fields
[3].GetFloat();
14776 m_homebindZ
= fields
[4].GetFloat();
14779 // accept saved data only for valid position (and non instanceable)
14780 if( MapManager::IsValidMapCoord(m_homebindMapId
,m_homebindX
,m_homebindY
,m_homebindZ
) &&
14781 !sMapStore
.LookupEntry(m_homebindMapId
)->Instanceable() )
14786 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
14791 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(), getClass());
14792 if(!info
) return false;
14794 m_homebindMapId
= info
->mapId
;
14795 m_homebindZoneId
= info
->zoneId
;
14796 m_homebindX
= info
->positionX
;
14797 m_homebindY
= info
->positionY
;
14798 m_homebindZ
= info
->positionZ
;
14800 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
);
14803 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",
14804 m_homebindMapId
, m_homebindZoneId
, m_homebindX
, m_homebindY
, m_homebindZ
);
14809 /*********************************************************/
14810 /*** SAVE SYSTEM ***/
14811 /*********************************************************/
14813 void Player::SaveToDB()
14815 // delay auto save at any saves (manual, in code, or autosave)
14816 m_nextSave
= sWorld
.getConfig(CONFIG_INTERVAL_SAVE
);
14818 // first save/honor gain after midnight will also update the player's honor fields
14819 UpdateHonorFields();
14821 // Must saved before enter into BattleGround
14822 if(InBattleGround())
14825 int is_save_resting
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
) ? 1 : 0;
14826 //save, far from tavern/city
14827 //save, but in tavern/city
14828 sLog
.outDebug("The value of player %s at save: ", m_name
.c_str());
14831 // save state (after auras removing), if aura remove some flags then it must set it back by self)
14832 uint32 tmp_bytes
= GetUInt32Value(UNIT_FIELD_BYTES_1
);
14833 uint32 tmp_bytes2
= GetUInt32Value(UNIT_FIELD_BYTES_2
);
14834 uint32 tmp_flags
= GetUInt32Value(UNIT_FIELD_FLAGS
);
14835 uint32 tmp_pflags
= GetUInt32Value(PLAYER_FLAGS
);
14836 uint32 tmp_displayid
= GetDisplayId();
14838 // Set player sit state to standing on save, also stealth and shifted form
14839 SetByteValue(UNIT_FIELD_BYTES_1
, 0, 0); // stand state
14840 SetByteValue(UNIT_FIELD_BYTES_2
, 3, 0); // shapeshift
14841 SetByteValue(UNIT_FIELD_BYTES_1
, 3, 0); // stand flags?
14842 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_DISABLE_ROTATE
);
14843 SetDisplayId(GetNativeDisplayId());
14845 bool inworld
= IsInWorld();
14847 CharacterDatabase
.BeginTransaction();
14849 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
14851 std::string sql_name
= m_name
;
14852 CharacterDatabase
.escape_string(sql_name
);
14854 std::ostringstream ss
;
14855 ss
<< "INSERT INTO characters (guid,account,name,race,class,"
14856 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
14857 "taximask, online, cinematic, "
14858 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
14859 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
14860 "death_expire_time, taxi_path) VALUES ("
14861 << GetGUIDLow() << ", "
14862 << GetSession()->GetAccountId() << ", '"
14863 << sql_name
<< "', "
14865 << m_class
<< ", ";
14867 bool save_to_dest
= false;
14868 if(IsBeingTeleported())
14870 // don't save to battlegrounds or arenas
14871 const MapEntry
*entry
= sMapStore
.LookupEntry(GetTeleportDest().mapid
);
14872 if(entry
&& entry
->map_type
!= MAP_BATTLEGROUND
&& entry
->map_type
!= MAP_ARENA
)
14873 save_to_dest
= true;
14878 ss
<< GetMapId() << ", "
14879 << (uint32
)GetDifficulty() << ", "
14880 << finiteAlways(GetPositionX()) << ", "
14881 << finiteAlways(GetPositionY()) << ", "
14882 << finiteAlways(GetPositionZ()) << ", "
14883 << finiteAlways(GetOrientation()) << ", '";
14887 ss
<< GetTeleportDest().mapid
<< ", "
14888 << (uint32
)GetDifficulty() << ", "
14889 << finiteAlways(GetTeleportDest().x
) << ", "
14890 << finiteAlways(GetTeleportDest().y
) << ", "
14891 << finiteAlways(GetTeleportDest().z
) << ", "
14892 << finiteAlways(GetTeleportDest().o
) << ", '";
14896 for( i
= 0; i
< m_valuesCount
; i
++ )
14898 ss
<< GetUInt32Value(i
) << " ";
14903 for( i
= 0; i
< 8; i
++ )
14904 ss
<< m_taxi
.GetTaximask(i
) << " ";
14907 ss
<< (inworld
? 1 : 0);
14913 ss
<< m_Played_time
[0];
14915 ss
<< m_Played_time
[1];
14918 ss
<< finiteAlways(m_rest_bonus
);
14920 ss
<< (uint64
)time(NULL
);
14922 ss
<< is_save_resting
;
14924 ss
<< m_resetTalentsCost
;
14926 ss
<< (uint64
)m_resetTalentsTime
;
14929 ss
<< finiteAlways(m_movementInfo
.t_x
);
14931 ss
<< finiteAlways(m_movementInfo
.t_y
);
14933 ss
<< finiteAlways(m_movementInfo
.t_z
);
14935 ss
<< finiteAlways(m_movementInfo
.t_o
);
14938 ss
<< m_transport
->GetGUIDLow();
14943 ss
<< m_ExtraFlags
;
14946 ss
<< uint32(m_stableSlots
); // to prevent save uint8 as char
14949 ss
<< uint32(m_atLoginFlags
);
14955 ss
<< (uint64
)m_deathExpireTime
;
14958 ss
<< m_taxi
.SaveTaxiDestinationsToString();
14961 CharacterDatabase
.Execute( ss
.str().c_str() );
14963 if(m_mailsUpdated
) //save mails only when needed
14967 _SaveQuestStatus();
14968 _SaveDailyQuestStatus();
14971 _SaveSpellCooldowns();
14976 CharacterDatabase
.CommitTransaction();
14978 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
14979 SetDisplayId(tmp_displayid
);
14980 SetUInt32Value(UNIT_FIELD_BYTES_1
, tmp_bytes
);
14981 SetUInt32Value(UNIT_FIELD_BYTES_2
, tmp_bytes2
);
14982 SetUInt32Value(UNIT_FIELD_FLAGS
, tmp_flags
);
14983 SetUInt32Value(PLAYER_FLAGS
, tmp_pflags
);
14985 // save pet (hunter pet level and experience and all type pets health/mana).
14986 if(Pet
* pet
= GetPet())
14987 pet
->SavePetToDB(PET_SAVE_AS_CURRENT
);
14990 // fast save function for item/money cheating preventing - save only inventory and money state
14991 void Player::SaveInventoryAndGoldToDB()
14994 //money is in data field
14995 SaveDataFieldToDB();
14998 void Player::_SaveActions()
15000 for(ActionButtonList::iterator itr
= m_actionButtons
.begin(); itr
!= m_actionButtons
.end(); )
15002 switch (itr
->second
.uState
)
15004 case ACTIONBUTTON_NEW
:
15005 CharacterDatabase
.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15006 GetGUIDLow(), (uint32
)itr
->first
, (uint32
)itr
->second
.action
, (uint32
)itr
->second
.type
, (uint32
)itr
->second
.misc
);
15007 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
15010 case ACTIONBUTTON_CHANGED
:
15011 CharacterDatabase
.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15012 (uint32
)itr
->second
.action
, (uint32
)itr
->second
.type
, (uint32
)itr
->second
.misc
, GetGUIDLow(), (uint32
)itr
->first
);
15013 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
15016 case ACTIONBUTTON_DELETED
:
15017 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32
)itr
->first
);
15018 m_actionButtons
.erase(itr
++);
15027 void Player::_SaveAuras()
15029 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15031 AuraMap
const& auras
= GetAuras();
15036 spellEffectPair lastEffectPair
= auras
.begin()->first
;
15037 uint32 stackCounter
= 1;
15039 for(AuraMap::const_iterator itr
= auras
.begin(); ; ++itr
)
15041 if(itr
== auras
.end() || lastEffectPair
!= itr
->first
)
15043 AuraMap::const_iterator itr2
= itr
;
15044 // save previous spellEffectPair to db
15046 SpellEntry
const *spellInfo
= itr2
->second
->GetSpellProto();
15048 //skip all auras from spells that are passive or need a shapeshift
15049 if (!(itr2
->second
->IsPassive() || itr2
->second
->IsRemovedOnShapeLost()))
15051 //do not save single target auras (unless they were cast by the player)
15052 if (!(itr2
->second
->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo
)))
15055 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15056 for (i
= 0; i
< 3; i
++)
15057 if (spellInfo
->EffectApplyAuraName
[i
] == SPELL_AURA_MOD_SHAPESHIFT
||
15058 spellInfo
->EffectApplyAuraName
[i
] == SPELL_AURA_MOD_STEALTH
)
15063 CharacterDatabase
.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15064 "VALUES ('%u', '" I64FMTD
"' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15065 GetGUIDLow(), itr2
->second
->GetCasterGUID(), (uint32
)itr2
->second
->GetId(), (uint32
)itr2
->second
->GetEffIndex(), stackCounter
, itr2
->second
->GetModifier()->m_amount
,int(itr2
->second
->GetAuraMaxDuration()),int(itr2
->second
->GetAuraDuration()),int(itr2
->second
->m_procCharges
));
15070 if(itr
== auras
.end())
15074 if (lastEffectPair
== itr
->first
)
15078 lastEffectPair
= itr
->first
;
15084 void Player::_SaveInventory()
15086 // force items in buyback slots to new state
15087 // and remove those that aren't already
15088 for (uint8 i
= BUYBACK_SLOT_START
; i
< BUYBACK_SLOT_END
; i
++)
15090 Item
*item
= m_items
[i
];
15091 if (!item
|| item
->GetState() == ITEM_NEW
) continue;
15092 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
15093 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item
->GetGUIDLow());
15094 m_items
[i
]->FSetState(ITEM_NEW
);
15097 // update enchantment durations
15098 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
15100 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
15104 if (m_itemUpdateQueue
.empty()) return;
15106 // do not save if the update queue is corrupt
15107 bool error
= false;
15108 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); i
++)
15110 Item
*item
= m_itemUpdateQueue
[i
];
15111 if(!item
|| item
->GetState() == ITEM_REMOVED
) continue;
15112 Item
*test
= GetItemByPos( item
->GetBagSlot(), item
->GetSlot());
15116 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());
15119 else if (test
!= item
)
15121 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());
15128 sLog
.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15129 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED
);
15133 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); i
++)
15135 Item
*item
= m_itemUpdateQueue
[i
];
15136 if(!item
) continue;
15138 Bag
*container
= item
->GetContainer();
15139 uint32 bag_guid
= container
? container
->GetGUIDLow() : 0;
15141 switch(item
->GetState())
15144 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());
15147 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());
15150 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
15152 case ITEM_UNCHANGED
:
15156 item
->SaveToDB(); // item have unchanged inventory record and can be save standalone
15158 m_itemUpdateQueue
.clear();
15161 void Player::_SaveMail()
15163 if (!m_mailsLoaded
)
15166 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
15169 if (m
->state
== MAIL_STATE_CHANGED
)
15171 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'",
15172 m
->itemTextId
, m
->HasItems() ? 1 : 0, (uint64
)m
->expire_time
, (uint64
)m
->deliver_time
, m
->money
, m
->COD
, m
->checked
, m
->messageID
);
15173 if(m
->removedItems
.size())
15175 for(std::vector
<uint32
>::iterator itr2
= m
->removedItems
.begin(); itr2
!= m
->removedItems
.end(); ++itr2
)
15176 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2
);
15177 m
->removedItems
.clear();
15179 m
->state
= MAIL_STATE_UNCHANGED
;
15181 else if (m
->state
== MAIL_STATE_DELETED
)
15184 for(std::vector
<MailItemInfo
>::iterator itr2
= m
->items
.begin(); itr2
!= m
->items
.end(); ++itr2
)
15185 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2
->item_guid
);
15187 CharacterDatabase
.PExecute("DELETE FROM item_text WHERE id = '%u'", m
->itemTextId
);
15188 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", m
->messageID
);
15189 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m
->messageID
);
15193 //deallocate deleted mails...
15194 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); )
15196 if ((*itr
)->state
== MAIL_STATE_DELETED
)
15201 itr
= m_mail
.begin();
15207 m_mailsUpdated
= false;
15210 void Player::_SaveQuestStatus()
15212 // we don't need transactions here.
15213 for( QuestStatusMap::iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
15215 switch (i
->second
.uState
)
15218 CharacterDatabase
.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15219 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD
"', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15220 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]);
15222 case QUEST_CHANGED
:
15223 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' ",
15224 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
);
15226 case QUEST_UNCHANGED
:
15229 i
->second
.uState
= QUEST_UNCHANGED
;
15233 void Player::_SaveDailyQuestStatus()
15235 if(!m_DailyQuestChanged
)
15238 m_DailyQuestChanged
= false;
15240 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15242 // we don't need transactions here.
15243 CharacterDatabase
.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15244 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
15245 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
15246 CharacterDatabase
.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD
"')",
15247 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
),uint64(m_lastDailyQuestTime
));
15250 void Player::_SaveReputation()
15252 for(FactionStateList::iterator itr
= m_factions
.begin(); itr
!= m_factions
.end(); ++itr
)
15254 if (itr
->second
.Changed
)
15256 CharacterDatabase
.PExecute("DELETE FROM character_reputation WHERE guid = '%u' AND faction='%u'", GetGUIDLow(), itr
->second
.ID
);
15257 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
);
15258 itr
->second
.Changed
= false;
15263 void Player::_SaveSpells()
15265 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(), next
= m_spells
.begin(); itr
!= m_spells
.end(); itr
= next
)
15268 if (itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->second
->state
== PLAYERSPELL_CHANGED
)
15269 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr
->first
);
15270 if (itr
->second
->state
== PLAYERSPELL_NEW
|| itr
->second
->state
== PLAYERSPELL_CHANGED
)
15271 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);
15273 if (itr
->second
->state
== PLAYERSPELL_REMOVED
)
15274 _removeSpell(itr
->first
);
15276 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
15280 void Player::_SaveTutorials()
15282 if(!m_TutorialsChanged
)
15286 // it's better than rebuilding indexes multiple times
15287 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID
);
15290 Rows
= result
->Fetch()[0].GetUInt32();
15296 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'",
15297 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
);
15301 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]);
15304 m_TutorialsChanged
= false;
15307 void Player::outDebugValues() const
15309 if(!sLog
.IsOutDebug()) // optimize disabled debug output
15312 sLog
.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA
));
15313 sLog
.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY
), GetStat(STAT_STRENGTH
));
15314 sLog
.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT
), GetStat(STAT_SPIRIT
));
15315 sLog
.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA
), GetStat(STAT_SPIRIT
));
15316 sLog
.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE
));
15317 sLog
.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY
), GetResistance(SPELL_SCHOOL_FIRE
));
15318 sLog
.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE
), GetResistance(SPELL_SCHOOL_FROST
));
15319 sLog
.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW
), GetResistance(SPELL_SCHOOL_ARCANE
));
15320 sLog
.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE
), GetFloatValue(UNIT_FIELD_MAXDAMAGE
));
15321 sLog
.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
));
15322 sLog
.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
));
15323 sLog
.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK
), GetAttackTime(RANGED_ATTACK
));
15326 /*********************************************************/
15327 /*** FLOOD FILTER SYSTEM ***/
15328 /*********************************************************/
15330 void Player::UpdateSpeakTime()
15332 // ignore chat spam protection for GMs in any mode
15333 if(GetSession()->GetSecurity() > SEC_PLAYER
)
15336 time_t current
= time (NULL
);
15337 if(m_speakTime
> current
)
15339 uint32 max_count
= sWorld
.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT
);
15344 if(m_speakCount
>= max_count
)
15346 // prevent overwrite mute time, if message send just before mutes set, for example.
15347 time_t new_mute
= current
+ sWorld
.getConfig(CONFIG_CHATFLOOD_MUTE_TIME
);
15348 if(GetSession()->m_muteTime
< new_mute
)
15349 GetSession()->m_muteTime
= new_mute
;
15357 m_speakTime
= current
+ sWorld
.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY
);
15360 bool Player::CanSpeak() const
15362 return GetSession()->m_muteTime
<= time (NULL
);
15365 /*********************************************************/
15366 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15367 /*********************************************************/
15369 void Player::SendAttackSwingNotInRange()
15371 WorldPacket
data(SMSG_ATTACKSWING_NOTINRANGE
, 0);
15372 GetSession()->SendPacket( &data
);
15375 void Player::SavePositionInDB(uint32 mapid
, float x
,float y
,float z
,float o
,uint32 zone
,uint64 guid
)
15377 std::ostringstream ss
;
15378 ss
<< "UPDATE characters SET position_x='"<<x
<<"',position_y='"<<y
15379 << "',position_z='"<<z
<<"',orientation='"<<o
<<"',map='"<<mapid
15380 << "',zone='"<<zone
<<"',trans_x='0',trans_y='0',trans_z='0',"
15381 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
15382 sLog
.outDebug(ss
.str().c_str());
15383 CharacterDatabase
.Execute(ss
.str().c_str());
15386 void Player::SaveDataFieldToDB()
15388 std::ostringstream ss
;
15389 ss
<<"UPDATE characters SET data='";
15391 for(uint16 i
= 0; i
< m_valuesCount
; i
++ )
15393 ss
<< GetUInt32Value(i
) << " ";
15395 ss
<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
15397 CharacterDatabase
.Execute(ss
.str().c_str());
15400 bool Player::SaveValuesArrayInDB(Tokens
const& tokens
, uint64 guid
)
15402 std::ostringstream ss2
;
15403 ss2
<<"UPDATE characters SET data='";
15405 for (Tokens::const_iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
, ++i
)
15407 ss2
<<tokens
[i
]<<" ";
15409 ss2
<<"' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
15411 return CharacterDatabase
.Execute(ss2
.str().c_str());
15414 void Player::SetUInt32ValueInArray(Tokens
& tokens
,uint16 index
, uint32 value
)
15417 snprintf(buf
,11,"%u",value
);
15419 if(index
>= tokens
.size())
15422 tokens
[index
] = buf
;
15425 void Player::SetUInt32ValueInDB(uint16 index
, uint32 value
, uint64 guid
)
15428 if(!LoadValuesArrayFromDB(tokens
,guid
))
15431 if(index
>= tokens
.size())
15435 snprintf(buf
,11,"%u",value
);
15436 tokens
[index
] = buf
;
15438 SaveValuesArrayInDB(tokens
,guid
);
15441 void Player::SetFloatValueInDB(uint16 index
, float value
, uint64 guid
)
15444 memcpy(&temp
, &value
, sizeof(value
));
15445 Player::SetUInt32ValueInDB(index
, temp
, guid
);
15448 void Player::SendAttackSwingNotStanding()
15450 WorldPacket
data(SMSG_ATTACKSWING_NOTSTANDING
, 0);
15451 GetSession()->SendPacket( &data
);
15454 void Player::SendAttackSwingDeadTarget()
15456 WorldPacket
data(SMSG_ATTACKSWING_DEADTARGET
, 0);
15457 GetSession()->SendPacket( &data
);
15460 void Player::SendAttackSwingCantAttack()
15462 WorldPacket
data(SMSG_ATTACKSWING_CANT_ATTACK
, 0);
15463 GetSession()->SendPacket( &data
);
15466 void Player::SendAttackSwingCancelAttack()
15468 WorldPacket
data(SMSG_CANCEL_COMBAT
, 0);
15469 GetSession()->SendPacket( &data
);
15472 void Player::SendAttackSwingBadFacingAttack()
15474 WorldPacket
data(SMSG_ATTACKSWING_BADFACING
, 0);
15475 GetSession()->SendPacket( &data
);
15478 void Player::SendAutoRepeatCancel()
15480 WorldPacket
data(SMSG_CANCEL_AUTO_REPEAT
, 0);
15481 GetSession()->SendPacket( &data
);
15484 void Player::PlaySound(uint32 Sound
, bool OnlySelf
)
15486 WorldPacket
data(SMSG_PLAY_SOUND
, 4);
15489 GetSession()->SendPacket( &data
);
15491 SendMessageToSet( &data
, true );
15494 void Player::SendExplorationExperience(uint32 Area
, uint32 Experience
)
15496 WorldPacket
data( SMSG_EXPLORATION_EXPERIENCE
, 8 );
15498 data
<< Experience
;
15499 GetSession()->SendPacket(&data
);
15502 void Player::SendDungeonDifficulty(bool IsInGroup
)
15504 uint8 val
= 0x00000001;
15505 WorldPacket
data(MSG_SET_DUNGEON_DIFFICULTY
, 12);
15506 data
<< (uint32
)GetDifficulty();
15507 data
<< uint32(val
);
15508 data
<< uint32(IsInGroup
);
15509 GetSession()->SendPacket(&data
);
15512 void Player::SendResetFailedNotify(uint32 mapid
)
15514 WorldPacket
data(SMSG_RESET_FAILED_NOTIFY
, 4);
15515 data
<< uint32(mapid
);
15516 GetSession()->SendPacket(&data
);
15519 /// Reset all solo instances and optionally send a message on success for each
15520 void Player::ResetInstances(uint8 method
)
15522 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
15524 // we assume that when the difficulty changes, all instances that can be reset will be
15525 uint8 dif
= GetDifficulty();
15527 for (BoundInstancesMap::iterator itr
= m_boundInstances
[dif
].begin(); itr
!= m_boundInstances
[dif
].end();)
15529 InstanceSave
*p
= itr
->second
.save
;
15530 const MapEntry
*entry
= sMapStore
.LookupEntry(itr
->first
);
15531 if(!entry
|| !p
->CanReset())
15537 if(method
== INSTANCE_RESET_ALL
)
15539 // the "reset all instances" method can only reset normal maps
15540 if(dif
== DIFFICULTY_HEROIC
|| entry
->map_type
== MAP_RAID
)
15547 // if the map is loaded, reset it
15548 Map
*map
= MapManager::Instance().FindMap(p
->GetMapId(), p
->GetInstanceId());
15549 if(map
&& map
->IsDungeon())
15550 ((InstanceMap
*)map
)->Reset(method
);
15552 // since this is a solo instance there should not be any players inside
15553 if(method
== INSTANCE_RESET_ALL
|| method
== INSTANCE_RESET_CHANGE_DIFFICULTY
)
15554 SendResetInstanceSuccess(p
->GetMapId());
15557 m_boundInstances
[dif
].erase(itr
++);
15559 // the following should remove the instance save from the manager and delete it as well
15560 p
->RemovePlayer(this);
15564 void Player::SendResetInstanceSuccess(uint32 MapId
)
15566 WorldPacket
data(SMSG_INSTANCE_RESET
, 4);
15568 GetSession()->SendPacket(&data
);
15571 void Player::SendResetInstanceFailed(uint32 reason
, uint32 MapId
)
15573 // TODO: find what other fail reasons there are besides players in the instance
15574 WorldPacket
data(SMSG_INSTANCE_RESET_FAILED
, 4);
15577 GetSession()->SendPacket(&data
);
15580 /*********************************************************/
15581 /*** Update timers ***/
15582 /*********************************************************/
15584 ///checks the 15 afk reports per 5 minutes limit
15585 void Player::UpdateAfkReport(time_t currTime
)
15587 if(m_bgAfkReportedTimer
<= currTime
)
15589 m_bgAfkReportedCount
= 0;
15590 m_bgAfkReportedTimer
= currTime
+5*MINUTE
;
15594 void Player::UpdateContestedPvP(uint32 diff
)
15596 if(!m_contestedPvPTimer
||isInCombat())
15598 if(m_contestedPvPTimer
<= diff
)
15600 ResetContestedPvP();
15603 m_contestedPvPTimer
-= diff
;
15606 void Player::UpdatePvPFlag(time_t currTime
)
15610 if(pvpInfo
.endTimer
== 0 || currTime
< (pvpInfo
.endTimer
+ 300))
15616 void Player::UpdateDuelFlag(time_t currTime
)
15618 if(!duel
|| duel
->startTimer
== 0 ||currTime
< duel
->startTimer
+ 3)
15621 SetUInt32Value(PLAYER_DUEL_TEAM
, 1);
15622 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 2);
15624 duel
->startTimer
= 0;
15625 duel
->startTime
= currTime
;
15626 duel
->opponent
->duel
->startTimer
= 0;
15627 duel
->opponent
->duel
->startTime
= currTime
;
15630 void Player::RemovePet(Pet
* pet
, PetSaveMode mode
, bool returnreagent
)
15635 if(returnreagent
&& (pet
|| m_temporaryUnsummonedPetNumber
))
15637 //returning of reagents only for players, so best done here
15638 uint32 spellId
= pet
? pet
->GetUInt32Value(UNIT_CREATED_BY_SPELL
) : m_oldpetspell
;
15639 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellId
);
15643 for(uint32 i
= 0; i
< 7; ++i
)
15645 if(spellInfo
->Reagent
[i
] > 0)
15647 ItemPosCountVec dest
; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
15648 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, spellInfo
->Reagent
[i
], spellInfo
->ReagentCount
[i
] );
15649 if( msg
== EQUIP_ERR_OK
)
15651 Item
* item
= StoreNewItem( dest
, spellInfo
->Reagent
[i
], true);
15653 SendNewItem(item
,spellInfo
->ReagentCount
[i
],true,false);
15658 m_temporaryUnsummonedPetNumber
= 0;
15661 if(!pet
|| pet
->GetOwnerGUID()!=GetGUID())
15664 // only if current pet in slot
15665 switch(pet
->getPetType())
15671 m_guardianPets
.erase(pet
->GetGUID());
15674 if(GetPetGUID() == pet
->GetGUID())
15683 switch(pet
->GetEntry())
15685 //warlock pets except imp are removed(?) when logging out
15690 mode
= PET_SAVE_NOT_IN_SLOT
;
15695 pet
->SavePetToDB(mode
);
15697 pet
->CleanupsBeforeDelete();
15698 pet
->AddObjectToRemoveList();
15699 pet
->m_removed
= true;
15701 if(pet
->isControlled())
15703 WorldPacket
data(SMSG_PET_SPELLS
, 8);
15705 GetSession()->SendPacket(&data
);
15708 SetGroupUpdateFlag(GROUP_UPDATE_PET
);
15712 void Player::RemoveMiniPet()
15714 if(Pet
* pet
= GetMiniPet())
15716 pet
->Remove(PET_SAVE_AS_DELETED
);
15721 Pet
* Player::GetMiniPet()
15725 return ObjectAccessor::GetPet(m_miniPet
);
15728 void Player::RemoveGuardians()
15730 while(!m_guardianPets
.empty())
15732 uint64 guid
= *m_guardianPets
.begin();
15733 if(Pet
* pet
= ObjectAccessor::GetPet(guid
))
15734 pet
->Remove(PET_SAVE_AS_DELETED
);
15736 m_guardianPets
.erase(guid
);
15740 bool Player::HasGuardianWithEntry(uint32 entry
)
15742 // pet guid middle part is entry (and creature also)
15743 // and in guardian list must be guardians with same entry _always_
15744 for(GuardianPetList::const_iterator itr
= m_guardianPets
.begin(); itr
!= m_guardianPets
.end(); ++itr
)
15745 if(GUID_ENPART(*itr
)==entry
)
15751 void Player::Uncharm()
15753 Unit
* charm
= GetCharm();
15757 charm
->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM
);
15758 charm
->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS
);
15761 void Player::BuildPlayerChat(WorldPacket
*data
, uint8 msgtype
, const std::string
& text
, uint32 language
) const
15763 *data
<< (uint8
)msgtype
;
15764 *data
<< (uint32
)language
;
15765 *data
<< (uint64
)GetGUID();
15766 *data
<< (uint32
)language
; //language 2.1.0 ?
15767 *data
<< (uint64
)GetGUID();
15768 *data
<< (uint32
)(text
.length()+1);
15770 *data
<< (uint8
)chatTag();
15773 void Player::Say(const std::string
& text
, const uint32 language
)
15775 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
15776 BuildPlayerChat(&data
, CHAT_MSG_SAY
, text
, language
);
15777 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_SAY
),true);
15780 void Player::Yell(const std::string
& text
, const uint32 language
)
15782 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
15783 BuildPlayerChat(&data
, CHAT_MSG_YELL
, text
, language
);
15784 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_YELL
),true);
15787 void Player::TextEmote(const std::string
& text
)
15789 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
15790 BuildPlayerChat(&data
, CHAT_MSG_EMOTE
, text
, LANG_UNIVERSAL
);
15791 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE
),true, !sWorld
.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT
) );
15794 void Player::Whisper(const std::string
& text
, uint32 language
,uint64 receiver
)
15796 if (language
!= LANG_ADDON
) // if not addon data
15797 language
= LANG_UNIVERSAL
; // whispers should always be readable
15799 Player
*rPlayer
= objmgr
.GetPlayer(receiver
);
15801 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
15802 if(!rPlayer
->isDND() || isGameMaster())
15804 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
15805 BuildPlayerChat(&data
, CHAT_MSG_WHISPER
, text
, language
);
15806 rPlayer
->GetSession()->SendPacket(&data
);
15808 data
.Initialize(SMSG_MESSAGECHAT
, 200);
15809 rPlayer
->BuildPlayerChat(&data
, CHAT_MSG_REPLY
, text
, language
);
15810 GetSession()->SendPacket(&data
);
15814 // announce to player that player he is whispering to is dnd and cannot receive his message
15815 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND
, rPlayer
->GetName(), rPlayer
->dndMsg
.c_str());
15818 if(!isAcceptWhispers())
15820 SetAcceptWhispers(true);
15821 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON
);
15824 // announce to player that player he is whispering to is afk
15825 if(rPlayer
->isAFK())
15826 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK
, rPlayer
->GetName(), rPlayer
->afkMsg
.c_str());
15828 // if player whisper someone, auto turn of dnd to be able to receive an answer
15829 if(isDND() && !rPlayer
->isGameMaster())
15833 void Player::PetSpellInitialize()
15835 Pet
* pet
= GetPet();
15841 sLog
.outDebug("Pet Spells Groups");
15843 CreatureInfo
const *cinfo
= pet
->GetCreatureInfo();
15845 if(pet
->isControlled() && (pet
->getPetType() == HUNTER_PET
|| cinfo
&& cinfo
->type
== CREATURE_TYPE_DEMON
&& getClass() == CLASS_WARLOCK
))
15847 for(PetSpellMap::iterator itr
= pet
->m_spells
.begin();itr
!= pet
->m_spells
.end();++itr
)
15849 if(itr
->second
->state
== PETSPELL_REMOVED
)
15855 // first line + actionbar + spellcount + spells + last adds
15856 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);
15858 CharmInfo
*charmInfo
= pet
->GetCharmInfo();
15861 data
<< (uint64
)pet
->GetGUID() << uint32(0x00000000) << uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState()) << uint16(0);
15863 for(uint32 i
= 0; i
< 10; i
++) //40
15865 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
15868 data
<< uint8(addlist
); //1
15870 if(addlist
&& pet
->isControlled())
15872 for (PetSpellMap::iterator itr
= pet
->m_spells
.begin(); itr
!= pet
->m_spells
.end(); ++itr
)
15874 if(itr
->second
->state
== PETSPELL_REMOVED
)
15877 data
<< uint16(itr
->first
);
15878 data
<< uint16(itr
->second
->active
); // pet spell active state isn't boolean
15882 //data << uint8(0x01) << uint32(0x6010) << uint32(0x01) << uint32(0x05) << uint16(0x00); //15
15883 uint8 count
= 3; //1+8+8+8=25
15885 // if count = 0, then end of packet...
15887 // uint32 value is spell id...
15888 // uint64 value is constant 0, unknown...
15889 data
<< uint32(0x6010) << uint64(0); // if count = 1, 2 or 3
15890 //data << uint32(0x5fd1) << uint64(0); // if count = 2
15891 data
<< uint32(0x8e8c) << uint64(0); // if count = 3
15892 data
<< uint32(0x8e8b) << uint64(0); // if count = 3
15894 GetSession()->SendPacket(&data
);
15898 void Player::PossessSpellInitialize()
15900 Unit
* charm
= GetCharm();
15905 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
15909 sLog
.outError("Player::PossessSpellInitialize(): charm ("I64FMTD
") has no charminfo!", charm
->GetGUID());
15914 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);// first line + actionbar + spellcount + spells + last adds
15917 data
<< (uint64
)charm
->GetGUID() << uint32(0x00000000) << uint8(0) << uint8(0) << uint16(0);
15919 for(uint32 i
= 0; i
< 10; i
++) //40
15921 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
15924 data
<< uint8(addlist
); //1
15928 data
<< uint32(0x6010) << uint64(0); // if count = 1, 2 or 3
15929 data
<< uint32(0x8e8c) << uint64(0); // if count = 3
15930 data
<< uint32(0x8e8b) << uint64(0); // if count = 3
15932 GetSession()->SendPacket(&data
);
15935 void Player::CharmSpellInitialize()
15937 Unit
* charm
= GetCharm();
15942 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
15945 sLog
.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD
") has no charminfo!", charm
->GetGUID());
15951 if(charm
->GetTypeId() != TYPEID_PLAYER
)
15953 CreatureInfo
const *cinfo
= ((Creature
*)charm
)->GetCreatureInfo();
15955 if(cinfo
&& cinfo
->type
== CREATURE_TYPE_DEMON
&& getClass() == CLASS_WARLOCK
)
15957 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
15959 if(charmInfo
->GetCharmSpell(i
)->spellId
)
15965 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);// first line + actionbar + spellcount + spells + last adds
15967 data
<< (uint64
)charm
->GetGUID() << uint32(0x00000000);
15969 if(charm
->GetTypeId() != TYPEID_PLAYER
)
15970 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState());
15972 data
<< uint8(0) << uint8(0);
15976 for(uint32 i
= 0; i
< 10; i
++) //40
15978 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
15981 data
<< uint8(addlist
); //1
15985 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
15987 CharmSpellEntry
*cspell
= charmInfo
->GetCharmSpell(i
);
15988 if(cspell
->spellId
)
15990 data
<< uint16(cspell
->spellId
);
15991 data
<< uint16(cspell
->active
);
15998 data
<< uint32(0x6010) << uint64(0); // if count = 1, 2 or 3
15999 data
<< uint32(0x8e8c) << uint64(0); // if count = 3
16000 data
<< uint32(0x8e8b) << uint64(0); // if count = 3
16002 GetSession()->SendPacket(&data
);
16005 int32
Player::GetTotalFlatMods(uint32 spellId
, SpellModOp op
)
16007 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellId
);
16008 if (!spellInfo
) return 0;
16010 for (SpellModList::iterator itr
= m_spellMods
[op
].begin(); itr
!= m_spellMods
[op
].end(); ++itr
)
16012 SpellModifier
*mod
= *itr
;
16014 if(!IsAffectedBySpellmod(spellInfo
,mod
))
16017 if (mod
->type
== SPELLMOD_FLAT
)
16018 total
+= mod
->value
;
16023 int32
Player::GetTotalPctMods(uint32 spellId
, SpellModOp op
)
16025 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellId
);
16026 if (!spellInfo
) return 0;
16028 for (SpellModList::iterator itr
= m_spellMods
[op
].begin(); itr
!= m_spellMods
[op
].end(); ++itr
)
16030 SpellModifier
*mod
= *itr
;
16032 if(!IsAffectedBySpellmod(spellInfo
,mod
))
16035 if (mod
->type
== SPELLMOD_PCT
)
16036 total
+= mod
->value
;
16041 bool Player::IsAffectedBySpellmod(SpellEntry
const *spellInfo
, SpellModifier
*mod
, Spell
const* spell
)
16043 if (!mod
|| !spellInfo
)
16046 if(mod
->charges
== -1 && mod
->lastAffected
) // marked as expired but locked until spell casting finish
16048 // prevent apply to any spell except spell that trigger expire
16051 if(mod
->lastAffected
!= spell
)
16054 else if(mod
->lastAffected
!= FindCurrentSpellBySpellId(spellInfo
->Id
))
16058 return spellmgr
.IsAffectedBySpell(spellInfo
,mod
->spellId
,mod
->effectId
,mod
->mask
);
16061 void Player::AddSpellMod(SpellModifier
* mod
, bool apply
)
16063 uint16 Opcode
= (mod
->type
== SPELLMOD_FLAT
) ? SMSG_SET_FLAT_SPELL_MODIFIER
: SMSG_SET_PCT_SPELL_MODIFIER
;
16065 for(int eff
=0;eff
<64;++eff
)
16067 uint64 _mask
= uint64(1) << eff
;
16068 if ( mod
->mask
& _mask
)
16071 for (SpellModList::iterator itr
= m_spellMods
[mod
->op
].begin(); itr
!= m_spellMods
[mod
->op
].end(); ++itr
)
16073 if ((*itr
)->type
== mod
->type
&& (*itr
)->mask
& _mask
)
16074 val
+= (*itr
)->value
;
16076 val
+= apply
? mod
->value
: -(mod
->value
);
16077 WorldPacket
data(Opcode
, (1+1+4));
16078 data
<< uint8(eff
);
16079 data
<< uint8(mod
->op
);
16080 data
<< int32(val
);
16081 SendDirectMessage(&data
);
16086 m_spellMods
[mod
->op
].push_back(mod
);
16089 if (mod
->charges
== -1)
16090 --m_SpellModRemoveCount
;
16091 m_spellMods
[mod
->op
].remove(mod
);
16096 void Player::RemoveSpellMods(Spell
const* spell
)
16098 if(!spell
|| (m_SpellModRemoveCount
== 0))
16101 for(int i
=0;i
<MAX_SPELLMOD
;++i
)
16103 for (SpellModList::iterator itr
= m_spellMods
[i
].begin(); itr
!= m_spellMods
[i
].end();)
16105 SpellModifier
*mod
= *itr
;
16108 if (mod
&& mod
->charges
== -1 && (mod
->lastAffected
== spell
|| mod
->lastAffected
==NULL
))
16110 RemoveAurasDueToSpell(mod
->spellId
);
16111 if (m_spellMods
[i
].empty())
16114 itr
= m_spellMods
[i
].begin();
16120 // send Proficiency
16121 void Player::SendProficiency(uint8 pr1
, uint32 pr2
)
16123 WorldPacket
data(SMSG_SET_PROFICIENCY
, 8);
16124 data
<< pr1
<< pr2
;
16125 GetSession()->SendPacket (&data
);
16128 void Player::RemovePetitionsAndSigns(uint64 guid
, uint32 type
)
16130 QueryResult
*result
= NULL
;
16132 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
16134 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16137 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.
16138 { // and SendPetitionQueryOpcode reads data from the DB
16139 Field
*fields
= result
->Fetch();
16140 uint64 ownerguid
= MAKE_NEW_GUID(fields
[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
16141 uint64 petitionguid
= MAKE_NEW_GUID(fields
[1].GetUInt32(), 0, HIGHGUID_ITEM
);
16143 // send update if charter owner in game
16144 Player
* owner
= objmgr
.GetPlayer(ownerguid
);
16146 owner
->GetSession()->SendPetitionQueryOpcode(petitionguid
);
16148 } while ( result
->NextRow() );
16153 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
16155 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16158 CharacterDatabase
.BeginTransaction();
16161 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid
));
16162 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid
));
16166 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16167 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16169 CharacterDatabase
.CommitTransaction();
16172 void Player::SetRestBonus (float rest_bonus_new
)
16174 // Prevent resting on max level
16175 if(getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
16176 rest_bonus_new
= 0;
16178 if(rest_bonus_new
< 0)
16179 rest_bonus_new
= 0;
16181 float rest_bonus_max
= (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)*1.5/2;
16183 if(rest_bonus_new
> rest_bonus_max
)
16184 m_rest_bonus
= rest_bonus_max
;
16186 m_rest_bonus
= rest_bonus_new
;
16188 // update data for client
16189 if(m_rest_bonus
>10)
16190 SetByteValue(PLAYER_BYTES_2
, 3, 0x01); // Set Reststate = Rested
16191 else if(m_rest_bonus
<=1)
16192 SetByteValue(PLAYER_BYTES_2
, 3, 0x02); // Set Reststate = Normal
16195 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE
, uint32(m_rest_bonus
));
16198 void Player::HandleStealthedUnitsDetection()
16200 std::list
<Unit
*> stealthedUnits
;
16202 CellPair
p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16204 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
16205 cell
.SetNoCreate();
16207 MaNGOS::AnyStealthedCheck u_check
;
16208 MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
> searcher(stealthedUnits
, u_check
);
16210 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, WorldTypeMapContainer
> world_unit_searcher(searcher
);
16211 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, GridTypeMapContainer
> grid_unit_searcher(searcher
);
16213 CellLock
<GridReadGuard
> cell_lock(cell
, p
);
16214 cell_lock
->Visit(cell_lock
, world_unit_searcher
, *GetMap());
16215 cell_lock
->Visit(cell_lock
, grid_unit_searcher
, *GetMap());
16217 for (std::list
<Unit
*>::iterator i
= stealthedUnits
.begin(); i
!= stealthedUnits
.end();)
16221 i
= stealthedUnits
.erase(i
);
16225 if ((*i
)->isVisibleForOrDetect(this,true))
16228 (*i
)->SendUpdateToPlayer(this);
16229 m_clientGUIDs
.insert((*i
)->GetGUID());
16231 #ifdef MANGOS_DEBUG
16232 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
16233 sLog
.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i
)->GetGUIDLow(),(*i
)->GetTypeId(),GetGUIDLow(),GetDistance(*i
));
16236 // target aura duration for caster show only if target exist at caster client
16237 // send data at target visibility change (adding to client)
16238 if((*i
)!=this && (*i
)->isType(TYPEMASK_UNIT
))
16239 SendAuraDurationsForTarget(*i
);
16241 i
= stealthedUnits
.erase(i
);
16249 bool Player::ActivateTaxiPathTo(std::vector
<uint32
> const& nodes
, uint32 mount_id
, Creature
* npc
)
16251 if(nodes
.size() < 2)
16254 // not let cheating with start flight mounted
16257 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16258 data
<< uint32(ERR_TAXIPLAYERALREADYMOUNTED
);
16259 GetSession()->SendPacket(&data
);
16263 if( m_ShapeShiftFormSpellId
&& m_form
!= FORM_BATTLESTANCE
&& m_form
!= FORM_BERSERKERSTANCE
&& m_form
!= FORM_DEFENSIVESTANCE
&& m_form
!= FORM_SHADOW
)
16265 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16266 data
<< uint32(ERR_TAXIPLAYERSHAPESHIFTED
);
16267 GetSession()->SendPacket(&data
);
16271 // 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
16272 if(GetSession()->isLogingOut() ||
16273 (!m_currentSpells
[CURRENT_GENERIC_SPELL
] ||
16274 m_currentSpells
[CURRENT_GENERIC_SPELL
]->m_spellInfo
->Effect
[0] != SPELL_EFFECT_SEND_TAXI
)&&
16275 IsNonMeleeSpellCasted(false) ||
16278 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16279 data
<< uint32(ERR_TAXIPLAYERBUSY
);
16280 GetSession()->SendPacket(&data
);
16284 if(HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_DISABLE_MOVE
))
16287 uint32 sourcenode
= nodes
[0];
16289 // starting node too far away (cheat?)
16290 TaxiNodesEntry
const* node
= sTaxiNodesStore
.LookupEntry(sourcenode
);
16291 if( !node
|| node
->map_id
!= GetMapId() ||
16292 (node
->x
- GetPositionX())*(node
->x
- GetPositionX())+
16293 (node
->y
- GetPositionY())*(node
->y
- GetPositionY())+
16294 (node
->z
- GetPositionZ())*(node
->z
- GetPositionZ()) >
16295 (2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
) )
16297 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16298 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
16299 GetSession()->SendPacket(&data
);
16303 // Prepare to flight start now
16305 // stop combat at start taxi flight if any
16308 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16311 // clean not finished taxi path if any
16312 m_taxi
.ClearTaxiDestinations();
16314 // 0 element current node
16315 m_taxi
.AddTaxiDestination(sourcenode
);
16317 // fill destinations path tail
16318 uint32 sourcepath
= 0;
16319 uint32 totalcost
= 0;
16321 uint32 prevnode
= sourcenode
;
16322 uint32 lastnode
= 0;
16324 for(uint32 i
= 1; i
< nodes
.size(); ++i
)
16328 lastnode
= nodes
[i
];
16329 objmgr
.GetTaxiPath(prevnode
, lastnode
, path
, cost
);
16333 m_taxi
.ClearTaxiDestinations();
16339 if(prevnode
== sourcenode
)
16342 m_taxi
.AddTaxiDestination(lastnode
);
16344 prevnode
= lastnode
;
16347 if(!mount_id
) // if not provide then attempt use default.
16348 mount_id
= objmgr
.GetTaxiMount(sourcenode
, GetTeam());
16350 if (mount_id
== 0 || sourcepath
== 0)
16352 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16353 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
16354 GetSession()->SendPacket(&data
);
16355 m_taxi
.ClearTaxiDestinations();
16359 uint32 money
= GetMoney();
16363 totalcost
= (uint32
)ceil(totalcost
*GetReputationPriceDiscount(npc
));
16366 if(money
< totalcost
)
16368 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16369 data
<< uint32(ERR_TAXINOTENOUGHMONEY
);
16370 GetSession()->SendPacket(&data
);
16371 m_taxi
.ClearTaxiDestinations();
16375 //Checks and preparations done, DO FLIGHT
16376 ModifyMoney(-(int32
)totalcost
);
16378 // prevent stealth flight
16379 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH
);
16381 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16382 data
<< uint32(ERR_TAXIOK
);
16383 GetSession()->SendPacket(&data
);
16385 sLog
.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16387 GetSession()->SendDoFlight(mount_id
, sourcepath
);
16392 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask
, uint32 unTimeMs
)
16394 // last check 2.0.10
16395 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+m_spells
.size()*8);
16397 data
<< uint8(0x0); // flags (0x1, 0x2)
16398 time_t curTime
= time(NULL
);
16399 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
16401 if (itr
->second
->state
== PLAYERSPELL_REMOVED
)
16403 uint32 unSpellId
= itr
->first
;
16404 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(unSpellId
);
16411 // Not send cooldown for this spells
16412 if (spellInfo
->Attributes
& SPELL_ATTR_DISABLED_WHILE_ACTIVE
)
16415 if((idSchoolMask
& GetSpellSchoolMask(spellInfo
)) && GetSpellCooldownDelay(unSpellId
) < unTimeMs
)
16418 data
<< unTimeMs
; // in m.secs
16419 AddSpellCooldown(unSpellId
, 0, curTime
+ unTimeMs
/1000);
16422 GetSession()->SendPacket(&data
);
16425 void Player::InitDataForForm(bool reapplyMods
)
16427 SpellShapeshiftEntry
const* ssEntry
= sSpellShapeshiftStore
.LookupEntry(m_form
);
16428 if(ssEntry
&& ssEntry
->attackSpeed
)
16430 SetAttackTime(BASE_ATTACK
,ssEntry
->attackSpeed
);
16431 SetAttackTime(OFF_ATTACK
,ssEntry
->attackSpeed
);
16432 SetAttackTime(RANGED_ATTACK
, BASE_ATTACK_TIME
);
16435 SetRegularAttackTime();
16441 if(getPowerType()!=POWER_ENERGY
)
16442 setPowerType(POWER_ENERGY
);
16446 case FORM_DIREBEAR
:
16448 if(getPowerType()!=POWER_RAGE
)
16449 setPowerType(POWER_RAGE
);
16452 default: // 0, for example
16454 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(getClass());
16455 if(cEntry
&& cEntry
->powerType
< MAX_POWERS
&& uint32(getPowerType()) != cEntry
->powerType
)
16456 setPowerType(Powers(cEntry
->powerType
));
16461 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
16463 UpdateEquipSpellsAtFormChange();
16465 UpdateAttackPowerAndDamage();
16466 UpdateAttackPowerAndDamage(true);
16469 // Return true is the bought item has a max count to force refresh of window by caller
16470 bool Player::BuyItemFromVendor(uint64 vendorguid
, uint32 item
, uint8 count
, uint64 bagguid
, uint8 slot
)
16472 // cheating attempt
16473 if(count
< 1) count
= 1;
16478 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
16481 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, NULL
, item
, 0);
16485 Creature
*pCreature
= ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid
,UNIT_NPC_FLAG_VENDOR
);
16488 sLog
.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid
)) );
16489 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR
, NULL
, item
, 0);
16493 VendorItemData
const* vItems
= pCreature
->GetVendorItems();
16494 if(!vItems
|| vItems
->Empty())
16496 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
16500 size_t vendor_slot
= vItems
->FindItemSlot(item
);
16501 if(vendor_slot
>= vItems
->GetItemCount())
16503 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
16507 VendorItem
const* crItem
= vItems
->m_items
[vendor_slot
];
16509 // check current item amount if it limited
16510 if( crItem
->maxcount
!= 0 )
16512 if(pCreature
->GetVendorItemCurrentCount(crItem
) < pProto
->BuyCount
* count
)
16514 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD
, pCreature
, item
, 0);
16519 if( uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
16521 SendBuyError( BUY_ERR_REPUTATION_REQUIRE
, pCreature
, item
, 0);
16525 if(crItem
->ExtendedCost
)
16527 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
16530 sLog
.outError("Item %u have wrong ExtendedCost field value %u", pProto
->ItemId
, crItem
->ExtendedCost
);
16534 // honor points price
16535 if(GetHonorPoints() < (iece
->reqhonorpoints
* count
))
16537 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS
, NULL
, NULL
);
16541 // arena points price
16542 if(GetArenaPoints() < (iece
->reqarenapoints
* count
))
16544 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS
, NULL
, NULL
);
16549 for (uint8 i
= 0; i
< 5; ++i
)
16551 if(iece
->reqitem
[i
] && !HasItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
)))
16553 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS
, NULL
, NULL
);
16558 // check for personal arena rating requirement
16559 if( GetMaxPersonalArenaRatingRequirement() < iece
->reqpersonalarenarating
)
16561 // probably not the proper equip err
16562 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK
,NULL
,NULL
);
16567 uint32 price
= pProto
->BuyPrice
* count
;
16569 // reputation discount
16570 price
= uint32(floor(price
* GetReputationPriceDiscount(pCreature
)));
16572 if( GetMoney() < price
)
16574 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, pCreature
, item
, 0);
16578 uint8 bag
= 0; // init for case invalid bagGUID
16580 if (bagguid
!= NULL_BAG
&& slot
!= NULL_SLOT
)
16583 if( bagguid
== GetGUID() )
16585 bag
= INVENTORY_SLOT_BAG_0
;
16589 for (int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
;i
++)
16591 pBag
= (Bag
*)GetItemByPos(INVENTORY_SLOT_BAG_0
,i
);
16594 if( bagguid
== pBag
->GetGUID() )
16604 if( IsInventoryPos( bag
, slot
) || (bagguid
== NULL_BAG
&& slot
== NULL_SLOT
) )
16606 ItemPosCountVec dest
;
16607 uint8 msg
= CanStoreNewItem( bag
, slot
, dest
, item
, pProto
->BuyCount
* count
);
16608 if( msg
!= EQUIP_ERR_OK
)
16610 SendEquipError( msg
, NULL
, NULL
);
16614 ModifyMoney( -(int32
)price
);
16615 if(crItem
->ExtendedCost
) // case for new honor system
16617 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
16618 if(iece
->reqhonorpoints
)
16619 ModifyHonorPoints( - int32(iece
->reqhonorpoints
* count
));
16620 if(iece
->reqarenapoints
)
16621 ModifyArenaPoints( - int32(iece
->reqarenapoints
* count
));
16622 for (uint8 i
= 0; i
< 5; ++i
)
16624 if(iece
->reqitem
[i
])
16625 DestroyItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
), true);
16629 if(Item
*it
= StoreNewItem( dest
, item
, true ))
16631 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
16633 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
16634 data
<< pCreature
->GetGUID();
16635 data
<< (uint32
)(vendor_slot
+1); // numbered from 1 at client
16636 data
<< (uint32
)(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
16637 data
<< (uint32
)count
;
16638 GetSession()->SendPacket(&data
);
16640 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
16643 else if( IsEquipmentPos( bag
, slot
) )
16645 if(pProto
->BuyCount
* count
!= 1)
16647 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
, NULL
, NULL
);
16652 uint8 msg
= CanEquipNewItem( slot
, dest
, item
, false );
16653 if( msg
!= EQUIP_ERR_OK
)
16655 SendEquipError( msg
, NULL
, NULL
);
16659 ModifyMoney( -(int32
)price
);
16660 if(crItem
->ExtendedCost
) // case for new honor system
16662 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
16663 if(iece
->reqhonorpoints
)
16664 ModifyHonorPoints( - int32(iece
->reqhonorpoints
));
16665 if(iece
->reqarenapoints
)
16666 ModifyArenaPoints( - int32(iece
->reqarenapoints
));
16667 for (uint8 i
= 0; i
< 5; ++i
)
16669 if(iece
->reqitem
[i
])
16670 DestroyItemCount(iece
->reqitem
[i
], iece
->reqitemcount
[i
], true);
16674 if(Item
*it
= EquipNewItem( dest
, item
, true ))
16676 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
16678 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
16679 data
<< pCreature
->GetGUID();
16680 data
<< (uint32
)(vendor_slot
+1); // numbered from 1 at client
16681 data
<< (uint32
)(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
16682 data
<< (uint32
)count
;
16683 GetSession()->SendPacket(&data
);
16685 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
16687 AutoUnequipOffhandIfNeed();
16692 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
, NULL
, NULL
);
16696 return crItem
->maxcount
!=0;
16699 uint32
Player::GetMaxPersonalArenaRatingRequirement()
16701 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
16702 // the personal rating of the arena team must match the required limit as well
16703 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
16704 uint32 max_personal_rating
= 0;
16705 for(int i
= 0; i
< MAX_ARENA_SLOT
; ++i
)
16707 if(ArenaTeam
* at
= objmgr
.GetArenaTeamById(GetArenaTeamId(i
)))
16709 uint32 p_rating
= GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ (i
* 6) + 5);
16710 uint32 t_rating
= at
->GetRating();
16711 p_rating
= p_rating
<t_rating
? p_rating
: t_rating
;
16712 if(max_personal_rating
< p_rating
)
16713 max_personal_rating
= p_rating
;
16716 return max_personal_rating
;
16719 void Player::UpdateHomebindTime(uint32 time
)
16721 // GMs never get homebind timer online
16722 if (m_InstanceValid
|| isGameMaster())
16724 if(m_HomebindTimer
) // instance valid, but timer not reset
16727 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
16730 GetSession()->SendPacket(&data
);
16732 // instance is valid, reset homebind timer
16733 m_HomebindTimer
= 0;
16735 else if (m_HomebindTimer
> 0)
16737 if (time
>= m_HomebindTimer
)
16739 // teleport to homebind location
16740 TeleportTo(m_homebindMapId
, m_homebindX
, m_homebindY
, m_homebindZ
, GetOrientation());
16743 m_HomebindTimer
-= time
;
16747 // instance is invalid, start homebind timer
16748 m_HomebindTimer
= 60000;
16749 // send message to player
16750 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
16751 data
<< m_HomebindTimer
;
16753 GetSession()->SendPacket(&data
);
16754 sLog
.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
16758 void Player::UpdatePvP(bool state
, bool ovrride
)
16760 if(!state
|| ovrride
)
16763 if(Pet
* pet
= GetPet())
16764 pet
->SetPvP(state
);
16765 if(Unit
* charmed
= GetCharm())
16766 charmed
->SetPvP(state
);
16768 pvpInfo
.endTimer
= 0;
16772 if(pvpInfo
.endTimer
!= 0)
16773 pvpInfo
.endTimer
= time(NULL
);
16778 if(Pet
* pet
= GetPet())
16779 pet
->SetPvP(state
);
16780 if(Unit
* charmed
= GetCharm())
16781 charmed
->SetPvP(state
);
16786 void Player::AddSpellCooldown(uint32 spellid
, uint32 itemid
, time_t end_time
)
16790 sc
.itemid
= itemid
;
16791 m_spellCooldowns
[spellid
] = sc
;
16794 void Player::SendCooldownEvent(SpellEntry
const *spellInfo
)
16796 if ( !(spellInfo
->Attributes
& SPELL_ATTR_DISABLED_WHILE_ACTIVE
) )
16799 // Get spell cooldown
16800 int32 cooldown
= GetSpellRecoveryTime(spellInfo
);
16802 ApplySpellMod(spellInfo
->Id
, SPELLMOD_COOLDOWN
, cooldown
);
16806 AddSpellCooldown(spellInfo
->Id
, 0, time(NULL
) + cooldown
/ 1000);
16808 WorldPacket
data(SMSG_COOLDOWN_EVENT
, (4+8));
16809 data
<< spellInfo
->Id
;
16811 SendDirectMessage(&data
);
16813 //slot to be excluded while counting
16814 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition
, int8 slot
)
16816 if(!enchantmentcondition
)
16819 SpellItemEnchantmentConditionEntry
const *Condition
= sSpellItemEnchantmentConditionStore
.LookupEntry(enchantmentcondition
);
16824 uint8 curcount
[4] = {0, 0, 0, 0};
16826 //counting current equipped gem colors
16827 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
16831 Item
*pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
16832 if(pItem2
&& pItem2
->GetProto()->Socket
[0].Color
)
16834 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
16836 uint32 enchant_id
= pItem2
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
16840 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
16844 uint32 gemid
= enchantEntry
->GemID
;
16848 ItemPrototype
const* gemProto
= sItemStorage
.LookupEntry
<ItemPrototype
>(gemid
);
16852 GemPropertiesEntry
const* gemProperty
= sGemPropertiesStore
.LookupEntry(gemProto
->GemProperties
);
16856 uint8 GemColor
= gemProperty
->color
;
16858 for(uint8 b
= 0, tmpcolormask
= 1; b
< 4; b
++, tmpcolormask
<<= 1)
16860 if(tmpcolormask
& GemColor
)
16867 bool activate
= true;
16869 for(int i
= 0; i
< 5; i
++)
16871 if(!Condition
->Color
[i
])
16874 uint32 _cur_gem
= curcount
[Condition
->Color
[i
] - 1];
16876 // if have <CompareColor> use them as count, else use <value> from Condition
16877 uint32 _cmp_gem
= Condition
->CompareColor
[i
] ? curcount
[Condition
->CompareColor
[i
] - 1]: Condition
->Value
[i
];
16879 switch(Condition
->Comparator
[i
])
16881 case 2: // requires less <color> than (<value> || <comparecolor>) gems
16882 activate
&= (_cur_gem
< _cmp_gem
) ? true : false;
16884 case 3: // requires more <color> than (<value> || <comparecolor>) gems
16885 activate
&= (_cur_gem
> _cmp_gem
) ? true : false;
16887 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
16888 activate
&= (_cur_gem
>= _cmp_gem
) ? true : false;
16893 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");
16898 void Player::CorrectMetaGemEnchants(uint8 exceptslot
, bool apply
)
16900 //cycle all equipped items
16901 for(uint32 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
16903 //enchants for the slot being socketed are handled by Player::ApplyItemMods
16904 if(slot
== exceptslot
)
16907 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
16909 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
)
16912 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
16914 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
16918 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
16922 uint32 condition
= enchantEntry
->EnchantmentCondition
;
16925 //was enchant active with/without item?
16926 bool wasactive
= EnchantmentFitsRequirements(condition
, apply
? exceptslot
: -1);
16927 //should it now be?
16928 if(wasactive
^ EnchantmentFitsRequirements(condition
, apply
? -1 : exceptslot
))
16930 // ignore item gem conditions
16931 //if state changed, (dis)apply enchant
16932 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
),!wasactive
,true,true);
16939 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
16940 void Player::ToggleMetaGemsActive(uint8 exceptslot
, bool apply
)
16942 //cycle all equipped items
16943 for(int slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
16945 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
16946 if(slot
== exceptslot
)
16949 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
16951 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
) //if item has no sockets or no item is equipped go to next item
16954 //cycle all (gem)enchants
16955 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
16957 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
16958 if(!enchant_id
) //if no enchant go to next enchant(slot)
16961 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
16965 //only metagems to be (de)activated, so only enchants with condition
16966 uint32 condition
= enchantEntry
->EnchantmentCondition
;
16968 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
), apply
);
16973 void Player::LeaveBattleground(bool teleportToEntryPoint
)
16975 if(BattleGround
*bg
= GetBattleGround())
16977 bool need_debuf
= bg
->isBattleGround() && (bg
->GetStatus() == STATUS_IN_PROGRESS
) && sWorld
.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER
);
16979 bg
->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint
, true);
16981 // call after remove to be sure that player resurrected for correct cast
16983 CastSpell(this, 26013, true); // Deserter
16987 bool Player::CanJoinToBattleground() const
16989 // check Deserter debuff
16990 if(GetDummyAura(26013))
16996 bool Player::CanReportAfkDueToLimit()
16998 // a player can complain about 15 people per 5 minutes
16999 if(m_bgAfkReportedCount
>= 15)
17001 ++m_bgAfkReportedCount
;
17005 ///This player has been blamed to be inactive in a battleground
17006 void Player::ReportedAfkBy(Player
* reporter
)
17008 BattleGround
*bg
= GetBattleGround();
17009 if(!bg
|| bg
!= reporter
->GetBattleGround() || GetTeam() != reporter
->GetTeam())
17012 // check if player has 'Idle' or 'Inactive' debuff
17013 if(m_bgAfkReporter
.find(reporter
->GetGUIDLow())==m_bgAfkReporter
.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter
->CanReportAfkDueToLimit())
17015 m_bgAfkReporter
.insert(reporter
->GetGUIDLow());
17016 // 3 players have to complain to apply debuff
17017 if(m_bgAfkReporter
.size() >= 3)
17019 // cast 'Idle' spell
17020 CastSpell(this, 43680, true);
17021 m_bgAfkReporter
.clear();
17026 bool Player::IsVisibleInGridForPlayer( Player
* pl
) const
17028 // gamemaster in GM mode see all, including ghosts
17029 if(pl
->isGameMaster() && GetSession()->GetSecurity() <= pl
->GetSession()->GetSecurity())
17032 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17033 if (InBattleGround())
17035 if (!(isAlive() || m_deathTimer
> 0) && !IsFriendlyTo(pl
) )
17040 // Live player see live player or dead player with not realized corpse
17041 if(pl
->isAlive() || pl
->m_deathTimer
> 0)
17043 return isAlive() || m_deathTimer
> 0;
17046 // Ghost see other friendly ghosts, that's for sure
17047 if(!(isAlive() || m_deathTimer
> 0) && IsFriendlyTo(pl
))
17050 // Dead player see live players near own corpse
17053 Corpse
*corpse
= pl
->GetCorpse();
17056 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17057 if(corpse
->IsWithinDistInMap(this,(20+25)*sWorld
.getRate(RATE_CREATURE_AGGRO
)))
17062 // and not see any other
17066 bool Player::IsVisibleGloballyFor( Player
* u
) const
17071 // Always can see self
17075 // Visible units, always are visible for all players
17076 if (GetVisibility() == VISIBILITY_ON
)
17079 // GMs are visible for higher gms (or players are visible for gms)
17080 if (u
->GetSession()->GetSecurity() > SEC_PLAYER
)
17081 return GetSession()->GetSecurity() <= u
->GetSession()->GetSecurity();
17083 // non faction visibility non-breakable for non-GMs
17084 if (GetVisibility() == VISIBILITY_OFF
)
17087 // non-gm stealth/invisibility not hide from global player lists
17091 void Player::UpdateVisibilityOf(WorldObject
* target
)
17093 if(HaveAtClient(target
))
17095 if(!target
->isVisibleForInState(this,true))
17097 target
->DestroyForPlayer(this);
17098 m_clientGUIDs
.erase(target
->GetGUID());
17100 #ifdef MANGOS_DEBUG
17101 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17102 sLog
.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
17108 if(target
->isVisibleForInState(this,false))
17110 target
->SendUpdateToPlayer(this);
17111 if(target
->GetTypeId()!=TYPEID_GAMEOBJECT
||!((GameObject
*)target
)->IsTransport())
17112 m_clientGUIDs
.insert(target
->GetGUID());
17114 #ifdef MANGOS_DEBUG
17115 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17116 sLog
.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
17119 // target aura duration for caster show only if target exist at caster client
17120 // send data at target visibility change (adding to client)
17121 if(target
!=this && target
->isType(TYPEMASK_UNIT
))
17122 SendAuraDurationsForTarget((Unit
*)target
);
17124 if(target
->GetTypeId()==TYPEID_UNIT
&& ((Creature
*)target
)->isAlive())
17125 ((Creature
*)target
)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17131 inline void UpdateVisibilityOf_helper(std::set
<uint64
>& s64
, T
* target
)
17133 s64
.insert(target
->GetGUID());
17137 inline void UpdateVisibilityOf_helper(std::set
<uint64
>& s64
, GameObject
* target
)
17139 if(!target
->IsTransport())
17140 s64
.insert(target
->GetGUID());
17144 void Player::UpdateVisibilityOf(T
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
)
17146 if(HaveAtClient(target
))
17148 if(!target
->isVisibleForInState(this,true))
17150 target
->BuildOutOfRangeUpdateBlock(&data
);
17151 m_clientGUIDs
.erase(target
->GetGUID());
17153 #ifdef MANGOS_DEBUG
17154 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17155 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
));
17161 if(target
->isVisibleForInState(this,false))
17163 visibleNow
.insert(target
);
17164 target
->BuildUpdate(data_updates
);
17165 target
->BuildCreateUpdateBlockForPlayer(&data
, this);
17166 UpdateVisibilityOf_helper(m_clientGUIDs
,target
);
17168 #ifdef MANGOS_DEBUG
17169 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17170 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
));
17176 template void Player::UpdateVisibilityOf(Player
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17177 template void Player::UpdateVisibilityOf(Creature
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17178 template void Player::UpdateVisibilityOf(Corpse
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17179 template void Player::UpdateVisibilityOf(GameObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17180 template void Player::UpdateVisibilityOf(DynamicObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17182 void Player::InitPrimaryProffesions()
17184 SetFreePrimaryProffesions(sWorld
.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL
));
17187 void Player::SendComboPoints()
17189 Unit
*combotarget
= ObjectAccessor::GetUnit(*this, m_comboTarget
);
17192 WorldPacket
data(SMSG_UPDATE_COMBO_POINTS
, combotarget
->GetPackGUID().size()+1);
17193 data
.append(combotarget
->GetPackGUID());
17194 data
<< uint8(m_comboPoints
);
17195 GetSession()->SendPacket(&data
);
17199 void Player::AddComboPoints(Unit
* target
, int8 count
)
17204 // without combo points lost (duration checked in aura)
17205 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
17207 if(target
->GetGUID() == m_comboTarget
)
17209 m_comboPoints
+= count
;
17214 if(Unit
* target
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
17215 target
->RemoveComboPointHolder(GetGUIDLow());
17217 m_comboTarget
= target
->GetGUID();
17218 m_comboPoints
= count
;
17220 target
->AddComboPointHolder(GetGUIDLow());
17223 if (m_comboPoints
> 5) m_comboPoints
= 5;
17224 if (m_comboPoints
< 0) m_comboPoints
= 0;
17229 void Player::ClearComboPoints()
17234 // without combopoints lost (duration checked in aura)
17235 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
17241 if(Unit
* target
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
17242 target
->RemoveComboPointHolder(GetGUIDLow());
17247 void Player::SetGroup(Group
*group
, int8 subgroup
)
17249 if(group
== NULL
) m_group
.unlink();
17252 // never use SetGroup without a subgroup unless you specify NULL for group
17253 assert(subgroup
>= 0);
17254 m_group
.link(group
, this);
17255 m_group
.setSubGroup((uint8
)subgroup
);
17259 void Player::SendInitialPacketsBeforeAddToMap()
17261 WorldPacket
data(SMSG_SET_REST_START
, 4);
17262 data
<< uint32(0); // unknown, may be rest state time or experience
17263 GetSession()->SendPacket(&data
);
17266 data
.Initialize(SMSG_BINDPOINTUPDATE
, 5*4);
17267 data
<< m_homebindX
<< m_homebindY
<< m_homebindZ
;
17268 data
<< (uint32
) m_homebindMapId
;
17269 data
<< (uint32
) m_homebindZoneId
;
17270 GetSession()->SendPacket(&data
);
17272 // SMSG_SET_PROFICIENCY
17273 // SMSG_UPDATE_AURA_DURATION
17276 data
.Initialize(SMSG_TUTORIAL_FLAGS
, 8*4);
17277 for (int i
= 0; i
< 8; ++i
)
17278 data
<< uint32( GetTutorialInt(i
) );
17279 GetSession()->SendPacket(&data
);
17281 SendInitialSpells();
17283 data
.Initialize(SMSG_SEND_UNLEARN_SPELLS
, 4);
17284 data
<< uint32(0); // count, for(count) uint32;
17285 GetSession()->SendPacket(&data
);
17287 SendInitialActionButtons();
17288 SendInitialReputations();
17289 UpdateZone(GetZoneId());
17290 SendInitWorldStates();
17292 // SMSG_SET_AURA_SINGLE
17294 data
.Initialize(SMSG_LOGIN_SETTIMESPEED
, 8);
17295 data
<< uint32(secsToTimeBitFields(sWorld
.GetGameTime()));
17296 data
<< (float)0.01666667f
; // game speed
17297 GetSession()->SendPacket( &data
);
17299 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17300 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
) || isInFlight())
17301 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2
);
17304 void Player::SendInitialPacketsAfterAddToMap()
17306 CastSpell(this, 836, true); // LOGINEFFECT
17308 // set some aura effects that send packet to player client after add player to map
17309 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17310 // same auras state lost at far teleport, send it one more time in this case also
17311 static const AuraType auratypes
[] =
17313 SPELL_AURA_MOD_FEAR
, SPELL_AURA_TRANSFORM
, SPELL_AURA_WATER_WALK
,
17314 SPELL_AURA_FEATHER_FALL
, SPELL_AURA_HOVER
, SPELL_AURA_SAFE_FALL
,
17315 SPELL_AURA_FLY
, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
, SPELL_AURA_NONE
17317 for(AuraType
const* itr
= &auratypes
[0]; itr
&& itr
[0] != SPELL_AURA_NONE
; ++itr
)
17319 Unit::AuraList
const& auraList
= GetAurasByType(*itr
);
17320 if(!auraList
.empty())
17321 auraList
.front()->ApplyModifier(true,true);
17324 if(HasAuraType(SPELL_AURA_MOD_STUN
))
17325 SetMovement(MOVE_ROOT
);
17327 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17328 if(HasAuraType(SPELL_AURA_MOD_ROOT
))
17330 WorldPacket
data(SMSG_FORCE_MOVE_ROOT
, 10);
17331 data
.append(GetPackGUID());
17333 SendMessageToSet(&data
,true);
17336 SendEnchantmentDurations(); // must be after add to map
17337 SendItemDurations(); // must be after add to map
17340 void Player::SendUpdateToOutOfRangeGroupMembers()
17342 if (m_groupUpdateMask
== GROUP_UPDATE_FLAG_NONE
)
17344 if(Group
* group
= GetGroup())
17345 group
->UpdatePlayerOutOfRange(this);
17347 m_groupUpdateMask
= GROUP_UPDATE_FLAG_NONE
;
17348 m_auraUpdateMask
= 0;
17349 if(Pet
*pet
= GetPet())
17350 pet
->ResetAuraUpdateMask();
17353 void Player::SendTransferAborted(uint32 mapid
, uint16 reason
)
17355 WorldPacket
data(SMSG_TRANSFER_ABORTED
, 4+2);
17356 data
<< uint32(mapid
);
17357 data
<< uint16(reason
); // transfer abort reason
17358 GetSession()->SendPacket(&data
);
17361 void Player::SendInstanceResetWarning(uint32 mapid
, uint32 time
)
17363 // type of warning, based on the time remaining until reset
17366 type
= RAID_INSTANCE_WELCOME
;
17367 else if(time
> 900 && time
<= 3600)
17368 type
= RAID_INSTANCE_WARNING_HOURS
;
17369 else if(time
> 300 && time
<= 900)
17370 type
= RAID_INSTANCE_WARNING_MIN
;
17372 type
= RAID_INSTANCE_WARNING_MIN_SOON
;
17373 WorldPacket
data(SMSG_RAID_INSTANCE_MESSAGE
, 4+4+4);
17374 data
<< uint32(type
);
17375 data
<< uint32(mapid
);
17376 data
<< uint32(time
);
17377 GetSession()->SendPacket(&data
);
17380 void Player::ApplyEquipCooldown( Item
* pItem
)
17382 for(int i
= 0; i
<5; ++i
)
17384 _Spell
const& spellData
= pItem
->GetProto()->Spells
[i
];
17387 if( !spellData
.SpellId
)
17390 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
17391 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
)
17394 AddSpellCooldown(spellData
.SpellId
, pItem
->GetEntry(), time(NULL
) + 30);
17396 WorldPacket
data(SMSG_ITEM_COOLDOWN
, 12);
17397 data
<< pItem
->GetGUID();
17398 data
<< uint32(spellData
.SpellId
);
17399 GetSession()->SendPacket(&data
);
17403 void Player::resetSpells()
17405 // not need after this call
17406 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS
))
17408 m_atLoginFlags
= m_atLoginFlags
& ~AT_LOGIN_RESET_SPELLS
;
17409 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS
), GetGUIDLow());
17412 // make full copy of map (spells removed and marked as deleted at another spell remove
17413 // and we can't use original map for safe iterative with visit each spell at loop end
17414 PlayerSpellMap smap
= GetSpellMap();
17416 for(PlayerSpellMap::const_iterator iter
= smap
.begin();iter
!= smap
.end(); ++iter
)
17417 removeSpell(iter
->first
); // only iter->first can be accessed, object by iter->second can be deleted already
17419 learnDefaultSpells();
17420 learnQuestRewardedSpells();
17423 void Player::learnDefaultSpells(bool loading
)
17425 // learn default race/class spells
17426 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(),getClass());
17427 std::list
<CreateSpellPair
>::const_iterator spell_itr
;
17428 for (spell_itr
= info
->spell
.begin(); spell_itr
!=info
->spell
.end(); ++spell_itr
)
17430 uint16 tspell
= spell_itr
->first
;
17433 sLog
.outDebug("PLAYER: Adding initial spell, id = %u",tspell
);
17434 if(loading
|| !spell_itr
->second
) // not care about passive spells or loading case
17435 addSpell(tspell
,spell_itr
->second
);
17436 else // but send in normal spell in game learn case
17437 learnSpell(tspell
);
17442 void Player::learnQuestRewardedSpells(Quest
const* quest
)
17444 uint32 spell_id
= quest
->GetRewSpellCast();
17446 // skip quests without rewarded spell
17450 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
17454 // check learned spells state
17455 bool found
= false;
17456 for(int i
=0; i
< 3; ++i
)
17458 if(spellInfo
->Effect
[i
] == SPELL_EFFECT_LEARN_SPELL
&& !HasSpell(spellInfo
->EffectTriggerSpell
[i
]))
17465 // skip quests with not teaching spell or already known spell
17469 // prevent learn non first rank unknown profession and second specialization for same profession)
17470 uint32 learned_0
= spellInfo
->EffectTriggerSpell
[0];
17471 if( spellmgr
.GetSpellRank(learned_0
) > 1 && !HasSpell(learned_0
) )
17473 // not have first rank learned (unlearned prof?)
17474 uint32 first_spell
= spellmgr
.GetFirstSpellInChain(learned_0
);
17475 if( !HasSpell(first_spell
) )
17478 SpellEntry
const *learnedInfo
= sSpellStore
.LookupEntry(learned_0
);
17483 if(learnedInfo
->Effect
[0]==SPELL_EFFECT_TRADE_SKILL
&& learnedInfo
->Effect
[1]==0)
17485 // search other specialization for same prof
17486 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
17488 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->first
==learned_0
)
17491 SpellEntry
const *itrInfo
= sSpellStore
.LookupEntry(itr
->first
);
17495 // compare only specializations
17496 if(itrInfo
->Effect
[0]!=SPELL_EFFECT_TRADE_SKILL
|| itrInfo
->Effect
[1]!=0)
17499 // compare same chain spells
17500 if(spellmgr
.GetFirstSpellInChain(itr
->first
) != first_spell
)
17503 // now we have 2 specialization, learn possible only if found is lesser specialization rank
17504 if(!spellmgr
.IsHighRankOfSpell(learned_0
,itr
->first
))
17510 CastSpell( this, spell_id
, true);
17513 void Player::learnQuestRewardedSpells()
17515 // learn spells received from quest completing
17516 for(QuestStatusMap::const_iterator itr
= mQuestStatus
.begin(); itr
!= mQuestStatus
.end(); ++itr
)
17518 // skip no rewarded quests
17519 if(!itr
->second
.m_rewarded
)
17522 Quest
const* quest
= objmgr
.GetQuestTemplate(itr
->first
);
17526 learnQuestRewardedSpells(quest
);
17530 void Player::learnSkillRewardedSpells(uint32 skill_id
)
17532 uint32 raceMask
= getRaceMask();
17533 uint32 classMask
= getClassMask();
17534 for (uint32 j
=0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
17536 SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
);
17537 if (!pAbility
|| pAbility
->skillId
!=skill_id
|| pAbility
->learnOnGetSkill
!= ABILITY_LEARNED_ON_GET_PROFESSION_SKILL
)
17539 // Check race if set
17540 if (pAbility
->racemask
&& !(pAbility
->racemask
& raceMask
))
17542 // Check class if set
17543 if (pAbility
->classmask
&& !(pAbility
->classmask
& classMask
))
17546 if (sSpellStore
.LookupEntry(pAbility
->spellId
))
17548 // Ok need learn spell
17549 learnSpell(pAbility
->spellId
);
17554 void Player::learnSkillRewardedSpells()
17556 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
17558 if(!GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
17561 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
17563 learnSkillRewardedSpells(pskill
);
17567 void Player::SendAuraDurationsForTarget(Unit
* target
)
17569 for(Unit::AuraMap::const_iterator itr
= target
->GetAuras().begin(); itr
!= target
->GetAuras().end(); ++itr
)
17571 Aura
* aura
= itr
->second
;
17572 if(aura
->GetAuraSlot() >= MAX_AURAS
|| aura
->IsPassive() || aura
->GetCasterGUID()!=GetGUID())
17575 aura
->SendAuraDurationForCaster(this);
17579 void Player::SetDailyQuestStatus( uint32 quest_id
)
17581 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
17583 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
17585 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
17586 m_lastDailyQuestTime
= time(NULL
); // last daily quest time
17587 m_DailyQuestChanged
= true;
17593 void Player::ResetDailyQuestStatus()
17595 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
17596 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
17598 // DB data deleted in caller
17599 m_DailyQuestChanged
= false;
17600 m_lastDailyQuestTime
= 0;
17603 BattleGround
* Player::GetBattleGround() const
17605 if(GetBattleGroundId()==0)
17608 return sBattleGroundMgr
.GetBattleGround(GetBattleGroundId());
17611 bool Player::InArena() const
17613 BattleGround
*bg
= GetBattleGround();
17614 if(!bg
|| !bg
->isArena())
17620 bool Player::GetBGAccessByLevel(uint32 bgTypeId
) const
17622 BattleGround
*bg
= sBattleGroundMgr
.GetBattleGround(bgTypeId
);
17626 if(getLevel() < bg
->GetMinLevel() || getLevel() > bg
->GetMaxLevel())
17632 uint32
Player::GetMinLevelForBattleGroundQueueId(uint32 queue_id
)
17640 return 10*(queue_id
+1);
17643 uint32
Player::GetMaxLevelForBattleGroundQueueId(uint32 queue_id
)
17646 return 255; // hardcoded max level
17648 return 10*(queue_id
+2)-1;
17651 uint32
Player::GetBattleGroundQueueIdFromLevel() const
17653 uint32 level
= getLevel();
17656 else if (level
> 69)
17659 return level
/10 - 1; // 20..29 -> 1, 30-39 -> 2, ...
17662 float Player::GetReputationPriceDiscount( Creature
const* pCreature
) const
17664 FactionTemplateEntry
const* vendor_faction
= pCreature
->getFactionTemplateEntry();
17665 if(!vendor_faction
)
17668 ReputationRank rank
= GetReputationRank(vendor_faction
->faction
);
17669 if(rank
<= REP_NEUTRAL
)
17672 return 1.0f
- 0.05f
* (rank
- REP_NEUTRAL
);
17675 bool Player::IsSpellFitByClassAndRace( uint32 spell_id
) const
17677 uint32 racemask
= getRaceMask();
17678 uint32 classmask
= getClassMask();
17680 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
17681 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
17683 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
17685 // skip wrong race skills
17686 if( _spell_idx
->second
->racemask
&& (_spell_idx
->second
->racemask
& racemask
) == 0)
17689 // skip wrong class skills
17690 if( _spell_idx
->second
->classmask
&& (_spell_idx
->second
->classmask
& classmask
) == 0)
17696 bool Player::HasQuestForGO(int32 GOId
)
17698 for( QuestStatusMap::iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
17700 QuestStatusData qs
=i
->second
;
17701 if (qs
.m_status
== QUEST_STATUS_INCOMPLETE
)
17703 Quest
const* qinfo
= objmgr
.GetQuestTemplate(i
->first
);
17707 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
17710 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
17712 if (qinfo
->ReqCreatureOrGOId
[j
]>=0) //skip non GO case
17715 if((-1)*GOId
== qinfo
->ReqCreatureOrGOId
[j
] && qs
.m_creatureOrGOcount
[j
] < qinfo
->ReqCreatureOrGOCount
[j
])
17723 void Player::UpdateForQuestsGO()
17725 if(m_clientGUIDs
.empty())
17729 WorldPacket packet
;
17730 for(ClientGUIDs::iterator itr
=m_clientGUIDs
.begin(); itr
!=m_clientGUIDs
.end(); ++itr
)
17732 if(IS_GAMEOBJECT_GUID(*itr
))
17734 GameObject
*obj
= HashMapHolder
<GameObject
>::Find(*itr
);
17736 obj
->BuildValuesUpdateBlockForPlayer(&udata
,this);
17739 udata
.BuildPacket(&packet
);
17740 GetSession()->SendPacket(&packet
);
17743 void Player::SummonIfPossible(bool agree
)
17747 m_summon_expire
= 0;
17751 // expire and auto declined
17752 if(m_summon_expire
< time(NULL
))
17755 // stop taxi flight at summon
17758 GetMotionMaster()->MovementExpired();
17759 m_taxi
.ClearTaxiDestinations();
17762 // drop flag at summon
17763 if(BattleGround
*bg
= GetBattleGround())
17764 bg
->EventPlayerDroppedFlag(this);
17766 m_summon_expire
= 0;
17768 TeleportTo(m_summon_mapid
, m_summon_x
, m_summon_y
, m_summon_z
,GetOrientation());
17771 void Player::RemoveItemDurations( Item
*item
)
17773 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); ++itr
)
17777 m_itemDuration
.erase(itr
);
17783 void Player::AddItemDurations( Item
*item
)
17785 if(item
->GetUInt32Value(ITEM_FIELD_DURATION
))
17787 m_itemDuration
.push_back(item
);
17788 item
->SendTimeUpdate(this);
17792 void Player::AutoUnequipOffhandIfNeed()
17794 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
17798 Item
*mainItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_MAINHAND
);
17800 if(!mainItem
|| mainItem
->GetProto()->InventoryType
!= INVTYPE_2HWEAPON
)
17803 ItemPosCountVec off_dest
;
17804 uint8 off_msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false );
17805 if( off_msg
== EQUIP_ERR_OK
)
17807 RemoveItem(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
, true);
17808 StoreItem( off_dest
, offItem
, true );
17812 sLog
.outError("Player::EquipItem: Can's store offhand item at 2hand item equip for player (GUID: %u).",GetGUIDLow());
17816 bool Player::HasItemFitToSpellReqirements(SpellEntry
const* spellInfo
, Item
const* ignoreItem
)
17818 if(spellInfo
->EquippedItemClass
< 0)
17821 // scan other equipped items for same requirements (mostly 2 daggers/etc)
17822 // for optimize check 2 used cases only
17823 switch(spellInfo
->EquippedItemClass
)
17825 case ITEM_CLASS_WEAPON
:
17827 for(int i
= EQUIPMENT_SLOT_MAINHAND
; i
< EQUIPMENT_SLOT_TABARD
; ++i
)
17828 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
17829 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
17833 case ITEM_CLASS_ARMOR
:
17835 // tabard not have dependent spells
17836 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_MAINHAND
; ++i
)
17837 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
17838 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
17841 // shields can be equipped to offhand slot
17842 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
))
17843 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
17846 // ranged slot can have some armor subclasses
17847 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_RANGED
))
17848 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
17854 sLog
.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo
->EquippedItemClass
);
17861 void Player::RemoveItemDependentAurasAndCasts( Item
* pItem
)
17863 AuraMap
& auras
= GetAuras();
17864 for(AuraMap::iterator itr
= auras
.begin(); itr
!= auras
.end(); )
17866 Aura
* aura
= itr
->second
;
17868 // skip passive (passive item dependent spells work in another way) and not self applied auras
17869 SpellEntry
const* spellInfo
= aura
->GetSpellProto();
17870 if(aura
->IsPassive() || aura
->GetCasterGUID()!=GetGUID())
17876 // skip if not item dependent or have alternative item
17877 if(HasItemFitToSpellReqirements(spellInfo
,pItem
))
17883 // no alt item, remove aura, restart check
17884 RemoveAurasDueToSpell(aura
->GetId());
17885 itr
= auras
.begin();
17888 // currently casted spells can be dependent from item
17889 for (uint32 i
= 0; i
< CURRENT_MAX_SPELL
; i
++)
17891 if( m_currentSpells
[i
] && m_currentSpells
[i
]->getState()!=SPELL_STATE_DELAYED
&&
17892 !HasItemFitToSpellReqirements(m_currentSpells
[i
]->m_spellInfo
,pItem
) )
17897 uint32
Player::GetResurrectionSpellId()
17899 // search priceless resurrection possibilities
17901 uint32 spell_id
= 0;
17902 AuraList
const& dummyAuras
= GetAurasByType(SPELL_AURA_DUMMY
);
17903 for(AuraList::const_iterator itr
= dummyAuras
.begin(); itr
!= dummyAuras
.end(); ++itr
)
17905 // Soulstone Resurrection // prio: 3 (max, non death persistent)
17906 if( prio
< 2 && (*itr
)->GetSpellProto()->SpellVisual
== 99 && (*itr
)->GetSpellProto()->SpellIconID
== 92 )
17908 switch((*itr
)->GetId())
17910 case 20707: spell_id
= 3026; break; // rank 1
17911 case 20762: spell_id
= 20758; break; // rank 2
17912 case 20763: spell_id
= 20759; break; // rank 3
17913 case 20764: spell_id
= 20760; break; // rank 4
17914 case 20765: spell_id
= 20761; break; // rank 5
17915 case 27239: spell_id
= 27240; break; // rank 6
17917 sLog
.outError("Unhandled spell %%u: S.Resurrection",(*itr
)->GetId());
17923 // Twisting Nether // prio: 2 (max)
17924 else if((*itr
)->GetId()==23701 && roll_chance_i(10))
17931 // Reincarnation (passive spell) // prio: 1
17932 if(prio
< 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
17938 bool Player::RewardPlayerAndGroupAtKill(Unit
* pVictim
)
17940 bool PvP
= pVictim
->isCharmedOwnedByPlayerOrPlayer();
17942 // prepare data for near group iteration (PvP and !PvP cases)
17944 bool honored_kill
= false;
17946 if(Group
*pGroup
= GetGroup())
17949 uint32 sum_level
= 0;
17950 Player
* member_with_max_level
= NULL
;
17951 Player
* not_gray_member_with_max_level
= NULL
;
17953 pGroup
->GetDataForXPAtKill(pVictim
,count
,sum_level
,member_with_max_level
,not_gray_member_with_max_level
);
17955 if(member_with_max_level
)
17957 /// not get Xp in PvP or no not gray players in group
17958 xp
= (PvP
|| !not_gray_member_with_max_level
) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level
, pVictim
);
17960 /// skip in check PvP case (for speed, not used)
17961 bool is_raid
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsRaid() && pGroup
->isRaidGroup();
17962 bool is_dungeon
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsDungeon();
17963 float group_rate
= MaNGOS::XP::xp_in_group_rate(count
,is_raid
);
17965 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
17967 Player
* pGroupGuy
= itr
->getSource();
17971 if(!pGroupGuy
->IsAtGroupRewardDistance(pVictim
))
17972 continue; // member (alive or dead) or his corpse at req. distance
17974 // honor can be in PvP and !PvP (racial leader) cases (for alive)
17975 if(pGroupGuy
->isAlive() && pGroupGuy
->RewardHonor(pVictim
,count
) && pGroupGuy
==this)
17976 honored_kill
= true;
17978 // xp and reputation only in !PvP case
17981 float rate
= group_rate
* float(pGroupGuy
->getLevel()) / sum_level
;
17983 // if is in dungeon then all receive full reputation at kill
17984 // rewarded any alive/dead/near_corpse group member
17985 pGroupGuy
->RewardReputation(pVictim
,is_dungeon
? 1.0f
: rate
);
17987 // XP updated only for alive group member
17988 if(pGroupGuy
->isAlive() && not_gray_member_with_max_level
&&
17989 pGroupGuy
->getLevel() <= not_gray_member_with_max_level
->getLevel())
17991 uint32 itr_xp
= (member_with_max_level
== not_gray_member_with_max_level
) ? uint32(xp
*rate
) : uint32((xp
*rate
/2)+1);
17993 pGroupGuy
->GiveXP(itr_xp
, pVictim
);
17994 if(Pet
* pet
= pGroupGuy
->GetPet())
17995 pet
->GivePetXP(itr_xp
/2);
17998 // quest objectives updated only for alive group member or dead but with not released body
17999 if(pGroupGuy
->isAlive()|| !pGroupGuy
->GetCorpse())
18001 // normal creature (not pet/etc) can be only in !PvP case
18002 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
18003 pGroupGuy
->KilledMonster(pVictim
->GetEntry(), pVictim
->GetGUID());
18009 else // if (!pGroup)
18011 xp
= PvP
? 0 : MaNGOS::XP::Gain(this, pVictim
);
18013 // honor can be in PvP and !PvP (racial leader) cases
18014 if(RewardHonor(pVictim
,1))
18015 honored_kill
= true;
18017 // xp and reputation only in !PvP case
18020 RewardReputation(pVictim
,1);
18021 GiveXP(xp
, pVictim
);
18023 if(Pet
* pet
= GetPet())
18024 pet
->GivePetXP(xp
);
18026 // normal creature (not pet/etc) can be only in !PvP case
18027 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
18028 KilledMonster(pVictim
->GetEntry(),pVictim
->GetGUID());
18031 return xp
|| honored_kill
;
18034 bool Player::IsAtGroupRewardDistance(WorldObject
const* pRewardSource
) const
18036 if(pRewardSource
->GetDistance(this) <= sWorld
.getConfig(CONFIG_GROUP_XP_DISTANCE
))
18042 Corpse
* corpse
= GetCorpse();
18046 return pRewardSource
->GetDistance(corpse
) <= sWorld
.getConfig(CONFIG_GROUP_XP_DISTANCE
);
18049 uint32
Player::GetBaseWeaponSkillValue (WeaponAttackType attType
) const
18051 Item
* item
= GetWeaponForAttack(attType
,true);
18053 // unarmed only with base attack
18054 if(attType
!= BASE_ATTACK
&& !item
)
18057 // weapon skill or (unarmed for base attack)
18058 uint32 skill
= item
? item
->GetSkill() : SKILL_UNARMED
;
18059 return GetBaseSkillValue(skill
);
18062 void Player::ResurectUsingRequestData()
18064 ResurrectPlayer(0.0f
,false);
18066 if(GetMaxHealth() > m_resurrectHealth
)
18067 SetHealth( m_resurrectHealth
);
18069 SetHealth( GetMaxHealth() );
18071 if(GetMaxPower(POWER_MANA
) > m_resurrectMana
)
18072 SetPower(POWER_MANA
, m_resurrectMana
);
18074 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
) );
18076 SetPower(POWER_RAGE
, 0 );
18078 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
) );
18080 SpawnCorpseBones();
18082 TeleportTo(m_resurrectMap
, m_resurrectX
, m_resurrectY
, m_resurrectZ
, GetOrientation());
18085 void Player::SetClientControl(Unit
* target
, uint8 allowMove
)
18087 WorldPacket
data(SMSG_CLIENT_CONTROL_UPDATE
, target
->GetPackGUID().size()+1);
18088 data
.append(target
->GetPackGUID());
18089 data
<< uint8(allowMove
);
18090 GetSession()->SendPacket(&data
);
18093 void Player::UpdateZoneDependentAuras( uint32 newZone
)
18095 // remove new continent flight forms
18096 if( !isGameMaster() &&
18097 GetVirtualMapForMapAndZone(GetMapId(),newZone
) != 530)
18099 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
);
18100 RemoveSpellsCausingAura(SPELL_AURA_FLY
);
18103 // Some spells applied at enter into zone (with subzones)
18105 // NOTE: these are removed by RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
18106 if ( newZone
== 2367 ) // Old Hillsbrad Foothills
18108 uint32 spellid
= 0;
18110 if( GetTeam() == HORDE
)
18111 spellid
= getGender() == GENDER_FEMALE
? 35481 : 35480;
18112 // and some alliance races
18113 else if( getRace() == RACE_NIGHTELF
|| getRace() == RACE_DRAENEI
)
18114 spellid
= getGender() == GENDER_FEMALE
? 35483 : 35482;
18116 if(spellid
&& !HasAura(spellid
,0) )
18117 CastSpell(this,spellid
,true);
18121 void Player::UpdateAreaDependentAuras( uint32 newArea
)
18123 // remove auras from spells with area limitations
18124 for(AuraMap::iterator iter
= m_Auras
.begin(); iter
!= m_Auras
.end();)
18126 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18127 if(!IsSpellAllowedInLocation(iter
->second
->GetSpellProto(),GetMapId(),m_zoneUpdateId
,newArea
))
18133 // unmount if enter in this subzone
18135 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED
);
18136 // Dragonmaw Illusion
18137 else if( newArea
== 3759 || newArea
== 3966 || newArea
== 3939 )
18139 if( GetDummyAura(40214) )
18141 if( !HasAura(40216,0) )
18142 CastSpell(this,40216,true);
18143 if( !HasAura(42016,0) )
18144 CastSpell(this,42016,true);
18149 uint32
Player::GetCorpseReclaimDelay(bool pvp
) const
18151 if( pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18152 !pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18154 return copseReclaimDelay
[0];
18157 time_t now
= time(NULL
);
18158 // 0..2 full period
18159 uint32 count
= (now
< m_deathExpireTime
) ? (m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
: 0;
18160 return copseReclaimDelay
[count
];
18163 void Player::UpdateCorpseReclaimDelay()
18165 bool pvp
= m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
;
18167 if( pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18168 !pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18171 time_t now
= time(NULL
);
18172 if(now
< m_deathExpireTime
)
18174 // full and partly periods 1..3
18175 uint32 count
= (m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
+1;
18176 if(count
< MAX_DEATH_COUNT
)
18177 m_deathExpireTime
= now
+(count
+1)*DEATH_EXPIRE_STEP
;
18179 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
;
18182 m_deathExpireTime
= now
+DEATH_EXPIRE_STEP
;
18185 void Player::SendCorpseReclaimDelay(bool load
)
18187 Corpse
* corpse
= GetCorpse();
18194 if(corpse
->GetGhostTime() > m_deathExpireTime
)
18197 bool pvp
= corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
;
18200 if( pvp
&& sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18201 !pvp
&& sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18203 count
= (m_deathExpireTime
-corpse
->GetGhostTime())/DEATH_EXPIRE_STEP
;
18204 if(count
>=MAX_DEATH_COUNT
)
18205 count
= MAX_DEATH_COUNT
-1;
18210 time_t expected_time
= corpse
->GetGhostTime()+copseReclaimDelay
[count
];
18212 time_t now
= time(NULL
);
18213 if(now
>= expected_time
)
18216 delay
= expected_time
-now
;
18219 delay
= GetCorpseReclaimDelay(corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
);
18221 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
18222 WorldPacket
data(SMSG_CORPSE_RECLAIM_DELAY
, 4);
18223 data
<< uint32(delay
*1000);
18224 GetSession()->SendPacket( &data
);
18227 Player
* Player::GetNextRandomRaidMember(float radius
)
18229 Group
*pGroup
= GetGroup();
18233 std::vector
<Player
*> nearMembers
;
18234 nearMembers
.reserve(pGroup
->GetMembersCount());
18236 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
18238 Player
* Target
= itr
->getSource();
18240 // IsHostileTo check duel and controlled by enemy
18241 if( Target
&& Target
!= this && IsWithinDistInMap(Target
, radius
) &&
18242 !Target
->HasInvisibilityAura() && !IsHostileTo(Target
) )
18243 nearMembers
.push_back(Target
);
18246 if (nearMembers
.empty())
18249 uint32 randTarget
= urand(0,nearMembers
.size()-1);
18250 return nearMembers
[randTarget
];
18253 PartyResult
Player::CanUninviteFromGroup() const
18255 const Group
* grp
= GetGroup();
18257 return PARTY_RESULT_YOU_NOT_IN_GROUP
;
18259 if(!grp
->IsLeader(GetGUID()) && !grp
->IsAssistant(GetGUID()))
18260 return PARTY_RESULT_YOU_NOT_LEADER
;
18262 if(InBattleGround())
18263 return PARTY_RESULT_INVITE_RESTRICTED
;
18265 return PARTY_RESULT_OK
;
18268 void Player::UpdateUnderwaterState( Map
* m
, float x
, float y
, float z
)
18270 float water_z
= m
->GetWaterLevel(x
,y
);
18271 float height_z
= m
->GetHeight(x
,y
,z
, false); // use .map base surface height
18272 uint8 flag1
= m
->GetTerrainType(x
,y
);
18274 //!Underwater check, not in water if underground or above water level
18275 if (height_z
<= INVALID_HEIGHT
|| z
< (height_z
-2) || z
> (water_z
- 2) )
18276 m_isunderwater
&= 0x7A;
18277 else if ((z
< (water_z
- 2)) && (flag1
& 0x01))
18278 m_isunderwater
|= 0x01;
18280 //!in lava check, anywhere under lava level
18281 if ((height_z
<= INVALID_HEIGHT
|| z
< (height_z
- 0)) && (flag1
== 0x00) && IsInWater())
18282 m_isunderwater
|= 0x80;
18285 void Player::SetCanParry( bool value
)
18287 if(m_canParry
==value
)
18290 m_canParry
= value
;
18291 UpdateParryPercentage();
18294 void Player::SetCanBlock( bool value
)
18296 if(m_canBlock
==value
)
18299 m_canBlock
= value
;
18300 UpdateBlockPercentage();
18303 bool ItemPosCount::isContainedIn(ItemPosCountVec
const& vec
) const
18305 for(ItemPosCountVec::const_iterator itr
= vec
.begin(); itr
!= vec
.end();++itr
)
18306 if(itr
->pos
== pos
)
18312 bool Player::isAllowUseBattleGroundObject()
18314 return ( //InBattleGround() && // in battleground - not need, check in other cases
18315 !IsMounted() && // not mounted
18316 !HasStealthAura() && // not stealthed
18317 !HasInvisibilityAura() && // not invisible
18318 !HasAura(SPELL_RECENTLY_DROPPED_FLAG
, 0) && // can't pickup
18319 isAlive() // live player
18323 bool Player::HasTitle(uint32 bitIndex
)
18325 if (bitIndex
> 128)
18328 uint32 fieldIndexOffset
= bitIndex
/32;
18329 uint32 flag
= 1 << (bitIndex
%32);
18330 return HasFlag(PLAYER__FIELD_KNOWN_TITLES
+fieldIndexOffset
, flag
);
18333 void Player::SetTitle(CharTitlesEntry
const* title
)
18335 uint32 fieldIndexOffset
= title
->bit_index
/32;
18336 uint32 flag
= 1 << (title
->bit_index
%32);
18337 SetFlag(PLAYER__FIELD_KNOWN_TITLES
+fieldIndexOffset
, flag
);