2 * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 #include "Database/DatabaseEnv.h"
26 #include "WorldPacket.h"
27 #include "WorldSession.h"
28 #include "UpdateMask.h"
31 #include "SkillDiscovery.h"
33 #include "GossipDef.h"
34 #include "UpdateData.h"
36 #include "ChannelMgr.h"
37 #include "MapManager.h"
38 #include "MapInstanced.h"
39 #include "InstanceSaveMgr.h"
40 #include "GridNotifiers.h"
41 #include "GridNotifiersImpl.h"
43 #include "ObjectMgr.h"
44 #include "ObjectAccessor.h"
45 #include "CreatureAI.h"
51 #include "Transports.h"
53 #include "BattleGround.h"
54 #include "BattleGroundMgr.h"
55 #include "ArenaTeam.h"
57 #include "Database/DatabaseImpl.h"
59 #include "SocialMgr.h"
60 #include "AchievementMgr.h"
64 #define ZONE_UPDATE_INTERVAL (1*IN_MILISECONDS)
66 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
67 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
68 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
70 #define SKILL_VALUE(x) PAIR32_LOPART(x)
71 #define SKILL_MAX(x) PAIR32_HIPART(x)
72 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
74 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
75 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
76 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
80 CHARACTER_FLAG_NONE
= 0x00000000,
81 CHARACTER_FLAG_UNK1
= 0x00000001,
82 CHARACTER_FLAG_UNK2
= 0x00000002,
83 CHARACTER_LOCKED_FOR_TRANSFER
= 0x00000004,
84 CHARACTER_FLAG_UNK4
= 0x00000008,
85 CHARACTER_FLAG_UNK5
= 0x00000010,
86 CHARACTER_FLAG_UNK6
= 0x00000020,
87 CHARACTER_FLAG_UNK7
= 0x00000040,
88 CHARACTER_FLAG_UNK8
= 0x00000080,
89 CHARACTER_FLAG_UNK9
= 0x00000100,
90 CHARACTER_FLAG_UNK10
= 0x00000200,
91 CHARACTER_FLAG_HIDE_HELM
= 0x00000400,
92 CHARACTER_FLAG_HIDE_CLOAK
= 0x00000800,
93 CHARACTER_FLAG_UNK13
= 0x00001000,
94 CHARACTER_FLAG_GHOST
= 0x00002000,
95 CHARACTER_FLAG_RENAME
= 0x00004000,
96 CHARACTER_FLAG_UNK16
= 0x00008000,
97 CHARACTER_FLAG_UNK17
= 0x00010000,
98 CHARACTER_FLAG_UNK18
= 0x00020000,
99 CHARACTER_FLAG_UNK19
= 0x00040000,
100 CHARACTER_FLAG_UNK20
= 0x00080000,
101 CHARACTER_FLAG_UNK21
= 0x00100000,
102 CHARACTER_FLAG_UNK22
= 0x00200000,
103 CHARACTER_FLAG_UNK23
= 0x00400000,
104 CHARACTER_FLAG_UNK24
= 0x00800000,
105 CHARACTER_FLAG_LOCKED_BY_BILLING
= 0x01000000,
106 CHARACTER_FLAG_DECLINED
= 0x02000000,
107 CHARACTER_FLAG_UNK27
= 0x04000000,
108 CHARACTER_FLAG_UNK28
= 0x08000000,
109 CHARACTER_FLAG_UNK29
= 0x10000000,
110 CHARACTER_FLAG_UNK30
= 0x20000000,
111 CHARACTER_FLAG_UNK31
= 0x40000000,
112 CHARACTER_FLAG_UNK32
= 0x80000000
115 // corpse reclaim times
116 #define DEATH_EXPIRE_STEP (5*MINUTE)
117 #define MAX_DEATH_COUNT 3
119 static uint32 copseReclaimDelay
[MAX_DEATH_COUNT
] = { 30, 60, 120 };
121 //== PlayerTaxi ================================================
123 PlayerTaxi::PlayerTaxi()
126 memset(m_taximask
, 0, sizeof(m_taximask
));
129 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race
, uint32 chrClass
, uint32 level
)
131 // class specific initial known nodes
134 case CLASS_DEATH_KNIGHT
:
136 for(int i
= 0; i
< TaxiMaskSize
; ++i
)
137 m_taximask
[i
] |= sOldContinentsNodesMask
[i
];
142 // race specific initial known nodes: capital and taxi hub masks
145 case RACE_HUMAN
: SetTaximaskNode(2); break; // Human
146 case RACE_ORC
: SetTaximaskNode(23); break; // Orc
147 case RACE_DWARF
: SetTaximaskNode(6); break; // Dwarf
148 case RACE_NIGHTELF
: SetTaximaskNode(26);
149 SetTaximaskNode(27); break; // Night Elf
150 case RACE_UNDEAD_PLAYER
: SetTaximaskNode(11); break;// Undead
151 case RACE_TAUREN
: SetTaximaskNode(22); break; // Tauren
152 case RACE_GNOME
: SetTaximaskNode(6); break; // Gnome
153 case RACE_TROLL
: SetTaximaskNode(23); break; // Troll
154 case RACE_BLOODELF
: SetTaximaskNode(82); break; // Blood Elf
155 case RACE_DRAENEI
: SetTaximaskNode(94); break; // Draenei
158 // new continent starting masks (It will be accessible only at new map)
159 switch(Player::TeamForRace(race
))
161 case ALLIANCE
: SetTaximaskNode(100); break;
162 case HORDE
: SetTaximaskNode(99); break;
164 // level dependent taxi hubs
166 SetTaximaskNode(213); //Shattered Sun Staging Area
169 void PlayerTaxi::LoadTaxiMask(const char* data
)
171 Tokens tokens
= StrSplit(data
, " ");
174 Tokens::iterator iter
;
175 for (iter
= tokens
.begin(), index
= 0;
176 (index
< TaxiMaskSize
) && (iter
!= tokens
.end()); ++iter
, ++index
)
178 // load and set bits only for existed taxi nodes
179 m_taximask
[index
] = sTaxiNodesMask
[index
] & uint32(atol((*iter
).c_str()));
183 void PlayerTaxi::AppendTaximaskTo( ByteBuffer
& data
, bool all
)
187 for (uint8 i
=0; i
<TaxiMaskSize
; i
++)
188 data
<< uint32(sTaxiNodesMask
[i
]); // all existed nodes
192 for (uint8 i
=0; i
<TaxiMaskSize
; i
++)
193 data
<< uint32(m_taximask
[i
]); // known nodes
197 bool PlayerTaxi::LoadTaxiDestinationsFromString( const std::string
& values
, uint32 team
)
199 ClearTaxiDestinations();
201 Tokens tokens
= StrSplit(values
," ");
203 for(Tokens::iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
)
205 uint32 node
= uint32(atol(iter
->c_str()));
206 AddTaxiDestination(node
);
209 if(m_TaxiDestinations
.empty())
213 if(m_TaxiDestinations
.size() < 2)
216 for(size_t i
= 1; i
< m_TaxiDestinations
.size(); ++i
)
220 objmgr
.GetTaxiPath(m_TaxiDestinations
[i
-1],m_TaxiDestinations
[i
],path
,cost
);
225 // can't load taxi path without mount set (quest taxi path?)
226 if(!objmgr
.GetTaxiMount(GetTaxiSource(),team
))
232 std::string
PlayerTaxi::SaveTaxiDestinationsToString()
234 if(m_TaxiDestinations
.empty())
237 std::ostringstream ss
;
239 for(size_t i
=0; i
< m_TaxiDestinations
.size(); ++i
)
240 ss
<< m_TaxiDestinations
[i
] << " ";
245 uint32
PlayerTaxi::GetCurrentTaxiPath() const
247 if(m_TaxiDestinations
.size() < 2)
253 objmgr
.GetTaxiPath(m_TaxiDestinations
[0],m_TaxiDestinations
[1],path
,cost
);
258 std::ostringstream
& operator<< (std::ostringstream
& ss
, PlayerTaxi
const& taxi
)
261 for(int i
= 0; i
< TaxiMaskSize
; ++i
)
262 ss
<< taxi
.m_taximask
[i
] << " ";
267 //== Player ====================================================
269 UpdateMask
Player::updateVisualBits
;
271 Player::Player (WorldSession
*session
): Unit(), m_achievementMgr(this), m_reputationMgr(this)
278 m_objectType
|= TYPEMASK_PLAYER
;
279 m_objectTypeId
= TYPEID_PLAYER
;
281 m_valuesCount
= PLAYER_END
;
288 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER
)
289 SetAcceptTicket(true);
291 // players always accept
292 if(GetSession()->GetSecurity() == SEC_PLAYER
)
293 SetAcceptWhispers(true);
301 m_usedTalentCount
= 0;
302 m_questRewardTalentCount
= 0;
305 m_weaponChangeTimer
= 0;
308 m_zoneUpdateTimer
= 0;
312 m_nextSave
= sWorld
.getConfig(CONFIG_INTERVAL_SAVE
);
314 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
315 // this must help in case next save after mass player load after server startup
316 m_nextSave
= urand(m_nextSave
/2,m_nextSave
*3/2);
318 clearResurrectRequestData();
320 m_SpellModRemoveCount
= 0;
322 memset(m_items
, 0, sizeof(Item
*)*PLAYER_SLOTS_COUNT
);
326 // group is initialized in the reference constructor
327 SetGroupInvite(NULL
);
328 m_groupUpdateMask
= 0;
329 m_auraUpdateMask
= 0;
333 m_GuildIdInvited
= 0;
334 m_ArenaTeamIdInvited
= 0;
336 m_atLoginFlags
= AT_LOGIN_NONE
;
345 PlayerTalkClass
= new PlayerMenu( GetSession() );
346 m_currentBuybackSlot
= BUYBACK_SLOT_START
;
348 for ( int aX
= 0 ; aX
< 8 ; aX
++ )
349 m_Tutorials
[ aX
] = 0x00;
350 m_TutorialsChanged
= false;
352 m_DailyQuestChanged
= false;
353 m_lastDailyQuestTime
= 0;
355 for (int i
=0; i
<MAX_TIMERS
; i
++)
356 m_MirrorTimer
[i
] = DISABLED_MIRROR_TIMER
;
358 m_MirrorTimerFlags
= UNDERWATER_NONE
;
359 m_MirrorTimerFlagsLast
= UNDERWATER_NONE
;
365 m_deathExpireTime
= 0;
369 m_DetectInvTimer
= 1*IN_MILISECONDS
;
371 m_bgBattleGroundID
= 0;
372 m_bgTypeID
= BATTLEGROUND_TYPE_NONE
;
373 for (int j
=0; j
< PLAYER_MAX_BATTLEGROUND_QUEUES
; j
++)
375 m_bgBattleGroundQueueID
[j
].bgQueueTypeId
= BATTLEGROUND_QUEUE_NONE
;
376 m_bgBattleGroundQueueID
[j
].invitedToInstance
= 0;
380 m_logintime
= time(NULL
);
381 m_Last_tick
= m_logintime
;
382 m_WeaponProficiency
= 0;
383 m_ArmorProficiency
= 0;
386 m_canDualWield
= false;
387 m_canTitanGrip
= false;
390 m_temporaryUnsummonedPetNumber
= 0;
391 //cache for UNIT_CREATED_BY_SPELL to allow
392 //returning reagents for temporarily removed pets
393 //when dying/logging out
396 ////////////////////Rest System/////////////////////
403 rest_type
=REST_TYPE_NO
;
404 ////////////////////Rest System/////////////////////
406 m_mailsLoaded
= false;
407 m_mailsUpdated
= false;
409 m_nextMailDelivereTime
= 0;
411 m_resetTalentsCost
= 0;
412 m_resetTalentsTime
= 0;
413 m_itemUpdateQueueBlocked
= false;
415 for (int i
= 0; i
< MAX_MOVE_TYPE
; ++i
)
416 m_forced_speed_changes
[i
] = 0;
420 /////////////////// Instance System /////////////////////
423 m_InstanceValid
= true;
424 m_dungeonDifficulty
= DIFFICULTY_NORMAL
;
428 for (int i
= 0; i
< BASEMOD_END
; i
++)
430 m_auraBaseMod
[i
][FLAT_MOD
] = 0.0f
;
431 m_auraBaseMod
[i
][PCT_MOD
] = 1.0f
;
434 for (int i
= 0; i
< MAX_COMBAT_RATING
; i
++)
435 m_baseRatingValue
[i
] = 0;
437 m_baseSpellDamage
= 0;
438 m_baseSpellHealing
= 0;
443 m_lastHonorUpdateTime
= time(NULL
);
452 //Default movement to run mode
453 m_unit_movement_flags
= 0;
458 m_bgAfkReportedTimer
= 0;
459 m_contestedPvPTimer
= 0;
461 m_declinedname
= NULL
;
470 CleanupsBeforeDelete();
472 // it must be unloaded already in PlayerLogout and accessed only for loggined player
475 // Note: buy back item already deleted from DB when player was saved
476 for(int i
= 0; i
< PLAYER_SLOTS_COUNT
; ++i
)
483 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
486 //all mailed items should be deleted, also all mail should be deallocated
487 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
490 for (ItemMap::iterator iter
= mMitems
.begin(); iter
!= mMitems
.end(); ++iter
)
491 delete iter
->second
; //if item is duplicated... then server may crash ... but that item should be deallocated
493 delete PlayerTalkClass
;
497 m_transport
->RemovePassenger(this);
500 for(size_t x
= 0; x
< ItemSetEff
.size(); x
++)
502 delete ItemSetEff
[x
];
504 // clean up player-instance binds, may unload some instance saves
505 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
506 for(BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
507 itr
->second
.save
->RemovePlayer(this);
509 delete m_declinedname
;
513 void Player::CleanupsBeforeDelete()
515 if(m_uint32Values
) // only for fully created Object
518 DuelComplete(DUEL_INTERUPTED
);
520 Unit::CleanupsBeforeDelete();
523 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
)
525 //FIXME: outfitId not used in player creating
527 Object::_Create(guidlow
, 0, HIGHGUID_PLAYER
);
531 PlayerInfo
const* info
= objmgr
.GetPlayerInfo(race
, class_
);
534 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
538 for (int i
= 0; i
< PLAYER_SLOTS_COUNT
; i
++)
544 SetMapId(info
->mapId
);
545 Relocate(info
->positionX
,info
->positionY
,info
->positionZ
);
547 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(class_
);
550 sLog
.outError("Class %u not found in DBC (Wrong DBC files?)",class_
);
554 uint8 powertype
= cEntry
->powerType
;
556 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, DEFAULT_WORLD_OBJECT_SIZE
);
557 SetFloatValue(UNIT_FIELD_COMBATREACH
, 1.5f
);
562 SetDisplayId(info
->displayId_f
);
563 SetNativeDisplayId(info
->displayId_f
);
566 SetDisplayId(info
->displayId_m
);
567 SetNativeDisplayId(info
->displayId_m
);
570 sLog
.outError("Invalid gender %u for player",gender
);
575 setFactionForRace(m_race
);
577 uint32 RaceClassGender
= ( race
) | ( class_
<< 8 ) | ( gender
<< 16 );
579 SetUInt32Value(UNIT_FIELD_BYTES_0
, ( RaceClassGender
| ( powertype
<< 24 ) ) );
580 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_PVP
);
581 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
);
582 SetFlag(UNIT_FIELD_FLAGS_2
, UNIT_FLAG2_REGENERATE_POWER
);
583 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
); // fix cast time showed in spell tooltip on client
584 SetFloatValue(UNIT_FIELD_HOVERHEIGHT
, 1.0f
); // default for players in 3.0.3
586 // -1 is default value
587 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX
, uint32(-1));
589 SetUInt32Value(PLAYER_BYTES
, (skin
| (face
<< 8) | (hairStyle
<< 16) | (hairColor
<< 24)));
590 SetUInt32Value(PLAYER_BYTES_2
, (facialHair
| (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
591 SetByteValue(PLAYER_BYTES_3
, 0, gender
);
593 SetUInt32Value( PLAYER_GUILDID
, 0 );
594 SetUInt32Value( PLAYER_GUILDRANK
, 0 );
595 SetUInt32Value( PLAYER_GUILD_TIMESTAMP
, 0 );
597 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES
, 0 ); // 0=disabled
598 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1
, 0 ); // 0=disabled
599 SetUInt32Value( PLAYER_CHOSEN_TITLE
, 0 );
600 SetUInt32Value( PLAYER_FIELD_KILLS
, 0 );
601 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 0 );
602 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION
, 0 );
603 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0 );
605 // set starting level
606 uint32 start_level
= getClass() != CLASS_DEATH_KNIGHT
607 ? sWorld
.getConfig(CONFIG_START_PLAYER_LEVEL
)
608 : sWorld
.getConfig(CONFIG_START_HEROIC_PLAYER_LEVEL
);
610 if (GetSession()->GetSecurity() >= SEC_MODERATOR
)
612 uint32 gm_level
= sWorld
.getConfig(CONFIG_START_GM_LEVEL
);
613 if(gm_level
> start_level
)
614 start_level
= gm_level
;
617 SetUInt32Value(UNIT_FIELD_LEVEL
, start_level
);
621 SetUInt32Value (PLAYER_FIELD_COINAGE
, sWorld
.getConfig(CONFIG_START_PLAYER_MONEY
));
622 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_START_HONOR_POINTS
));
623 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_START_ARENA_POINTS
));
626 m_Last_tick
= time(NULL
);
627 m_Played_time
[0] = 0;
628 m_Played_time
[1] = 0;
630 // base stats and related field values
632 InitTaxiNodesForLevel();
633 InitGlyphsForLevel();
634 InitTalentForLevel();
635 InitPrimaryProffesions(); // to max set before any spell added
637 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
638 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
639 SetHealth(GetMaxHealth());
640 if (getPowerType()==POWER_MANA
)
642 UpdateMaxPower(POWER_MANA
); // Update max Mana (for add bonus from intellect)
643 SetPower(POWER_MANA
,GetMaxPower(POWER_MANA
));
646 if(getPowerType() == POWER_RUNIC_POWER
)
648 SetPower(POWER_RUNE
, 8);
649 SetMaxPower(POWER_RUNE
, 8);
650 SetPower(POWER_RUNIC_POWER
, 0);
651 SetMaxPower(POWER_RUNIC_POWER
, 1000);
655 learnDefaultSpells();
657 // original action bar
658 std::list
<uint16
>::const_iterator action_itr
[4];
659 for(int i
=0; i
<4; i
++)
660 action_itr
[i
] = info
->action
[i
].begin();
662 for (; action_itr
[0]!=info
->action
[0].end() && action_itr
[1]!=info
->action
[1].end();)
665 for(int i
=0; i
<4 ;i
++)
666 taction
[i
] = (*action_itr
[i
]);
668 addActionButton((uint8
)taction
[0], taction
[1], (uint8
)taction
[2], (uint8
)taction
[3]);
670 for(int i
=0; i
<4 ;i
++)
675 CharStartOutfitEntry
const* oEntry
= NULL
;
676 for (uint32 i
= 1; i
< sCharStartOutfitStore
.GetNumRows(); ++i
)
678 if(CharStartOutfitEntry
const* entry
= sCharStartOutfitStore
.LookupEntry(i
))
680 if(entry
->RaceClassGender
== RaceClassGender
)
690 for(int j
= 0; j
< MAX_OUTFIT_ITEMS
; ++j
)
692 if(oEntry
->ItemId
[j
] <= 0)
695 uint32 item_id
= oEntry
->ItemId
[j
];
698 // Hack for not existed item id in dbc 3.0.3
702 ItemPrototype
const* iProto
= objmgr
.GetItemPrototype(item_id
);
705 sLog
.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id
,getRace(),getClass());
709 // max stack by default (mostly 1), 1 for infinity stackable
710 uint32 count
= iProto
->Stackable
> 0 ? uint32(iProto
->Stackable
) : 1;
712 if(iProto
->Class
==ITEM_CLASS_CONSUMABLE
&& iProto
->SubClass
==ITEM_SUBCLASS_FOOD
)
714 switch(iProto
->Spells
[0].SpellCategory
)
717 if(iProto
->Stackable
> 4)
721 if(iProto
->Stackable
> 2)
727 StoreNewItemInBestSlots(item_id
, count
);
731 for (PlayerCreateInfoItems::const_iterator item_id_itr
= info
->item
.begin(); item_id_itr
!=info
->item
.end(); ++item_id_itr
++)
732 StoreNewItemInBestSlots(item_id_itr
->item_id
, item_id_itr
->item_amount
);
734 // bags and main-hand weapon must equipped at this moment
735 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
736 // or ammo not equipped in special bag
737 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
739 if(Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
742 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
743 uint8 msg
= CanEquipItem( NULL_SLOT
, eDest
, pItem
, false );
744 if( msg
== EQUIP_ERR_OK
)
746 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
747 EquipItem( eDest
, pItem
, true);
749 // move other items to more appropriate slots (ammo not equipped in special bag)
752 ItemPosCountVec sDest
;
753 msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, sDest
, pItem
, false );
754 if( msg
== EQUIP_ERR_OK
)
756 RemoveItem(INVENTORY_SLOT_BAG_0
, i
,true);
757 pItem
= StoreItem( sDest
, pItem
, true);
760 // if this is ammo then use it
761 uint8 msg
= CanUseAmmo( pItem
->GetEntry() );
762 if( msg
== EQUIP_ERR_OK
)
763 SetAmmo( pItem
->GetEntry() );
767 // all item positions resolved
772 bool Player::StoreNewItemInBestSlots(uint32 titem_id
, uint32 titem_amount
)
774 sLog
.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id
, titem_amount
);
776 // attempt equip by one
777 while(titem_amount
> 0)
780 uint8 msg
= CanEquipNewItem( NULL_SLOT
, eDest
, titem_id
, false );
781 if( msg
!= EQUIP_ERR_OK
)
784 EquipNewItem( eDest
, titem_id
, true);
785 AutoUnequipOffhandIfNeed();
789 if(titem_amount
== 0)
790 return true; // equipped
793 ItemPosCountVec sDest
;
794 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
795 uint8 msg
= CanStoreNewItem( INVENTORY_SLOT_BAG_0
, NULL_SLOT
, sDest
, titem_id
, titem_amount
);
796 if( msg
== EQUIP_ERR_OK
)
798 StoreNewItem( sDest
, titem_id
, true, Item::GenerateItemRandomPropertyId(titem_id
) );
799 return true; // stored
802 // item can't be added
803 sLog
.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id
,getRace(),getClass(),msg
);
807 void Player::SendMirrorTimer(MirrorTimerType Type
, uint32 MaxValue
, uint32 CurrentValue
, int32 Regen
)
809 if (MaxValue
== DISABLED_MIRROR_TIMER
)
811 if (CurrentValue
!=DISABLED_MIRROR_TIMER
)
812 StopMirrorTimer(Type
);
815 WorldPacket
data(SMSG_START_MIRROR_TIMER
, (21));
816 data
<< (uint32
)Type
;
817 data
<< CurrentValue
;
821 data
<< (uint32
)0; // spell id
822 GetSession()->SendPacket( &data
);
825 void Player::StopMirrorTimer(MirrorTimerType Type
)
827 m_MirrorTimer
[Type
] = DISABLED_MIRROR_TIMER
;
828 WorldPacket
data(SMSG_STOP_MIRROR_TIMER
, 4);
829 data
<< (uint32
)Type
;
830 GetSession()->SendPacket( &data
);
833 void Player::EnvironmentalDamage(EnviromentalDamage type
, uint32 damage
)
835 if(!isAlive() || isGameMaster())
838 // Absorb, resist some environmental damage type
841 if (type
== DAMAGE_LAVA
)
842 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_FIRE
, DIRECT_DAMAGE
, damage
, &absorb
, &resist
);
843 else if (type
== DAMAGE_SLIME
)
844 CalcAbsorbResist(this, SPELL_SCHOOL_MASK_NATURE
, DIRECT_DAMAGE
, damage
, &absorb
, &resist
);
846 damage
-=absorb
+resist
;
848 WorldPacket
data(SMSG_ENVIRONMENTALDAMAGELOG
, (21));
849 data
<< uint64(GetGUID());
850 data
<< uint8(type
!=DAMAGE_FALL_TO_VOID
? type
: DAMAGE_FALL
);
851 data
<< uint32(damage
);
852 data
<< uint32(absorb
);
853 data
<< uint32(resist
);
854 SendMessageToSet(&data
, true);
856 DealDamage(this, damage
, NULL
, SELF_DAMAGE
, SPELL_SCHOOL_MASK_NORMAL
, NULL
, false);
860 if(type
==DAMAGE_FALL
) // DealDamage not apply item durability loss at self damage
862 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
863 DurabilityLossAll(0.10f
,false);
864 // durability lost message
865 WorldPacket
data(SMSG_DURABILITY_DAMAGE_DEATH
, 0);
866 GetSession()->SendPacket(&data
);
869 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM
, 1, type
);
873 int32
Player::getMaxTimer(MirrorTimerType timer
)
878 return MINUTE
*IN_MILISECONDS
;
881 if (!isAlive() || HasAuraType(SPELL_AURA_WATER_BREATHING
) || GetSession()->GetSecurity() >= sWorld
.getConfig(CONFIG_DISABLE_BREATHING
))
882 return DISABLED_MIRROR_TIMER
;
883 int32 UnderWaterTime
= 3*MINUTE
*IN_MILISECONDS
;
884 AuraList
const& mModWaterBreathing
= GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING
);
885 for(AuraList::const_iterator i
= mModWaterBreathing
.begin(); i
!= mModWaterBreathing
.end(); ++i
)
886 UnderWaterTime
= uint32(UnderWaterTime
* (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
);
887 return UnderWaterTime
;
892 return DISABLED_MIRROR_TIMER
;
893 return 1*IN_MILISECONDS
;
901 void Player::UpdateMirrorTimers()
903 // Desync flags for update on next HandleDrowning
904 if (m_MirrorTimerFlags
)
905 m_MirrorTimerFlagsLast
= ~m_MirrorTimerFlags
;
908 void Player::HandleDrowning(uint32 time_diff
)
910 if (!m_MirrorTimerFlags
)
914 if (m_MirrorTimerFlags
& UNDERWATER_INWATER
)
916 // Breath timer not activated - activate it
917 if (m_MirrorTimer
[BREATH_TIMER
] == DISABLED_MIRROR_TIMER
)
919 m_MirrorTimer
[BREATH_TIMER
] = getMaxTimer(BREATH_TIMER
);
920 SendMirrorTimer(BREATH_TIMER
, m_MirrorTimer
[BREATH_TIMER
], m_MirrorTimer
[BREATH_TIMER
], -1);
922 else // If activated - do tick
924 m_MirrorTimer
[BREATH_TIMER
]-=time_diff
;
925 // Timer limit - need deal damage
926 if (m_MirrorTimer
[BREATH_TIMER
] < 0)
928 m_MirrorTimer
[BREATH_TIMER
]+= 1*IN_MILISECONDS
;
929 // Calculate and deal damage
930 // TODO: Check this formula
931 uint32 damage
= GetMaxHealth() / 5 + urand(0, getLevel()-1);
932 EnvironmentalDamage(DAMAGE_DROWNING
, damage
);
934 else if (!(m_MirrorTimerFlagsLast
& UNDERWATER_INWATER
)) // Update time in client if need
935 SendMirrorTimer(BREATH_TIMER
, getMaxTimer(BREATH_TIMER
), m_MirrorTimer
[BREATH_TIMER
], -1);
938 else if (m_MirrorTimer
[BREATH_TIMER
] != DISABLED_MIRROR_TIMER
) // Regen timer
940 int32 UnderWaterTime
= getMaxTimer(BREATH_TIMER
);
942 m_MirrorTimer
[BREATH_TIMER
]+=10*time_diff
;
943 if (m_MirrorTimer
[BREATH_TIMER
] >= UnderWaterTime
|| !isAlive())
944 StopMirrorTimer(BREATH_TIMER
);
945 else if (m_MirrorTimerFlagsLast
& UNDERWATER_INWATER
)
946 SendMirrorTimer(BREATH_TIMER
, UnderWaterTime
, m_MirrorTimer
[BREATH_TIMER
], 10);
950 if (m_MirrorTimerFlags
& UNDERWARER_INDARKWATER
)
952 // Fatigue timer not activated - activate it
953 if (m_MirrorTimer
[FATIGUE_TIMER
] == DISABLED_MIRROR_TIMER
)
955 m_MirrorTimer
[FATIGUE_TIMER
] = getMaxTimer(FATIGUE_TIMER
);
956 SendMirrorTimer(FATIGUE_TIMER
, m_MirrorTimer
[FATIGUE_TIMER
], m_MirrorTimer
[FATIGUE_TIMER
], -1);
960 m_MirrorTimer
[FATIGUE_TIMER
]-=time_diff
;
961 // Timer limit - need deal damage or teleport ghost to graveyard
962 if (m_MirrorTimer
[FATIGUE_TIMER
] < 0)
964 m_MirrorTimer
[FATIGUE_TIMER
]+= 1*IN_MILISECONDS
;
965 if (isAlive()) // Calculate and deal damage
967 uint32 damage
= GetMaxHealth() / 5 + urand(0, getLevel()-1);
968 EnvironmentalDamage(DAMAGE_EXHAUSTED
, damage
);
970 else if (HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
)) // Teleport ghost to graveyard
973 else if (!(m_MirrorTimerFlagsLast
& UNDERWARER_INDARKWATER
))
974 SendMirrorTimer(FATIGUE_TIMER
, getMaxTimer(FATIGUE_TIMER
), m_MirrorTimer
[FATIGUE_TIMER
], -1);
977 else if (m_MirrorTimer
[FATIGUE_TIMER
] != DISABLED_MIRROR_TIMER
) // Regen timer
979 int32 DarkWaterTime
= getMaxTimer(FATIGUE_TIMER
);
980 m_MirrorTimer
[FATIGUE_TIMER
]+=10*time_diff
;
981 if (m_MirrorTimer
[FATIGUE_TIMER
] >= DarkWaterTime
|| !isAlive())
982 StopMirrorTimer(FATIGUE_TIMER
);
983 else if (m_MirrorTimerFlagsLast
& UNDERWARER_INDARKWATER
)
984 SendMirrorTimer(FATIGUE_TIMER
, DarkWaterTime
, m_MirrorTimer
[FATIGUE_TIMER
], 10);
987 if (m_MirrorTimerFlags
& (UNDERWATER_INLAVA
|UNDERWATER_INSLIME
))
989 // Breath timer not activated - activate it
990 if (m_MirrorTimer
[FIRE_TIMER
] == DISABLED_MIRROR_TIMER
)
991 m_MirrorTimer
[FIRE_TIMER
] = getMaxTimer(FIRE_TIMER
);
994 m_MirrorTimer
[FIRE_TIMER
]-=time_diff
;
995 if (m_MirrorTimer
[FIRE_TIMER
] < 0)
997 m_MirrorTimer
[FIRE_TIMER
]+= 1*IN_MILISECONDS
;
998 // Calculate and deal damage
999 // TODO: Check this formula
1000 uint32 damage
= urand(600, 700);
1001 if (m_MirrorTimerFlags
&UNDERWATER_INLAVA
)
1002 EnvironmentalDamage(DAMAGE_LAVA
, damage
);
1004 EnvironmentalDamage(DAMAGE_SLIME
, damage
);
1009 m_MirrorTimer
[FIRE_TIMER
] = DISABLED_MIRROR_TIMER
;
1011 // Recheck timers flag
1012 m_MirrorTimerFlags
&=~UNDERWATER_EXIST_TIMERS
;
1013 for (int i
= 0; i
< MAX_TIMERS
; ++i
)
1014 if (m_MirrorTimer
[i
]!=DISABLED_MIRROR_TIMER
)
1016 m_MirrorTimerFlags
|=UNDERWATER_EXIST_TIMERS
;
1019 m_MirrorTimerFlagsLast
= m_MirrorTimerFlags
;
1022 ///The player sobers by 256 every 10 seconds
1023 void Player::HandleSobering()
1027 uint32 drunk
= (m_drunk
<= 256) ? 0 : (m_drunk
- 256);
1028 SetDrunkValue(drunk
);
1031 DrunkenState
Player::GetDrunkenstateByValue(uint16 value
)
1034 return DRUNKEN_SMASHED
;
1036 return DRUNKEN_DRUNK
;
1038 return DRUNKEN_TIPSY
;
1039 return DRUNKEN_SOBER
;
1042 void Player::SetDrunkValue(uint16 newDrunkenValue
, uint32 itemId
)
1044 uint32 oldDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
1046 m_drunk
= newDrunkenValue
;
1047 SetUInt32Value(PLAYER_BYTES_3
,(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFF0001) | (m_drunk
& 0xFFFE));
1049 uint32 newDrunkenState
= Player::GetDrunkenstateByValue(m_drunk
);
1051 // special drunk invisibility detection
1052 if(newDrunkenState
>= DRUNKEN_DRUNK
)
1053 m_detectInvisibilityMask
|= (1<<6);
1055 m_detectInvisibilityMask
&= ~(1<<6);
1057 if(newDrunkenState
== oldDrunkenState
)
1060 WorldPacket
data(SMSG_CROSSED_INEBRIATION_THRESHOLD
, (8+4+4));
1061 data
<< uint64(GetGUID());
1062 data
<< uint32(newDrunkenState
);
1063 data
<< uint32(itemId
);
1065 SendMessageToSet(&data
, true);
1068 void Player::Update( uint32 p_time
)
1074 if(m_nextMailDelivereTime
&& m_nextMailDelivereTime
<= time(NULL
))
1079 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
1080 m_nextMailDelivereTime
= 0;
1083 Unit::Update( p_time
);
1085 // update player only attacks
1086 if(uint32 ranged_att
= getAttackTimer(RANGED_ATTACK
))
1088 setAttackTimer(RANGED_ATTACK
, (p_time
>= ranged_att
? 0 : ranged_att
- p_time
) );
1091 if(uint32 off_att
= getAttackTimer(OFF_ATTACK
))
1093 setAttackTimer(OFF_ATTACK
, (p_time
>= off_att
? 0 : off_att
- p_time
) );
1096 time_t now
= time (NULL
);
1100 UpdateContestedPvP(p_time
);
1102 UpdateDuelFlag(now
);
1104 CheckDuelDistance(now
);
1106 UpdateAfkReport(now
);
1108 // Update items that have just a limited lifetime
1109 if (now
>m_Last_tick
)
1110 UpdateItemDuration(uint32(now
- m_Last_tick
));
1112 if (!m_timedquests
.empty())
1114 std::set
<uint32
>::iterator iter
= m_timedquests
.begin();
1115 while (iter
!= m_timedquests
.end())
1117 QuestStatusData
& q_status
= mQuestStatus
[*iter
];
1118 if( q_status
.m_timer
<= p_time
)
1120 uint32 quest_id
= *iter
;
1121 ++iter
; // current iter will be removed in FailTimedQuest
1122 FailTimedQuest( quest_id
);
1126 q_status
.m_timer
-= p_time
;
1127 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
1133 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING
))
1135 Unit
*pVictim
= getVictim();
1136 if( !IsNonMeleeSpellCasted(false) && pVictim
)
1138 // default combat reach 10
1139 // TODO add weapon,skill check
1141 float pldistance
= ATTACK_DISTANCE
;
1143 if (isAttackReady(BASE_ATTACK
))
1145 if(!IsWithinDistInMap(pVictim
, pldistance
))
1147 setAttackTimer(BASE_ATTACK
,100);
1148 if(m_swingErrorMsg
!= 1) // send single time (client auto repeat)
1150 SendAttackSwingNotInRange();
1151 m_swingErrorMsg
= 1;
1154 //120 degrees of radiant range
1155 else if( !HasInArc( 2*M_PI
/3, pVictim
))
1157 setAttackTimer(BASE_ATTACK
,100);
1158 if(m_swingErrorMsg
!= 2) // send single time (client auto repeat)
1160 SendAttackSwingBadFacingAttack();
1161 m_swingErrorMsg
= 2;
1166 m_swingErrorMsg
= 0; // reset swing error state
1168 // prevent base and off attack in same time, delay attack at 0.2 sec
1169 if(haveOffhandWeapon())
1171 uint32 off_att
= getAttackTimer(OFF_ATTACK
);
1172 if(off_att
< ATTACK_DISPLAY_DELAY
)
1173 setAttackTimer(OFF_ATTACK
,ATTACK_DISPLAY_DELAY
);
1175 AttackerStateUpdate(pVictim
, BASE_ATTACK
);
1176 resetAttackTimer(BASE_ATTACK
);
1180 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK
))
1182 if(!IsWithinDistInMap(pVictim
, pldistance
))
1184 setAttackTimer(OFF_ATTACK
,100);
1186 else if( !HasInArc( 2*M_PI
/3, pVictim
))
1188 setAttackTimer(OFF_ATTACK
,100);
1192 // prevent base and off attack in same time, delay attack at 0.2 sec
1193 uint32 base_att
= getAttackTimer(BASE_ATTACK
);
1194 if(base_att
< ATTACK_DISPLAY_DELAY
)
1195 setAttackTimer(BASE_ATTACK
,ATTACK_DISPLAY_DELAY
);
1197 AttackerStateUpdate(pVictim
, OFF_ATTACK
);
1198 resetAttackTimer(OFF_ATTACK
);
1202 Unit
*owner
= pVictim
->GetOwner();
1203 Unit
*u
= owner
? owner
: pVictim
;
1204 if(u
->IsPvP() && (!duel
|| duel
->opponent
!= u
))
1207 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT
);
1212 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
))
1214 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1216 int time_inn
= time(NULL
)-GetTimeInnEnter();
1217 if (time_inn
>= 10) //freeze update
1219 float bubble
= 0.125*sWorld
.getRate(RATE_REST_INGAME
);
1220 //speed collect rest bonus (section/in hour)
1221 SetRestBonus( GetRestBonus()+ time_inn
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
1222 UpdateInnerTime(time(NULL
));
1227 if(m_regenTimer
> 0)
1229 if(p_time
>= m_regenTimer
)
1232 m_regenTimer
-= p_time
;
1235 if (m_weaponChangeTimer
> 0)
1237 if(p_time
>= m_weaponChangeTimer
)
1238 m_weaponChangeTimer
= 0;
1240 m_weaponChangeTimer
-= p_time
;
1243 if (m_zoneUpdateTimer
> 0)
1245 if(p_time
>= m_zoneUpdateTimer
)
1247 uint32 newzone
, newarea
;
1248 GetZoneAndAreaId(newzone
,newarea
);
1250 if( m_zoneUpdateId
!= newzone
)
1251 UpdateZone(newzone
,newarea
); // also update area
1254 // use area updates as well
1255 // needed for free far all arenas for example
1256 if( m_areaUpdateId
!= newarea
)
1257 UpdateArea(newarea
);
1259 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
1263 m_zoneUpdateTimer
-= p_time
;
1271 if (m_deathState
== JUST_DIED
)
1278 if(p_time
>= m_nextSave
)
1280 // m_nextSave reseted in SaveToDB call
1282 sLog
.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1286 m_nextSave
-= p_time
;
1290 //Handle Water/drowning
1291 HandleDrowning(p_time
);
1293 //Handle detect stealth players
1294 if (m_DetectInvTimer
> 0)
1296 if (p_time
>= m_DetectInvTimer
)
1298 m_DetectInvTimer
= 3000;
1299 HandleStealthedUnitsDetection();
1302 m_DetectInvTimer
-= p_time
;
1306 if (now
> m_Last_tick
)
1308 uint32 elapsed
= uint32(now
- m_Last_tick
);
1309 m_Played_time
[0] += elapsed
; // Total played time
1310 m_Played_time
[1] += elapsed
; // Level played time
1316 m_drunkTimer
+= p_time
;
1318 if (m_drunkTimer
> 10*IN_MILISECONDS
)
1322 // not auto-free ghost from body in instances
1323 if(m_deathTimer
> 0 && !GetBaseMap()->Instanceable())
1325 if(p_time
>= m_deathTimer
)
1332 m_deathTimer
-= p_time
;
1335 UpdateEnchantTime(p_time
);
1336 UpdateHomebindTime(p_time
);
1339 SendUpdateToOutOfRangeGroupMembers();
1341 Pet
* pet
= GetPet();
1342 if(pet
&& !IsWithinDistInMap(pet
, OWNER_MAX_DISTANCE
) && (GetCharmGUID() && (pet
->GetGUID() != GetCharmGUID())))
1344 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
, true);
1349 void Player::setDeathState(DeathState s
)
1351 uint32 ressSpellId
= 0;
1353 bool cur
= isAlive();
1355 if(s
== JUST_DIED
&& cur
)
1357 // drunken state is cleared on death
1359 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1362 clearResurrectRequestData();
1364 // remove form before other mods to prevent incorrect stats calculation
1365 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId
);
1367 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1368 RemovePet(NULL
, PET_SAVE_NOT_IN_SLOT
, true);
1370 // remove uncontrolled pets
1374 // save value before aura remove in Unit::setDeathState
1375 ressSpellId
= GetUInt32Value(PLAYER_SELF_RES_SPELL
);
1379 ressSpellId
= GetResurrectionSpellId();
1380 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP
, 1);
1381 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH
, 1);
1382 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON
, 1);
1384 Unit::setDeathState(s
);
1386 // restore resurrection spell id for player after aura remove
1387 if(s
== JUST_DIED
&& cur
&& ressSpellId
)
1388 SetUInt32Value(PLAYER_SELF_RES_SPELL
, ressSpellId
);
1390 if(isAlive() && !cur
)
1392 //clear aura case after resurrection by another way (spells will be applied before next death)
1393 SetUInt32Value(PLAYER_SELF_RES_SPELL
, 0);
1395 // restore default warrior stance
1396 if(getClass()== CLASS_WARRIOR
)
1397 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
1401 void Player::BuildEnumData( QueryResult
* result
, WorldPacket
* p_data
)
1403 Field
*fields
= result
->Fetch();
1405 *p_data
<< uint64(GetGUID());
1408 *p_data
<< uint8(getRace());
1409 uint8 pClass
= getClass();
1410 *p_data
<< uint8(pClass
);
1411 *p_data
<< uint8(getGender());
1413 uint32 bytes
= GetUInt32Value(PLAYER_BYTES
);
1414 *p_data
<< uint8(bytes
);
1415 *p_data
<< uint8(bytes
>> 8);
1416 *p_data
<< uint8(bytes
>> 16);
1417 *p_data
<< uint8(bytes
>> 24);
1419 bytes
= GetUInt32Value(PLAYER_BYTES_2
);
1420 *p_data
<< uint8(bytes
);
1422 *p_data
<< uint8(getLevel()); // player level
1423 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1424 uint32 zoneId
= MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY(),GetPositionZ());
1425 sLog
.outDebug("Player::BuildEnumData: m:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId
);
1426 *p_data
<< uint32(zoneId
);
1427 *p_data
<< uint32(GetMapId());
1429 *p_data
<< GetPositionX();
1430 *p_data
<< GetPositionY();
1431 *p_data
<< GetPositionZ();
1434 *p_data
<< (result
? fields
[13].GetUInt32() : 0);
1436 uint32 char_flags
= 0;
1437 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
1438 char_flags
|= CHARACTER_FLAG_HIDE_HELM
;
1439 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
1440 char_flags
|= CHARACTER_FLAG_HIDE_CLOAK
;
1441 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
))
1442 char_flags
|= CHARACTER_FLAG_GHOST
;
1443 if(HasAtLoginFlag(AT_LOGIN_RENAME
))
1444 char_flags
|= CHARACTER_FLAG_RENAME
;
1445 if(sWorld
.getConfig(CONFIG_DECLINED_NAMES_USED
) && (fields
[14].GetCppString() != ""))
1446 char_flags
|= CHARACTER_FLAG_DECLINED
;
1448 *p_data
<< uint32(char_flags
); // character flags
1449 // character customize (flags?)
1450 *p_data
<< uint32(HasAtLoginFlag(AT_LOGIN_CUSTOMIZE
) ? 1 : 0);
1451 *p_data
<< uint8(1); // unknown
1455 uint32 petDisplayId
= 0;
1456 uint32 petLevel
= 0;
1457 uint32 petFamily
= 0;
1459 // show pet at selection character in character list only for non-ghost character
1460 if(result
&& isAlive() && (pClass
== CLASS_WARLOCK
|| pClass
== CLASS_HUNTER
))
1462 uint32 entry
= fields
[10].GetUInt32();
1463 CreatureInfo
const* cInfo
= sCreatureStorage
.LookupEntry
<CreatureInfo
>(entry
);
1466 petDisplayId
= fields
[11].GetUInt32();
1467 petLevel
= fields
[12].GetUInt32();
1468 petFamily
= cInfo
->family
;
1472 *p_data
<< uint32(petDisplayId
);
1473 *p_data
<< uint32(petLevel
);
1474 *p_data
<< uint32(petFamily
);
1477 for (uint8 slot
= 0; slot
< EQUIPMENT_SLOT_END
; slot
++)
1479 uint32 visualbase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
1480 uint32 item_id
= GetUInt32Value(visualbase
);
1481 const ItemPrototype
* proto
= objmgr
.GetItemPrototype(item_id
);
1482 SpellItemEnchantmentEntry
const *enchant
= NULL
;
1484 for(uint8 enchantSlot
= PERM_ENCHANTMENT_SLOT
; enchantSlot
<=TEMP_ENCHANTMENT_SLOT
; enchantSlot
++)
1486 uint32 enchantId
= GetUInt32Value(visualbase
+1+enchantSlot
);
1487 if(enchant
= sSpellItemEnchantmentStore
.LookupEntry(enchantId
))
1493 *p_data
<< uint32(proto
->DisplayInfoID
);
1494 *p_data
<< uint8(proto
->InventoryType
);
1495 *p_data
<< uint32(enchant
? enchant
->aura_id
: 0);
1499 *p_data
<< uint32(0);
1500 *p_data
<< uint8(0);
1501 *p_data
<< uint32(0); // enchant?
1504 *p_data
<< uint32(0); // first bag display id
1505 *p_data
<< uint8(0); // first bag inventory type
1506 *p_data
<< uint32(0); // enchant?
1509 bool Player::ToggleAFK()
1511 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1513 bool state
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
);
1515 // afk player not allowed in battleground
1516 if(state
&& InBattleGround())
1517 LeaveBattleground();
1522 bool Player::ToggleDND()
1524 ToggleFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1526 return HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_DND
);
1529 uint8
Player::chatTag() const
1546 bool Player::TeleportTo(uint32 mapid
, float x
, float y
, float z
, float orientation
, uint32 options
)
1548 if(!MapManager::IsValidMapCoord(mapid
, x
, y
, z
, orientation
))
1550 sLog
.outError("TeleportTo: invalid map %d or absent instance template.", mapid
);
1554 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1555 Pet
* pet
= GetPet();
1557 MapEntry
const* mEntry
= sMapStore
.LookupEntry(mapid
);
1559 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1560 // don't let gm level > 1 either
1561 if(!InBattleGround() && mEntry
->IsBattleGroundOrArena())
1564 // client without expansion support
1565 if(GetSession()->Expansion() < mEntry
->Expansion())
1567 sLog
.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid
);
1570 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1572 SendTransferAborted(mapid
, TRANSFER_ABORT_INSUF_EXPAN_LVL
, mEntry
->Expansion());
1574 return false; // normal client can't teleport to this map...
1578 sLog
.outDebug("Player %s is being teleported to map %u", GetName(), mapid
);
1581 // if we were on a transport, leave
1582 if (!(options
& TELE_TO_NOT_LEAVE_TRANSPORT
) && m_transport
)
1584 m_transport
->RemovePassenger(this);
1586 m_movementInfo
.t_x
= 0.0f
;
1587 m_movementInfo
.t_y
= 0.0f
;
1588 m_movementInfo
.t_z
= 0.0f
;
1589 m_movementInfo
.t_o
= 0.0f
;
1590 m_movementInfo
.t_time
= 0;
1593 SetSemaphoreTeleport(true);
1595 // The player was ported to another map and looses the duel immediately.
1596 // We have to perform this check before the teleport, otherwise the
1597 // ObjectAccessor won't find the flag.
1598 if (duel
&& GetMapId()!=mapid
)
1600 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER
));
1602 DuelComplete(DUEL_FLED
);
1605 // reset movement flags at teleport, because player will continue move with these flags after teleport
1606 SetUnitMovementFlags(0);
1608 if ((GetMapId() == mapid
) && (!m_transport
))
1610 // prepare zone change detect
1611 uint32 old_zone
= GetZoneId();
1614 if(!GetSession()->PlayerLogout())
1617 BuildTeleportAckMsg(&data
, x
, y
, z
, orientation
);
1618 GetSession()->SendPacket(&data
);
1619 SetPosition( x
, y
, z
, orientation
, true);
1622 // this will be used instead of the current location in SaveToDB
1623 m_teleport_dest
= WorldLocation(mapid
, x
, y
, z
, orientation
);
1625 SetFallInformation(0, z
);
1627 //BuildHeartBeatMsg(&data);
1628 //SendMessageToSet(&data, true);
1629 if (!(options
& TELE_TO_NOT_UNSUMMON_PET
))
1631 //same map, only remove pet if out of range
1632 if(pet
&& !IsWithinDistInMap(pet
, OWNER_MAX_DISTANCE
))
1634 if(pet
->isControlled() && !pet
->isTemporarySummoned() )
1635 m_temporaryUnsummonedPetNumber
= pet
->GetCharmInfo()->GetPetNumber();
1637 m_temporaryUnsummonedPetNumber
= 0;
1639 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
);
1643 if(!(options
& TELE_TO_NOT_LEAVE_COMBAT
))
1646 if (!(options
& TELE_TO_NOT_UNSUMMON_PET
))
1649 if(pet
&& m_temporaryUnsummonedPetNumber
)
1651 Pet
* NewPet
= new Pet
;
1652 if(!NewPet
->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber
, true))
1655 m_temporaryUnsummonedPetNumber
= 0;
1659 uint32 newzone
, newarea
;
1660 GetZoneAndAreaId(newzone
,newarea
);
1662 if(!GetSession()->PlayerLogout())
1664 // don't reset teleport semaphore while logging out, otherwise m_teleport_dest won't be used in Player::SaveToDB
1665 SetSemaphoreTeleport(false);
1667 UpdateZone(newzone
,newarea
);
1671 if(old_zone
!= newzone
)
1674 if(pvpInfo
.inHostileArea
)
1675 CastSpell(this, 2479, true);
1680 // far teleport to another map
1681 Map
* oldmap
= IsInWorld() ? GetMap() : NULL
;
1682 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1684 // Check enter rights before map getting to avoid creating instance copy for player
1685 // this check not dependent from map instance copy and same for all instance copies of selected map
1686 if (!MapManager::Instance().CanPlayerEnter(mapid
, this))
1688 SetSemaphoreTeleport(false);
1692 // If the map is not created, assume it is possible to enter it.
1693 // It will be created in the WorldPortAck.
1694 Map
*map
= MapManager::Instance().FindMap(mapid
);
1695 if (!map
|| map
->CanEnter(this))
1701 ResetContestedPvP();
1703 // remove player from battleground on far teleport (when changing maps)
1704 if(BattleGround
const* bg
= GetBattleGround())
1706 // Note: at battleground join battleground id set before teleport
1707 // and we already will found "current" battleground
1708 // just need check that this is targeted map or leave
1709 if(bg
->GetMapId() != mapid
)
1710 LeaveBattleground(false); // don't teleport to entry point
1713 // remove pet on map change
1716 //leaving map -> delete pet right away (doing this later will cause problems)
1717 if(pet
->isControlled() && !pet
->isTemporarySummoned())
1718 m_temporaryUnsummonedPetNumber
= pet
->GetCharmInfo()->GetPetNumber();
1720 m_temporaryUnsummonedPetNumber
= 0;
1722 RemovePet(pet
, PET_SAVE_NOT_IN_SLOT
);
1725 // remove all dyn objects
1726 RemoveAllDynObjects();
1728 // stop spellcasting
1729 // not attempt interrupt teleportation spell at caster teleport
1730 if(!(options
& TELE_TO_SPELL
))
1731 if(IsNonMeleeSpellCasted(true))
1732 InterruptNonMeleeSpells(true);
1734 if(!GetSession()->PlayerLogout())
1736 // send transfer packets
1737 WorldPacket
data(SMSG_TRANSFER_PENDING
, (4+4+4));
1738 data
<< uint32(mapid
);
1741 data
<< m_transport
->GetEntry() << GetMapId();
1743 GetSession()->SendPacket(&data
);
1745 data
.Initialize(SMSG_NEW_WORLD
, (20));
1748 data
<< (uint32
)mapid
<< m_movementInfo
.t_x
<< m_movementInfo
.t_y
<< m_movementInfo
.t_z
<< m_movementInfo
.t_o
;
1752 data
<< (uint32
)mapid
<< (float)x
<< (float)y
<< (float)z
<< (float)orientation
;
1754 GetSession()->SendPacket( &data
);
1755 SendSavedInstances();
1757 // remove from old map now
1758 if(oldmap
) oldmap
->Remove(this, false);
1761 // new final coordinates
1765 float final_o
= orientation
;
1769 final_x
+= m_movementInfo
.t_x
;
1770 final_y
+= m_movementInfo
.t_y
;
1771 final_z
+= m_movementInfo
.t_z
;
1772 final_o
+= m_movementInfo
.t_o
;
1775 m_teleport_dest
= WorldLocation(mapid
, final_x
, final_y
, final_z
, final_o
);
1776 SetFallInformation(0, final_z
);
1777 // if the player is saved before worldportack (at logout for example)
1778 // this will be used instead of the current location in SaveToDB
1780 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP
| AURA_INTERRUPT_FLAG_MOVE
| AURA_INTERRUPT_FLAG_TURNING
);
1782 // move packet sent by client always after far teleport
1783 // SetPosition(final_x, final_y, final_z, final_o, true);
1786 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1794 void Player::AddToWorld()
1796 ///- Do not add/remove the player from the object storage
1797 ///- It will crash when updating the ObjectAccessor
1798 ///- The player should only be added when logging in
1801 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; i
++)
1804 m_items
[i
]->AddToWorld();
1808 void Player::RemoveFromWorld()
1813 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1815 UnsummonAllTotems();
1820 for(int i
= PLAYER_SLOT_START
; i
< PLAYER_SLOT_END
; i
++)
1823 m_items
[i
]->RemoveFromWorld();
1826 ///- Do not add/remove the player from the object storage
1827 ///- It will crash when updating the ObjectAccessor
1828 ///- The player should only be removed when logging out
1829 Unit::RemoveFromWorld();
1832 void Player::RewardRage( uint32 damage
, uint32 weaponSpeedHitFactor
, bool attacker
)
1836 float rageconversion
= ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1840 addRage
= ((damage
/rageconversion
*7.5 + weaponSpeedHitFactor
)/2);
1842 // talent who gave more rage on attack
1843 addRage
*= 1.0f
+ GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT
) / 100.0f
;
1847 addRage
= damage
/rageconversion
*2.5;
1849 // Berserker Rage effect
1850 if(HasAura(18499,0))
1854 addRage
*= sWorld
.getRate(RATE_POWER_RAGE_INCOME
);
1856 ModifyPower(POWER_RAGE
, uint32(addRage
*10));
1859 void Player::RegenerateAll()
1861 if (m_regenTimer
!= 0)
1863 uint32 regenDelay
= 2000;
1865 // Not in combat or they have regeneration
1866 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) ||
1867 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
) || IsPolymorphed() )
1870 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN
))
1872 Regenerate(POWER_RAGE
);
1873 if(getClass() == CLASS_DEATH_KNIGHT
)
1874 Regenerate(POWER_RUNIC_POWER
);
1878 Regenerate( POWER_ENERGY
);
1880 Regenerate( POWER_MANA
);
1882 if(getClass() == CLASS_DEATH_KNIGHT
)
1883 Regenerate( POWER_RUNE
);
1885 m_regenTimer
= regenDelay
;
1888 void Player::Regenerate(Powers power
)
1890 uint32 curValue
= GetPower(power
);
1891 uint32 maxValue
= GetMaxPower(power
);
1893 float addvalue
= 0.0f
;
1899 bool recentCast
= IsUnderLastManaUseEffect();
1900 float ManaIncreaseRate
= sWorld
.getRate(RATE_POWER_MANA
);
1903 // Mangos Updates Mana in intervals of 2s, which is correct
1904 addvalue
= GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER
) * ManaIncreaseRate
* 2.00f
;
1908 addvalue
= GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER
) * ManaIncreaseRate
* 2.00f
;
1911 case POWER_RAGE
: // Regenerate rage
1913 float RageDecreaseRate
= sWorld
.getRate(RATE_POWER_RAGE_LOSS
);
1914 addvalue
= 30 * RageDecreaseRate
; // 3 rage by tick
1916 case POWER_ENERGY
: // Regenerate energy (rogue)
1919 case POWER_RUNIC_POWER
:
1921 float RunicPowerDecreaseRate
= sWorld
.getRate(RATE_POWER_RUNICPOWER_LOSS
);
1922 addvalue
= 30 * RunicPowerDecreaseRate
; // 3 RunicPower by tick
1926 for(uint32 i
= 0; i
< MAX_RUNES
; ++i
)
1927 if(uint8 cd
= GetRuneCooldown(i
)) // if we have cooldown, reduce it...
1928 SetRuneCooldown(i
, cd
- 1); // ... by 2 sec (because update is every 2 sec)
1931 case POWER_HAPPINESS
:
1935 // Mana regen calculated in Player::UpdateManaRegen()
1936 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1937 if(power
!= POWER_MANA
)
1939 AuraList
const& ModPowerRegenPCTAuras
= GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT
);
1940 for(AuraList::const_iterator i
= ModPowerRegenPCTAuras
.begin(); i
!= ModPowerRegenPCTAuras
.end(); ++i
)
1941 if ((*i
)->GetModifier()->m_miscvalue
== power
)
1942 addvalue
*= ((*i
)->GetModifier()->m_amount
+ 100) / 100.0f
;
1945 if (power
!= POWER_RAGE
&& power
!= POWER_RUNIC_POWER
)
1947 curValue
+= uint32(addvalue
);
1948 if (curValue
> maxValue
)
1949 curValue
= maxValue
;
1953 if(curValue
<= uint32(addvalue
))
1956 curValue
-= uint32(addvalue
);
1958 SetPower(power
, curValue
);
1961 void Player::RegenerateHealth()
1963 uint32 curValue
= GetHealth();
1964 uint32 maxValue
= GetMaxHealth();
1966 if (curValue
>= maxValue
) return;
1968 float HealthIncreaseRate
= sWorld
.getRate(RATE_HEALTH
);
1970 float addvalue
= 0.0f
;
1973 if ( IsPolymorphed() )
1974 addvalue
= GetMaxHealth()/3;
1975 // normal regen case (maybe partly in combat case)
1976 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) )
1978 addvalue
= OCTRegenHPPerSpirit()* HealthIncreaseRate
;
1981 AuraList
const& mModHealthRegenPct
= GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT
);
1982 for(AuraList::const_iterator i
= mModHealthRegenPct
.begin(); i
!= mModHealthRegenPct
.end(); ++i
)
1983 addvalue
*= (100.0f
+ (*i
)->GetModifier()->m_amount
) / 100.0f
;
1985 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT
))
1986 addvalue
*= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT
) / 100.0f
;
1992 // always regeneration bonus (including combat)
1993 addvalue
+= GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT
);
1998 ModifyHealth(int32(addvalue
));
2001 bool Player::CanInteractWithNPCs(bool alive
) const
2003 if(alive
&& !isAlive())
2011 bool Player::IsUnderWater() const
2013 return IsInWater() &&
2014 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
2017 void Player::SetInWater(bool apply
)
2019 if(m_isInWater
==apply
)
2022 //define player in water by opcodes
2023 //move player's guid into HateOfflineList of those mobs
2024 //which can't swim and move guid back into ThreatList when
2026 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
2027 m_isInWater
= apply
;
2029 // remove auras that need water/land
2030 RemoveAurasWithInterruptFlags(apply
? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER
: AURA_INTERRUPT_FLAG_NOT_UNDERWATER
);
2032 getHostilRefManager().updateThreatTables();
2035 void Player::SetGameMaster(bool on
)
2039 m_ExtraFlags
|= PLAYER_EXTRA_GM_ON
;
2041 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
2043 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
2044 ResetContestedPvP();
2046 getHostilRefManager().setOnlineOfflineState(false);
2049 SetPhaseMask(PHASEMASK_ANYWHERE
,false); // see and visible in all phases
2054 AuraList
const& phases
= GetAurasByType(SPELL_AURA_PHASE
);
2055 SetPhaseMask(!phases
.empty() ? phases
.front()->GetMiscValue() : PHASEMASK_NORMAL
,false);
2057 m_ExtraFlags
&= ~ PLAYER_EXTRA_GM_ON
;
2058 setFactionForRace(getRace());
2059 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
);
2061 // restore FFA PvP Server state
2062 if(sWorld
.IsFFAPvPRealm())
2063 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
2065 // restore FFA PvP area state, remove not allowed for GM mounts
2066 UpdateArea(m_areaUpdateId
);
2068 getHostilRefManager().setOnlineOfflineState(true);
2071 ObjectAccessor::UpdateVisibilityForPlayer(this);
2074 void Player::SetGMVisible(bool on
)
2078 m_ExtraFlags
&= ~PLAYER_EXTRA_GM_INVISIBLE
; //remove flag
2080 // Reapply stealth/invisibility if active or show if not any
2081 if(HasAuraType(SPELL_AURA_MOD_STEALTH
))
2082 SetVisibility(VISIBILITY_GROUP_STEALTH
);
2083 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY
))
2084 SetVisibility(VISIBILITY_GROUP_INVISIBILITY
);
2086 SetVisibility(VISIBILITY_ON
);
2090 m_ExtraFlags
|= PLAYER_EXTRA_GM_INVISIBLE
; //add flag
2092 SetAcceptWhispers(false);
2093 SetGameMaster(true);
2095 SetVisibility(VISIBILITY_OFF
);
2099 bool Player::IsGroupVisibleFor(Player
* p
) const
2101 switch(sWorld
.getConfig(CONFIG_GROUP_VISIBILITY
))
2103 default: return IsInSameGroupWith(p
);
2104 case 1: return IsInSameRaidWith(p
);
2105 case 2: return GetTeam()==p
->GetTeam();
2109 bool Player::IsInSameGroupWith(Player
const* p
) const
2111 return p
==this || GetGroup() != NULL
&&
2112 GetGroup() == p
->GetGroup() &&
2113 GetGroup()->SameSubGroup((Player
*)this, (Player
*)p
);
2116 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2117 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2118 void Player::UninviteFromGroup()
2120 Group
* group
= GetGroupInvite();
2124 group
->RemoveInvite(this);
2126 if(group
->GetMembersCount() <= 1) // group has just 1 member => disband
2128 if(group
->IsCreated())
2130 group
->Disband(true);
2131 objmgr
.RemoveGroup(group
);
2134 group
->RemoveAllInvites();
2140 void Player::RemoveFromGroup(Group
* group
, uint64 guid
)
2144 if (group
->RemoveMember(guid
, 0) <= 1)
2146 // group->Disband(); already disbanded in RemoveMember
2147 objmgr
.RemoveGroup(group
);
2149 // removemember sets the player's group pointer to NULL
2154 void Player::SendLogXPGain(uint32 GivenXP
, Unit
* victim
, uint32 RestXP
)
2156 WorldPacket
data(SMSG_LOG_XPGAIN
, 21);
2157 data
<< uint64(victim
? victim
->GetGUID() : 0); // guid
2158 data
<< uint32(GivenXP
+RestXP
); // given experience
2159 data
<< uint8(victim
? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2162 data
<< uint32(GivenXP
); // experience without rested bonus
2163 data
<< float(1); // 1 - none 0 - 100% group bonus output
2165 data
<< uint8(0); // new 2.4.0
2166 GetSession()->SendPacket(&data
);
2169 void Player::GiveXP(uint32 xp
, Unit
* victim
)
2177 uint32 level
= getLevel();
2179 // XP to money conversion processed in Player::RewardQuest
2180 if(level
>= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
2183 // handle SPELL_AURA_MOD_XP_PCT auras
2184 Unit::AuraList
const& ModXPPctAuras
= GetAurasByType(SPELL_AURA_MOD_XP_PCT
);
2185 for(Unit::AuraList::const_iterator i
= ModXPPctAuras
.begin();i
!= ModXPPctAuras
.end(); ++i
)
2186 xp
= uint32(xp
*(1.0f
+ (*i
)->GetModifier()->m_amount
/ 100.0f
));
2188 // XP resting bonus for kill
2189 uint32 rested_bonus_xp
= victim
? GetXPRestBonus(xp
) : 0;
2191 SendLogXPGain(xp
,victim
,rested_bonus_xp
);
2193 uint32 curXP
= GetUInt32Value(PLAYER_XP
);
2194 uint32 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2195 uint32 newXP
= curXP
+ xp
+ rested_bonus_xp
;
2197 while( newXP
>= nextLvlXP
&& level
< sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
2201 if ( level
< sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
2202 GiveLevel(level
+ 1);
2205 nextLvlXP
= GetUInt32Value(PLAYER_NEXT_LEVEL_XP
);
2208 SetUInt32Value(PLAYER_XP
, newXP
);
2211 // Update player to next level
2212 // Current player experience not update (must be update by caller)
2213 void Player::GiveLevel(uint32 level
)
2215 if ( level
== getLevel() )
2218 PlayerLevelInfo info
;
2219 objmgr
.GetPlayerLevelInfo(getRace(),getClass(),level
,&info
);
2221 PlayerClassLevelInfo classInfo
;
2222 objmgr
.GetPlayerClassLevelInfo(getClass(),level
,&classInfo
);
2224 // send levelup info to client
2225 WorldPacket
data(SMSG_LEVELUP_INFO
, (4+4+MAX_POWERS
*4+MAX_STATS
*4));
2226 data
<< uint32(level
);
2227 data
<< uint32(int32(classInfo
.basehealth
) - int32(GetCreateHealth()));
2228 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2229 data
<< uint32(int32(classInfo
.basemana
) - int32(GetCreateMana()));
2237 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
) // Stats loop (0-4)
2238 data
<< uint32(int32(info
.stats
[i
]) - GetCreateStat(Stats(i
)));
2240 GetSession()->SendPacket(&data
);
2242 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, objmgr
.GetXPForLevel(level
));
2244 //update level, max level of skills
2245 if(getLevel()!= level
)
2246 m_Played_time
[1] = 0; // Level Played Time reset
2248 UpdateSkillsForLevel ();
2250 // save base values (bonuses already included in stored stats
2251 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2252 SetCreateStat(Stats(i
), info
.stats
[i
]);
2254 SetCreateHealth(classInfo
.basehealth
);
2255 SetCreateMana(classInfo
.basemana
);
2257 InitTalentForLevel();
2258 InitTaxiNodesForLevel();
2259 InitGlyphsForLevel();
2263 // set current level health and mana/energy to maximum after applying all mods.
2264 SetHealth(GetMaxHealth());
2265 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2266 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2267 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2268 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2269 SetPower(POWER_FOCUS
, 0);
2270 SetPower(POWER_HAPPINESS
, 0);
2272 // give level to summoned pet
2273 Pet
* pet
= GetPet();
2274 if(pet
&& pet
->getPetType()==SUMMON_PET
)
2275 pet
->GivePetLevel(level
);
2276 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL
);
2279 void Player::InitTalentForLevel()
2281 uint32 level
= getLevel();
2282 // talents base at level diff ( talents = level - 9 but some can be used already)
2285 // Remove all talent points
2286 if(m_usedTalentCount
> 0) // Free any used talents
2289 SetFreeTalentPoints(0);
2294 uint32 talentPointsForLevel
= CalculateTalentsPoints();
2296 // if used more that have then reset
2297 if(m_usedTalentCount
> talentPointsForLevel
)
2299 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR
)
2302 SetFreeTalentPoints(0);
2304 // else update amount of free points
2306 SetFreeTalentPoints(talentPointsForLevel
-m_usedTalentCount
);
2310 void Player::InitStatsForLevel(bool reapplyMods
)
2312 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2313 _RemoveAllStatBonuses();
2315 PlayerClassLevelInfo classInfo
;
2316 objmgr
.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo
);
2318 PlayerLevelInfo info
;
2319 objmgr
.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info
);
2321 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL
, sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) );
2322 SetUInt32Value(PLAYER_NEXT_LEVEL_XP
, objmgr
.GetXPForLevel(getLevel()));
2324 UpdateSkillsForLevel ();
2326 // set default cast time multiplier
2327 SetFloatValue(UNIT_MOD_CAST_SPEED
, 1.0f
);
2329 // reset size before reapply auras
2330 SetFloatValue(OBJECT_FIELD_SCALE_X
,1.0f
);
2332 // save base values (bonuses already included in stored stats
2333 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2334 SetCreateStat(Stats(i
), info
.stats
[i
]);
2336 for(int i
= STAT_STRENGTH
; i
< MAX_STATS
; ++i
)
2337 SetStat(Stats(i
), info
.stats
[i
]);
2339 SetCreateHealth(classInfo
.basehealth
);
2342 SetCreateMana(classInfo
.basemana
);
2344 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2348 //reset rating fields values
2349 for(uint16 index
= PLAYER_FIELD_COMBAT_RATING_1
; index
< PLAYER_FIELD_COMBAT_RATING_1
+ MAX_COMBAT_RATING
; ++index
)
2350 SetUInt32Value(index
, 0);
2352 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS
,0);
2353 for (int i
= 0; i
< 7; i
++)
2355 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG
+i
, 0);
2356 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS
+i
, 0);
2357 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT
+i
, 1.00f
);
2360 //reset attack power, damage and attack speed fields
2361 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
, 2000.0f
);
2362 SetFloatValue(UNIT_FIELD_BASEATTACKTIME
+ 1, 2000.0f
); // offhand attack time
2363 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME
, 2000.0f
);
2365 SetFloatValue(UNIT_FIELD_MINDAMAGE
, 0.0f
);
2366 SetFloatValue(UNIT_FIELD_MAXDAMAGE
, 0.0f
);
2367 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
, 0.0f
);
2368 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
, 0.0f
);
2369 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
, 0.0f
);
2370 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
, 0.0f
);
2372 SetInt32Value(UNIT_FIELD_ATTACK_POWER
, 0 );
2373 SetInt32Value(UNIT_FIELD_ATTACK_POWER_MODS
, 0 );
2374 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER
,0.0f
);
2375 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER
, 0 );
2376 SetInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS
,0 );
2377 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER
,0.0f
);
2379 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2380 SetFloatValue(PLAYER_CRIT_PERCENTAGE
,0.0f
);
2381 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE
,0.0f
);
2382 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE
,0.0f
);
2384 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2385 for (uint8 i
= 0; i
< 7; ++i
)
2386 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1
+i
, 0.0f
);
2388 SetFloatValue(PLAYER_PARRY_PERCENTAGE
, 0.0f
);
2389 SetFloatValue(PLAYER_BLOCK_PERCENTAGE
, 0.0f
);
2390 SetUInt32Value(PLAYER_SHIELD_BLOCK
, 0);
2393 SetFloatValue(PLAYER_DODGE_PERCENTAGE
, 0.0f
);
2395 // set armor (resistance 0) to original value (create_agility*2)
2396 SetArmor(int32(m_createStats
[STAT_AGILITY
]*2));
2397 SetResistanceBuffMods(SpellSchools(0), true, 0.0f
);
2398 SetResistanceBuffMods(SpellSchools(0), false, 0.0f
);
2399 // set other resistance to original value (0)
2400 for (int i
= 1; i
< MAX_SPELL_SCHOOL
; i
++)
2402 SetResistance(SpellSchools(i
), 0);
2403 SetResistanceBuffMods(SpellSchools(i
), true, 0.0f
);
2404 SetResistanceBuffMods(SpellSchools(i
), false, 0.0f
);
2407 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE
,0);
2408 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE
,0);
2409 for(int i
= 0; i
< MAX_SPELL_SCHOOL
; ++i
)
2411 SetFloatValue(UNIT_FIELD_POWER_COST_MODIFIER
+i
,0.0f
);
2412 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER
+i
,0.0f
);
2414 // Reset no reagent cost field
2415 for(int i
= 0; i
< 3; i
++)
2416 SetUInt32Value(PLAYER_NO_REAGENT_COST_1
+ i
, 0);
2417 // Init data for form but skip reapply item mods for form
2418 InitDataForForm(reapplyMods
);
2421 for (int i
= POWER_MANA
; i
< MAX_POWERS
; i
++)
2422 SetMaxPower(Powers(i
), uint32(GetCreatePowers(Powers(i
))));
2424 SetMaxHealth(classInfo
.basehealth
); // stamina bonus will applied later
2426 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2427 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID
, 0);
2429 // cleanup unit flags (will be re-applied if need at aura load).
2430 RemoveFlag( UNIT_FIELD_FLAGS
,
2431 UNIT_FLAG_NON_ATTACKABLE
| UNIT_FLAG_DISABLE_MOVE
| UNIT_FLAG_NOT_ATTACKABLE_1
|
2432 UNIT_FLAG_PET_IN_COMBAT
| UNIT_FLAG_SILENCED
| UNIT_FLAG_PACIFIED
|
2433 UNIT_FLAG_STUNNED
| UNIT_FLAG_IN_COMBAT
| UNIT_FLAG_DISARMED
|
2434 UNIT_FLAG_CONFUSED
| UNIT_FLAG_FLEEING
| UNIT_FLAG_NOT_SELECTABLE
|
2435 UNIT_FLAG_SKINNABLE
| UNIT_FLAG_MOUNT
| UNIT_FLAG_TAXI_FLIGHT
);
2436 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PVP_ATTACKABLE
); // must be set
2438 SetFlag(UNIT_FIELD_FLAGS_2
,UNIT_FLAG2_REGENERATE_POWER
);// must be set
2440 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2441 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_AFK
| PLAYER_FLAGS_DND
| PLAYER_FLAGS_GM
| PLAYER_FLAGS_GHOST
);
2443 RemoveStandFlags(UNIT_STAND_FLAGS_ALL
); // one form stealth modified bytes
2444 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
| UNIT_BYTE2_FLAG_SANCTUARY
);
2446 // restore if need some important flags
2447 SetUInt32Value(PLAYER_FIELD_BYTES2
, 0 ); // flags empty by default
2449 if(reapplyMods
) //reapply stats values only on .reset stats (level) command
2450 _ApplyAllStatBonuses();
2452 // set current level health and mana/energy to maximum after applying all mods.
2453 SetHealth(GetMaxHealth());
2454 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
));
2455 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
));
2456 if(GetPower(POWER_RAGE
) > GetMaxPower(POWER_RAGE
))
2457 SetPower(POWER_RAGE
, GetMaxPower(POWER_RAGE
));
2458 SetPower(POWER_FOCUS
, 0);
2459 SetPower(POWER_HAPPINESS
, 0);
2460 SetPower(POWER_RUNIC_POWER
, 0);
2463 void Player::SendInitialSpells()
2465 time_t curTime
= time(NULL
);
2466 time_t infTime
= curTime
+ MONTH
/2;
2468 uint16 spellCount
= 0;
2470 WorldPacket
data(SMSG_INITIAL_SPELLS
, (1+2+4*m_spells
.size()+2+m_spellCooldowns
.size()*(2+2+2+4+4)));
2473 size_t countPos
= data
.wpos();
2474 data
<< uint16(spellCount
); // spell count placeholder
2476 for (PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2478 if(itr
->second
->state
== PLAYERSPELL_REMOVED
)
2481 if(!itr
->second
->active
|| itr
->second
->disabled
)
2484 data
<< uint16(itr
->first
);
2485 data
<< uint16(0); // it's not slot id
2490 data
.put
<uint16
>(countPos
,spellCount
); // write real count value
2492 uint16 spellCooldowns
= m_spellCooldowns
.size();
2493 data
<< uint16(spellCooldowns
);
2494 for(SpellCooldowns::const_iterator itr
=m_spellCooldowns
.begin(); itr
!=m_spellCooldowns
.end(); ++itr
)
2496 SpellEntry
const *sEntry
= sSpellStore
.LookupEntry(itr
->first
);
2500 // not send infinity cooldown
2501 if(itr
->second
.end
> infTime
)
2504 data
<< uint16(itr
->first
);
2506 time_t cooldown
= 0;
2507 if(itr
->second
.end
> curTime
)
2508 cooldown
= (itr
->second
.end
-curTime
)*IN_MILISECONDS
;
2510 data
<< uint16(itr
->second
.itemid
); // cast item id
2511 data
<< uint16(sEntry
->Category
); // spell category
2512 if(sEntry
->Category
) // may be wrong, but anyway better than nothing...
2514 data
<< uint32(0); // cooldown
2515 data
<< uint32(cooldown
); // category cooldown
2519 data
<< uint32(cooldown
); // cooldown
2520 data
<< uint32(0); // category cooldown
2524 GetSession()->SendPacket(&data
);
2526 sLog
.outDetail( "CHARACTER: Sent Initial Spells" );
2529 void Player::RemoveMail(uint32 id
)
2531 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end();++itr
)
2533 if ((*itr
)->messageID
== id
)
2535 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2542 void Player::SendMailResult(uint32 mailId
, uint32 mailAction
, uint32 mailError
, uint32 equipError
, uint32 item_guid
, uint32 item_count
)
2544 WorldPacket
data(SMSG_SEND_MAIL_RESULT
, (4+4+4+(mailError
== MAIL_ERR_BAG_FULL
?4:(mailAction
== MAIL_ITEM_TAKEN
?4+4:0))));
2545 data
<< (uint32
) mailId
;
2546 data
<< (uint32
) mailAction
;
2547 data
<< (uint32
) mailError
;
2548 if ( mailError
== MAIL_ERR_BAG_FULL
)
2549 data
<< (uint32
) equipError
;
2550 else if( mailAction
== MAIL_ITEM_TAKEN
)
2552 data
<< (uint32
) item_guid
; // item guid low?
2553 data
<< (uint32
) item_count
; // item count?
2555 GetSession()->SendPacket(&data
);
2558 void Player::SendNewMail()
2560 // deliver undelivered mail
2561 WorldPacket
data(SMSG_RECEIVED_MAIL
, 4);
2563 GetSession()->SendPacket(&data
);
2566 void Player::UpdateNextMailTimeAndUnreads()
2568 // calculate next delivery time (min. from non-delivered mails
2569 // and recalculate unReadMail
2570 time_t cTime
= time(NULL
);
2571 m_nextMailDelivereTime
= 0;
2573 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
2575 if((*itr
)->deliver_time
> cTime
)
2577 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> (*itr
)->deliver_time
)
2578 m_nextMailDelivereTime
= (*itr
)->deliver_time
;
2580 else if(((*itr
)->checked
& MAIL_CHECK_MASK_READ
) == 0)
2585 void Player::AddNewMailDeliverTime(time_t deliver_time
)
2587 if(deliver_time
<= time(NULL
)) // ready now
2592 else // not ready and no have ready mails
2594 if(!m_nextMailDelivereTime
|| m_nextMailDelivereTime
> deliver_time
)
2595 m_nextMailDelivereTime
= deliver_time
;
2599 bool Player::addSpell(uint32 spell_id
, bool active
, bool learning
, bool dependent
, bool disabled
)
2601 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
2604 // do character spell book cleanup (all characters)
2605 if(!IsInWorld() && !learning
) // spell load case
2607 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id
);
2608 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2611 sLog
.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id
);
2616 if(!SpellMgr::IsSpellValid(spellInfo
,this,false))
2618 // do character spell book cleanup (all characters)
2619 if(!IsInWorld() && !learning
) // spell load case
2621 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id
);
2622 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id
);
2625 sLog
.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id
);
2630 PlayerSpellState state
= learning
? PLAYERSPELL_NEW
: PLAYERSPELL_UNCHANGED
;
2632 bool dependent_set
= false;
2633 bool disabled_case
= false;
2634 bool superceded_old
= false;
2636 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2637 if (itr
!= m_spells
.end())
2639 uint32 next_active_spell_id
= 0;
2640 // fix activate state for non-stackable low rank (and find next spell for !active case)
2641 if(!SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
2643 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
2644 for(SpellChainMapNext::const_iterator next_itr
= nextMap
.lower_bound(spell_id
); next_itr
!= nextMap
.upper_bound(spell_id
); ++next_itr
)
2646 if(HasSpell(next_itr
->second
))
2648 // high rank already known so this must !active
2650 next_active_spell_id
= next_itr
->second
;
2656 // not do anything if already known in expected state
2657 if(itr
->second
->state
!= PLAYERSPELL_REMOVED
&& itr
->second
->active
== active
&&
2658 itr
->second
->dependent
== dependent
&& itr
->second
->disabled
== disabled
)
2660 if(!IsInWorld() && !learning
) // explicitly load from DB and then exist in it already and set correctly
2661 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2666 // dependent spell known as not dependent, overwrite state
2667 if (itr
->second
->state
!= PLAYERSPELL_REMOVED
&& !itr
->second
->dependent
&& dependent
)
2669 itr
->second
->dependent
= dependent
;
2670 if (itr
->second
->state
!= PLAYERSPELL_NEW
)
2671 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2672 dependent_set
= true;
2675 // update active state for known spell
2676 if(itr
->second
->active
!= active
&& itr
->second
->state
!= PLAYERSPELL_REMOVED
&& !itr
->second
->disabled
)
2678 itr
->second
->active
= active
;
2680 if(!IsInWorld() && !learning
&& !dependent_set
) // explicitly load from DB and then exist in it already and set correctly
2681 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2682 else if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2683 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2687 if (IsPassiveSpell(spell_id
) && IsNeedCastPassiveSpellAtLearn(spellInfo
))
2688 CastSpell (this,spell_id
,true);
2690 else if(IsInWorld())
2692 if(next_active_spell_id
)
2694 // update spell ranks in spellbook and action bar
2695 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2696 data
<< uint16(spell_id
);
2697 data
<< uint16(next_active_spell_id
);
2698 GetSession()->SendPacket( &data
);
2702 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
2703 data
<< uint16(spell_id
);
2704 GetSession()->SendPacket(&data
);
2708 return active
; // learn (show in spell book if active now)
2711 if(itr
->second
->disabled
!= disabled
&& itr
->second
->state
!= PLAYERSPELL_REMOVED
)
2713 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2714 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2715 itr
->second
->disabled
= disabled
;
2720 disabled_case
= true;
2722 else switch(itr
->second
->state
)
2724 case PLAYERSPELL_UNCHANGED
: // known saved spell
2726 case PLAYERSPELL_REMOVED
: // re-learning removed not saved spell
2729 m_spells
.erase(itr
);
2730 state
= PLAYERSPELL_CHANGED
;
2731 break; // need re-add
2733 default: // known not saved yet spell (new or modified)
2735 // can be in case spell loading but learned at some previous spell loading
2736 if(!IsInWorld() && !learning
&& !dependent_set
)
2737 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
2744 if(!disabled_case
) // skip new spell adding if spell already known (disabled spells case)
2746 // talent: unlearn all other talent ranks (high and low)
2747 if(TalentSpellPos
const* talentPos
= GetTalentSpellPos(spell_id
))
2749 if(TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry( talentPos
->talent_id
))
2751 for(int i
=0; i
< MAX_TALENT_RANK
; ++i
)
2753 // skip learning spell and no rank spell case
2754 uint32 rankSpellId
= talentInfo
->RankID
[i
];
2755 if(!rankSpellId
|| rankSpellId
==spell_id
)
2758 removeSpell(rankSpellId
);
2762 // non talent spell: learn low ranks (recursive call)
2763 else if(uint32 prev_spell
= spellmgr
.GetPrevSpellInChain(spell_id
))
2765 if(!IsInWorld() || disabled
) // at spells loading, no output, but allow save
2766 addSpell(prev_spell
,active
,true,true,disabled
);
2767 else // at normal learning
2768 learnSpell(prev_spell
,true);
2771 PlayerSpell
*newspell
= new PlayerSpell
;
2772 newspell
->state
= state
;
2773 newspell
->active
= active
;
2774 newspell
->dependent
= dependent
;
2775 newspell
->disabled
= disabled
;
2777 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2778 if(newspell
->active
&& !newspell
->disabled
&& !SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
2780 for( PlayerSpellMap::iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
2782 if(itr
->second
->state
== PLAYERSPELL_REMOVED
) continue;
2783 SpellEntry
const *i_spellInfo
= sSpellStore
.LookupEntry(itr
->first
);
2784 if(!i_spellInfo
) continue;
2786 if( spellmgr
.IsRankSpellDueToSpell(spellInfo
,itr
->first
) )
2788 if(itr
->second
->active
)
2790 if(spellmgr
.IsHighRankOfSpell(spell_id
,itr
->first
))
2792 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2794 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2795 data
<< uint16(itr
->first
);
2796 data
<< uint16(spell_id
);
2797 GetSession()->SendPacket( &data
);
2800 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2801 itr
->second
->active
= false;
2802 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
2803 itr
->second
->state
= PLAYERSPELL_CHANGED
;
2804 superceded_old
= true; // new spell replace old in action bars and spell book.
2806 else if(spellmgr
.IsHighRankOfSpell(itr
->first
,spell_id
))
2808 if(IsInWorld()) // not send spell (re-/over-)learn packets at loading
2810 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
2811 data
<< uint16(spell_id
);
2812 data
<< uint16(itr
->first
);
2813 GetSession()->SendPacket( &data
);
2816 // mark new spell as disable (not learned yet for client and will not learned)
2817 newspell
->active
= false;
2818 if(newspell
->state
!= PLAYERSPELL_NEW
)
2819 newspell
->state
= PLAYERSPELL_CHANGED
;
2826 m_spells
[spell_id
] = newspell
;
2828 // return false if spell disabled
2829 if (newspell
->disabled
)
2833 uint32 talentCost
= GetTalentSpellCost(spell_id
);
2835 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2836 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2837 if( talentCost
> 0 && IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_LEARN_SPELL
) )
2839 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2840 CastSpell(this, spell_id
, true);
2842 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2843 else if (IsPassiveSpell(spell_id
))
2845 if(IsNeedCastPassiveSpellAtLearn(spellInfo
))
2846 CastSpell(this, spell_id
, true);
2848 else if( IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_SKILL_STEP
) )
2850 CastSpell(this, spell_id
, true);
2854 // update used talent points count
2855 m_usedTalentCount
+= talentCost
;
2857 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2858 if(uint32 freeProfs
= GetFreePrimaryProffesionPoints())
2860 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
2861 SetFreePrimaryProffesions(freeProfs
-1);
2864 // add dependent skills
2865 uint16 maxskill
= GetMaxSkillValueForLevel();
2867 SpellLearnSkillNode
const* spellLearnSkill
= spellmgr
.GetSpellLearnSkill(spell_id
);
2871 uint32 skill_value
= GetPureSkillValue(spellLearnSkill
->skill
);
2872 uint32 skill_max_value
= GetPureMaxSkillValue(spellLearnSkill
->skill
);
2874 if(skill_value
< spellLearnSkill
->value
)
2875 skill_value
= spellLearnSkill
->value
;
2877 uint32 new_skill_max_value
= spellLearnSkill
->maxvalue
== 0 ? maxskill
: spellLearnSkill
->maxvalue
;
2879 if(skill_max_value
< new_skill_max_value
)
2880 skill_max_value
= new_skill_max_value
;
2882 SetSkill(spellLearnSkill
->skill
,skill_value
,skill_max_value
);
2886 // not ranked skills
2887 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
2888 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
2890 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
2892 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
2896 if(HasSkill(pSkill
->id
))
2899 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
2900 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2901 (pSkill
->id
==SKILL_LOCKPICKING
|| pSkill
->id
==SKILL_RUNEFORGING
) && _spell_idx
->second
->max_value
==0 )
2903 switch(GetSkillRangeType(pSkill
,_spell_idx
->second
->racemask
!=0))
2905 case SKILL_RANGE_LANGUAGE
:
2906 SetSkill(pSkill
->id
, 300, 300 );
2908 case SKILL_RANGE_LEVEL
:
2909 SetSkill(pSkill
->id
, 1, GetMaxSkillValueForLevel() );
2911 case SKILL_RANGE_MONO
:
2912 SetSkill(pSkill
->id
, 1, 1 );
2921 // learn dependent spells
2922 SpellLearnSpellMap::const_iterator spell_begin
= spellmgr
.GetBeginSpellLearnSpell(spell_id
);
2923 SpellLearnSpellMap::const_iterator spell_end
= spellmgr
.GetEndSpellLearnSpell(spell_id
);
2925 for(SpellLearnSpellMap::const_iterator itr
= spell_begin
; itr
!= spell_end
; ++itr
)
2927 if(!itr
->second
.autoLearned
)
2929 if(!IsInWorld() || !itr
->second
.active
) // at spells loading, no output, but allow save
2930 addSpell(itr
->second
.spell
,itr
->second
.active
,true,true,false);
2931 else // at normal learning
2932 learnSpell(itr
->second
.spell
,true);
2938 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL
,spell_id
);
2939 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS
,spell_id
);
2942 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2943 return active
&& !disabled
&& !superceded_old
;
2946 bool Player::IsNeedCastPassiveSpellAtLearn(SpellEntry
const* spellInfo
) const
2948 bool need_cast
= false;
2950 switch(spellInfo
->Id
)
2952 // some spells not have stance data expacted cast at form change or present
2953 case 5420: need_cast
= (m_form
== FORM_TREE
); break;
2954 case 5419: need_cast
= (m_form
== FORM_TRAVEL
); break;
2955 case 7376: need_cast
= (m_form
== FORM_DEFENSIVESTANCE
); break;
2956 case 7381: need_cast
= (m_form
== FORM_BERSERKERSTANCE
); break;
2957 case 21156: need_cast
= (m_form
== FORM_BATTLESTANCE
); break;
2958 case 21178: need_cast
= (m_form
== FORM_BEAR
|| m_form
== FORM_DIREBEAR
); break;
2959 case 33948: need_cast
= (m_form
== FORM_FLIGHT
); break;
2960 case 34764: need_cast
= (m_form
== FORM_FLIGHT
); break;
2961 case 40121: need_cast
= (m_form
== FORM_FLIGHT_EPIC
); break;
2962 case 40122: need_cast
= (m_form
== FORM_FLIGHT_EPIC
); break;
2963 // another spells have proper stance data
2964 default: need_cast
= !spellInfo
->Stances
|| m_form
!= 0 && (spellInfo
->Stances
& (1<<(m_form
-1))); break;
2967 //Check CasterAuraStates
2968 return need_cast
&& (!spellInfo
->CasterAuraState
|| HasAuraState(AuraState(spellInfo
->CasterAuraState
)));
2971 void Player::learnSpell(uint32 spell_id
, bool dependent
)
2973 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
2975 bool disabled
= (itr
!= m_spells
.end()) ? itr
->second
->disabled
: false;
2976 bool active
= disabled
? itr
->second
->active
: true;
2978 bool learning
= addSpell(spell_id
,active
,true,dependent
,false);
2980 // learn all disabled higher ranks (recursive)
2983 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
2984 for(SpellChainMapNext::const_iterator i
= nextMap
.lower_bound(spell_id
); i
!= nextMap
.upper_bound(spell_id
); ++i
)
2986 PlayerSpellMap::iterator iter
= m_spells
.find(i
->second
);
2987 if (iter
!= m_spells
.end() && iter
->second
->disabled
)
2988 learnSpell(i
->second
,false);
2992 // prevent duplicated entires in spell book, also not send if not in world (loading)
2993 if(!learning
|| !IsInWorld ())
2996 WorldPacket
data(SMSG_LEARNED_SPELL
, 4);
2997 data
<< uint32(spell_id
);
2998 GetSession()->SendPacket(&data
);
3001 void Player::removeSpell(uint32 spell_id
, bool disabled
, bool update_action_bar_for_low_rank
)
3003 PlayerSpellMap::iterator itr
= m_spells
.find(spell_id
);
3004 if (itr
== m_spells
.end())
3007 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| disabled
&& itr
->second
->disabled
)
3010 // unlearn non talent higher ranks (recursive)
3011 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
3012 for(SpellChainMapNext::const_iterator itr2
= nextMap
.lower_bound(spell_id
); itr2
!= nextMap
.upper_bound(spell_id
); ++itr2
)
3013 if(HasSpell(itr2
->second
) && !GetTalentSpellPos(itr2
->second
))
3014 removeSpell(itr2
->second
,disabled
);
3016 bool cur_active
= itr
->second
->active
;
3017 bool cur_dependent
= itr
->second
->dependent
;
3021 itr
->second
->disabled
= disabled
;
3022 if(itr
->second
->state
!= PLAYERSPELL_NEW
)
3023 itr
->second
->state
= PLAYERSPELL_CHANGED
;
3027 if(itr
->second
->state
== PLAYERSPELL_NEW
)
3030 m_spells
.erase(itr
);
3033 itr
->second
->state
= PLAYERSPELL_REMOVED
;
3036 RemoveAurasDueToSpell(spell_id
);
3039 if(PetAura
const* petSpell
= spellmgr
.GetPetAura(spell_id
))
3040 RemovePetAura(petSpell
);
3042 // free talent points
3043 uint32 talentCosts
= GetTalentSpellCost(spell_id
);
3046 if(talentCosts
< m_usedTalentCount
)
3047 m_usedTalentCount
-= talentCosts
;
3049 m_usedTalentCount
= 0;
3052 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
3053 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell_id
))
3055 uint32 freeProfs
= GetFreePrimaryProffesionPoints()+1;
3056 if(freeProfs
<= sWorld
.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL
))
3057 SetFreePrimaryProffesions(freeProfs
);
3060 // remove dependent skill
3061 SpellLearnSkillNode
const* spellLearnSkill
= spellmgr
.GetSpellLearnSkill(spell_id
);
3064 uint32 prev_spell
= spellmgr
.GetPrevSpellInChain(spell_id
);
3065 if(!prev_spell
) // first rank, remove skill
3066 SetSkill(spellLearnSkill
->skill
,0,0);
3069 // search prev. skill setting by spell ranks chain
3070 SpellLearnSkillNode
const* prevSkill
= spellmgr
.GetSpellLearnSkill(prev_spell
);
3071 while(!prevSkill
&& prev_spell
)
3073 prev_spell
= spellmgr
.GetPrevSpellInChain(prev_spell
);
3074 prevSkill
= spellmgr
.GetSpellLearnSkill(spellmgr
.GetFirstSpellInChain(prev_spell
));
3077 if(!prevSkill
) // not found prev skill setting, remove skill
3078 SetSkill(spellLearnSkill
->skill
,0,0);
3079 else // set to prev. skill setting values
3081 uint32 skill_value
= GetPureSkillValue(prevSkill
->skill
);
3082 uint32 skill_max_value
= GetPureMaxSkillValue(prevSkill
->skill
);
3084 if(skill_value
> prevSkill
->value
)
3085 skill_value
= prevSkill
->value
;
3087 uint32 new_skill_max_value
= prevSkill
->maxvalue
== 0 ? GetMaxSkillValueForLevel() : prevSkill
->maxvalue
;
3089 if(skill_max_value
> new_skill_max_value
)
3090 skill_max_value
= new_skill_max_value
;
3092 SetSkill(prevSkill
->skill
,skill_value
,skill_max_value
);
3099 // not ranked skills
3100 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
3101 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
3103 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
3105 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(_spell_idx
->second
->skillId
);
3109 if(_spell_idx
->second
->learnOnGetSkill
== ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
||
3110 // lockpicking/runeforging special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
3111 (pSkill
->id
==SKILL_LOCKPICKING
|| pSkill
->id
==SKILL_RUNEFORGING
) && _spell_idx
->second
->max_value
==0 )
3113 // not reset skills for professions and racial abilities
3114 if( (pSkill
->categoryId
==SKILL_CATEGORY_SECONDARY
|| pSkill
->categoryId
==SKILL_CATEGORY_PROFESSION
) &&
3115 (IsProfessionSkill(pSkill
->id
) || _spell_idx
->second
->racemask
!=0) )
3118 SetSkill(pSkill
->id
, 0, 0 );
3123 // remove dependent spells
3124 SpellLearnSpellMap::const_iterator spell_begin
= spellmgr
.GetBeginSpellLearnSpell(spell_id
);
3125 SpellLearnSpellMap::const_iterator spell_end
= spellmgr
.GetEndSpellLearnSpell(spell_id
);
3127 for(SpellLearnSpellMap::const_iterator itr2
= spell_begin
; itr2
!= spell_end
; ++itr2
)
3128 removeSpell(itr2
->second
.spell
, disabled
);
3130 // activate lesser rank in spellbook/action bar, and cast it if need
3131 bool prev_activate
= false;
3133 if(uint32 prev_id
= spellmgr
.GetPrevSpellInChain (spell_id
))
3135 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
3137 // if talent then lesser rank also talent and need learn
3139 learnSpell (prev_id
,false);
3140 // if ranked non-stackable spell: need activate lesser rank and update dendence state
3141 else if(cur_active
&& !SpellMgr::canStackSpellRanks(spellInfo
) && spellmgr
.GetSpellRank(spellInfo
->Id
) != 0)
3143 // need manually update dependence state (learn spell ignore like attempts)
3144 PlayerSpellMap::iterator prev_itr
= m_spells
.find(prev_id
);
3145 if (prev_itr
!= m_spells
.end())
3147 if(prev_itr
->second
->dependent
!= cur_dependent
)
3149 prev_itr
->second
->dependent
= cur_dependent
;
3150 if(prev_itr
->second
->state
!= PLAYERSPELL_NEW
)
3151 prev_itr
->second
->state
= PLAYERSPELL_CHANGED
;
3154 // now re-learn if need re-activate
3155 if(cur_active
&& !prev_itr
->second
->active
)
3157 if(addSpell(prev_id
,true,false,prev_itr
->second
->dependent
,prev_itr
->second
->disabled
))
3159 if(update_action_bar_for_low_rank
)
3161 // downgrade spell ranks in spellbook and action bar
3162 WorldPacket
data(SMSG_SUPERCEDED_SPELL
, (4));
3163 data
<< uint16(spell_id
);
3164 data
<< uint16(prev_id
);
3165 GetSession()->SendPacket( &data
);
3166 prev_activate
= true;
3174 // remove from spell book if not replaced by lesser rank
3177 WorldPacket
data(SMSG_REMOVED_SPELL
, 4);
3178 data
<< uint16(spell_id
);
3179 GetSession()->SendPacket(&data
);
3183 void Player::RemoveArenaSpellCooldowns()
3185 // remove cooldowns on spells that has < 15 min CD
3186 SpellCooldowns::iterator itr
, next
;
3187 // iterate spell cooldowns
3188 for(itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); itr
= next
)
3192 SpellEntry
const * entry
= sSpellStore
.LookupEntry(itr
->first
);
3193 // check if spellentry is present and if the cooldown is less than 15 mins
3195 entry
->RecoveryTime
<= 15 * MINUTE
* IN_MILISECONDS
&&
3196 entry
->CategoryRecoveryTime
<= 15 * MINUTE
* IN_MILISECONDS
)
3199 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, (4+8));
3200 data
<< uint32(itr
->first
);
3201 data
<< uint64(GetGUID());
3202 GetSession()->SendPacket(&data
);
3204 m_spellCooldowns
.erase(itr
);
3209 void Player::RemoveAllSpellCooldown()
3211 if(!m_spellCooldowns
.empty())
3213 for(SpellCooldowns::const_iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end(); ++itr
)
3215 WorldPacket
data(SMSG_CLEAR_COOLDOWN
, (4+8));
3216 data
<< uint32(itr
->first
);
3217 data
<< uint64(GetGUID());
3218 GetSession()->SendPacket(&data
);
3220 m_spellCooldowns
.clear();
3224 void Player::_LoadSpellCooldowns(QueryResult
*result
)
3226 // some cooldowns can be already set at aura loading...
3228 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3232 time_t curTime
= time(NULL
);
3236 Field
*fields
= result
->Fetch();
3238 uint32 spell_id
= fields
[0].GetUInt32();
3239 uint32 item_id
= fields
[1].GetUInt32();
3240 time_t db_time
= (time_t)fields
[2].GetUInt64();
3242 if(!sSpellStore
.LookupEntry(spell_id
))
3244 sLog
.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id
);
3248 // skip outdated cooldown
3249 if(db_time
<= curTime
)
3252 AddSpellCooldown(spell_id
, item_id
, db_time
);
3254 sLog
.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id
, item_id
, uint32(db_time
-curTime
));
3256 while( result
->NextRow() );
3262 void Player::_SaveSpellCooldowns()
3264 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3266 time_t curTime
= time(NULL
);
3267 time_t infTime
= curTime
+ MONTH
/2;
3269 // remove outdated and save active
3270 for(SpellCooldowns::iterator itr
= m_spellCooldowns
.begin();itr
!= m_spellCooldowns
.end();)
3272 if(itr
->second
.end
<= curTime
)
3273 m_spellCooldowns
.erase(itr
++);
3274 else if(itr
->second
.end
<= infTime
) // not save locked cooldowns, it will be reset or set at reload
3276 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
));
3284 uint32
Player::resetTalentsCost() const
3286 // The first time reset costs 1 gold
3287 if(m_resetTalentsCost
< 1*GOLD
)
3290 else if(m_resetTalentsCost
< 5*GOLD
)
3292 // After that it increases in increments of 5 gold
3293 else if(m_resetTalentsCost
< 10*GOLD
)
3297 uint32 months
= (sWorld
.GetGameTime() - m_resetTalentsTime
)/MONTH
;
3300 // This cost will be reduced by a rate of 5 gold per month
3301 int32 new_cost
= int32(m_resetTalentsCost
) - 5*GOLD
*months
;
3302 // to a minimum of 10 gold.
3303 return (new_cost
< 10*GOLD
? 10*GOLD
: new_cost
);
3307 // After that it increases in increments of 5 gold
3308 int32 new_cost
= m_resetTalentsCost
+ 5*GOLD
;
3309 // until it hits a cap of 50 gold.
3310 if(new_cost
> 50*GOLD
)
3317 bool Player::resetTalents(bool no_cost
)
3319 // not need after this call
3320 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS
))
3322 m_atLoginFlags
= m_atLoginFlags
& ~AT_LOGIN_RESET_TALENTS
;
3323 CharacterDatabase
.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS
), GetGUIDLow());
3326 uint32 talentPointsForLevel
= CalculateTalentsPoints();
3328 if (m_usedTalentCount
== 0)
3330 SetFreeTalentPoints(talentPointsForLevel
);
3338 cost
= resetTalentsCost();
3340 if (GetMoney() < cost
)
3342 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, 0, 0, 0);
3347 for (unsigned int i
= 0; i
< sTalentStore
.GetNumRows(); i
++)
3349 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry(i
);
3351 if (!talentInfo
) continue;
3353 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentInfo
->TalentTab
);
3358 // unlearn only talents for character class
3359 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3360 // to prevent unexpected lost normal learned spell skip another class talents
3361 if( (getClassMask() & talentTabInfo
->ClassMask
) == 0 )
3364 for (int j
= 0; j
< MAX_TALENT_RANK
; j
++)
3366 for(PlayerSpellMap::iterator itr
= GetSpellMap().begin(); itr
!= GetSpellMap().end();)
3368 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->second
->disabled
)
3374 // remove learned spells (all ranks)
3375 uint32 itrFirstId
= spellmgr
.GetFirstSpellInChain(itr
->first
);
3377 // unlearn if first rank is talent or learned by talent
3378 if (itrFirstId
== talentInfo
->RankID
[j
] || spellmgr
.IsSpellLearnToSpell(talentInfo
->RankID
[j
],itrFirstId
))
3380 removeSpell(itr
->first
,!IsPassiveSpell(itr
->first
));
3381 itr
= GetSpellMap().begin();
3390 SetFreeTalentPoints(talentPointsForLevel
);
3394 ModifyMoney(-(int32
)cost
);
3395 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS
, cost
);
3397 m_resetTalentsCost
= cost
;
3398 m_resetTalentsTime
= time(NULL
);
3401 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3402 RemovePet(NULL
,PET_SAVE_NOT_IN_SLOT
, true);
3406 m_canTitanGrip
= false;
3407 if(sWorld
.getConfig(CONFIG_OFFHAND_CHECK_AT_TALENTS_RESET
))
3408 AutoUnequipOffhandIfNeed();
3414 Mail
* Player::GetMail(uint32 id
)
3416 for(PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
3418 if ((*itr
)->messageID
== id
)
3426 void Player::_SetCreateBits(UpdateMask
*updateMask
, Player
*target
) const
3430 Object::_SetCreateBits(updateMask
, target
);
3434 for(uint16 index
= 0; index
< m_valuesCount
; index
++)
3436 if(GetUInt32Value(index
) != 0 && updateVisualBits
.GetBit(index
))
3437 updateMask
->SetBit(index
);
3442 void Player::_SetUpdateBits(UpdateMask
*updateMask
, Player
*target
) const
3446 Object::_SetUpdateBits(updateMask
, target
);
3450 Object::_SetUpdateBits(updateMask
, target
);
3451 *updateMask
&= updateVisualBits
;
3455 void Player::InitVisibleBits()
3457 updateVisualBits
.SetCount(PLAYER_END
);
3459 updateVisualBits
.SetBit(OBJECT_FIELD_GUID
);
3460 updateVisualBits
.SetBit(OBJECT_FIELD_TYPE
);
3461 updateVisualBits
.SetBit(OBJECT_FIELD_ENTRY
);
3462 updateVisualBits
.SetBit(OBJECT_FIELD_SCALE_X
);
3463 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 0);
3464 updateVisualBits
.SetBit(UNIT_FIELD_CHARM
+ 1);
3465 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 0);
3466 updateVisualBits
.SetBit(UNIT_FIELD_SUMMON
+ 1);
3467 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 0);
3468 updateVisualBits
.SetBit(UNIT_FIELD_CHARMEDBY
+ 1);
3469 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 0);
3470 updateVisualBits
.SetBit(UNIT_FIELD_TARGET
+ 1);
3471 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 0);
3472 updateVisualBits
.SetBit(UNIT_FIELD_CHANNEL_OBJECT
+ 1);
3473 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_0
);
3474 updateVisualBits
.SetBit(UNIT_FIELD_HEALTH
);
3475 updateVisualBits
.SetBit(UNIT_FIELD_POWER1
);
3476 updateVisualBits
.SetBit(UNIT_FIELD_POWER2
);
3477 updateVisualBits
.SetBit(UNIT_FIELD_POWER3
);
3478 updateVisualBits
.SetBit(UNIT_FIELD_POWER4
);
3479 updateVisualBits
.SetBit(UNIT_FIELD_POWER5
);
3480 updateVisualBits
.SetBit(UNIT_FIELD_POWER6
);
3481 updateVisualBits
.SetBit(UNIT_FIELD_POWER7
);
3482 updateVisualBits
.SetBit(UNIT_FIELD_MAXHEALTH
);
3483 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER1
);
3484 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER2
);
3485 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER3
);
3486 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER4
);
3487 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER5
);
3488 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER6
);
3489 updateVisualBits
.SetBit(UNIT_FIELD_MAXPOWER7
);
3490 updateVisualBits
.SetBit(UNIT_FIELD_LEVEL
);
3491 updateVisualBits
.SetBit(UNIT_FIELD_FACTIONTEMPLATE
);
3492 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 0);
3493 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 1);
3494 updateVisualBits
.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID
+ 2);
3495 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS
);
3496 updateVisualBits
.SetBit(UNIT_FIELD_FLAGS_2
);
3497 updateVisualBits
.SetBit(UNIT_FIELD_AURASTATE
);
3498 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 0);
3499 updateVisualBits
.SetBit(UNIT_FIELD_BASEATTACKTIME
+ 1);
3500 updateVisualBits
.SetBit(UNIT_FIELD_BOUNDINGRADIUS
);
3501 updateVisualBits
.SetBit(UNIT_FIELD_COMBATREACH
);
3502 updateVisualBits
.SetBit(UNIT_FIELD_DISPLAYID
);
3503 updateVisualBits
.SetBit(UNIT_FIELD_NATIVEDISPLAYID
);
3504 updateVisualBits
.SetBit(UNIT_FIELD_MOUNTDISPLAYID
);
3505 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_1
);
3506 updateVisualBits
.SetBit(UNIT_FIELD_PETNUMBER
);
3507 updateVisualBits
.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP
);
3508 updateVisualBits
.SetBit(UNIT_DYNAMIC_FLAGS
);
3509 updateVisualBits
.SetBit(UNIT_CHANNEL_SPELL
);
3510 updateVisualBits
.SetBit(UNIT_MOD_CAST_SPEED
);
3511 updateVisualBits
.SetBit(UNIT_FIELD_BASE_MANA
);
3512 updateVisualBits
.SetBit(UNIT_FIELD_BYTES_2
);
3513 updateVisualBits
.SetBit(UNIT_FIELD_HOVERHEIGHT
);
3515 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 0);
3516 updateVisualBits
.SetBit(PLAYER_DUEL_ARBITER
+ 1);
3517 updateVisualBits
.SetBit(PLAYER_FLAGS
);
3518 updateVisualBits
.SetBit(PLAYER_GUILDID
);
3519 updateVisualBits
.SetBit(PLAYER_GUILDRANK
);
3520 updateVisualBits
.SetBit(PLAYER_BYTES
);
3521 updateVisualBits
.SetBit(PLAYER_BYTES_2
);
3522 updateVisualBits
.SetBit(PLAYER_BYTES_3
);
3523 updateVisualBits
.SetBit(PLAYER_DUEL_TEAM
);
3524 updateVisualBits
.SetBit(PLAYER_GUILD_TIMESTAMP
);
3526 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3527 for(uint16 i
= PLAYER_QUEST_LOG_1_1
; i
< PLAYER_QUEST_LOG_25_2
; i
+= 4)
3528 updateVisualBits
.SetBit(i
);
3530 // Players visible items are not inventory stuff
3531 for(uint16 i
= 0; i
< EQUIPMENT_SLOT_END
; ++i
)
3533 uint32 offset
= i
* MAX_VISIBLE_ITEM_OFFSET
;
3536 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR
+ 0 + offset
);
3537 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR
+ 1 + offset
);
3540 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_0
+ 0 + offset
);
3542 // item enchantments
3543 for(uint8 j
= 0; j
< MAX_ENCHANTMENT_SLOT
; ++j
)
3544 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_0
+ 1 + j
+ offset
);
3546 // random properties
3547 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ offset
);
3548 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_SEED
+ offset
);
3549 updateVisualBits
.SetBit(PLAYER_VISIBLE_ITEM_1_PAD
+ offset
);
3552 updateVisualBits
.SetBit(PLAYER_CHOSEN_TITLE
);
3555 void Player::BuildCreateUpdateBlockForPlayer( UpdateData
*data
, Player
*target
) const
3557 for(int i
= 0; i
< EQUIPMENT_SLOT_END
; i
++)
3559 if(m_items
[i
] == NULL
)
3562 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3567 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
3569 if(m_items
[i
] == NULL
)
3572 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3574 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
3576 if(m_items
[i
] == NULL
)
3579 m_items
[i
]->BuildCreateUpdateBlockForPlayer( data
, target
);
3583 Unit::BuildCreateUpdateBlockForPlayer( data
, target
);
3586 void Player::DestroyForPlayer( Player
*target
) const
3588 Unit::DestroyForPlayer( target
);
3590 for(int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
3592 if(m_items
[i
] == NULL
)
3595 m_items
[i
]->DestroyForPlayer( target
);
3600 for(int i
= INVENTORY_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
3602 if(m_items
[i
] == NULL
)
3605 m_items
[i
]->DestroyForPlayer( target
);
3607 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
3609 if(m_items
[i
] == NULL
)
3612 m_items
[i
]->DestroyForPlayer( target
);
3617 bool Player::HasSpell(uint32 spell
) const
3619 PlayerSpellMap::const_iterator itr
= m_spells
.find(spell
);
3620 return (itr
!= m_spells
.end() && itr
->second
->state
!= PLAYERSPELL_REMOVED
&&
3621 !itr
->second
->disabled
);
3624 bool Player::HasActiveSpell(uint32 spell
) const
3626 PlayerSpellMap::const_iterator itr
= m_spells
.find(spell
);
3627 return (itr
!= m_spells
.end() && itr
->second
->state
!= PLAYERSPELL_REMOVED
&&
3628 itr
->second
->active
&& !itr
->second
->disabled
);
3631 TrainerSpellState
Player::GetTrainerSpellState(TrainerSpell
const* trainer_spell
) const
3634 return TRAINER_SPELL_RED
;
3636 if (!trainer_spell
->learnedSpell
)
3637 return TRAINER_SPELL_RED
;
3640 if(HasSpell(trainer_spell
->learnedSpell
))
3641 return TRAINER_SPELL_GRAY
;
3643 // check race/class requirement
3644 if(!IsSpellFitByClassAndRace(trainer_spell
->learnedSpell
))
3645 return TRAINER_SPELL_RED
;
3647 // check level requirement
3648 if(getLevel() < trainer_spell
->reqLevel
)
3649 return TRAINER_SPELL_RED
;
3651 if(SpellChainNode
const* spell_chain
= spellmgr
.GetSpellChainNode(trainer_spell
->learnedSpell
))
3653 // check prev.rank requirement
3654 if(spell_chain
->prev
&& !HasSpell(spell_chain
->prev
))
3655 return TRAINER_SPELL_RED
;
3657 // check additional spell requirement
3658 if(spell_chain
->req
&& !HasSpell(spell_chain
->req
))
3659 return TRAINER_SPELL_RED
;
3662 // check skill requirement
3663 if(trainer_spell
->reqSkill
&& GetBaseSkillValue(trainer_spell
->reqSkill
) < trainer_spell
->reqSkillValue
)
3664 return TRAINER_SPELL_RED
;
3666 // exist, already checked at loading
3667 SpellEntry
const* spell
= sSpellStore
.LookupEntry(trainer_spell
->learnedSpell
);
3669 // secondary prof. or not prof. spell
3670 uint32 skill
= spell
->EffectMiscValue
[1];
3672 if(spell
->Effect
[1] != SPELL_EFFECT_SKILL
|| !IsPrimaryProfessionSkill(skill
))
3673 return TRAINER_SPELL_GREEN
;
3675 // check primary prof. limit
3676 if(spellmgr
.IsPrimaryProfessionFirstRankSpell(spell
->Id
) && GetFreePrimaryProffesionPoints() == 0)
3677 return TRAINER_SPELL_RED
;
3679 return TRAINER_SPELL_GREEN
;
3682 void Player::DeleteFromDB(uint64 playerguid
, uint32 accountId
, bool updateRealmChars
)
3684 uint32 guid
= GUID_LOPART(playerguid
);
3686 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3687 // bones will be deleted by corpse/bones deleting thread shortly
3688 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid
);
3690 // remove from guild
3691 uint32 guildId
= GetGuildIdFromDB(playerguid
);
3694 Guild
* guild
= objmgr
.GetGuildById(guildId
);
3696 guild
->DelMember(guid
);
3699 // remove from arena teams
3700 LeaveAllArenaTeams(playerguid
);
3702 // the player was uninvited already on logout so just remove from group
3703 QueryResult
*resultGroup
= CharacterDatabase
.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid
);
3706 uint64 leaderGuid
= MAKE_NEW_GUID((*resultGroup
)[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
3708 Group
* group
= objmgr
.GetGroupByLeader(leaderGuid
);
3711 RemoveFromGroup(group
, playerguid
);
3715 // remove signs from petitions (also remove petitions if owner);
3716 RemovePetitionsAndSigns(playerguid
, 10);
3718 // return back all mails with COD and Item 0 1 2 3 4 5 6
3719 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
);
3724 Field
*fields
= resultMail
->Fetch();
3726 uint32 mail_id
= fields
[0].GetUInt32();
3727 uint16 mailTemplateId
= fields
[1].GetUInt16();
3728 uint32 sender
= fields
[2].GetUInt32();
3729 std::string subject
= fields
[3].GetCppString();
3730 uint32 itemTextId
= fields
[4].GetUInt32();
3731 uint32 money
= fields
[5].GetUInt32();
3732 bool has_items
= fields
[6].GetBool();
3734 //we can return mail now
3735 //so firstly delete the old one
3736 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id
);
3741 // data needs to be at first place for Item::LoadFromDB
3742 QueryResult
*resultItems
= CharacterDatabase
.PQuery("SELECT data,item_guid,item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE mail_id='%u'", mail_id
);
3747 Field
*fields2
= resultItems
->Fetch();
3749 uint32 item_guidlow
= fields2
[1].GetUInt32();
3750 uint32 item_template
= fields2
[2].GetUInt32();
3752 ItemPrototype
const* itemProto
= objmgr
.GetItemPrototype(item_template
);
3755 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow
);
3759 Item
*pItem
= NewItemOrBag(itemProto
);
3760 if(!pItem
->LoadFromDB(item_guidlow
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
),resultItems
))
3762 pItem
->FSetState(ITEM_REMOVED
);
3763 pItem
->SaveToDB(); // it also deletes item object !
3767 mi
.AddItem(item_guidlow
, item_template
, pItem
);
3769 while (resultItems
->NextRow());
3775 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id
);
3777 uint32 pl_account
= objmgr
.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
3779 WorldSession::SendReturnToSender(MAIL_NORMAL
, pl_account
, guid
, sender
, subject
, itemTextId
, &mi
, money
, mailTemplateId
);
3781 while (resultMail
->NextRow());
3786 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3787 // Get guids of character's pets, will deleted in transaction
3788 QueryResult
*resultPets
= CharacterDatabase
.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid
);
3790 // NOW we can finally clear other DB data related to character
3791 CharacterDatabase
.BeginTransaction();
3796 Field
*fields3
= resultPets
->Fetch();
3797 uint32 petguidlow
= fields3
[0].GetUInt32();
3798 Pet::DeleteFromDB(petguidlow
);
3799 } while (resultPets
->NextRow());
3803 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",guid
);
3804 CharacterDatabase
.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid
);
3805 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid
);
3806 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid
);
3807 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid
);
3808 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid
);
3809 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid
);
3810 CharacterDatabase
.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid
);
3811 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid
);
3812 CharacterDatabase
.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid
);
3813 CharacterDatabase
.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid
);
3814 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid
);
3815 CharacterDatabase
.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid
);
3816 CharacterDatabase
.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid
);
3817 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid
);
3818 CharacterDatabase
.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid
,guid
);
3819 CharacterDatabase
.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid
);
3820 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid
);
3821 CharacterDatabase
.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid
);
3822 CharacterDatabase
.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid
);
3823 CharacterDatabase
.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid
);
3824 CharacterDatabase
.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid
);
3825 CharacterDatabase
.CommitTransaction();
3827 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3828 if(updateRealmChars
) sWorld
.UpdateRealmCharCount(accountId
);
3831 void Player::SetMovement(PlayerMovementType pType
)
3836 case MOVE_ROOT
: data
.Initialize(SMSG_FORCE_MOVE_ROOT
, GetPackGUID().size()+4); break;
3837 case MOVE_UNROOT
: data
.Initialize(SMSG_FORCE_MOVE_UNROOT
, GetPackGUID().size()+4); break;
3838 case MOVE_WATER_WALK
: data
.Initialize(SMSG_MOVE_WATER_WALK
, GetPackGUID().size()+4); break;
3839 case MOVE_LAND_WALK
: data
.Initialize(SMSG_MOVE_LAND_WALK
, GetPackGUID().size()+4); break;
3841 sLog
.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType
);
3844 data
.append(GetPackGUID());
3846 GetSession()->SendPacket( &data
);
3850 - a resurrectable corpse must not be loaded for the player (only bones)
3851 - the player must be in world
3853 void Player::BuildPlayerRepop()
3855 WorldPacket
data(SMSG_PRE_RESURRECT
, GetPackGUID().size());
3856 data
.append(GetPackGUID());
3857 GetSession()->SendPacket(&data
);
3859 if(getRace() == RACE_NIGHTELF
)
3860 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)
3861 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3863 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3864 // there must be SMSG.STOP_MIRROR_TIMER
3865 // there we must send 888 opcode
3867 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3870 sLog
.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3874 // create a corpse and place it at the player's location
3876 Corpse
*corpse
= GetCorpse();
3879 sLog
.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3882 GetMap()->Add(corpse
);
3884 // convert player body to ghost
3887 SetMovement(MOVE_WATER_WALK
);
3888 if(!GetSession()->isLogingOut())
3889 SetMovement(MOVE_UNROOT
);
3891 // BG - remove insignia related
3892 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_SKINNABLE
);
3894 SendCorpseReclaimDelay();
3896 // to prevent cheating
3897 corpse
->ResetGhostTime();
3899 StopMirrorTimers(); //disable timers(bars)
3901 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS
, (float)1.0); //see radius of death player?
3903 // set and clear other
3904 SetByteValue(UNIT_FIELD_BYTES_1
, 3, UNIT_BYTE1_FLAG_ALWAYS_STAND
);
3907 void Player::SendDelayResponse(const uint32 ml_seconds
)
3909 //FIXME: is this delay time arg really need? 50msec by default in code
3910 WorldPacket
data( SMSG_QUERY_TIME_RESPONSE
, 4+4 );
3911 data
<< (uint32
)time(NULL
);
3913 GetSession()->SendPacket( &data
);
3916 void Player::ResurrectPlayer(float restore_percent
, bool applySickness
)
3918 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // remove spirit healer position
3923 GetSession()->SendPacket(&data
);
3925 // speed change, land walk
3927 // remove death flag + set aura
3928 SetByteValue(UNIT_FIELD_BYTES_1
, 3, 0x00);
3929 if(getRace() == RACE_NIGHTELF
)
3930 RemoveAurasDueToSpell(20584); // speed bonuses
3931 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3933 setDeathState(ALIVE
);
3935 SetMovement(MOVE_LAND_WALK
);
3936 SetMovement(MOVE_UNROOT
);
3940 // set health/powers (0- will be set in caller)
3941 if(restore_percent
>0.0f
)
3943 SetHealth(uint32(GetMaxHealth()*restore_percent
));
3944 SetPower(POWER_MANA
, uint32(GetMaxPower(POWER_MANA
)*restore_percent
));
3945 SetPower(POWER_RAGE
, 0);
3946 SetPower(POWER_ENERGY
, uint32(GetMaxPower(POWER_ENERGY
)*restore_percent
));
3949 // trigger update zone for alive state zone updates
3950 uint32 newzone
, newarea
;
3951 GetZoneAndAreaId(newzone
,newarea
);
3952 UpdateZone(newzone
,newarea
);
3954 // update visibility
3955 ObjectAccessor::UpdateVisibilityForPlayer(this);
3960 //Characters from level 1-10 are not affected by resurrection sickness.
3961 //Characters from level 11-19 will suffer from one minute of sickness
3962 //for each level they are above 10.
3963 //Characters level 20 and up suffer from ten minutes of sickness.
3964 int32 startLevel
= sWorld
.getConfig(CONFIG_DEATH_SICKNESS_LEVEL
);
3966 if(int32(getLevel()) >= startLevel
)
3968 // set resurrection sickness
3969 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,true);
3971 // not full duration
3972 if(int32(getLevel()) < startLevel
+9)
3974 int32 delta
= (int32(getLevel()) - startLevel
+ 1)*MINUTE
;
3976 for(int i
=0; i
< 3; ++i
)
3978 if(Aura
* Aur
= GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS
,i
))
3980 Aur
->SetAuraDuration(delta
*IN_MILISECONDS
);
3981 Aur
->SendAuraUpdate(false);
3988 void Player::KillPlayer()
3990 SetMovement(MOVE_ROOT
);
3992 StopMirrorTimers(); //disable timers(bars)
3994 setDeathState(CORPSE
);
3995 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
3997 SetFlag(UNIT_DYNAMIC_FLAGS
, 0x00);
3998 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, !sMapStore
.LookupEntry(GetMapId())->Instanceable());
4000 // 6 minutes until repop at graveyard
4001 m_deathTimer
= 6*MINUTE
*IN_MILISECONDS
;
4003 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
4005 // don't create corpse at this moment, player might be falling
4007 // update visibility
4008 ObjectAccessor::UpdateObjectVisibility(this);
4011 void Player::CreateCorpse()
4013 // prevent existence 2 corpse for player
4016 uint32 _uf
, _pb
, _pb2
, _cfb1
, _cfb2
;
4018 Corpse
*corpse
= new Corpse( (m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
) ? CORPSE_RESURRECTABLE_PVP
: CORPSE_RESURRECTABLE_PVE
);
4021 if(!corpse
->Create(objmgr
.GenerateLowGuid(HIGHGUID_CORPSE
), this))
4027 _uf
= GetUInt32Value(UNIT_FIELD_BYTES_0
);
4028 _pb
= GetUInt32Value(PLAYER_BYTES
);
4029 _pb2
= GetUInt32Value(PLAYER_BYTES_2
);
4031 uint8 race
= (uint8
)(_uf
);
4032 uint8 skin
= (uint8
)(_pb
);
4033 uint8 face
= (uint8
)(_pb
>> 8);
4034 uint8 hairstyle
= (uint8
)(_pb
>> 16);
4035 uint8 haircolor
= (uint8
)(_pb
>> 24);
4036 uint8 facialhair
= (uint8
)(_pb2
);
4038 _cfb1
= ((0x00) | (race
<< 8) | (getGender() << 16) | (skin
<< 24));
4039 _cfb2
= ((face
) | (hairstyle
<< 8) | (haircolor
<< 16) | (facialhair
<< 24));
4041 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_1
, _cfb1
);
4042 corpse
->SetUInt32Value( CORPSE_FIELD_BYTES_2
, _cfb2
);
4044 uint32 flags
= CORPSE_FLAG_UNK2
;
4045 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_HELM
))
4046 flags
|= CORPSE_FLAG_HIDE_HELM
;
4047 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_HIDE_CLOAK
))
4048 flags
|= CORPSE_FLAG_HIDE_CLOAK
;
4049 if(InBattleGround() && !InArena())
4050 flags
|= CORPSE_FLAG_LOOTABLE
; // to be able to remove insignia
4051 corpse
->SetUInt32Value( CORPSE_FIELD_FLAGS
, flags
);
4053 corpse
->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID
, GetNativeDisplayId() );
4055 corpse
->SetUInt32Value( CORPSE_FIELD_GUILD
, GetGuildId() );
4058 uint16 iIventoryType
;
4060 for (int i
= 0; i
< EQUIPMENT_SLOT_END
; i
++)
4064 iDisplayID
= m_items
[i
]->GetProto()->DisplayInfoID
;
4065 iIventoryType
= (uint16
)m_items
[i
]->GetProto()->InventoryType
;
4067 _cfi
= (uint16(iDisplayID
)) | (iIventoryType
)<< 24;
4068 corpse
->SetUInt32Value(CORPSE_FIELD_ITEM
+ i
,_cfi
);
4072 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
4073 const MapEntry
*entry
= sMapStore
.LookupEntry(corpse
->GetMapId());
4075 if(entry
->map_type
!= MAP_BATTLEGROUND
)
4078 // register for player, but not show
4079 ObjectAccessor::Instance().AddCorpse(corpse
);
4082 void Player::SpawnCorpseBones()
4084 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
4085 SaveToDB(); // prevent loading as ghost without corpse
4088 Corpse
* Player::GetCorpse() const
4090 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
4093 void Player::DurabilityLossAll(double percent
, bool inventory
)
4095 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
4096 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4097 DurabilityLoss(pItem
,percent
);
4101 // bags not have durability
4102 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4104 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
4105 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4106 DurabilityLoss(pItem
,percent
);
4108 // keys not have durability
4109 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
4111 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
4112 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4113 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
4114 if(Item
* pItem
= GetItemByPos( i
, j
))
4115 DurabilityLoss(pItem
,percent
);
4119 void Player::DurabilityLoss(Item
* item
, double percent
)
4124 uint32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4129 uint32 pDurabilityLoss
= uint32(pMaxDurability
*percent
);
4131 if(pDurabilityLoss
< 1 )
4132 pDurabilityLoss
= 1;
4134 DurabilityPointsLoss(item
,pDurabilityLoss
);
4137 void Player::DurabilityPointsLossAll(int32 points
, bool inventory
)
4139 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; i
++)
4140 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4141 DurabilityPointsLoss(pItem
,points
);
4145 // bags not have durability
4146 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
4148 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
4149 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4150 DurabilityPointsLoss(pItem
,points
);
4152 // keys not have durability
4153 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
4155 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
4156 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
4157 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
4158 if(Item
* pItem
= GetItemByPos( i
, j
))
4159 DurabilityPointsLoss(pItem
,points
);
4163 void Player::DurabilityPointsLoss(Item
* item
, int32 points
)
4165 int32 pMaxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4166 int32 pOldDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4167 int32 pNewDurability
= pOldDurability
- points
;
4169 if (pNewDurability
< 0)
4171 else if (pNewDurability
> pMaxDurability
)
4172 pNewDurability
= pMaxDurability
;
4174 if (pOldDurability
!= pNewDurability
)
4176 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
4177 if ( pNewDurability
== 0 && pOldDurability
> 0 && item
->IsEquipped())
4178 _ApplyItemMods(item
,item
->GetSlot(), false);
4180 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, pNewDurability
);
4182 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
4183 if ( pNewDurability
> 0 && pOldDurability
== 0 && item
->IsEquipped())
4184 _ApplyItemMods(item
,item
->GetSlot(), true);
4186 item
->SetState(ITEM_CHANGED
, this);
4190 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot
)
4192 if(Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
))
4193 DurabilityPointsLoss(pItem
,1);
4196 uint32
Player::DurabilityRepairAll(bool cost
, float discountMod
, bool guildBank
)
4198 uint32 TotalCost
= 0;
4199 // equipped, backpack, bags itself
4200 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
4201 TotalCost
+= DurabilityRepair(( (INVENTORY_SLOT_BAG_0
<< 8) | i
),cost
,discountMod
, guildBank
);
4203 // bank, buyback and keys not repaired
4205 // items in inventory bags
4206 for(int j
= INVENTORY_SLOT_BAG_START
; j
< INVENTORY_SLOT_BAG_END
; j
++)
4207 for(int i
= 0; i
< MAX_BAG_SIZE
; i
++)
4208 TotalCost
+= DurabilityRepair(( (j
<< 8) | i
),cost
,discountMod
, guildBank
);
4212 uint32
Player::DurabilityRepair(uint16 pos
, bool cost
, float discountMod
, bool guildBank
)
4214 Item
* item
= GetItemByPos(pos
);
4216 uint32 TotalCost
= 0;
4220 uint32 maxDurability
= item
->GetUInt32Value(ITEM_FIELD_MAXDURABILITY
);
4224 uint32 curDurability
= item
->GetUInt32Value(ITEM_FIELD_DURABILITY
);
4228 uint32 LostDurability
= maxDurability
- curDurability
;
4229 if(LostDurability
>0)
4231 ItemPrototype
const *ditemProto
= item
->GetProto();
4233 DurabilityCostsEntry
const *dcost
= sDurabilityCostsStore
.LookupEntry(ditemProto
->ItemLevel
);
4236 sLog
.outError("RepairDurability: Wrong item lvl %u", ditemProto
->ItemLevel
);
4240 uint32 dQualitymodEntryId
= (ditemProto
->Quality
+1)*2;
4241 DurabilityQualityEntry
const *dQualitymodEntry
= sDurabilityQualityStore
.LookupEntry(dQualitymodEntryId
);
4242 if(!dQualitymodEntry
)
4244 sLog
.outError("RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId
);
4248 uint32 dmultiplier
= dcost
->multiplier
[ItemSubClassToDurabilityMultiplierId(ditemProto
->Class
,ditemProto
->SubClass
)];
4249 uint32 costs
= uint32(LostDurability
*dmultiplier
*double(dQualitymodEntry
->quality_mod
));
4251 costs
= uint32(costs
* discountMod
);
4253 if (costs
==0) //fix for ITEM_QUALITY_ARTIFACT
4258 if (GetGuildId()==0)
4260 DEBUG_LOG("You are not member of a guild");
4264 Guild
*pGuild
= objmgr
.GetGuildById(GetGuildId());
4268 if (!pGuild
->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR
))
4270 DEBUG_LOG("You do not have rights to withdraw for repairs");
4274 if (pGuild
->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs
)
4276 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4280 if (pGuild
->GetGuildBankMoney() < costs
)
4282 DEBUG_LOG("There is not enough money in bank");
4286 pGuild
->MemberMoneyWithdraw(costs
, GetGUIDLow());
4289 else if (GetMoney() < costs
)
4291 DEBUG_LOG("You do not have enough money");
4295 ModifyMoney( -int32(costs
) );
4299 item
->SetUInt32Value(ITEM_FIELD_DURABILITY
, maxDurability
);
4300 item
->SetState(ITEM_CHANGED
, this);
4302 // reapply mods for total broken and repaired item if equipped
4303 if(IsEquipmentPos(pos
) && !curDurability
)
4304 _ApplyItemMods(item
,pos
& 255, true);
4308 void Player::RepopAtGraveyard()
4310 // note: this can be called also when the player is alive
4311 // for example from WorldSession::HandleMovementOpcodes
4313 AreaTableEntry
const *zone
= GetAreaEntryByAreaID(GetAreaId());
4315 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4316 if(!isAlive() && zone
&& zone
->flags
& AREA_FLAG_NEED_FLY
|| GetTransport())
4318 ResurrectPlayer(0.5f
);
4322 WorldSafeLocsEntry
const *ClosestGrave
= NULL
;
4324 // Special handle for battleground maps
4325 if( BattleGround
*bg
= GetBattleGround() )
4326 ClosestGrave
= bg
->GetClosestGraveYard(this);
4328 ClosestGrave
= objmgr
.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4330 // stop countdown until repop
4333 // if no grave found, stay at the current location
4334 // and don't show spirit healer location
4337 TeleportTo(ClosestGrave
->map_id
, ClosestGrave
->x
, ClosestGrave
->y
, ClosestGrave
->z
, GetOrientation());
4338 if(isDead()) // not send if alive, because it used in TeleportTo()
4340 WorldPacket
data(SMSG_DEATH_RELEASE_LOC
, 4*4); // show spirit healer position on minimap
4341 data
<< ClosestGrave
->map_id
;
4342 data
<< ClosestGrave
->x
;
4343 data
<< ClosestGrave
->y
;
4344 data
<< ClosestGrave
->z
;
4345 GetSession()->SendPacket(&data
);
4350 void Player::JoinedChannel(Channel
*c
)
4352 m_channels
.push_back(c
);
4355 void Player::LeftChannel(Channel
*c
)
4357 m_channels
.remove(c
);
4360 void Player::CleanupChannels()
4362 while(!m_channels
.empty())
4364 Channel
* ch
= *m_channels
.begin();
4365 m_channels
.erase(m_channels
.begin()); // remove from player's channel list
4366 ch
->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4367 if (ChannelMgr
* cMgr
= channelMgr(GetTeam()))
4368 cMgr
->LeftChannel(ch
->GetName()); // deleted channel if empty
4371 sLog
.outDebug("Player: channels cleaned up!");
4374 void Player::UpdateLocalChannels(uint32 newZone
)
4376 if(m_channels
.empty())
4379 AreaTableEntry
const* current_zone
= GetAreaEntryByAreaID(newZone
);
4383 ChannelMgr
* cMgr
= channelMgr(GetTeam());
4387 std::string current_zone_name
= current_zone
->area_name
[GetSession()->GetSessionDbcLocale()];
4389 for(JoinedChannelsList::iterator i
= m_channels
.begin(), next
; i
!= m_channels
.end(); i
= next
)
4393 // skip non built-in channels
4394 if(!(*i
)->IsConstant())
4397 ChatChannelsEntry
const* ch
= GetChannelEntryFor((*i
)->GetChannelId());
4401 if((ch
->flags
& 4) == 4) // global channel without zone name in pattern
4405 char new_channel_name_buf
[100];
4406 snprintf(new_channel_name_buf
,100,ch
->pattern
[m_session
->GetSessionDbcLocale()],current_zone_name
.c_str());
4407 Channel
* new_channel
= cMgr
->GetJoinChannel(new_channel_name_buf
,ch
->ChannelID
);
4409 if((*i
)!=new_channel
)
4411 new_channel
->Join(GetGUID(),""); // will output Changed Channel: N. Name
4413 // leave old channel
4414 (*i
)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4415 std::string name
= (*i
)->GetName(); // store name, (*i)erase in LeftChannel
4416 LeftChannel(*i
); // remove from player's channel list
4417 cMgr
->LeftChannel(name
); // delete if empty
4420 sLog
.outDebug("Player: channels cleaned up!");
4423 void Player::LeaveLFGChannel()
4425 for(JoinedChannelsList::iterator i
= m_channels
.begin(); i
!= m_channels
.end(); ++i
)
4429 (*i
)->Leave(GetGUID());
4435 void Player::UpdateDefense()
4437 uint32 defense_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_DEFENSE
);
4439 if(UpdateSkill(SKILL_DEFENSE
,defense_skill_gain
))
4441 // update dependent from defense skill part
4442 UpdateDefenseBonusesMod();
4446 void Player::HandleBaseModValue(BaseModGroup modGroup
, BaseModType modType
, float amount
, bool apply
)
4448 if(modGroup
>= BASEMOD_END
|| modType
>= MOD_END
)
4450 sLog
.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4459 m_auraBaseMod
[modGroup
][modType
] += apply
? amount
: -amount
;
4462 if(amount
<= -100.0f
)
4465 val
= (100.0f
+ amount
) / 100.0f
;
4466 m_auraBaseMod
[modGroup
][modType
] *= apply
? val
: (1.0f
/val
);
4470 if(!CanModifyStats())
4475 case CRIT_PERCENTAGE
: UpdateCritPercentage(BASE_ATTACK
); break;
4476 case RANGED_CRIT_PERCENTAGE
: UpdateCritPercentage(RANGED_ATTACK
); break;
4477 case OFFHAND_CRIT_PERCENTAGE
: UpdateCritPercentage(OFF_ATTACK
); break;
4478 case SHIELD_BLOCK_VALUE
: UpdateShieldBlockValue(); break;
4483 float Player::GetBaseModValue(BaseModGroup modGroup
, BaseModType modType
) const
4485 if(modGroup
>= BASEMOD_END
|| modType
> MOD_END
)
4487 sLog
.outError("trial to access non existed BaseModGroup or wrong BaseModType!");
4491 if(modType
== PCT_MOD
&& m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4494 return m_auraBaseMod
[modGroup
][modType
];
4497 float Player::GetTotalBaseModValue(BaseModGroup modGroup
) const
4499 if(modGroup
>= BASEMOD_END
)
4501 sLog
.outError("wrong BaseModGroup in GetTotalBaseModValue()!");
4505 if(m_auraBaseMod
[modGroup
][PCT_MOD
] <= 0.0f
)
4508 return m_auraBaseMod
[modGroup
][FLAT_MOD
] * m_auraBaseMod
[modGroup
][PCT_MOD
];
4511 uint32
Player::GetShieldBlockValue() const
4513 float value
= (m_auraBaseMod
[SHIELD_BLOCK_VALUE
][FLAT_MOD
] + GetStat(STAT_STRENGTH
) * 0.5f
- 10)*m_auraBaseMod
[SHIELD_BLOCK_VALUE
][PCT_MOD
];
4515 value
= (value
< 0) ? 0 : value
;
4517 return uint32(value
);
4520 float Player::GetMeleeCritFromAgility()
4522 uint32 level
= getLevel();
4523 uint32 pclass
= getClass();
4525 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4527 GtChanceToMeleeCritBaseEntry
const *critBase
= sGtChanceToMeleeCritBaseStore
.LookupEntry(pclass
-1);
4528 GtChanceToMeleeCritEntry
const *critRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4529 if (critBase
==NULL
|| critRatio
==NULL
)
4532 float crit
=critBase
->base
+ GetStat(STAT_AGILITY
)*critRatio
->ratio
;
4536 float Player::GetDodgeFromAgility()
4538 // Table for base dodge values
4539 float dodge_base
[MAX_CLASSES
] = {
4541 0.00652f
, // Paladin
4548 0.02011f
, // Warlock
4552 // Crit/agility to dodge/agility coefficient multipliers
4553 float crit_to_dodge
[MAX_CLASSES
] = {
4567 uint32 level
= getLevel();
4568 uint32 pclass
= getClass();
4570 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4572 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4573 GtChanceToMeleeCritEntry
const *dodgeRatio
= sGtChanceToMeleeCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4574 if (dodgeRatio
==NULL
|| pclass
> MAX_CLASSES
)
4577 float dodge
=dodge_base
[pclass
-1] + GetStat(STAT_AGILITY
) * dodgeRatio
->ratio
* crit_to_dodge
[pclass
-1];
4578 return dodge
*100.0f
;
4581 float Player::GetSpellCritFromIntellect()
4583 uint32 level
= getLevel();
4584 uint32 pclass
= getClass();
4586 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4588 GtChanceToSpellCritBaseEntry
const *critBase
= sGtChanceToSpellCritBaseStore
.LookupEntry(pclass
-1);
4589 GtChanceToSpellCritEntry
const *critRatio
= sGtChanceToSpellCritStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4590 if (critBase
==NULL
|| critRatio
==NULL
)
4593 float crit
=critBase
->base
+ GetStat(STAT_INTELLECT
)*critRatio
->ratio
;
4597 float Player::GetRatingCoefficient(CombatRating cr
) const
4599 uint32 level
= getLevel();
4601 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4603 GtCombatRatingsEntry
const *Rating
= sGtCombatRatingsStore
.LookupEntry(cr
*GT_MAX_LEVEL
+level
-1);
4605 return 1.0f
; // By default use minimum coefficient (not must be called)
4607 return Rating
->ratio
;
4610 float Player::GetRatingBonusValue(CombatRating cr
) const
4612 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
)) / GetRatingCoefficient(cr
);
4615 uint32
Player::GetMeleeCritDamageReduction(uint32 damage
) const
4617 float melee
= GetRatingBonusValue(CR_CRIT_TAKEN_MELEE
)*2.0f
;
4618 if (melee
>25.0f
) melee
= 25.0f
;
4619 return uint32 (melee
* damage
/100.0f
);
4622 uint32
Player::GetRangedCritDamageReduction(uint32 damage
) const
4624 float ranged
= GetRatingBonusValue(CR_CRIT_TAKEN_RANGED
)*2.0f
;
4625 if (ranged
>25.0f
) ranged
=25.0f
;
4626 return uint32 (ranged
* damage
/100.0f
);
4629 uint32
Player::GetSpellCritDamageReduction(uint32 damage
) const
4631 float spell
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
)*2.0f
;
4632 // In wow script resilience limited to 25%
4635 return uint32 (spell
* damage
/ 100.0f
);
4638 uint32
Player::GetDotDamageReduction(uint32 damage
) const
4640 float spellDot
= GetRatingBonusValue(CR_CRIT_TAKEN_SPELL
);
4641 // Dot resilience not limited (limit it by 100%)
4642 if (spellDot
> 100.0f
)
4644 return uint32 (spellDot
* damage
/ 100.0f
);
4647 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType
) const
4652 return GetUInt32Value(PLAYER_EXPERTISE
) / 4.0f
;
4654 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE
) / 4.0f
;
4661 float Player::OCTRegenHPPerSpirit()
4663 uint32 level
= getLevel();
4664 uint32 pclass
= getClass();
4666 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4668 GtOCTRegenHPEntry
const *baseRatio
= sGtOCTRegenHPStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4669 GtRegenHPPerSptEntry
const *moreRatio
= sGtRegenHPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4670 if (baseRatio
==NULL
|| moreRatio
==NULL
)
4673 // Formula from PaperDollFrame script
4674 float spirit
= GetStat(STAT_SPIRIT
);
4675 float baseSpirit
= spirit
;
4676 if (baseSpirit
>50) baseSpirit
= 50;
4677 float moreSpirit
= spirit
- baseSpirit
;
4678 float regen
= baseSpirit
* baseRatio
->ratio
+ moreSpirit
* moreRatio
->ratio
;
4682 float Player::OCTRegenMPPerSpirit()
4684 uint32 level
= getLevel();
4685 uint32 pclass
= getClass();
4687 if (level
>GT_MAX_LEVEL
) level
= GT_MAX_LEVEL
;
4689 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4690 GtRegenMPPerSptEntry
const *moreRatio
= sGtRegenMPPerSptStore
.LookupEntry((pclass
-1)*GT_MAX_LEVEL
+ level
-1);
4691 if (moreRatio
==NULL
)
4694 // Formula get from PaperDollFrame script
4695 float spirit
= GetStat(STAT_SPIRIT
);
4696 float regen
= spirit
* moreRatio
->ratio
;
4700 void Player::ApplyRatingMod(CombatRating cr
, int32 value
, bool apply
)
4702 m_baseRatingValue
[cr
]+=(apply
? value
: -value
);
4704 int32 amount
= uint32(m_baseRatingValue
[cr
]);
4705 // Apply bonus from SPELL_AURA_MOD_RATING_FROM_STAT
4706 // stat used stored in miscValueB for this aura
4707 AuraList
const& modRatingFromStat
= GetAurasByType(SPELL_AURA_MOD_RATING_FROM_STAT
);
4708 for(AuraList::const_iterator i
= modRatingFromStat
.begin();i
!= modRatingFromStat
.end(); ++i
)
4709 if ((*i
)->GetMiscValue() & (1<<cr
))
4710 amount
+= int32(GetStat(Stats((*i
)->GetMiscBValue())) * (*i
)->GetModifier()->m_amount
/ 100.0f
);
4713 SetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1
+ cr
, uint32(amount
));
4715 float RatingCoeffecient
= GetRatingCoefficient(cr
);
4716 float RatingChange
= 0.0f
;
4718 bool affectStats
= CanModifyStats();
4722 case CR_WEAPON_SKILL
: // Implemented in Unit::RollMeleeOutcomeAgainst
4723 case CR_DEFENSE_SKILL
:
4724 UpdateDefenseBonusesMod();
4727 UpdateDodgePercentage();
4730 UpdateParryPercentage();
4733 UpdateBlockPercentage();
4736 UpdateMeleeHitChances();
4739 UpdateRangedHitChances();
4742 UpdateSpellHitChances();
4747 UpdateCritPercentage(BASE_ATTACK
);
4748 UpdateCritPercentage(OFF_ATTACK
);
4751 case CR_CRIT_RANGED
:
4753 UpdateCritPercentage(RANGED_ATTACK
);
4757 UpdateAllSpellCritChances();
4759 case CR_HIT_TAKEN_MELEE
: // Implemented in Unit::MeleeMissChanceCalc
4760 case CR_HIT_TAKEN_RANGED
:
4762 case CR_HIT_TAKEN_SPELL
: // Implemented in Unit::MagicSpellHitResult
4764 case CR_CRIT_TAKEN_MELEE
: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4765 case CR_CRIT_TAKEN_RANGED
:
4767 case CR_CRIT_TAKEN_SPELL
: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4769 case CR_HASTE_MELEE
:
4770 RatingChange
= value
/ RatingCoeffecient
;
4771 ApplyAttackTimePercentMod(BASE_ATTACK
,RatingChange
,apply
);
4772 ApplyAttackTimePercentMod(OFF_ATTACK
,RatingChange
,apply
);
4774 case CR_HASTE_RANGED
:
4775 RatingChange
= value
/ RatingCoeffecient
;
4776 ApplyAttackTimePercentMod(RANGED_ATTACK
, RatingChange
, apply
);
4778 case CR_HASTE_SPELL
:
4779 RatingChange
= value
/ RatingCoeffecient
;
4780 ApplyCastTimePercentMod(RatingChange
,apply
);
4782 case CR_WEAPON_SKILL_MAINHAND
: // Implemented in Unit::RollMeleeOutcomeAgainst
4783 case CR_WEAPON_SKILL_OFFHAND
:
4784 case CR_WEAPON_SKILL_RANGED
:
4789 UpdateExpertise(BASE_ATTACK
);
4790 UpdateExpertise(OFF_ATTACK
);
4796 void Player::SetRegularAttackTime()
4798 for(int i
= 0; i
< MAX_ATTACK
; ++i
)
4800 Item
*tmpitem
= GetWeaponForAttack(WeaponAttackType(i
));
4801 if(tmpitem
&& !tmpitem
->IsBroken())
4803 ItemPrototype
const *proto
= tmpitem
->GetProto();
4805 SetAttackTime(WeaponAttackType(i
), proto
->Delay
);
4807 SetAttackTime(WeaponAttackType(i
), BASE_ATTACK_TIME
);
4812 //skill+step, checking for max value
4813 bool Player::UpdateSkill(uint32 skill_id
, uint32 step
)
4819 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4820 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill_id
)
4823 if(i
>=PLAYER_MAX_SKILLS
)
4826 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4827 uint32 value
= SKILL_VALUE(data
);
4828 uint32 max
= SKILL_MAX(data
);
4830 if ((!max
) || (!value
) || (value
>= max
))
4833 if (value
*512 < max
*urand(0,512))
4835 uint32 new_value
= value
+step
;
4839 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,max
));
4840 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,skill_id
);
4847 inline int SkillGainChance(uint32 SkillValue
, uint32 GrayLevel
, uint32 GreenLevel
, uint32 YellowLevel
)
4849 if ( SkillValue
>= GrayLevel
)
4850 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREY
)*10;
4851 if ( SkillValue
>= GreenLevel
)
4852 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_GREEN
)*10;
4853 if ( SkillValue
>= YellowLevel
)
4854 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_YELLOW
)*10;
4855 return sWorld
.getConfig(CONFIG_SKILL_CHANCE_ORANGE
)*10;
4858 bool Player::UpdateCraftSkill(uint32 spellid
)
4860 sLog
.outDebug("UpdateCraftSkill spellid %d", spellid
);
4862 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spellid
);
4863 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spellid
);
4865 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
4867 if(_spell_idx
->second
->skillId
)
4869 uint32 SkillValue
= GetPureSkillValue(_spell_idx
->second
->skillId
);
4871 // Alchemy Discoveries here
4872 SpellEntry
const* spellEntry
= sSpellStore
.LookupEntry(spellid
);
4873 if(spellEntry
&& spellEntry
->Mechanic
==MECHANIC_DISCOVERY
)
4875 if(uint32 discoveredSpell
= GetSkillDiscoverySpell(_spell_idx
->second
->skillId
, spellid
, this))
4876 learnSpell(discoveredSpell
,false);
4879 uint32 craft_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_CRAFTING
);
4881 return UpdateSkillPro(_spell_idx
->second
->skillId
, SkillGainChance(SkillValue
,
4882 _spell_idx
->second
->max_value
,
4883 (_spell_idx
->second
->max_value
+ _spell_idx
->second
->min_value
)/2,
4884 _spell_idx
->second
->min_value
),
4891 bool Player::UpdateGatherSkill(uint32 SkillId
, uint32 SkillValue
, uint32 RedLevel
, uint32 Multiplicator
)
4893 sLog
.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId
, SkillValue
, RedLevel
);
4895 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
4897 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4900 case SKILL_HERBALISM
:
4901 case SKILL_LOCKPICKING
:
4902 case SKILL_JEWELCRAFTING
:
4903 case SKILL_INSCRIPTION
:
4904 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4905 case SKILL_SKINNING
:
4906 if( sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)==0)
4907 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4909 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS
)), gathering_skill_gain
);
4911 if (sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)==0)
4912 return UpdateSkillPro(SkillId
, SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
,gathering_skill_gain
);
4914 return UpdateSkillPro(SkillId
, (SkillGainChance(SkillValue
, RedLevel
+100, RedLevel
+50, RedLevel
+25)*Multiplicator
) >> (SkillValue
/sWorld
.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS
)),gathering_skill_gain
);
4919 bool Player::UpdateFishingSkill()
4921 sLog
.outDebug("UpdateFishingSkill");
4923 uint32 SkillValue
= GetPureSkillValue(SKILL_FISHING
);
4925 int32 chance
= SkillValue
< 75 ? 100 : 2500/(SkillValue
-50);
4927 uint32 gathering_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_GATHERING
);
4929 return UpdateSkillPro(SKILL_FISHING
,chance
*10,gathering_skill_gain
);
4932 // levels sync. with spell requirement for skill levels to learn
4933 // bonus abilities in sSkillLineAbilityStore
4934 // Used only to avoid scan DBC at each skill grow
4935 static uint32 bonusSkillLevels
[] = {75,150,225,300,375,450};
4937 bool Player::UpdateSkillPro(uint16 SkillId
, int32 Chance
, uint32 step
)
4939 sLog
.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId
, Chance
/10.0);
4943 if(Chance
<= 0) // speedup in 0 chance case
4945 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
4950 for (; i
< PLAYER_MAX_SKILLS
; i
++)
4951 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i
))) == SkillId
) break;
4952 if ( i
>= PLAYER_MAX_SKILLS
)
4955 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
4956 uint16 SkillValue
= SKILL_VALUE(data
);
4957 uint16 MaxValue
= SKILL_MAX(data
);
4959 if ( !MaxValue
|| !SkillValue
|| SkillValue
>= MaxValue
)
4962 int32 Roll
= irand(1,1000);
4964 if ( Roll
<= Chance
)
4966 uint32 new_value
= SkillValue
+step
;
4967 if(new_value
> MaxValue
)
4968 new_value
= MaxValue
;
4970 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(new_value
,MaxValue
));
4971 for(uint32
* bsl
= &bonusSkillLevels
[0]; *bsl
; ++bsl
)
4973 if((SkillValue
< *bsl
&& new_value
>= *bsl
))
4975 learnSkillRewardedSpells( SkillId
, new_value
);
4979 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,SkillId
);
4980 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance
/10.0);
4984 sLog
.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance
/10.0);
4988 void Player::UpdateWeaponSkill (WeaponAttackType attType
)
4990 // no skill gain in pvp
4991 Unit
*pVictim
= getVictim();
4992 if(pVictim
&& pVictim
->GetTypeId() == TYPEID_PLAYER
)
4996 return; // always maximized SKILL_FERAL_COMBAT in fact
4998 if(m_form
== FORM_TREE
)
4999 return; // use weapon but not skill up
5001 uint32 weapon_skill_gain
= sWorld
.getConfig(CONFIG_SKILL_GAIN_WEAPON
);
5007 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
5010 UpdateSkill(SKILL_UNARMED
,weapon_skill_gain
);
5011 else if(tmpitem
->GetProto()->SubClass
!= ITEM_SUBCLASS_WEAPON_FISHING_POLE
)
5012 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
5018 Item
*tmpitem
= GetWeaponForAttack(attType
,true);
5020 UpdateSkill(tmpitem
->GetSkill(),weapon_skill_gain
);
5024 UpdateAllCritPercentages();
5027 void Player::UpdateCombatSkills(Unit
*pVictim
, WeaponAttackType attType
, bool defence
)
5029 uint32 plevel
= getLevel(); // if defense than pVictim == attacker
5030 uint32 greylevel
= MaNGOS::XP::GetGrayLevel(plevel
);
5031 uint32 moblevel
= pVictim
->getLevelForTarget(this);
5032 if(moblevel
< greylevel
)
5035 if (moblevel
> plevel
+ 5)
5036 moblevel
= plevel
+ 5;
5038 uint32 lvldif
= moblevel
- greylevel
;
5042 uint32 skilldif
= 5 * plevel
- (defence
? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType
));
5046 float chance
= float(3 * lvldif
* skilldif
) / plevel
;
5049 if(getClass() == CLASS_WARRIOR
|| getClass() == CLASS_ROGUE
)
5050 chance
*= 0.1f
* GetStat(STAT_INTELLECT
);
5053 chance
= chance
< 1.0f
? 1.0f
: chance
; //minimum chance to increase skill is 1%
5055 if(roll_chance_f(chance
))
5060 UpdateWeaponSkill(attType
);
5066 void Player::ModifySkillBonus(uint32 skillid
,int32 val
, bool talent
)
5068 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5069 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skillid
)
5071 uint32 bonus_val
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5072 int16 temp_bonus
= SKILL_TEMP_BONUS(bonus_val
);
5073 int16 perm_bonus
= SKILL_PERM_BONUS(bonus_val
);
5075 if(talent
) // permanent bonus stored in high part
5076 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
,perm_bonus
+val
));
5077 else // temporary/item bonus stored in low part
5078 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),MAKE_SKILL_BONUS(temp_bonus
+val
,perm_bonus
));
5083 void Player::UpdateSkillsForLevel()
5085 uint16 maxconfskill
= sWorld
.GetConfigMaxSkillValue();
5086 uint32 maxSkill
= GetMaxSkillValueForLevel();
5088 bool alwaysMaxSkill
= sWorld
.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL
);
5090 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5091 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5093 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
5095 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(pskill
);
5099 if(GetSkillRangeType(pSkill
,false) != SKILL_RANGE_LEVEL
)
5102 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
5103 uint32 max
= SKILL_MAX(data
);
5104 uint32 val
= SKILL_VALUE(data
);
5106 /// update only level dependent max skill values
5109 /// miximize skill always
5111 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(maxSkill
,maxSkill
));
5112 /// update max skill value if current max skill not maximized
5113 else if(max
!= maxconfskill
)
5114 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(val
,maxSkill
));
5119 void Player::UpdateSkillsToMaxSkillsForLevel()
5121 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5122 if (GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5124 uint32 pskill
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
5125 if( IsProfessionOrRidingSkill(pskill
))
5127 uint32 data
= GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
));
5129 uint32 max
= SKILL_MAX(data
);
5132 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(max
,max
));
5134 if(pskill
== SKILL_DEFENSE
)
5135 UpdateDefenseBonusesMod();
5139 // This functions sets a skill line value (and adds if doesn't exist yet)
5140 // To "remove" a skill line, set it's values to zero
5141 void Player::SetSkill(uint32 id
, uint16 currVal
, uint16 maxVal
)
5147 for (; i
< PLAYER_MAX_SKILLS
; i
++)
5148 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == id
) break;
5150 if(i
<PLAYER_MAX_SKILLS
) //has skill
5154 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
5155 learnSkillRewardedSpells(id
, currVal
);
5156 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,id
);
5157 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL
,id
);
5161 // clear skill fields
5162 SetUInt32Value(PLAYER_SKILL_INDEX(i
),0);
5163 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),0);
5164 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
5166 // remove all spells that related to this skill
5167 for (uint32 j
=0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
5168 if(SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
))
5169 if (pAbility
->skillId
==id
)
5170 removeSpell(spellmgr
.GetFirstSpellInChain(pAbility
->spellId
));
5173 else if(currVal
) //add
5175 for (i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5176 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i
)))
5178 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
5181 sLog
.outError("Skill not found in SkillLineStore: skill #%u", id
);
5184 // enable unlearn button for primary professions only
5185 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
5186 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
5188 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
5189 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(currVal
,maxVal
));
5190 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL
,id
);
5191 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL
,id
);
5193 // apply skill bonuses
5194 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
5196 // temporary bonuses
5197 AuraList
const& mModSkill
= GetAurasByType(SPELL_AURA_MOD_SKILL
);
5198 for(AuraList::const_iterator i
= mModSkill
.begin(); i
!= mModSkill
.end(); ++i
)
5199 if ((*i
)->GetModifier()->m_miscvalue
== int32(id
))
5200 (*i
)->ApplyModifier(true);
5202 // permanent bonuses
5203 AuraList
const& mModSkillTalent
= GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT
);
5204 for(AuraList::const_iterator i
= mModSkillTalent
.begin(); i
!= mModSkillTalent
.end(); ++i
)
5205 if ((*i
)->GetModifier()->m_miscvalue
== int32(id
))
5206 (*i
)->ApplyModifier(true);
5208 // Learn all spells for skill
5209 learnSkillRewardedSpells(id
, currVal
);
5215 bool Player::HasSkill(uint32 skill
) const
5217 if(!skill
)return false;
5218 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5220 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5228 uint16
Player::GetSkillValue(uint32 skill
) const
5233 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5235 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5237 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5239 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5240 result
+= SKILL_TEMP_BONUS(bonus
);
5241 result
+= SKILL_PERM_BONUS(bonus
);
5242 return result
< 0 ? 0 : result
;
5248 uint16
Player::GetMaxSkillValue(uint32 skill
) const
5251 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5253 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5255 uint32 bonus
= GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
));
5257 int32 result
= int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5258 result
+= SKILL_TEMP_BONUS(bonus
);
5259 result
+= SKILL_PERM_BONUS(bonus
);
5260 return result
< 0 ? 0 : result
;
5266 uint16
Player::GetPureMaxSkillValue(uint32 skill
) const
5269 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5271 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5273 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5279 uint16
Player::GetBaseSkillValue(uint32 skill
) const
5282 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5284 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5286 int32 result
= int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
))));
5287 result
+= SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5288 return result
< 0 ? 0 : result
;
5294 uint16
Player::GetPureSkillValue(uint32 skill
) const
5297 for (uint16 i
=0; i
< PLAYER_MAX_SKILLS
; i
++)
5299 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5301 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
5307 int16
Player::GetSkillPermBonusValue(uint32 skill
) const
5312 for (int i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
5314 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5316 return SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5323 int16
Player::GetSkillTempBonusValue(uint32 skill
) const
5328 for (int i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
5330 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF) == skill
)
5332 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
)));
5339 void Player::SendInitialActionButtons()
5341 sLog
.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5343 WorldPacket
data(SMSG_ACTION_BUTTONS
, (MAX_ACTION_BUTTONS
*4));
5344 for(int button
= 0; button
< MAX_ACTION_BUTTONS
; ++button
)
5346 ActionButtonList::const_iterator itr
= m_actionButtons
.find(button
);
5347 if(itr
!= m_actionButtons
.end() && itr
->second
.uState
!= ACTIONBUTTON_DELETED
)
5349 data
<< uint16(itr
->second
.action
);
5350 data
<< uint8(itr
->second
.misc
);
5351 data
<< uint8(itr
->second
.type
);
5359 GetSession()->SendPacket( &data
);
5360 sLog
.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5363 bool Player::addActionButton(const uint8 button
, const uint16 action
, const uint8 type
, const uint8 misc
)
5365 if(button
>= MAX_ACTION_BUTTONS
)
5367 sLog
.outError( "Action %u not added into button %u for player %s: button must be < 132", action
, button
, GetName() );
5371 // check cheating with adding non-known spells to action bar
5372 if(type
==ACTION_BUTTON_SPELL
)
5374 if(!sSpellStore
.LookupEntry(action
))
5376 sLog
.outError( "Action %u not added into button %u for player %s: spell not exist", action
, button
, GetName() );
5380 if(!HasSpell(action
))
5382 sLog
.outError( "Action %u not added into button %u for player %s: player don't known this spell", action
, button
, GetName() );
5387 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5389 if (buttonItr
==m_actionButtons
.end())
5390 { // just add new button
5391 m_actionButtons
[button
] = ActionButton(action
,type
,misc
);
5394 { // change state of current button
5395 ActionButtonUpdateState uState
= buttonItr
->second
.uState
;
5396 buttonItr
->second
= ActionButton(action
,type
,misc
);
5397 if (uState
!= ACTIONBUTTON_NEW
) buttonItr
->second
.uState
= ACTIONBUTTON_CHANGED
;
5400 sLog
.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action
, button
);
5404 void Player::removeActionButton(uint8 button
)
5406 ActionButtonList::iterator buttonItr
= m_actionButtons
.find(button
);
5407 if (buttonItr
==m_actionButtons
.end())
5410 if(buttonItr
->second
.uState
==ACTIONBUTTON_NEW
)
5411 m_actionButtons
.erase(buttonItr
); // new and not saved
5413 buttonItr
->second
.uState
= ACTIONBUTTON_DELETED
; // saved, will deleted at next save
5415 sLog
.outDetail( "Action Button '%u' Removed from Player '%u'", button
, GetGUIDLow() );
5418 void Player::SetDontMove(bool dontMove
)
5420 m_dontMove
= dontMove
;
5423 bool Player::SetPosition(float x
, float y
, float z
, float orientation
, bool teleport
)
5425 // prevent crash when a bad coord is sent by the client
5426 if(!MaNGOS::IsValidMapCoord(x
,y
,z
,orientation
))
5428 sLog
.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x
,y
,z
,orientation
,teleport
,GetGUIDLow());
5434 const float old_x
= GetPositionX();
5435 const float old_y
= GetPositionY();
5436 const float old_z
= GetPositionZ();
5437 const float old_r
= GetOrientation();
5439 if( teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
|| old_r
!= orientation
)
5441 if (teleport
|| old_x
!= x
|| old_y
!= y
|| old_z
!= z
)
5442 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE
| AURA_INTERRUPT_FLAG_TURNING
);
5444 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING
);
5446 // move and update visible state if need
5447 m
->PlayerRelocation(this, x
, y
, z
, orientation
);
5449 // reread after Map::Relocation
5456 if(GetGroup() && (old_x
!= x
|| old_y
!= y
))
5457 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION
);
5460 // code block for underwater state update
5461 UpdateUnderwaterState(m
, x
, y
, z
);
5463 CheckExploreSystem();
5468 void Player::SaveRecallPosition()
5470 m_recallMap
= GetMapId();
5471 m_recallX
= GetPositionX();
5472 m_recallY
= GetPositionY();
5473 m_recallZ
= GetPositionZ();
5474 m_recallO
= GetOrientation();
5477 void Player::SendMessageToSet(WorldPacket
*data
, bool self
)
5479 GetMap()->MessageBroadcast(this, data
, self
);
5482 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
)
5484 GetMap()->MessageDistBroadcast(this, data
, dist
, self
);
5487 void Player::SendMessageToSetInRange(WorldPacket
*data
, float dist
, bool self
, bool own_team_only
)
5489 GetMap()->MessageDistBroadcast(this, data
, dist
, self
,own_team_only
);
5492 void Player::SendDirectMessage(WorldPacket
*data
)
5494 GetSession()->SendPacket(data
);
5497 void Player::CheckExploreSystem()
5505 uint16 areaFlag
=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY(),GetPositionZ());
5506 if(areaFlag
==0xffff)
5508 int offset
= areaFlag
/ 32;
5512 sLog
.outError("Wrong area flag %u in map data for (X: %f Y: %f) point to field PLAYER_EXPLORED_ZONES_1 + %u ( %u must be < 128 ).",areaFlag
,GetPositionX(),GetPositionY(),offset
,offset
);
5516 uint32 val
= (uint32
)(1 << (areaFlag
% 32));
5517 uint32 currFields
= GetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
);
5519 if( !(currFields
& val
) )
5521 SetUInt32Value(PLAYER_EXPLORED_ZONES_1
+ offset
, (uint32
)(currFields
| val
));
5523 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA
);
5525 AreaTableEntry
const *p
= GetAreaEntryByAreaFlagAndMap(areaFlag
,GetMapId());
5528 sLog
.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5530 else if(p
->area_level
> 0)
5532 uint32 area
= p
->ID
;
5533 if (getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
5535 SendExplorationExperience(area
,0);
5539 int32 diff
= int32(getLevel()) - p
->area_level
;
5543 XP
= uint32(objmgr
.GetBaseXP(getLevel()+5)*sWorld
.getRate(RATE_XP_EXPLORE
));
5547 int32 exploration_percent
= (100-((diff
-5)*5));
5548 if (exploration_percent
> 100)
5549 exploration_percent
= 100;
5550 else if (exploration_percent
< 0)
5551 exploration_percent
= 0;
5553 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*exploration_percent
/100*sWorld
.getRate(RATE_XP_EXPLORE
));
5557 XP
= uint32(objmgr
.GetBaseXP(p
->area_level
)*sWorld
.getRate(RATE_XP_EXPLORE
));
5561 SendExplorationExperience(area
,XP
);
5563 sLog
.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area
);
5568 uint32
Player::TeamForRace(uint8 race
)
5570 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5573 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5577 switch(rEntry
->TeamID
)
5579 case 7: return ALLIANCE
;
5580 case 1: return HORDE
;
5583 sLog
.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race
),rEntry
->TeamID
);
5587 uint32
Player::getFactionForRace(uint8 race
)
5589 ChrRacesEntry
const* rEntry
= sChrRacesStore
.LookupEntry(race
);
5592 sLog
.outError("Race %u not found in DBC: wrong DBC files?",uint32(race
));
5596 return rEntry
->FactionID
;
5599 void Player::setFactionForRace(uint8 race
)
5601 m_team
= TeamForRace(race
);
5602 setFaction( getFactionForRace(race
) );
5605 ReputationRank
Player::GetReputationRank(uint32 faction
) const
5607 FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(faction
);
5608 return GetReputationMgr().GetRank(factionEntry
);
5611 //Calculate total reputation percent player gain with quest/creature level
5612 int32
Player::CalculateReputationGain(uint32 creatureOrQuestLevel
, int32 rep
, bool for_quest
)
5614 float percent
= 100.0f
;
5616 float rate
= for_quest
? sWorld
.getRate(RATE_REPUTATION_LOWLEVEL_QUEST
) : sWorld
.getRate(RATE_REPUTATION_LOWLEVEL_KILL
);
5618 if(rate
!= 1.0f
&& creatureOrQuestLevel
<= MaNGOS::XP::GetGrayLevel(getLevel()))
5621 int32 repMod
= GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN
);
5623 percent
+= rep
> 0 ? repMod
: -repMod
;
5628 return int32(sWorld
.getRate(RATE_REPUTATION_GAIN
)*rep
*percent
/100);
5631 //Calculates how many reputation points player gains in victim's enemy factions
5632 void Player::RewardReputation(Unit
*pVictim
, float rate
)
5634 if(!pVictim
|| pVictim
->GetTypeId() == TYPEID_PLAYER
)
5637 ReputationOnKillEntry
const* Rep
= objmgr
.GetReputationOnKilEntry(((Creature
*)pVictim
)->GetCreatureInfo()->Entry
);
5642 if(Rep
->repfaction1
&& (!Rep
->team_dependent
|| GetTeam()==ALLIANCE
))
5644 int32 donerep1
= CalculateReputationGain(pVictim
->getLevel(),Rep
->repvalue1
,false);
5645 donerep1
= int32(donerep1
*rate
);
5646 FactionEntry
const *factionEntry1
= sFactionStore
.LookupEntry(Rep
->repfaction1
);
5647 uint32 current_reputation_rank1
= GetReputationMgr().GetRank(factionEntry1
);
5648 if(factionEntry1
&& current_reputation_rank1
<= Rep
->reputation_max_cap1
)
5649 GetReputationMgr().ModifyReputation(factionEntry1
, donerep1
);
5651 // Wiki: Team factions value divided by 2
5652 if(Rep
->is_teamaward1
)
5654 FactionEntry
const *team1_factionEntry
= sFactionStore
.LookupEntry(factionEntry1
->team
);
5655 if(team1_factionEntry
)
5656 GetReputationMgr().ModifyReputation(team1_factionEntry
, donerep1
/ 2);
5660 if(Rep
->repfaction2
&& (!Rep
->team_dependent
|| GetTeam()==HORDE
))
5662 int32 donerep2
= CalculateReputationGain(pVictim
->getLevel(),Rep
->repvalue2
,false);
5663 donerep2
= int32(donerep2
*rate
);
5664 FactionEntry
const *factionEntry2
= sFactionStore
.LookupEntry(Rep
->repfaction2
);
5665 uint32 current_reputation_rank2
= GetReputationMgr().GetRank(factionEntry2
);
5666 if(factionEntry2
&& current_reputation_rank2
<= Rep
->reputation_max_cap2
)
5667 GetReputationMgr().ModifyReputation(factionEntry2
, donerep2
);
5669 // Wiki: Team factions value divided by 2
5670 if(Rep
->is_teamaward2
)
5672 FactionEntry
const *team2_factionEntry
= sFactionStore
.LookupEntry(factionEntry2
->team
);
5673 if(team2_factionEntry
)
5674 GetReputationMgr().ModifyReputation(team2_factionEntry
, donerep2
/ 2);
5679 //Calculate how many reputation points player gain with the quest
5680 void Player::RewardReputation(Quest
const *pQuest
)
5682 // quest reputation reward/loss
5683 for(int i
= 0; i
< QUEST_REPUTATIONS_COUNT
; ++i
)
5685 if(pQuest
->RewRepFaction
[i
] && pQuest
->RewRepValue
[i
] )
5687 int32 rep
= CalculateReputationGain(GetQuestLevel(pQuest
),pQuest
->RewRepValue
[i
],true);
5688 FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(pQuest
->RewRepFaction
[i
]);
5690 GetReputationMgr().ModifyReputation(factionEntry
, rep
);
5694 // TODO: implement reputation spillover
5697 void Player::UpdateArenaFields(void)
5699 /* arena calcs go here */
5702 void Player::UpdateHonorFields()
5704 /// called when rewarding honor and at each save
5705 uint64 now
= time(NULL
);
5706 uint64 today
= uint64(time(NULL
) / DAY
) * DAY
;
5708 if(m_lastHonorUpdateTime
< today
)
5710 uint64 yesterday
= today
- DAY
;
5712 uint16 kills_today
= PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS
));
5714 // update yesterday's contribution
5715 if(m_lastHonorUpdateTime
>= yesterday
)
5717 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
));
5719 // this is the first update today, reset today's contribution
5720 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, 0);
5721 SetUInt32Value(PLAYER_FIELD_KILLS
, MAKE_PAIR32(0,kills_today
));
5725 // no honor/kills yesterday or today, reset
5726 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION
, 0);
5727 SetUInt32Value(PLAYER_FIELD_KILLS
, 0);
5731 m_lastHonorUpdateTime
= now
;
5734 ///Calculate the amount of honor gained based on the victim
5735 ///and the size of the group for which the honor is divided
5736 ///An exact honor value can also be given (overriding the calcs)
5737 bool Player::RewardHonor(Unit
*uVictim
, uint32 groupsize
, float honor
)
5739 // do not reward honor in arenas, but enable onkill spellproc
5742 if(!uVictim
|| uVictim
== this || uVictim
->GetTypeId() != TYPEID_PLAYER
)
5745 if( GetBGTeam() == ((Player
*)uVictim
)->GetBGTeam() )
5751 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5752 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE
))
5755 uint64 victim_guid
= 0;
5756 uint32 victim_rank
= 0;
5758 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5759 UpdateHonorFields();
5763 if(!uVictim
|| uVictim
== this || uVictim
->HasAuraType(SPELL_AURA_NO_PVP_CREDIT
))
5766 victim_guid
= uVictim
->GetGUID();
5768 if( uVictim
->GetTypeId() == TYPEID_PLAYER
)
5770 Player
*pVictim
= (Player
*)uVictim
;
5772 if( GetTeam() == pVictim
->GetTeam() && !sWorld
.IsFFAPvPRealm() )
5775 float f
= 1; //need for total kills (?? need more info)
5777 uint32 k_level
= getLevel();
5778 uint32 v_level
= pVictim
->getLevel();
5781 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
5783 // [1..14] Alliance honor titles and player name
5784 // [15..28] Horde honor titles and player name
5785 // [29..38] Other title and player name
5787 uint32 victim_title
= pVictim
->GetUInt32Value(PLAYER_CHOSEN_TITLE
);
5788 // Get Killer titles, CharTitlesEntry::bit_index
5790 // title[1..14] -> rank[5..18]
5791 // title[15..28] -> rank[5..18]
5792 // title[other] -> 0
5793 if (victim_title
== 0)
5794 victim_guid
= 0; // Don't show HK: <rank> message, only log.
5795 else if (victim_title
< 15)
5796 victim_rank
= victim_title
+ 4;
5797 else if (victim_title
< 29)
5798 victim_rank
= victim_title
- 14 + 4;
5800 victim_guid
= 0; // Don't show HK: <rank> message, only log.
5803 k_grey
= MaNGOS::XP::GetGrayLevel(k_level
);
5808 float diff_level
= (k_level
== k_grey
) ? 1 : ((float(v_level
) - float(k_grey
)) / (float(k_level
) - float(k_grey
)));
5810 int32 v_rank
=1; //need more info
5812 honor
= ((f
* diff_level
* (190 + v_rank
*10))/6);
5813 honor
*= ((float)k_level
) / 70.0f
; //factor of dependence on levels of the killer
5815 // count the number of playerkills in one day
5816 ApplyModUInt32Value(PLAYER_FIELD_KILLS
, 1, true);
5817 // and those in a lifetime
5818 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS
, 1, true);
5822 Creature
*cVictim
= (Creature
*)uVictim
;
5824 if (!cVictim
->isRacialLeader())
5827 honor
= 100; // ??? need more info
5828 victim_rank
= 19; // HK: Leader
5832 if (uVictim
!= NULL
)
5834 honor
*= sWorld
.getRate(RATE_HONOR
);
5839 honor
*= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
5842 // honor - for show honor points in log
5843 // victim_guid - for show victim name in log
5844 // victim_rank [1..4] HK: <dishonored rank>
5845 // victim_rank [5..19] HK: <alliance\horde rank>
5846 // victim_rank [0,20+] HK: <>
5847 WorldPacket
data(SMSG_PVP_CREDIT
,4+8+4);
5848 data
<< (uint32
) honor
;
5849 data
<< (uint64
) victim_guid
;
5850 data
<< (uint32
) victim_rank
;
5852 GetSession()->SendPacket(&data
);
5855 ModifyHonorPoints(int32(honor
));
5857 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION
, uint32(honor
), true);
5861 void Player::ModifyHonorPoints( int32 value
)
5865 if (GetHonorPoints() > sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
))
5866 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) + value
);
5868 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() > uint32(-value
) ? GetHonorPoints() + value
: 0);
5871 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY
, GetHonorPoints() < sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
) - value
? GetHonorPoints() + value
: sWorld
.getConfig(CONFIG_MAX_HONOR_POINTS
));
5874 void Player::ModifyArenaPoints( int32 value
)
5878 if (GetArenaPoints() > sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
))
5879 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) + value
);
5881 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() > uint32(-value
) ? GetArenaPoints() + value
: 0);
5884 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, GetArenaPoints() < sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
) - value
? GetArenaPoints() + value
: sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
));
5887 uint32
Player::GetGuildIdFromDB(uint64 guid
)
5889 QueryResult
* result
= CharacterDatabase
.PQuery("SELECT guildid FROM guild_member WHERE guid='%u'", GUID_LOPART(guid
));
5893 uint32 id
= result
->Fetch()[0].GetUInt32();
5898 uint32
Player::GetRankFromDB(uint64 guid
)
5900 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT rank FROM guild_member WHERE guid='%u'", GUID_LOPART(guid
) );
5903 uint32 v
= result
->Fetch()[0].GetUInt32();
5911 uint32
Player::GetArenaTeamIdFromDB(uint64 guid
, uint8 type
)
5913 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
);
5917 uint32 id
= (*result
)[0].GetUInt32();
5922 uint32
Player::GetZoneIdFromDB(uint64 guid
)
5924 uint32 guidLow
= GUID_LOPART(guid
);
5925 QueryResult
*result
= CharacterDatabase
.PQuery( "SELECT zone FROM characters WHERE guid='%u'", guidLow
);
5928 Field
* fields
= result
->Fetch();
5929 uint32 zone
= fields
[0].GetUInt32();
5934 // stored zone is zero, use generic and slow zone detection
5935 result
= CharacterDatabase
.PQuery("SELECT map,position_x,position_y,position_z FROM characters WHERE guid='%u'", guidLow
);
5938 fields
= result
->Fetch();
5939 uint32 map
= fields
[0].GetUInt32();
5940 float posx
= fields
[1].GetFloat();
5941 float posy
= fields
[2].GetFloat();
5942 float posz
= fields
[3].GetFloat();
5945 zone
= MapManager::Instance().GetZoneId(map
,posx
,posy
,posz
);
5947 CharacterDatabase
.PExecute("UPDATE characters SET zone='%u' WHERE guid='%u'", zone
, guidLow
);
5953 void Player::UpdateArea(uint32 newArea
)
5955 // FFA_PVP flags are area and not zone id dependent
5956 // so apply them accordingly
5957 m_areaUpdateId
= newArea
;
5959 AreaTableEntry
const* area
= GetAreaEntryByAreaID(newArea
);
5961 if(area
&& (area
->flags
& AREA_FLAG_ARENA
))
5964 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
5968 // remove ffa flag only if not ffapvp realm
5969 // removal in sanctuaries and capitals is handled in zone update
5970 if(HasByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
) && !sWorld
.IsFFAPvPRealm())
5971 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
5974 UpdateAreaDependentAuras(newArea
);
5977 void Player::UpdateZone(uint32 newZone
, uint32 newArea
)
5979 if(m_zoneUpdateId
!= newZone
)
5980 SendInitWorldStates(newZone
, newArea
); // only if really enters to new zone, not just area change, works strange...
5982 m_zoneUpdateId
= newZone
;
5983 m_zoneUpdateTimer
= ZONE_UPDATE_INTERVAL
;
5985 // zone changed, so area changed as well, update it
5986 UpdateArea(newArea
);
5988 AreaTableEntry
const* zone
= GetAreaEntryByAreaID(newZone
);
5992 if (sWorld
.getConfig(CONFIG_WEATHER
))
5994 Weather
*wth
= sWorld
.FindWeather(zone
->ID
);
5997 wth
->SendWeatherUpdateToPlayer(this);
6001 if(!sWorld
.AddWeather(zone
->ID
))
6003 // send fine weather packet to remove old zone's weather
6004 Weather::SendFineWeatherUpdateToPlayer(this);
6009 pvpInfo
.inHostileArea
=
6010 GetTeam() == ALLIANCE
&& zone
->team
== AREATEAM_HORDE
||
6011 GetTeam() == HORDE
&& zone
->team
== AREATEAM_ALLY
||
6012 sWorld
.IsPvPRealm() && zone
->team
== AREATEAM_NONE
||
6013 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6015 if(pvpInfo
.inHostileArea
) // in hostile area
6017 if(!IsPvP() || pvpInfo
.endTimer
!= 0)
6018 UpdatePvP(true, true);
6020 else // in friendly area
6022 if(IsPvP() && !HasFlag(PLAYER_FLAGS
,PLAYER_FLAGS_IN_PVP
) && pvpInfo
.endTimer
== 0)
6023 pvpInfo
.endTimer
= time(0); // start toggle-off
6026 if(zone
->flags
& AREA_FLAG_SANCTUARY
) // in sanctuary
6028 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_SANCTUARY
);
6029 if(sWorld
.IsFFAPvPRealm())
6030 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6034 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_SANCTUARY
);
6037 if(zone
->flags
& AREA_FLAG_CAPITAL
) // in capital city
6039 SetFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6040 SetRestType(REST_TYPE_IN_CITY
);
6041 InnEnter(time(0),GetMapId(),0,0,0);
6043 if(sWorld
.IsFFAPvPRealm())
6044 RemoveByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6046 else // anywhere else
6048 if(HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6050 if(GetRestType()==REST_TYPE_IN_TAVERN
) // has been in tavern. Is still in?
6052 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6054 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6055 SetRestType(REST_TYPE_NO
);
6057 if(sWorld
.IsFFAPvPRealm())
6058 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6061 else // not in tavern (leave city then)
6063 RemoveFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
);
6064 SetRestType(REST_TYPE_NO
);
6066 // Set player to FFA PVP when not in rested environment.
6067 if(sWorld
.IsFFAPvPRealm())
6068 SetByteFlag(UNIT_FIELD_BYTES_2
, 1, UNIT_BYTE2_FLAG_FFA_PVP
);
6073 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6074 // if player resurrected at teleport this will be applied in resurrect code
6076 DestroyZoneLimitedItem( true, newZone
);
6078 // check some item equip limitations (in result lost CanTitanGrip at talent reset, for example)
6079 AutoUnequipOffhandIfNeed();
6081 // recent client version not send leave/join channel packets for built-in local channels
6082 UpdateLocalChannels( newZone
);
6086 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE
);
6088 UpdateZoneDependentAuras(newZone
);
6091 //If players are too far way of duel flag... then player loose the duel
6092 void Player::CheckDuelDistance(time_t currTime
)
6097 uint64 duelFlagGUID
= GetUInt64Value(PLAYER_DUEL_ARBITER
);
6098 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, duelFlagGUID
);
6102 if(duel
->outOfBound
== 0)
6104 if(!IsWithinDistInMap(obj
, 50))
6106 duel
->outOfBound
= currTime
;
6108 WorldPacket
data(SMSG_DUEL_OUTOFBOUNDS
, 0);
6109 GetSession()->SendPacket(&data
);
6114 if(IsWithinDistInMap(obj
, 40))
6116 duel
->outOfBound
= 0;
6118 WorldPacket
data(SMSG_DUEL_INBOUNDS
, 0);
6119 GetSession()->SendPacket(&data
);
6121 else if(currTime
>= (duel
->outOfBound
+10))
6123 DuelComplete(DUEL_FLED
);
6128 void Player::DuelComplete(DuelCompleteType type
)
6130 // duel not requested
6134 WorldPacket
data(SMSG_DUEL_COMPLETE
, (1));
6135 data
<< (uint8
)((type
!= DUEL_INTERUPTED
) ? 1 : 0);
6136 GetSession()->SendPacket(&data
);
6137 duel
->opponent
->GetSession()->SendPacket(&data
);
6139 if(type
!= DUEL_INTERUPTED
)
6141 data
.Initialize(SMSG_DUEL_WINNER
, (1+20)); // we guess size
6142 data
<< (uint8
)((type
==DUEL_WON
) ? 0 : 1); // 0 = just won; 1 = fled
6143 data
<< duel
->opponent
->GetName();
6145 SendMessageToSet(&data
,true);
6148 // cool-down duel spell
6149 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6156 GetSession()->SendPacket(&data);
6157 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6158 data<<duel->opponent->GetGUID();
6162 duel->opponent->GetSession()->SendPacket(&data);*/
6164 //Remove Duel Flag object
6165 GameObject
* obj
= ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER
));
6167 duel
->initiator
->RemoveGameObject(obj
,true);
6170 std::vector
<uint32
> auras2remove
;
6171 AuraMap
const& vAuras
= duel
->opponent
->GetAuras();
6172 for (AuraMap::const_iterator i
= vAuras
.begin(); i
!= vAuras
.end(); ++i
)
6174 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6175 auras2remove
.push_back(i
->second
->GetId());
6178 for(size_t i
=0; i
<auras2remove
.size(); i
++)
6179 duel
->opponent
->RemoveAurasDueToSpell(auras2remove
[i
]);
6181 auras2remove
.clear();
6182 AuraMap
const& auras
= GetAuras();
6183 for (AuraMap::const_iterator i
= auras
.begin(); i
!= auras
.end(); ++i
)
6185 if (!i
->second
->IsPositive() && i
->second
->GetCasterGUID() == duel
->opponent
->GetGUID() && i
->second
->GetAuraApplyTime() >= duel
->startTime
)
6186 auras2remove
.push_back(i
->second
->GetId());
6188 for(size_t i
=0; i
<auras2remove
.size(); i
++)
6189 RemoveAurasDueToSpell(auras2remove
[i
]);
6191 // cleanup combo points
6192 if(GetComboTarget()==duel
->opponent
->GetGUID())
6194 else if(GetComboTarget()==duel
->opponent
->GetPetGUID())
6197 if(duel
->opponent
->GetComboTarget()==GetGUID())
6198 duel
->opponent
->ClearComboPoints();
6199 else if(duel
->opponent
->GetComboTarget()==GetPetGUID())
6200 duel
->opponent
->ClearComboPoints();
6203 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6204 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6205 duel
->opponent
->SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
6206 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
6208 delete duel
->opponent
->duel
;
6209 duel
->opponent
->duel
= NULL
;
6214 //---------------------------------------------------------//
6216 void Player::_ApplyItemMods(Item
*item
, uint8 slot
,bool apply
)
6218 if(slot
>= INVENTORY_SLOT_BAG_END
|| !item
)
6221 // not apply/remove mods for broken item
6222 if(item
->IsBroken())
6225 ItemPrototype
const *proto
= item
->GetProto();
6230 sLog
.outDetail("applying mods for item %u ",item
->GetGUIDLow());
6232 uint32 attacktype
= Player::GetAttackBySlot(slot
);
6233 if(attacktype
< MAX_ATTACK
)
6234 _ApplyWeaponDependentAuraMods(item
,WeaponAttackType(attacktype
),apply
);
6236 _ApplyItemBonuses(proto
,slot
,apply
);
6238 if( slot
==EQUIPMENT_SLOT_RANGED
)
6239 _ApplyAmmoBonuses();
6241 ApplyItemEquipSpell(item
,apply
);
6242 ApplyEnchantment(item
, apply
);
6244 if(proto
->Socket
[0].Color
) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6245 CorrectMetaGemEnchants(slot
, apply
);
6247 sLog
.outDebug("_ApplyItemMods complete.");
6250 void Player::_ApplyItemBonuses(ItemPrototype
const *proto
, uint8 slot
, bool apply
)
6252 if(slot
>= INVENTORY_SLOT_BAG_END
|| !proto
)
6255 for (int i
= 0; i
< MAX_ITEM_PROTO_STATS
; ++i
)
6257 uint32 statType
= 0;
6260 if(proto
->ScalingStatDistribution
)
6262 if(ScalingStatDistributionEntry
const *ssd
= sScalingStatDistributionStore
.LookupEntry(proto
->ScalingStatDistribution
))
6264 statType
= ssd
->StatMod
[i
];
6266 if(uint32 modifier
= ssd
->Modifier
[i
])
6268 uint32 level
= ((getLevel() > ssd
->MaxLevel
) ? ssd
->MaxLevel
: getLevel());
6269 if(ScalingStatValuesEntry
const *ssv
= sScalingStatValuesStore
.LookupEntry(level
))
6271 uint32 multiplier
= ssv
->Multiplier
[proto
->GetScalingStatValuesColumn()];
6272 val
= (multiplier
* modifier
) / 10000;
6279 statType
= proto
->ItemStat
[i
].ItemStatType
;
6280 val
= proto
->ItemStat
[i
].ItemStatValue
;
6289 HandleStatModifier(UNIT_MOD_MANA
, BASE_VALUE
, float(val
), apply
);
6291 case ITEM_MOD_HEALTH
: // modify HP
6292 HandleStatModifier(UNIT_MOD_HEALTH
, BASE_VALUE
, float(val
), apply
);
6294 case ITEM_MOD_AGILITY
: // modify agility
6295 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, BASE_VALUE
, float(val
), apply
);
6296 ApplyStatBuffMod(STAT_AGILITY
, float(val
), apply
);
6298 case ITEM_MOD_STRENGTH
: //modify strength
6299 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, BASE_VALUE
, float(val
), apply
);
6300 ApplyStatBuffMod(STAT_STRENGTH
, float(val
), apply
);
6302 case ITEM_MOD_INTELLECT
: //modify intellect
6303 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, BASE_VALUE
, float(val
), apply
);
6304 ApplyStatBuffMod(STAT_INTELLECT
, float(val
), apply
);
6306 case ITEM_MOD_SPIRIT
: //modify spirit
6307 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, BASE_VALUE
, float(val
), apply
);
6308 ApplyStatBuffMod(STAT_SPIRIT
, float(val
), apply
);
6310 case ITEM_MOD_STAMINA
: //modify stamina
6311 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, BASE_VALUE
, float(val
), apply
);
6312 ApplyStatBuffMod(STAT_STAMINA
, float(val
), apply
);
6314 case ITEM_MOD_DEFENSE_SKILL_RATING
:
6315 ApplyRatingMod(CR_DEFENSE_SKILL
, int32(val
), apply
);
6317 case ITEM_MOD_DODGE_RATING
:
6318 ApplyRatingMod(CR_DODGE
, int32(val
), apply
);
6320 case ITEM_MOD_PARRY_RATING
:
6321 ApplyRatingMod(CR_PARRY
, int32(val
), apply
);
6323 case ITEM_MOD_BLOCK_RATING
:
6324 ApplyRatingMod(CR_BLOCK
, int32(val
), apply
);
6326 case ITEM_MOD_HIT_MELEE_RATING
:
6327 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6329 case ITEM_MOD_HIT_RANGED_RATING
:
6330 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6332 case ITEM_MOD_HIT_SPELL_RATING
:
6333 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6335 case ITEM_MOD_CRIT_MELEE_RATING
:
6336 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6338 case ITEM_MOD_CRIT_RANGED_RATING
:
6339 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6341 case ITEM_MOD_CRIT_SPELL_RATING
:
6342 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6344 case ITEM_MOD_HIT_TAKEN_MELEE_RATING
:
6345 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6347 case ITEM_MOD_HIT_TAKEN_RANGED_RATING
:
6348 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6350 case ITEM_MOD_HIT_TAKEN_SPELL_RATING
:
6351 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6353 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING
:
6354 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6356 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING
:
6357 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6359 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING
:
6360 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6362 case ITEM_MOD_HASTE_MELEE_RATING
:
6363 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6365 case ITEM_MOD_HASTE_RANGED_RATING
:
6366 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6368 case ITEM_MOD_HASTE_SPELL_RATING
:
6369 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6371 case ITEM_MOD_HIT_RATING
:
6372 ApplyRatingMod(CR_HIT_MELEE
, int32(val
), apply
);
6373 ApplyRatingMod(CR_HIT_RANGED
, int32(val
), apply
);
6374 ApplyRatingMod(CR_HIT_SPELL
, int32(val
), apply
);
6376 case ITEM_MOD_CRIT_RATING
:
6377 ApplyRatingMod(CR_CRIT_MELEE
, int32(val
), apply
);
6378 ApplyRatingMod(CR_CRIT_RANGED
, int32(val
), apply
);
6379 ApplyRatingMod(CR_CRIT_SPELL
, int32(val
), apply
);
6381 case ITEM_MOD_HIT_TAKEN_RATING
:
6382 ApplyRatingMod(CR_HIT_TAKEN_MELEE
, int32(val
), apply
);
6383 ApplyRatingMod(CR_HIT_TAKEN_RANGED
, int32(val
), apply
);
6384 ApplyRatingMod(CR_HIT_TAKEN_SPELL
, int32(val
), apply
);
6386 case ITEM_MOD_CRIT_TAKEN_RATING
:
6387 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6388 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6389 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6391 case ITEM_MOD_RESILIENCE_RATING
:
6392 ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, int32(val
), apply
);
6393 ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, int32(val
), apply
);
6394 ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, int32(val
), apply
);
6396 case ITEM_MOD_HASTE_RATING
:
6397 ApplyRatingMod(CR_HASTE_MELEE
, int32(val
), apply
);
6398 ApplyRatingMod(CR_HASTE_RANGED
, int32(val
), apply
);
6399 ApplyRatingMod(CR_HASTE_SPELL
, int32(val
), apply
);
6401 case ITEM_MOD_EXPERTISE_RATING
:
6402 ApplyRatingMod(CR_EXPERTISE
, int32(val
), apply
);
6404 case ITEM_MOD_ATTACK_POWER
:
6405 HandleStatModifier(UNIT_MOD_ATTACK_POWER
, TOTAL_VALUE
, float(val
), apply
);
6406 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(val
), apply
);
6408 case ITEM_MOD_RANGED_ATTACK_POWER
:
6409 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(val
), apply
);
6411 case ITEM_MOD_FERAL_ATTACK_POWER
:
6412 ApplyFeralAPBonus(int32(val
), apply
);
6414 case ITEM_MOD_SPELL_HEALING_DONE
:
6415 ApplySpellHealingBonus(int32(val
), apply
);
6417 case ITEM_MOD_SPELL_DAMAGE_DONE
:
6418 ApplySpellDamageBonus(int32(val
), apply
);
6420 case ITEM_MOD_MANA_REGENERATION
:
6421 ApplyManaRegenBonus(int32(val
), apply
);
6423 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
6424 ApplyRatingMod(CR_ARMOR_PENETRATION
, int32(val
), apply
);
6426 case ITEM_MOD_SPELL_POWER
:
6427 ApplySpellHealingBonus(int32(val
), apply
);
6428 ApplySpellDamageBonus(int32(val
), apply
);
6434 HandleStatModifier(UNIT_MOD_ARMOR
, BASE_VALUE
, float(proto
->Armor
), apply
);
6437 HandleBaseModValue(SHIELD_BLOCK_VALUE
, FLAT_MOD
, float(proto
->Block
), apply
);
6440 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY
, BASE_VALUE
, float(proto
->HolyRes
), apply
);
6443 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE
, BASE_VALUE
, float(proto
->FireRes
), apply
);
6445 if (proto
->NatureRes
)
6446 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE
, BASE_VALUE
, float(proto
->NatureRes
), apply
);
6448 if (proto
->FrostRes
)
6449 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST
, BASE_VALUE
, float(proto
->FrostRes
), apply
);
6451 if (proto
->ShadowRes
)
6452 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW
, BASE_VALUE
, float(proto
->ShadowRes
), apply
);
6454 if (proto
->ArcaneRes
)
6455 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE
, BASE_VALUE
, float(proto
->ArcaneRes
), apply
);
6457 WeaponAttackType attType
= BASE_ATTACK
;
6458 float damage
= 0.0f
;
6460 if( slot
== EQUIPMENT_SLOT_RANGED
&& (
6461 proto
->InventoryType
== INVTYPE_RANGED
|| proto
->InventoryType
== INVTYPE_THROWN
||
6462 proto
->InventoryType
== INVTYPE_RANGEDRIGHT
))
6464 attType
= RANGED_ATTACK
;
6466 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6468 attType
= OFF_ATTACK
;
6471 if (proto
->Damage
[0].DamageMin
> 0 )
6473 damage
= apply
? proto
->Damage
[0].DamageMin
: BASE_MINDAMAGE
;
6474 SetBaseWeaponDamage(attType
, MINDAMAGE
, damage
);
6475 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6478 if (proto
->Damage
[0].DamageMax
> 0 )
6480 damage
= apply
? proto
->Damage
[0].DamageMax
: BASE_MAXDAMAGE
;
6481 SetBaseWeaponDamage(attType
, MAXDAMAGE
, damage
);
6484 // Druids get feral AP bonus from weapon dps
6485 if(getClass() == CLASS_DRUID
)
6487 int32 feral_bonus
= proto
->getFeralBonus();
6488 if (feral_bonus
> 0)
6489 ApplyFeralAPBonus(feral_bonus
, apply
);
6492 if(!IsUseEquipedWeapon(slot
==EQUIPMENT_SLOT_MAINHAND
))
6497 if(slot
== EQUIPMENT_SLOT_RANGED
)
6498 SetAttackTime(RANGED_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6499 else if(slot
==EQUIPMENT_SLOT_MAINHAND
)
6500 SetAttackTime(BASE_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6501 else if(slot
==EQUIPMENT_SLOT_OFFHAND
)
6502 SetAttackTime(OFF_ATTACK
, apply
? proto
->Delay
: BASE_ATTACK_TIME
);
6505 if(CanModifyStats() && (damage
|| proto
->Delay
))
6506 UpdateDamagePhysical(attType
);
6509 void Player::_ApplyWeaponDependentAuraMods(Item
*item
,WeaponAttackType attackType
,bool apply
)
6511 AuraList
const& auraCritList
= GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT
);
6512 for(AuraList::const_iterator itr
= auraCritList
.begin(); itr
!=auraCritList
.end();++itr
)
6513 _ApplyWeaponDependentAuraCritMod(item
,attackType
,*itr
,apply
);
6515 AuraList
const& auraDamageFlatList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE
);
6516 for(AuraList::const_iterator itr
= auraDamageFlatList
.begin(); itr
!=auraDamageFlatList
.end();++itr
)
6517 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6519 AuraList
const& auraDamagePCTList
= GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
);
6520 for(AuraList::const_iterator itr
= auraDamagePCTList
.begin(); itr
!=auraDamagePCTList
.end();++itr
)
6521 _ApplyWeaponDependentAuraDamageMod(item
,attackType
,*itr
,apply
);
6524 void Player::_ApplyWeaponDependentAuraCritMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6526 // generic not weapon specific case processes in aura code
6527 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6530 BaseModGroup mod
= BASEMOD_END
;
6533 case BASE_ATTACK
: mod
= CRIT_PERCENTAGE
; break;
6534 case OFF_ATTACK
: mod
= OFFHAND_CRIT_PERCENTAGE
;break;
6535 case RANGED_ATTACK
: mod
= RANGED_CRIT_PERCENTAGE
; break;
6539 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6541 HandleBaseModValue(mod
, FLAT_MOD
, float (aura
->GetModifier()->m_amount
), apply
);
6545 void Player::_ApplyWeaponDependentAuraDamageMod(Item
*item
, WeaponAttackType attackType
, Aura
* aura
, bool apply
)
6547 // ignore spell mods for not wands
6548 Modifier
const* modifier
= aura
->GetModifier();
6549 if((modifier
->m_miscvalue
& SPELL_SCHOOL_MASK_NORMAL
)==0 && (getClassMask() & CLASSMASK_WAND_USERS
)==0)
6552 // generic not weapon specific case processes in aura code
6553 if(aura
->GetSpellProto()->EquippedItemClass
== -1)
6556 UnitMods unitMod
= UNIT_MOD_END
;
6559 case BASE_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_MAINHAND
; break;
6560 case OFF_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_OFFHAND
; break;
6561 case RANGED_ATTACK
: unitMod
= UNIT_MOD_DAMAGE_RANGED
; break;
6565 UnitModifierType unitModType
= TOTAL_VALUE
;
6566 switch(modifier
->m_auraname
)
6568 case SPELL_AURA_MOD_DAMAGE_DONE
: unitModType
= TOTAL_VALUE
; break;
6569 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE
: unitModType
= TOTAL_PCT
; break;
6573 if (item
->IsFitToSpellRequirements(aura
->GetSpellProto()))
6575 HandleStatModifier(unitMod
, unitModType
, float(modifier
->m_amount
),apply
);
6579 void Player::ApplyItemEquipSpell(Item
*item
, bool apply
, bool form_change
)
6584 ItemPrototype
const *proto
= item
->GetProto();
6588 for (int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
6590 _Spell
const& spellData
= proto
->Spells
[i
];
6593 if(!spellData
.SpellId
)
6596 // wrong triggering type
6597 if(apply
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_EQUIP
)
6600 // check if it is valid spell
6601 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellData
.SpellId
);
6605 ApplyEquipSpell(spellproto
,item
,apply
,form_change
);
6609 void Player::ApplyEquipSpell(SpellEntry
const* spellInfo
, Item
* item
, bool apply
, bool form_change
)
6613 // Cannot be used in this stance/form
6614 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
) != SPELL_CAST_OK
)
6617 if(form_change
) // check aura active state from other form
6620 for (int k
=0; k
< 3; ++k
)
6622 spellEffectPair spair
= spellEffectPair(spellInfo
->Id
, k
);
6623 for (AuraMap::iterator iter
= m_Auras
.lower_bound(spair
); iter
!= m_Auras
.upper_bound(spair
); ++iter
)
6625 if(!item
|| iter
->second
->GetCastItemGUID() == item
->GetGUID())
6635 if(found
) // and skip re-cast already active aura at form change
6639 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item
? "item" : "itemset"), spellInfo
->Id
);
6641 CastSpell(this,spellInfo
,true,item
);
6645 if(form_change
) // check aura compatibility
6647 // Cannot be used in this stance/form
6648 if(GetErrorAtShapeshiftedCast(spellInfo
, m_form
)==SPELL_CAST_OK
)
6649 return; // and remove only not compatible at form change
6653 RemoveAurasDueToItemSpell(item
,spellInfo
->Id
); // un-apply all spells , not only at-equipped
6655 RemoveAurasDueToSpell(spellInfo
->Id
); // un-apply spell (item set case)
6659 void Player::UpdateEquipSpellsAtFormChange()
6661 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6663 if(m_items
[i
] && !m_items
[i
]->IsBroken())
6665 ApplyItemEquipSpell(m_items
[i
],false,true); // remove spells that not fit to form
6666 ApplyItemEquipSpell(m_items
[i
],true,true); // add spells that fit form but not active
6670 // item set bonuses not dependent from item broken state
6671 for(size_t setindex
= 0; setindex
< ItemSetEff
.size(); ++setindex
)
6673 ItemSetEffect
* eff
= ItemSetEff
[setindex
];
6677 for(uint32 y
=0;y
<8; ++y
)
6679 SpellEntry
const* spellInfo
= eff
->spells
[y
];
6683 ApplyEquipSpell(spellInfo
,NULL
,false,true); // remove spells that not fit to form
6684 ApplyEquipSpell(spellInfo
,NULL
,true,true); // add spells that fit form but not active
6689 void Player::CastItemCombatSpell(Item
*item
,Unit
* Target
, WeaponAttackType attType
)
6691 if(!item
|| item
->IsBroken())
6694 ItemPrototype
const *proto
= item
->GetProto();
6698 if (!Target
|| Target
== this )
6701 for (int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
6703 _Spell
const& spellData
= proto
->Spells
[i
];
6706 if(!spellData
.SpellId
)
6709 // wrong triggering type
6710 if(spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_CHANCE_ON_HIT
)
6713 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
6716 sLog
.outError("WORLD: unknown Item spellid %i", spellData
.SpellId
);
6720 // not allow proc extra attack spell at extra attack
6721 if( m_extraAttacks
&& IsSpellHaveEffect(spellInfo
,SPELL_EFFECT_ADD_EXTRA_ATTACKS
) )
6724 float chance
= spellInfo
->procChance
;
6726 if(spellData
.SpellPPMRate
)
6728 uint32 WeaponSpeed
= GetAttackTime(attType
);
6729 chance
= GetPPMProcChance(WeaponSpeed
, spellData
.SpellPPMRate
);
6731 else if(chance
> 100.0f
)
6733 chance
= GetWeaponProcChance();
6736 if (roll_chance_f(chance
))
6737 CastSpell(Target
, spellInfo
->Id
, true, item
);
6740 // item combat enchantments
6741 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
6743 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
6744 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
6745 if(!pEnchant
) continue;
6746 for (int s
=0;s
<3;s
++)
6748 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
)
6751 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
6754 sLog
.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
6758 float chance
= pEnchant
->amount
[s
] != 0 ? float(pEnchant
->amount
[s
]) : GetWeaponProcChance();
6759 if (roll_chance_f(chance
))
6761 if(IsPositiveSpell(pEnchant
->spellid
[s
]))
6762 CastSpell(this, pEnchant
->spellid
[s
], true, item
);
6764 CastSpell(Target
, pEnchant
->spellid
[s
], true, item
);
6770 void Player::CastItemUseSpell(Item
*item
,SpellCastTargets
const& targets
,uint8 cast_count
, uint32 glyphIndex
)
6772 ItemPrototype
const* proto
= item
->GetProto();
6773 // special learning case
6774 if(proto
->Spells
[0].SpellId
==SPELL_ID_GENERIC_LEARN
|| proto
->Spells
[0].SpellId
==SPELL_ID_GENERIC_LEARN_PET
)
6776 uint32 learn_spell_id
= proto
->Spells
[0].SpellId
;
6777 uint32 learning_spell_id
= proto
->Spells
[1].SpellId
;
6779 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(learn_spell_id
);
6782 sLog
.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring ",proto
->ItemId
, learn_spell_id
);
6783 SendEquipError(EQUIP_ERR_NONE
,item
,NULL
);
6787 Spell
*spell
= new Spell(this, spellInfo
, false);
6788 spell
->m_CastItem
= item
;
6789 spell
->m_cast_count
= cast_count
; //set count of casts
6790 spell
->m_currentBasePoints
[0] = learning_spell_id
;
6791 spell
->prepare(&targets
);
6795 // use triggered flag only for items with many spell casts and for not first cast
6798 // item spells casted at use
6799 for(int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
6801 _Spell
const& spellData
= proto
->Spells
[i
];
6804 if(!spellData
.SpellId
)
6807 // wrong triggering type
6808 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
&& spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_NO_DELAY_USE
)
6811 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellData
.SpellId
);
6814 sLog
.outError("Player::CastItemUseSpell: Item (Entry: %u) in have wrong spell id %u, ignoring",proto
->ItemId
, spellData
.SpellId
);
6818 Spell
*spell
= new Spell(this, spellInfo
, (count
> 0));
6819 spell
->m_CastItem
= item
;
6820 spell
->m_cast_count
= cast_count
; // set count of casts
6821 spell
->m_glyphIndex
= glyphIndex
; // glyph index
6822 spell
->prepare(&targets
);
6827 // Item enchantments spells casted at use
6828 for(int e_slot
= 0; e_slot
< MAX_ENCHANTMENT_SLOT
; ++e_slot
)
6830 uint32 enchant_id
= item
->GetEnchantmentId(EnchantmentSlot(e_slot
));
6831 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
6832 if(!pEnchant
) continue;
6833 for (int s
=0;s
<3;s
++)
6835 if(pEnchant
->type
[s
]!=ITEM_ENCHANTMENT_TYPE_USE_SPELL
)
6838 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(pEnchant
->spellid
[s
]);
6841 sLog
.outError("Player::CastItemUseSpell Enchant %i, cast unknown spell %i", pEnchant
->ID
, pEnchant
->spellid
[s
]);
6845 Spell
*spell
= new Spell(this, spellInfo
, (count
> 0));
6846 spell
->m_CastItem
= item
;
6847 spell
->m_cast_count
= cast_count
; // set count of casts
6848 spell
->m_glyphIndex
= glyphIndex
; // glyph index
6849 spell
->prepare(&targets
);
6856 void Player::_RemoveAllItemMods()
6858 sLog
.outDebug("_RemoveAllItemMods start.");
6860 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6864 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6868 // item set bonuses not dependent from item broken state
6870 RemoveItemsSetItem(this,proto
);
6872 if(m_items
[i
]->IsBroken())
6875 ApplyItemEquipSpell(m_items
[i
],false);
6876 ApplyEnchantment(m_items
[i
], false);
6880 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6884 if(m_items
[i
]->IsBroken())
6886 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6890 uint32 attacktype
= Player::GetAttackBySlot(i
);
6891 if(attacktype
< MAX_ATTACK
)
6892 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),false);
6894 _ApplyItemBonuses(proto
,i
, false);
6896 if( i
== EQUIPMENT_SLOT_RANGED
)
6897 _ApplyAmmoBonuses();
6901 sLog
.outDebug("_RemoveAllItemMods complete.");
6904 void Player::_ApplyAllItemMods()
6906 sLog
.outDebug("_ApplyAllItemMods start.");
6908 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6912 if(m_items
[i
]->IsBroken())
6915 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6919 uint32 attacktype
= Player::GetAttackBySlot(i
);
6920 if(attacktype
< MAX_ATTACK
)
6921 _ApplyWeaponDependentAuraMods(m_items
[i
],WeaponAttackType(attacktype
),true);
6923 _ApplyItemBonuses(proto
,i
, true);
6925 if( i
== EQUIPMENT_SLOT_RANGED
)
6926 _ApplyAmmoBonuses();
6930 for (int i
= 0; i
< INVENTORY_SLOT_BAG_END
; i
++)
6934 ItemPrototype
const *proto
= m_items
[i
]->GetProto();
6938 // item set bonuses not dependent from item broken state
6940 AddItemsSetItem(this,m_items
[i
]);
6942 if(m_items
[i
]->IsBroken())
6945 ApplyItemEquipSpell(m_items
[i
],true);
6946 ApplyEnchantment(m_items
[i
], true);
6950 sLog
.outDebug("_ApplyAllItemMods complete.");
6953 void Player::_ApplyAmmoBonuses()
6956 uint32 ammo_id
= GetUInt32Value(PLAYER_AMMO_ID
);
6960 float currentAmmoDPS
;
6962 ItemPrototype
const *ammo_proto
= objmgr
.GetItemPrototype( ammo_id
);
6963 if( !ammo_proto
|| ammo_proto
->Class
!=ITEM_CLASS_PROJECTILE
|| !CheckAmmoCompatibility(ammo_proto
))
6964 currentAmmoDPS
= 0.0f
;
6966 currentAmmoDPS
= ammo_proto
->Damage
[0].DamageMin
;
6968 if(currentAmmoDPS
== GetAmmoDPS())
6971 m_ammoDPS
= currentAmmoDPS
;
6973 if(CanModifyStats())
6974 UpdateDamagePhysical(RANGED_ATTACK
);
6977 bool Player::CheckAmmoCompatibility(const ItemPrototype
*ammo_proto
) const
6982 // check ranged weapon
6983 Item
*weapon
= GetWeaponForAttack( RANGED_ATTACK
);
6984 if(!weapon
|| weapon
->IsBroken() )
6987 ItemPrototype
const* weapon_proto
= weapon
->GetProto();
6988 if(!weapon_proto
|| weapon_proto
->Class
!=ITEM_CLASS_WEAPON
)
6991 // check ammo ws. weapon compatibility
6992 switch(weapon_proto
->SubClass
)
6994 case ITEM_SUBCLASS_WEAPON_BOW
:
6995 case ITEM_SUBCLASS_WEAPON_CROSSBOW
:
6996 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_ARROW
)
6999 case ITEM_SUBCLASS_WEAPON_GUN
:
7000 if(ammo_proto
->SubClass
!=ITEM_SUBCLASS_BULLET
)
7010 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7011 Called by remove insignia spell effect */
7012 void Player::RemovedInsignia(Player
* looterPlr
)
7014 if (!GetBattleGroundId())
7017 // If not released spirit, do it !
7018 if(m_deathTimer
> 0)
7025 Corpse
*corpse
= GetCorpse();
7029 // We have to convert player corpse to bones, not to be able to resurrect there
7030 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7031 Corpse
*bones
= ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID(),true);
7035 // Now we must make bones lootable, and send player loot
7036 bones
->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS
, CORPSE_DYNFLAG_LOOTABLE
);
7038 // We store the level of our player in the gold field
7039 // We retrieve this information at Player::SendLoot()
7040 bones
->loot
.gold
= getLevel();
7041 bones
->lootRecipient
= looterPlr
;
7042 looterPlr
->SendLoot(bones
->GetGUID(), LOOT_INSIGNIA
);
7051 void Player::SendLootRelease( uint64 guid
)
7053 WorldPacket
data( SMSG_LOOT_RELEASE_RESPONSE
, (8+1) );
7054 data
<< uint64(guid
) << uint8(1);
7055 SendDirectMessage( &data
);
7058 void Player::SendLoot(uint64 guid
, LootType loot_type
)
7060 if (uint64 lguid
= GetLootGUID())
7061 m_session
->DoLootRelease(lguid
);
7064 PermissionTypes permission
= ALL_PERMISSION
;
7066 sLog
.outDebug("Player::SendLoot");
7067 if (IS_GAMEOBJECT_GUID(guid
))
7069 sLog
.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7071 ObjectAccessor::GetGameObject(*this, guid
);
7073 // not check distance for GO in case owned GO (fishing bobber case, for example)
7074 // And permit out of range GO with no owner in case fishing hole
7075 if (!go
|| (loot_type
!= LOOT_FISHINGHOLE
&& (loot_type
!= LOOT_FISHING
|| go
->GetOwnerGUID() != GetGUID()) && !go
->IsWithinDistInMap(this,INTERACTION_DISTANCE
)))
7077 SendLootRelease(guid
);
7083 if(go
->getLootState() == GO_READY
)
7085 uint32 lootid
= go
->GetLootId();
7089 sLog
.outDebug(" if(lootid)");
7091 loot
->FillLoot(lootid
, LootTemplates_Gameobject
, this, false);
7094 if(loot_type
== LOOT_FISHING
)
7095 go
->getFishLoot(loot
,this);
7097 go
->SetLootState(GO_ACTIVATED
);
7100 else if (IS_ITEM_GUID(guid
))
7102 Item
*item
= GetItemByGuid( guid
);
7106 SendLootRelease(guid
);
7110 if(loot_type
== LOOT_DISENCHANTING
)
7114 if(!item
->m_lootGenerated
)
7116 item
->m_lootGenerated
= true;
7118 loot
->FillLoot(item
->GetProto()->DisenchantID
, LootTemplates_Disenchant
, this,true);
7121 else if(loot_type
== LOOT_PROSPECTING
)
7125 if(!item
->m_lootGenerated
)
7127 item
->m_lootGenerated
= true;
7129 loot
->FillLoot(item
->GetEntry(), LootTemplates_Prospecting
, this,true);
7132 else if(loot_type
== LOOT_MILLING
)
7136 if(!item
->m_lootGenerated
)
7138 item
->m_lootGenerated
= true;
7140 loot
->FillLoot(item
->GetEntry(), LootTemplates_Milling
, this,true);
7147 if(!item
->m_lootGenerated
)
7149 item
->m_lootGenerated
= true;
7151 loot
->FillLoot(item
->GetEntry(), LootTemplates_Item
, this,true);
7153 loot
->generateMoneyLoot(item
->GetProto()->MinMoneyLoot
,item
->GetProto()->MaxMoneyLoot
);
7157 else if (IS_CORPSE_GUID(guid
)) // remove insignia
7159 Corpse
*bones
= ObjectAccessor::GetCorpse(*this, guid
);
7161 if (!bones
|| !((loot_type
== LOOT_CORPSE
) || (loot_type
== LOOT_INSIGNIA
)) || (bones
->GetType() != CORPSE_BONES
) )
7163 SendLootRelease(guid
);
7167 loot
= &bones
->loot
;
7169 if (!bones
->lootForBody
)
7171 bones
->lootForBody
= true;
7172 uint32 pLevel
= bones
->loot
.gold
;
7173 bones
->loot
.clear();
7174 // It may need a better formula
7175 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7176 bones
->loot
.gold
= (uint32
)( urand(50, 150) * 0.016f
* pow( ((float)pLevel
)/5.76f
, 2.5f
) * sWorld
.getRate(RATE_DROP_MONEY
) );
7179 if (bones
->lootRecipient
!= this)
7180 permission
= NONE_PERMISSION
;
7184 Creature
*creature
= ObjectAccessor::GetCreature(*this, guid
);
7186 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7187 if (!creature
|| creature
->isAlive()!=(loot_type
== LOOT_PICKPOCKETING
) || !creature
->IsWithinDistInMap(this,INTERACTION_DISTANCE
))
7189 SendLootRelease(guid
);
7193 if(loot_type
== LOOT_PICKPOCKETING
&& IsFriendlyTo(creature
))
7195 SendLootRelease(guid
);
7199 loot
= &creature
->loot
;
7201 if(loot_type
== LOOT_PICKPOCKETING
)
7203 if ( !creature
->lootForPickPocketed
)
7205 creature
->lootForPickPocketed
= true;
7208 if (uint32 lootid
= creature
->GetCreatureInfo()->pickpocketLootId
)
7209 loot
->FillLoot(lootid
, LootTemplates_Pickpocketing
, this, false);
7211 // Generate extra money for pick pocket loot
7212 const uint32 a
= urand(0, creature
->getLevel()/2);
7213 const uint32 b
= urand(0, getLevel()/2);
7214 loot
->gold
= uint32(10 * (a
+ b
) * sWorld
.getRate(RATE_DROP_MONEY
));
7219 // the player whose group may loot the corpse
7220 Player
*recipient
= creature
->GetLootRecipient();
7223 creature
->SetLootRecipient(this);
7227 if (creature
->lootForPickPocketed
)
7229 creature
->lootForPickPocketed
= false;
7233 if(!creature
->lootForBody
)
7235 creature
->lootForBody
= true;
7238 if (uint32 lootid
= creature
->GetCreatureInfo()->lootid
)
7239 loot
->FillLoot(lootid
, LootTemplates_Creature
, recipient
, false);
7241 loot
->generateMoneyLoot(creature
->GetCreatureInfo()->mingold
,creature
->GetCreatureInfo()->maxgold
);
7243 if(Group
* group
= recipient
->GetGroup())
7245 group
->UpdateLooterGuid(creature
,true);
7247 switch (group
->GetLootMethod())
7250 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7251 group
->GroupLoot(recipient
->GetGUID(), loot
, creature
);
7253 case NEED_BEFORE_GREED
:
7254 group
->NeedBeforeGreed(recipient
->GetGUID(), loot
, creature
);
7257 group
->MasterLoot(recipient
->GetGUID(), loot
, creature
);
7265 // possible only if creature->lootForBody && loot->empty() at spell cast check
7266 if (loot_type
== LOOT_SKINNING
)
7269 loot
->FillLoot(creature
->GetCreatureInfo()->SkinLootId
, LootTemplates_Skinning
, this, false);
7271 // set group rights only for loot_type != LOOT_SKINNING
7274 if(Group
* group
= GetGroup())
7276 if( group
== recipient
->GetGroup() )
7278 if(group
->GetLootMethod() == FREE_FOR_ALL
)
7279 permission
= ALL_PERMISSION
;
7280 else if(group
->GetLooterGuid() == GetGUID())
7282 if(group
->GetLootMethod() == MASTER_LOOT
)
7283 permission
= MASTER_PERMISSION
;
7285 permission
= ALL_PERMISSION
;
7288 permission
= GROUP_PERMISSION
;
7291 permission
= NONE_PERMISSION
;
7293 else if(recipient
== this)
7294 permission
= ALL_PERMISSION
;
7296 permission
= NONE_PERMISSION
;
7303 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING, LOOT_INSIGNIA and LOOT_MILLING unsupported by client, sending LOOT_SKINNING instead
7304 if(loot_type
== LOOT_PICKPOCKETING
|| loot_type
== LOOT_DISENCHANTING
|| loot_type
== LOOT_PROSPECTING
|| loot_type
== LOOT_INSIGNIA
|| loot_type
== LOOT_MILLING
)
7305 loot_type
= LOOT_SKINNING
;
7307 if(loot_type
== LOOT_FISHINGHOLE
)
7308 loot_type
= LOOT_FISHING
;
7310 WorldPacket
data(SMSG_LOOT_RESPONSE
, (9+50)); // we guess size
7312 data
<< uint64(guid
);
7313 data
<< uint8(loot_type
);
7314 data
<< LootView(*loot
, this, permission
);
7316 SendDirectMessage(&data
);
7318 // add 'this' player as one of the players that are looting 'loot'
7319 if (permission
!= NONE_PERMISSION
)
7320 loot
->AddLooter(GetGUID());
7322 if ( loot_type
== LOOT_CORPSE
&& !IS_ITEM_GUID(guid
) )
7323 SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_LOOTING
);
7326 void Player::SendNotifyLootMoneyRemoved()
7328 WorldPacket
data(SMSG_LOOT_CLEAR_MONEY
, 0);
7329 GetSession()->SendPacket( &data
);
7332 void Player::SendNotifyLootItemRemoved(uint8 lootSlot
)
7334 WorldPacket
data(SMSG_LOOT_REMOVED
, 1);
7335 data
<< uint8(lootSlot
);
7336 GetSession()->SendPacket( &data
);
7339 void Player::SendUpdateWorldState(uint32 Field
, uint32 Value
)
7341 WorldPacket
data(SMSG_UPDATE_WORLD_STATE
, 8);
7344 GetSession()->SendPacket(&data
);
7347 void Player::SendInitWorldStates(uint32 zoneid
, uint32 areaid
)
7349 // data depends on zoneid/mapid...
7350 BattleGround
* bg
= GetBattleGround();
7351 uint16 NumberOfFields
= 0;
7352 uint32 mapid
= GetMapId();
7354 sLog
.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid
, zoneid
);
7356 // may be exist better way to do this...
7379 NumberOfFields
= 41;
7382 NumberOfFields
= 15;
7385 NumberOfFields
= 83;
7388 NumberOfFields
= 16;
7392 NumberOfFields
= 40;
7395 NumberOfFields
= 27;
7398 NumberOfFields
= 39;
7401 NumberOfFields
= 38;
7404 NumberOfFields
= 37;
7409 NumberOfFields
= 11;
7412 NumberOfFields
= 11;
7415 NumberOfFields
= 12;
7419 WorldPacket
data(SMSG_INIT_WORLD_STATES
, (4+4+4+2+(NumberOfFields
*8)));
7420 data
<< uint32(mapid
); // mapid
7421 data
<< uint32(zoneid
); // zone id
7422 data
<< uint32(areaid
); // area id, new 2.1.0
7423 data
<< uint16(NumberOfFields
); // count of uint64 blocks
7424 data
<< uint32(0x8d8) << uint32(0x0); // 1
7425 data
<< uint32(0x8d7) << uint32(0x0); // 2
7426 data
<< uint32(0x8d6) << uint32(0x0); // 3
7427 data
<< uint32(0x8d5) << uint32(0x0); // 4
7428 data
<< uint32(0x8d4) << uint32(0x0); // 5
7429 data
<< uint32(0x8d3) << uint32(0x0); // 6
7430 // 7 1 - Arena season in progress, 0 - end of season
7431 data
<< uint32(0xC77) << uint32(sWorld
.getConfig(CONFIG_ARENA_SEASON_IN_PROGRESS
));
7432 // 8 Arena season id
7433 data
<< uint32(0xF3D) << uint32(sWorld
.getConfig(CONFIG_ARENA_SEASON_ID
));
7434 if(mapid
== 530) // Outland
7436 data
<< uint32(0x9bf) << uint32(0x0); // 7
7437 data
<< uint32(0x9bd) << uint32(0xF); // 8
7438 data
<< uint32(0x9bb) << uint32(0xF); // 9
7453 data
<< uint32(0x7ae) << uint32(0x1); // 7
7454 data
<< uint32(0x532) << uint32(0x1); // 8
7455 data
<< uint32(0x531) << uint32(0x0); // 9
7456 data
<< uint32(0x52e) << uint32(0x0); // 10
7457 data
<< uint32(0x571) << uint32(0x0); // 11
7458 data
<< uint32(0x570) << uint32(0x0); // 12
7459 data
<< uint32(0x567) << uint32(0x1); // 13
7460 data
<< uint32(0x566) << uint32(0x1); // 14
7461 data
<< uint32(0x550) << uint32(0x1); // 15
7462 data
<< uint32(0x544) << uint32(0x0); // 16
7463 data
<< uint32(0x536) << uint32(0x0); // 17
7464 data
<< uint32(0x535) << uint32(0x1); // 18
7465 data
<< uint32(0x518) << uint32(0x0); // 19
7466 data
<< uint32(0x517) << uint32(0x0); // 20
7467 data
<< uint32(0x574) << uint32(0x0); // 21
7468 data
<< uint32(0x573) << uint32(0x0); // 22
7469 data
<< uint32(0x572) << uint32(0x0); // 23
7470 data
<< uint32(0x56f) << uint32(0x0); // 24
7471 data
<< uint32(0x56e) << uint32(0x0); // 25
7472 data
<< uint32(0x56d) << uint32(0x0); // 26
7473 data
<< uint32(0x56c) << uint32(0x0); // 27
7474 data
<< uint32(0x56b) << uint32(0x0); // 28
7475 data
<< uint32(0x56a) << uint32(0x1); // 29
7476 data
<< uint32(0x569) << uint32(0x1); // 30
7477 data
<< uint32(0x568) << uint32(0x1); // 13
7478 data
<< uint32(0x565) << uint32(0x0); // 32
7479 data
<< uint32(0x564) << uint32(0x0); // 33
7480 data
<< uint32(0x563) << uint32(0x0); // 34
7481 data
<< uint32(0x562) << uint32(0x0); // 35
7482 data
<< uint32(0x561) << uint32(0x0); // 36
7483 data
<< uint32(0x560) << uint32(0x0); // 37
7484 data
<< uint32(0x55f) << uint32(0x0); // 38
7485 data
<< uint32(0x55e) << uint32(0x0); // 39
7486 data
<< uint32(0x55d) << uint32(0x0); // 40
7487 data
<< uint32(0x3c6) << uint32(0x4); // 41
7488 data
<< uint32(0x3c4) << uint32(0x6); // 42
7489 data
<< uint32(0x3c2) << uint32(0x4); // 43
7490 data
<< uint32(0x516) << uint32(0x1); // 44
7491 data
<< uint32(0x515) << uint32(0x0); // 45
7492 data
<< uint32(0x3b6) << uint32(0x6); // 46
7493 data
<< uint32(0x55c) << uint32(0x0); // 47
7494 data
<< uint32(0x55b) << uint32(0x0); // 48
7495 data
<< uint32(0x55a) << uint32(0x0); // 49
7496 data
<< uint32(0x559) << uint32(0x0); // 50
7497 data
<< uint32(0x558) << uint32(0x0); // 51
7498 data
<< uint32(0x557) << uint32(0x0); // 52
7499 data
<< uint32(0x556) << uint32(0x0); // 53
7500 data
<< uint32(0x555) << uint32(0x0); // 54
7501 data
<< uint32(0x554) << uint32(0x1); // 55
7502 data
<< uint32(0x553) << uint32(0x1); // 56
7503 data
<< uint32(0x552) << uint32(0x1); // 57
7504 data
<< uint32(0x551) << uint32(0x1); // 58
7505 data
<< uint32(0x54f) << uint32(0x0); // 59
7506 data
<< uint32(0x54e) << uint32(0x0); // 60
7507 data
<< uint32(0x54d) << uint32(0x1); // 61
7508 data
<< uint32(0x54c) << uint32(0x0); // 62
7509 data
<< uint32(0x54b) << uint32(0x0); // 63
7510 data
<< uint32(0x545) << uint32(0x0); // 64
7511 data
<< uint32(0x543) << uint32(0x1); // 65
7512 data
<< uint32(0x542) << uint32(0x0); // 66
7513 data
<< uint32(0x540) << uint32(0x0); // 67
7514 data
<< uint32(0x53f) << uint32(0x0); // 68
7515 data
<< uint32(0x53e) << uint32(0x0); // 69
7516 data
<< uint32(0x53d) << uint32(0x0); // 70
7517 data
<< uint32(0x53c) << uint32(0x0); // 71
7518 data
<< uint32(0x53b) << uint32(0x0); // 72
7519 data
<< uint32(0x53a) << uint32(0x1); // 73
7520 data
<< uint32(0x539) << uint32(0x0); // 74
7521 data
<< uint32(0x538) << uint32(0x0); // 75
7522 data
<< uint32(0x537) << uint32(0x0); // 76
7523 data
<< uint32(0x534) << uint32(0x0); // 77
7524 data
<< uint32(0x533) << uint32(0x0); // 78
7525 data
<< uint32(0x530) << uint32(0x0); // 79
7526 data
<< uint32(0x52f) << uint32(0x0); // 80
7527 data
<< uint32(0x52d) << uint32(0x1); // 81
7530 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_WS
)
7531 bg
->FillInitialWorldStates(data
);
7534 data
<< uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7535 data
<< uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7536 data
<< uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7537 data
<< uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7538 data
<< uint32(0x60b) << uint32(0x2); // 11 1547 unk
7539 data
<< uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7540 data
<< uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7541 data
<< uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7545 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_AB
)
7546 bg
->FillInitialWorldStates(data
);
7549 data
<< uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7550 data
<< uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7551 data
<< uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7552 data
<< uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7553 data
<< uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7554 data
<< uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7555 data
<< uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7556 data
<< uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7557 data
<< uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7558 data
<< uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7559 data
<< uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7560 data
<< uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7561 data
<< uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7562 data
<< uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7563 data
<< uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7564 data
<< uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7565 data
<< uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7566 data
<< uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7567 data
<< uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7568 data
<< uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7569 data
<< uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7570 data
<< uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7571 data
<< uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7572 data
<< uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7573 data
<< uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7574 data
<< uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7575 data
<< uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7576 data
<< uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7577 data
<< uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7578 data
<< uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7579 data
<< uint32(0x745) << uint32(0x2); // 37 1861 unk
7580 data
<< uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7584 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_EY
)
7585 bg
->FillInitialWorldStates(data
);
7588 data
<< uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7589 data
<< uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7590 data
<< uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7591 data
<< uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7592 data
<< uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7593 data
<< uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7594 data
<< uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7595 data
<< uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7596 data
<< uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7597 data
<< uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7598 data
<< uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7599 data
<< uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7600 data
<< uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7601 data
<< uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7602 data
<< uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7603 data
<< uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7604 data
<< uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7605 data
<< uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7606 data
<< uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7607 data
<< uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7608 data
<< uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7609 data
<< uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7610 data
<< uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7611 data
<< uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7612 data
<< uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7613 data
<< uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7614 data
<< uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7615 data
<< uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7616 data
<< uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7617 data
<< uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7618 data
<< uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7619 data
<< uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7620 // and some more ... unknown
7623 case 3483: // Hellfire Peninsula
7624 data
<< uint32(0x9ba) << uint32(0x1); // 10
7625 data
<< uint32(0x9b9) << uint32(0x1); // 11
7626 data
<< uint32(0x9b5) << uint32(0x0); // 12
7627 data
<< uint32(0x9b4) << uint32(0x1); // 13
7628 data
<< uint32(0x9b3) << uint32(0x0); // 14
7629 data
<< uint32(0x9b2) << uint32(0x0); // 15
7630 data
<< uint32(0x9b1) << uint32(0x1); // 16
7631 data
<< uint32(0x9b0) << uint32(0x0); // 17
7632 data
<< uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7633 data
<< uint32(0x9ac) << uint32(0x0); // 19
7634 data
<< uint32(0x9a8) << uint32(0x0); // 20
7635 data
<< uint32(0x9a7) << uint32(0x0); // 21
7636 data
<< uint32(0x9a6) << uint32(0x1); // 22
7638 case 3519: // Terokkar Forest
7639 data
<< uint32(0xa41) << uint32(0x0); // 10
7640 data
<< uint32(0xa40) << uint32(0x14); // 11
7641 data
<< uint32(0xa3f) << uint32(0x0); // 12
7642 data
<< uint32(0xa3e) << uint32(0x0); // 13
7643 data
<< uint32(0xa3d) << uint32(0x5); // 14
7644 data
<< uint32(0xa3c) << uint32(0x0); // 15
7645 data
<< uint32(0xa87) << uint32(0x0); // 16
7646 data
<< uint32(0xa86) << uint32(0x0); // 17
7647 data
<< uint32(0xa85) << uint32(0x0); // 18
7648 data
<< uint32(0xa84) << uint32(0x0); // 19
7649 data
<< uint32(0xa83) << uint32(0x0); // 20
7650 data
<< uint32(0xa82) << uint32(0x0); // 21
7651 data
<< uint32(0xa81) << uint32(0x0); // 22
7652 data
<< uint32(0xa80) << uint32(0x0); // 23
7653 data
<< uint32(0xa7e) << uint32(0x0); // 24
7654 data
<< uint32(0xa7d) << uint32(0x0); // 25
7655 data
<< uint32(0xa7c) << uint32(0x0); // 26
7656 data
<< uint32(0xa7b) << uint32(0x0); // 27
7657 data
<< uint32(0xa7a) << uint32(0x0); // 28
7658 data
<< uint32(0xa79) << uint32(0x0); // 29
7659 data
<< uint32(0x9d0) << uint32(0x5); // 30
7660 data
<< uint32(0x9ce) << uint32(0x0); // 31
7661 data
<< uint32(0x9cd) << uint32(0x0); // 32
7662 data
<< uint32(0x9cc) << uint32(0x0); // 33
7663 data
<< uint32(0xa88) << uint32(0x0); // 34
7664 data
<< uint32(0xad0) << uint32(0x0); // 35
7665 data
<< uint32(0xacf) << uint32(0x1); // 36
7667 case 3521: // Zangarmarsh
7668 data
<< uint32(0x9e1) << uint32(0x0); // 10
7669 data
<< uint32(0x9e0) << uint32(0x0); // 11
7670 data
<< uint32(0x9df) << uint32(0x0); // 12
7671 data
<< uint32(0xa5d) << uint32(0x1); // 13
7672 data
<< uint32(0xa5c) << uint32(0x0); // 14
7673 data
<< uint32(0xa5b) << uint32(0x1); // 15
7674 data
<< uint32(0xa5a) << uint32(0x0); // 16
7675 data
<< uint32(0xa59) << uint32(0x1); // 17
7676 data
<< uint32(0xa58) << uint32(0x0); // 18
7677 data
<< uint32(0xa57) << uint32(0x0); // 19
7678 data
<< uint32(0xa56) << uint32(0x0); // 20
7679 data
<< uint32(0xa55) << uint32(0x1); // 21
7680 data
<< uint32(0xa54) << uint32(0x0); // 22
7681 data
<< uint32(0x9e7) << uint32(0x0); // 23
7682 data
<< uint32(0x9e6) << uint32(0x0); // 24
7683 data
<< uint32(0x9e5) << uint32(0x0); // 25
7684 data
<< uint32(0xa00) << uint32(0x0); // 26
7685 data
<< uint32(0x9ff) << uint32(0x1); // 27
7686 data
<< uint32(0x9fe) << uint32(0x0); // 28
7687 data
<< uint32(0x9fd) << uint32(0x0); // 29
7688 data
<< uint32(0x9fc) << uint32(0x1); // 30
7689 data
<< uint32(0x9fb) << uint32(0x0); // 31
7690 data
<< uint32(0xa62) << uint32(0x0); // 32
7691 data
<< uint32(0xa61) << uint32(0x1); // 33
7692 data
<< uint32(0xa60) << uint32(0x1); // 34
7693 data
<< uint32(0xa5f) << uint32(0x0); // 35
7695 case 3698: // Nagrand Arena
7696 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_NA
)
7697 bg
->FillInitialWorldStates(data
);
7700 data
<< uint32(0xa0f) << uint32(0x0); // 7
7701 data
<< uint32(0xa10) << uint32(0x0); // 8
7702 data
<< uint32(0xa11) << uint32(0x0); // 9 show
7705 case 3702: // Blade's Edge Arena
7706 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_BE
)
7707 bg
->FillInitialWorldStates(data
);
7710 data
<< uint32(0x9f0) << uint32(0x0); // 7 gold
7711 data
<< uint32(0x9f1) << uint32(0x0); // 8 green
7712 data
<< uint32(0x9f3) << uint32(0x0); // 9 show
7715 case 3968: // Ruins of Lordaeron
7716 if (bg
&& bg
->GetTypeID() == BATTLEGROUND_RL
)
7717 bg
->FillInitialWorldStates(data
);
7720 data
<< uint32(0xbb8) << uint32(0x0); // 7 gold
7721 data
<< uint32(0xbb9) << uint32(0x0); // 8 green
7722 data
<< uint32(0xbba) << uint32(0x0); // 9 show
7725 case 3703: // Shattrath City
7728 data
<< uint32(0x914) << uint32(0x0); // 7
7729 data
<< uint32(0x913) << uint32(0x0); // 8
7730 data
<< uint32(0x912) << uint32(0x0); // 9
7731 data
<< uint32(0x915) << uint32(0x0); // 10
7734 GetSession()->SendPacket(&data
);
7737 uint32
Player::GetXPRestBonus(uint32 xp
)
7739 uint32 rested_bonus
= (uint32
)GetRestBonus(); // xp for each rested bonus
7741 if(rested_bonus
> xp
) // max rested_bonus == xp or (r+x) = 200% xp
7744 SetRestBonus( GetRestBonus() - rested_bonus
);
7746 sLog
.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp
+rested_bonus
,rested_bonus
,GetRestBonus());
7747 return rested_bonus
;
7750 void Player::SetBindPoint(uint64 guid
)
7752 WorldPacket
data(SMSG_BINDER_CONFIRM
, 8);
7753 data
<< uint64(guid
);
7754 GetSession()->SendPacket( &data
);
7757 void Player::SendTalentWipeConfirm(uint64 guid
)
7759 WorldPacket
data(MSG_TALENT_WIPE_CONFIRM
, (8+4));
7760 data
<< uint64(guid
);
7761 data
<< uint32(resetTalentsCost());
7762 GetSession()->SendPacket( &data
);
7765 void Player::SendPetSkillWipeConfirm()
7767 Pet
* pet
= GetPet();
7770 WorldPacket
data(SMSG_PET_UNLEARN_CONFIRM
, (8+4));
7771 data
<< pet
->GetGUID();
7772 data
<< uint32(pet
->resetTalentsCost());
7773 GetSession()->SendPacket( &data
);
7776 /*********************************************************/
7777 /*** STORAGE SYSTEM ***/
7778 /*********************************************************/
7780 void Player::SetVirtualItemSlot( uint8 i
, Item
* item
)
7785 if(!item
->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT
))
7787 uint32 charges
= item
->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
);
7791 item
->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT
,charges
-1);
7792 else if(charges
<= 1)
7794 ApplyEnchantment(item
,TEMP_ENCHANTMENT_SLOT
,false);
7795 item
->ClearEnchantment(TEMP_ENCHANTMENT_SLOT
);
7800 void Player::SetSheath( uint32 sheathed
)
7804 case SHEATH_STATE_UNARMED
: // no prepared weapon
7805 SetVirtualItemSlot(0,NULL
);
7806 SetVirtualItemSlot(1,NULL
);
7807 SetVirtualItemSlot(2,NULL
);
7809 case SHEATH_STATE_MELEE
: // prepared melee weapon
7811 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK
,true));
7812 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK
,true));
7813 SetVirtualItemSlot(2,NULL
);
7815 case SHEATH_STATE_RANGED
: // prepared ranged weapon
7816 SetVirtualItemSlot(0,NULL
);
7817 SetVirtualItemSlot(1,NULL
);
7818 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK
,true));
7821 SetVirtualItemSlot(0,NULL
);
7822 SetVirtualItemSlot(1,NULL
);
7823 SetVirtualItemSlot(2,NULL
);
7826 SetByteValue(UNIT_FIELD_BYTES_2
, 0, sheathed
); // this must visualize Sheath changing for other players...
7829 uint8
Player::FindEquipSlot( ItemPrototype
const* proto
, uint32 slot
, bool swap
) const
7831 uint8 pClass
= getClass();
7834 slots
[0] = NULL_SLOT
;
7835 slots
[1] = NULL_SLOT
;
7836 slots
[2] = NULL_SLOT
;
7837 slots
[3] = NULL_SLOT
;
7838 switch( proto
->InventoryType
)
7841 slots
[0] = EQUIPMENT_SLOT_HEAD
;
7844 slots
[0] = EQUIPMENT_SLOT_NECK
;
7846 case INVTYPE_SHOULDERS
:
7847 slots
[0] = EQUIPMENT_SLOT_SHOULDERS
;
7850 slots
[0] = EQUIPMENT_SLOT_BODY
;
7853 slots
[0] = EQUIPMENT_SLOT_CHEST
;
7856 slots
[0] = EQUIPMENT_SLOT_CHEST
;
7859 slots
[0] = EQUIPMENT_SLOT_WAIST
;
7862 slots
[0] = EQUIPMENT_SLOT_LEGS
;
7865 slots
[0] = EQUIPMENT_SLOT_FEET
;
7867 case INVTYPE_WRISTS
:
7868 slots
[0] = EQUIPMENT_SLOT_WRISTS
;
7871 slots
[0] = EQUIPMENT_SLOT_HANDS
;
7873 case INVTYPE_FINGER
:
7874 slots
[0] = EQUIPMENT_SLOT_FINGER1
;
7875 slots
[1] = EQUIPMENT_SLOT_FINGER2
;
7877 case INVTYPE_TRINKET
:
7878 slots
[0] = EQUIPMENT_SLOT_TRINKET1
;
7879 slots
[1] = EQUIPMENT_SLOT_TRINKET2
;
7882 slots
[0] = EQUIPMENT_SLOT_BACK
;
7884 case INVTYPE_WEAPON
:
7886 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
7888 // suggest offhand slot only if know dual wielding
7889 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
7891 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
7894 case INVTYPE_SHIELD
:
7895 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
7897 case INVTYPE_RANGED
:
7898 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7900 case INVTYPE_2HWEAPON
:
7901 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
7902 if (CanDualWield() && CanTitanGrip())
7903 slots
[1] = EQUIPMENT_SLOT_OFFHAND
;
7905 case INVTYPE_TABARD
:
7906 slots
[0] = EQUIPMENT_SLOT_TABARD
;
7908 case INVTYPE_WEAPONMAINHAND
:
7909 slots
[0] = EQUIPMENT_SLOT_MAINHAND
;
7911 case INVTYPE_WEAPONOFFHAND
:
7912 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
7914 case INVTYPE_HOLDABLE
:
7915 slots
[0] = EQUIPMENT_SLOT_OFFHAND
;
7917 case INVTYPE_THROWN
:
7918 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7920 case INVTYPE_RANGEDRIGHT
:
7921 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7924 slots
[0] = INVENTORY_SLOT_BAG_START
+ 0;
7925 slots
[1] = INVENTORY_SLOT_BAG_START
+ 1;
7926 slots
[2] = INVENTORY_SLOT_BAG_START
+ 2;
7927 slots
[3] = INVENTORY_SLOT_BAG_START
+ 3;
7931 switch(proto
->SubClass
)
7933 case ITEM_SUBCLASS_ARMOR_LIBRAM
:
7934 if (pClass
== CLASS_PALADIN
)
7935 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7937 case ITEM_SUBCLASS_ARMOR_IDOL
:
7938 if (pClass
== CLASS_DRUID
)
7939 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7941 case ITEM_SUBCLASS_ARMOR_TOTEM
:
7942 if (pClass
== CLASS_SHAMAN
)
7943 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7945 case ITEM_SUBCLASS_ARMOR_MISC
:
7946 if (pClass
== CLASS_WARLOCK
)
7947 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7949 case ITEM_SUBCLASS_ARMOR_SIGIL
:
7950 if (pClass
== CLASS_DEATH_KNIGHT
)
7951 slots
[0] = EQUIPMENT_SLOT_RANGED
;
7960 if( slot
!= NULL_SLOT
)
7962 if( swap
|| !GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
) )
7964 for (int i
= 0; i
< 4; i
++)
7966 if ( slots
[i
] == slot
)
7973 // search free slot at first
7974 for (int i
= 0; i
< 4; i
++)
7976 if ( slots
[i
] != NULL_SLOT
&& !GetItemByPos( INVENTORY_SLOT_BAG_0
, slots
[i
] ) )
7978 // in case 2hand equipped weapon (without titan grip) offhand slot empty but not free
7979 if(slots
[i
]!=EQUIPMENT_SLOT_OFFHAND
|| !IsTwoHandUsed())
7984 // if not found free and can swap return first appropriate from used
7985 for (int i
= 0; i
< 4; i
++)
7987 if ( slots
[i
] != NULL_SLOT
&& swap
)
7996 uint8
Player::CanUnequipItems( uint32 item
, uint32 count
) const
7999 uint32 tempcount
= 0;
8001 uint8 res
= EQUIP_ERR_OK
;
8003 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8005 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8006 if( pItem
&& pItem
->GetEntry() == item
)
8008 uint8 ires
= CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
, false);
8009 if(ires
==EQUIP_ERR_OK
)
8011 tempcount
+= pItem
->GetCount();
8012 if( tempcount
>= count
)
8013 return EQUIP_ERR_OK
;
8019 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8021 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8022 if( pItem
&& pItem
->GetEntry() == item
)
8024 tempcount
+= pItem
->GetCount();
8025 if( tempcount
>= count
)
8026 return EQUIP_ERR_OK
;
8029 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8031 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8032 if( pItem
&& pItem
->GetEntry() == item
)
8034 tempcount
+= pItem
->GetCount();
8035 if( tempcount
>= count
)
8036 return EQUIP_ERR_OK
;
8040 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8042 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8045 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8047 pItem
= GetItemByPos( i
, j
);
8048 if( pItem
&& pItem
->GetEntry() == item
)
8050 tempcount
+= pItem
->GetCount();
8051 if( tempcount
>= count
)
8052 return EQUIP_ERR_OK
;
8058 // not found req. item count and have unequippable items
8062 uint32
Player::GetItemCount( uint32 item
, bool inBankAlso
, Item
* skipItem
) const
8065 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8067 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8068 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8069 count
+= pItem
->GetCount();
8071 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8073 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8074 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8075 count
+= pItem
->GetCount();
8077 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8079 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8081 count
+= pBag
->GetItemCount(item
,skipItem
);
8084 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8086 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8088 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8089 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8090 count
+= pItem
->GetGemCountWithID(item
);
8096 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8098 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8099 if( pItem
&& pItem
!= skipItem
&& pItem
->GetEntry() == item
)
8100 count
+= pItem
->GetCount();
8102 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8104 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8106 count
+= pBag
->GetItemCount(item
,skipItem
);
8109 if(skipItem
&& skipItem
->GetProto()->GemProperties
)
8111 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8113 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8114 if( pItem
&& pItem
!= skipItem
&& pItem
->GetProto()->Socket
[0].Color
)
8115 count
+= pItem
->GetGemCountWithID(item
);
8123 Item
* Player::GetItemByGuid( uint64 guid
) const
8125 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8127 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8128 if( pItem
&& pItem
->GetGUID() == guid
)
8131 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8133 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8134 if( pItem
&& pItem
->GetGUID() == guid
)
8138 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8140 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8143 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8145 Item
* pItem
= pBag
->GetItemByPos( j
);
8146 if( pItem
&& pItem
->GetGUID() == guid
)
8151 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8153 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8156 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8158 Item
* pItem
= pBag
->GetItemByPos( j
);
8159 if( pItem
&& pItem
->GetGUID() == guid
)
8168 Item
* Player::GetItemByPos( uint16 pos
) const
8170 uint8 bag
= pos
>> 8;
8171 uint8 slot
= pos
& 255;
8172 return GetItemByPos( bag
, slot
);
8175 Item
* Player::GetItemByPos( uint8 bag
, uint8 slot
) const
8177 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< BANK_SLOT_BAG_END
|| slot
>= KEYRING_SLOT_START
&& slot
< QUESTBAG_SLOT_END
) )
8178 return m_items
[slot
];
8179 else if(bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
8180 || bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8182 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8184 return pBag
->GetItemByPos(slot
);
8189 Item
* Player::GetWeaponForAttack(WeaponAttackType attackType
, bool useable
) const
8194 case BASE_ATTACK
: slot
= EQUIPMENT_SLOT_MAINHAND
; break;
8195 case OFF_ATTACK
: slot
= EQUIPMENT_SLOT_OFFHAND
; break;
8196 case RANGED_ATTACK
: slot
= EQUIPMENT_SLOT_RANGED
; break;
8197 default: return NULL
;
8200 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, slot
);
8201 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_WEAPON
)
8207 if( item
->IsBroken() || !IsUseEquipedWeapon(attackType
==BASE_ATTACK
) )
8213 Item
* Player::GetShield(bool useable
) const
8215 Item
* item
= GetItemByPos(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
8216 if (!item
|| item
->GetProto()->Class
!= ITEM_CLASS_ARMOR
)
8222 if( item
->IsBroken())
8228 uint32
Player::GetAttackBySlot( uint8 slot
)
8232 case EQUIPMENT_SLOT_MAINHAND
: return BASE_ATTACK
;
8233 case EQUIPMENT_SLOT_OFFHAND
: return OFF_ATTACK
;
8234 case EQUIPMENT_SLOT_RANGED
: return RANGED_ATTACK
;
8235 default: return MAX_ATTACK
;
8239 bool Player::HasBankBagSlot( uint8 slot
) const
8241 uint32 maxslot
= GetByteValue(PLAYER_BYTES_2
, 2) + BANK_SLOT_BAG_START
;
8242 if( slot
< maxslot
)
8247 bool Player::IsInventoryPos( uint8 bag
, uint8 slot
)
8249 if( bag
== INVENTORY_SLOT_BAG_0
&& slot
== NULL_SLOT
)
8251 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
) )
8253 if( bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8255 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= KEYRING_SLOT_START
&& slot
< QUESTBAG_SLOT_END
) )
8260 bool Player::IsEquipmentPos( uint8 bag
, uint8 slot
)
8262 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
< EQUIPMENT_SLOT_END
) )
8264 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8269 bool Player::IsBankPos( uint8 bag
, uint8 slot
)
8271 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
) )
8273 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8275 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8280 bool Player::IsBagPos( uint16 pos
)
8282 uint8 bag
= pos
>> 8;
8283 uint8 slot
= pos
& 255;
8284 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
) )
8286 if( bag
== INVENTORY_SLOT_BAG_0
&& ( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
) )
8291 bool Player::IsValidPos( uint8 bag
, uint8 slot
)
8297 if (bag
== INVENTORY_SLOT_BAG_0
)
8299 // any post selected
8300 if (slot
== NULL_SLOT
)
8304 if (slot
< EQUIPMENT_SLOT_END
)
8308 if (slot
>= INVENTORY_SLOT_BAG_START
&& slot
< INVENTORY_SLOT_BAG_END
)
8312 if (slot
>= INVENTORY_SLOT_ITEM_START
&& slot
< INVENTORY_SLOT_ITEM_END
)
8316 if (slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_END
)
8320 if (slot
>= BANK_SLOT_ITEM_START
&& slot
< BANK_SLOT_ITEM_END
)
8324 if (slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
8330 // bag content slots
8331 if (bag
>= INVENTORY_SLOT_BAG_START
&& bag
< INVENTORY_SLOT_BAG_END
)
8333 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8337 // any post selected
8338 if (slot
== NULL_SLOT
)
8341 return slot
< pBag
->GetBagSize();
8344 // bank bag content slots
8345 if( bag
>= BANK_SLOT_BAG_START
&& bag
< BANK_SLOT_BAG_END
)
8347 Bag
* pBag
= (Bag
*)GetItemByPos (INVENTORY_SLOT_BAG_0
, bag
);
8351 // any post selected
8352 if (slot
== NULL_SLOT
)
8355 return slot
< pBag
->GetBagSize();
8363 bool Player::HasItemCount( uint32 item
, uint32 count
, bool inBankAlso
) const
8365 uint32 tempcount
= 0;
8366 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
8368 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8369 if( pItem
&& pItem
->GetEntry() == item
)
8371 tempcount
+= pItem
->GetCount();
8372 if( tempcount
>= count
)
8376 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
8378 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8379 if( pItem
&& pItem
->GetEntry() == item
)
8381 tempcount
+= pItem
->GetCount();
8382 if( tempcount
>= count
)
8386 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
8388 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8390 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8392 Item
* pItem
= GetItemByPos( i
, j
);
8393 if( pItem
&& pItem
->GetEntry() == item
)
8395 tempcount
+= pItem
->GetCount();
8396 if( tempcount
>= count
)
8405 for(int i
= BANK_SLOT_ITEM_START
; i
< BANK_SLOT_ITEM_END
; i
++)
8407 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8408 if( pItem
&& pItem
->GetEntry() == item
)
8410 tempcount
+= pItem
->GetCount();
8411 if( tempcount
>= count
)
8415 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
8417 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8419 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8421 Item
* pItem
= GetItemByPos( i
, j
);
8422 if( pItem
&& pItem
->GetEntry() == item
)
8424 tempcount
+= pItem
->GetCount();
8425 if( tempcount
>= count
)
8436 bool Player::HasItemOrGemWithIdEquipped( uint32 item
, uint32 count
, uint8 except_slot
) const
8438 uint32 tempcount
= 0;
8439 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
8441 if(i
==int(except_slot
))
8444 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8445 if( pItem
&& pItem
->GetEntry() == item
)
8447 tempcount
+= pItem
->GetCount();
8448 if( tempcount
>= count
)
8453 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(item
);
8454 if (pProto
&& pProto
->GemProperties
)
8456 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
8458 if(i
==int(except_slot
))
8461 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8462 if( pItem
&& pItem
->GetProto()->Socket
[0].Color
)
8464 tempcount
+= pItem
->GetGemCountWithID(item
);
8465 if( tempcount
>= count
)
8474 bool Player::HasItemOrGemWithLimitCategoryEquipped( uint32 limitCategory
, uint32 count
, uint8 except_slot
) const
8476 uint32 tempcount
= 0;
8477 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
8479 if(i
==int(except_slot
))
8482 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8486 ItemPrototype
const *pProto
= pItem
->GetProto();
8490 if (pProto
->ItemLimitCategory
== limitCategory
)
8492 tempcount
+= pItem
->GetCount();
8493 if( tempcount
>= count
)
8497 if( pProto
->Socket
[0].Color
)
8499 tempcount
+= pItem
->GetGemCountWithLimitCategory(limitCategory
);
8500 if( tempcount
>= count
)
8508 uint8
Player::_CanTakeMoreSimilarItems(uint32 entry
, uint32 count
, Item
* pItem
, uint32
* no_space_count
) const
8510 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
8514 *no_space_count
= count
;
8515 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8519 if(pProto
->MaxCount
<= 0)
8520 return EQUIP_ERR_OK
;
8522 uint32 curcount
= GetItemCount(pProto
->ItemId
,true,pItem
);
8524 if (curcount
+ count
> uint32(pProto
->MaxCount
))
8527 *no_space_count
= count
+curcount
- pProto
->MaxCount
;
8528 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8531 return EQUIP_ERR_OK
;
8534 bool Player::HasItemTotemCategory( uint32 TotemCategory
) const
8537 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_ITEM_END
; ++i
)
8539 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8540 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8543 for(uint8 i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; ++i
)
8545 pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
8546 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8549 for(uint8 i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
8551 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
8553 for(uint32 j
= 0; j
< pBag
->GetBagSize(); ++j
)
8555 pItem
= GetItemByPos( i
, j
);
8556 if( pItem
&& IsTotemCategoryCompatiableWith(pItem
->GetProto()->TotemCategory
,TotemCategory
))
8564 uint8
Player::_CanStoreItem_InSpecificSlot( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, ItemPrototype
const *pProto
, uint32
& count
, bool swap
, Item
* pSrcItem
) const
8566 Item
* pItem2
= GetItemByPos( bag
, slot
);
8568 // ignore move item (this slot will be empty at move)
8569 if(pItem2
==pSrcItem
)
8574 // empty specific slot - check item fit to slot
8575 if( !pItem2
|| swap
)
8577 if( bag
== INVENTORY_SLOT_BAG_0
)
8580 if(slot
>= KEYRING_SLOT_START
&& slot
< KEYRING_SLOT_START
+GetMaxKeyringSize() && !(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
))
8581 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8583 // vanitypet case (not use, vanity pets stored as spells)
8584 if(slot
>= VANITYPET_SLOT_START
&& slot
< VANITYPET_SLOT_END
)
8585 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8587 // currencytoken case (disabled until proper implement)
8588 if(slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
&& !(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
))
8589 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8591 // guestbag case (not use)
8592 if(slot
>= QUESTBAG_SLOT_START
&& slot
< QUESTBAG_SLOT_END
)
8593 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8596 if(slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
|| slot
>= PLAYER_SLOT_END
)
8597 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8601 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8603 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8605 ItemPrototype
const* pBagProto
= pBag
->GetProto();
8607 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8609 if( !ItemCanGoIntoBag(pProto
,pBagProto
) )
8610 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8613 // non empty stack with space
8614 need_space
= pProto
->GetMaxStackSize();
8616 // non empty slot, check item type
8620 if(pItem2
->GetEntry() != pProto
->ItemId
)
8621 return EQUIP_ERR_ITEM_CANT_STACK
;
8624 if(pItem2
->GetCount() >= pProto
->GetMaxStackSize())
8625 return EQUIP_ERR_ITEM_CANT_STACK
;
8627 // free stack space or infinity
8628 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
8631 if(need_space
> count
)
8634 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | slot
, need_space
);
8635 if(!newPosition
.isContainedIn(dest
))
8637 dest
.push_back(newPosition
);
8638 count
-= need_space
;
8640 return EQUIP_ERR_OK
;
8643 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
8645 // skip specific bag already processed in first called _CanStoreItem_InBag
8647 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8649 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
8651 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8653 ItemPrototype
const* pBagProto
= pBag
->GetProto();
8655 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8657 // specialized bag mode or non-specilized
8658 if( non_specialized
!= (pBagProto
->Class
== ITEM_CLASS_CONTAINER
&& pBagProto
->SubClass
== ITEM_SUBCLASS_CONTAINER
) )
8659 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8661 if( !ItemCanGoIntoBag(pProto
,pBagProto
) )
8662 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG
;
8664 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
8666 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8670 Item
* pItem2
= GetItemByPos( bag
, j
);
8672 // ignore move item (this slot will be empty at move)
8673 if(pItem2
==pSrcItem
)
8676 // if merge skip empty, if !merge skip non-empty
8677 if((pItem2
!=NULL
)!=merge
)
8682 if(pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->GetMaxStackSize())
8684 uint32 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
8685 if(need_space
> count
)
8688 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
8689 if(!newPosition
.isContainedIn(dest
))
8691 dest
.push_back(newPosition
);
8692 count
-= need_space
;
8695 return EQUIP_ERR_OK
;
8701 uint32 need_space
= pProto
->GetMaxStackSize();
8702 if(need_space
> count
)
8705 ItemPosCount newPosition
= ItemPosCount((bag
<< 8) | j
, need_space
);
8706 if(!newPosition
.isContainedIn(dest
))
8708 dest
.push_back(newPosition
);
8709 count
-= need_space
;
8712 return EQUIP_ERR_OK
;
8716 return EQUIP_ERR_OK
;
8719 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
8721 for(uint32 j
= slot_begin
; j
< slot_end
; j
++)
8723 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8724 if(INVENTORY_SLOT_BAG_0
==skip_bag
&& j
==skip_slot
)
8727 Item
* pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, j
);
8729 // ignore move item (this slot will be empty at move)
8730 if(pItem2
==pSrcItem
)
8733 // if merge skip empty, if !merge skip non-empty
8734 if((pItem2
!=NULL
)!=merge
)
8739 if(pItem2
->GetEntry() == pProto
->ItemId
&& pItem2
->GetCount() < pProto
->GetMaxStackSize())
8741 uint32 need_space
= pProto
->GetMaxStackSize() - pItem2
->GetCount();
8742 if(need_space
> count
)
8744 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
8745 if(!newPosition
.isContainedIn(dest
))
8747 dest
.push_back(newPosition
);
8748 count
-= need_space
;
8751 return EQUIP_ERR_OK
;
8757 uint32 need_space
= pProto
->GetMaxStackSize();
8758 if(need_space
> count
)
8761 ItemPosCount newPosition
= ItemPosCount((INVENTORY_SLOT_BAG_0
<< 8) | j
, need_space
);
8762 if(!newPosition
.isContainedIn(dest
))
8764 dest
.push_back(newPosition
);
8765 count
-= need_space
;
8768 return EQUIP_ERR_OK
;
8772 return EQUIP_ERR_OK
;
8775 uint8
Player::_CanStoreItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, uint32 entry
, uint32 count
, Item
*pItem
, bool swap
, uint32
* no_space_count
) const
8777 sLog
.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, entry
, count
);
8779 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(entry
);
8783 *no_space_count
= count
;
8784 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
:EQUIP_ERR_ITEM_NOT_FOUND
;
8787 if(pItem
&& pItem
->IsBindedNotWith(GetGUID()))
8790 *no_space_count
= count
;
8791 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
8794 // check count of items (skip for auto move for same player from bank)
8795 uint32 no_similar_count
= 0; // can't store this amount similar items
8796 uint8 res
= _CanTakeMoreSimilarItems(entry
,count
,pItem
,&no_similar_count
);
8797 if(res
!=EQUIP_ERR_OK
)
8799 if(count
==no_similar_count
)
8802 *no_space_count
= no_similar_count
;
8805 count
-= no_similar_count
;
8809 if( bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
8811 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
8812 if(res
!=EQUIP_ERR_OK
)
8815 *no_space_count
= count
+ no_similar_count
;
8821 if(no_similar_count
==0)
8822 return EQUIP_ERR_OK
;
8825 *no_space_count
= count
+ no_similar_count
;
8826 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8830 // not specific slot or have space for partly store only in specific slot
8833 if( bag
!= NULL_BAG
)
8835 // search stack in bag for merge to
8836 if( pProto
->Stackable
!= 1 )
8838 if( bag
== INVENTORY_SLOT_BAG_0
) // inventory
8840 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,QUESTBAG_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
8841 if(res
!=EQUIP_ERR_OK
)
8844 *no_space_count
= count
+ no_similar_count
;
8850 if(no_similar_count
==0)
8851 return EQUIP_ERR_OK
;
8854 *no_space_count
= count
+ no_similar_count
;
8855 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8858 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
8859 if(res
!=EQUIP_ERR_OK
)
8862 *no_space_count
= count
+ no_similar_count
;
8868 if(no_similar_count
==0)
8869 return EQUIP_ERR_OK
;
8872 *no_space_count
= count
+ no_similar_count
;
8873 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8876 else // equipped bag
8878 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
8879 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
8880 if(res
!=EQUIP_ERR_OK
)
8881 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
8883 if(res
!=EQUIP_ERR_OK
)
8886 *no_space_count
= count
+ no_similar_count
;
8892 if(no_similar_count
==0)
8893 return EQUIP_ERR_OK
;
8896 *no_space_count
= count
+ no_similar_count
;
8897 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8902 // search free slot in bag for place to
8903 if( bag
== INVENTORY_SLOT_BAG_0
) // inventory
8905 // search free slot - keyring case
8906 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
8908 uint32 keyringSize
= GetMaxKeyringSize();
8909 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
8910 if(res
!=EQUIP_ERR_OK
)
8913 *no_space_count
= count
+ no_similar_count
;
8919 if(no_similar_count
==0)
8920 return EQUIP_ERR_OK
;
8923 *no_space_count
= count
+ no_similar_count
;
8924 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8927 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
8928 if(res
!=EQUIP_ERR_OK
)
8931 *no_space_count
= count
+ no_similar_count
;
8937 if(no_similar_count
==0)
8938 return EQUIP_ERR_OK
;
8941 *no_space_count
= count
+ no_similar_count
;
8942 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8945 else if(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
8947 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
8948 if(res
!=EQUIP_ERR_OK
)
8951 *no_space_count
= count
+ no_similar_count
;
8957 if(no_similar_count
==0)
8958 return EQUIP_ERR_OK
;
8961 *no_space_count
= count
+ no_similar_count
;
8962 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8966 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
8967 if(res
!=EQUIP_ERR_OK
)
8970 *no_space_count
= count
+ no_similar_count
;
8976 if(no_similar_count
==0)
8977 return EQUIP_ERR_OK
;
8980 *no_space_count
= count
+ no_similar_count
;
8981 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
8984 else // equipped bag
8986 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
8987 if(res
!=EQUIP_ERR_OK
)
8988 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
8990 if(res
!=EQUIP_ERR_OK
)
8993 *no_space_count
= count
+ no_similar_count
;
8999 if(no_similar_count
==0)
9000 return EQUIP_ERR_OK
;
9003 *no_space_count
= count
+ no_similar_count
;
9004 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9009 // not specific bag or have space for partly store only in specific bag
9011 // search stack for merge to
9012 if( pProto
->Stackable
!= 1 )
9014 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,QUESTBAG_SLOT_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9015 if(res
!=EQUIP_ERR_OK
)
9018 *no_space_count
= count
+ no_similar_count
;
9024 if(no_similar_count
==0)
9025 return EQUIP_ERR_OK
;
9028 *no_space_count
= count
+ no_similar_count
;
9029 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9032 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9033 if(res
!=EQUIP_ERR_OK
)
9036 *no_space_count
= count
+ no_similar_count
;
9042 if(no_similar_count
==0)
9043 return EQUIP_ERR_OK
;
9046 *no_space_count
= count
+ no_similar_count
;
9047 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9050 if( pProto
->BagFamily
)
9052 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9054 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
9055 if(res
!=EQUIP_ERR_OK
)
9060 if(no_similar_count
==0)
9061 return EQUIP_ERR_OK
;
9064 *no_space_count
= count
+ no_similar_count
;
9065 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9070 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9072 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
9073 if(res
!=EQUIP_ERR_OK
)
9078 if(no_similar_count
==0)
9079 return EQUIP_ERR_OK
;
9082 *no_space_count
= count
+ no_similar_count
;
9083 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9088 // search free slot - special bag case
9089 if( pProto
->BagFamily
)
9091 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9093 uint32 keyringSize
= GetMaxKeyringSize();
9094 res
= _CanStoreItem_InInventorySlots(KEYRING_SLOT_START
,KEYRING_SLOT_START
+keyringSize
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9095 if(res
!=EQUIP_ERR_OK
)
9098 *no_space_count
= count
+ no_similar_count
;
9104 if(no_similar_count
==0)
9105 return EQUIP_ERR_OK
;
9108 *no_space_count
= count
+ no_similar_count
;
9109 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9112 else if(pProto
->BagFamily
& BAG_FAMILY_MASK_CURRENCY_TOKENS
)
9114 res
= _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START
,CURRENCYTOKEN_SLOT_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9115 if(res
!=EQUIP_ERR_OK
)
9118 *no_space_count
= count
+ no_similar_count
;
9124 if(no_similar_count
==0)
9125 return EQUIP_ERR_OK
;
9128 *no_space_count
= count
+ no_similar_count
;
9129 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9133 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9135 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
9136 if(res
!=EQUIP_ERR_OK
)
9141 if(no_similar_count
==0)
9142 return EQUIP_ERR_OK
;
9145 *no_space_count
= count
+ no_similar_count
;
9146 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9152 res
= _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START
,INVENTORY_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9153 if(res
!=EQUIP_ERR_OK
)
9156 *no_space_count
= count
+ no_similar_count
;
9162 if(no_similar_count
==0)
9163 return EQUIP_ERR_OK
;
9166 *no_space_count
= count
+ no_similar_count
;
9167 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9170 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9172 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
9173 if(res
!=EQUIP_ERR_OK
)
9178 if(no_similar_count
==0)
9179 return EQUIP_ERR_OK
;
9182 *no_space_count
= count
+ no_similar_count
;
9183 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
;
9188 *no_space_count
= count
+ no_similar_count
;
9190 return EQUIP_ERR_INVENTORY_FULL
;
9193 //////////////////////////////////////////////////////////////////////////
9194 uint8
Player::CanStoreItems( Item
**pItems
,int count
) const
9199 int inv_slot_items
[INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
];
9200 int inv_bags
[INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
][MAX_BAG_SIZE
];
9201 int inv_keys
[KEYRING_SLOT_END
-KEYRING_SLOT_START
];
9202 int inv_tokens
[CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
];
9204 memset(inv_slot_items
,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END
-INVENTORY_SLOT_ITEM_START
));
9205 memset(inv_bags
,0,sizeof(int)*(INVENTORY_SLOT_BAG_END
-INVENTORY_SLOT_BAG_START
)*MAX_BAG_SIZE
);
9206 memset(inv_keys
,0,sizeof(int)*(KEYRING_SLOT_END
-KEYRING_SLOT_START
));
9207 memset(inv_tokens
,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END
-CURRENCYTOKEN_SLOT_START
));
9209 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
9211 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9213 if (pItem2
&& !pItem2
->IsInTrade())
9215 inv_slot_items
[i
-INVENTORY_SLOT_ITEM_START
] = pItem2
->GetCount();
9219 for(int i
= KEYRING_SLOT_START
; i
< KEYRING_SLOT_END
; i
++)
9221 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9223 if (pItem2
&& !pItem2
->IsInTrade())
9225 inv_keys
[i
-KEYRING_SLOT_START
] = pItem2
->GetCount();
9229 for(int i
= CURRENCYTOKEN_SLOT_START
; i
< CURRENCYTOKEN_SLOT_END
; i
++)
9231 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
9233 if (pItem2
&& !pItem2
->IsInTrade())
9235 inv_tokens
[i
-CURRENCYTOKEN_SLOT_START
] = pItem2
->GetCount();
9239 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
9241 if(Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
9243 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9245 pItem2
= GetItemByPos( i
, j
);
9246 if (pItem2
&& !pItem2
->IsInTrade())
9248 inv_bags
[i
-INVENTORY_SLOT_BAG_START
][j
] = pItem2
->GetCount();
9254 // check free space for all items
9255 for (int k
=0;k
<count
;k
++)
9257 Item
*pItem
= pItems
[k
];
9260 if (!pItem
) continue;
9262 sLog
.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k
+1, pItem
->GetEntry(), pItem
->GetCount());
9263 ItemPrototype
const *pProto
= pItem
->GetProto();
9267 return EQUIP_ERR_ITEM_NOT_FOUND
;
9270 if(pItem
->IsBindedNotWith(GetGUID()))
9271 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9274 ItemPrototype
const *pBagProto
;
9276 // item is 'one item only'
9277 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9278 if(res
!= EQUIP_ERR_OK
)
9281 // search stack for merge to
9282 if( pProto
->Stackable
!= 1 )
9284 bool b_found
= false;
9286 for(int t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_END
; t
++)
9288 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9289 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_keys
[t
-KEYRING_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9291 inv_keys
[t
-KEYRING_SLOT_START
] += pItem
->GetCount();
9296 if (b_found
) continue;
9298 for(int t
= CURRENCYTOKEN_SLOT_START
; t
< CURRENCYTOKEN_SLOT_END
; t
++)
9300 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9301 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9303 inv_tokens
[t
-CURRENCYTOKEN_SLOT_START
] += pItem
->GetCount();
9308 if (b_found
) continue;
9310 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; t
++)
9312 pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9313 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9315 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] += pItem
->GetCount();
9320 if (b_found
) continue;
9322 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9324 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9327 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9329 pItem2
= GetItemByPos( t
, j
);
9330 if( pItem2
&& pItem2
->GetEntry() == pItem
->GetEntry() && inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] + pItem
->GetCount() <= pProto
->GetMaxStackSize())
9332 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] += pItem
->GetCount();
9339 if (b_found
) continue;
9343 if( pProto
->BagFamily
)
9345 bool b_found
= false;
9346 if(pProto
->BagFamily
& BAG_FAMILY_MASK_KEYS
)
9348 uint32 keyringSize
= GetMaxKeyringSize();
9349 for(uint32 t
= KEYRING_SLOT_START
; t
< KEYRING_SLOT_START
+keyringSize
; ++t
)
9351 if( inv_keys
[t
-KEYRING_SLOT_START
] == 0 )
9353 inv_keys
[t
-KEYRING_SLOT_START
] = 1;
9360 if (b_found
) continue;
9362 /* until proper implementation
9363 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9365 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9367 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9369 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9376 if (b_found) continue;
9379 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9381 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9384 pBagProto
= pBag
->GetProto();
9386 // not plain container check
9387 if( pBagProto
&& (pBagProto
->Class
!= ITEM_CLASS_CONTAINER
|| pBagProto
->SubClass
!= ITEM_SUBCLASS_CONTAINER
) &&
9388 ItemCanGoIntoBag(pProto
,pBagProto
) )
9390 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9392 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9394 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9402 if (b_found
) continue;
9406 bool b_found
= false;
9407 for(int t
= INVENTORY_SLOT_ITEM_START
; t
< INVENTORY_SLOT_ITEM_END
; t
++)
9409 if( inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] == 0 )
9411 inv_slot_items
[t
-INVENTORY_SLOT_ITEM_START
] = 1;
9416 if (b_found
) continue;
9418 // search free slot in bags
9419 for(int t
= INVENTORY_SLOT_BAG_START
; !b_found
&& t
< INVENTORY_SLOT_BAG_END
; t
++)
9421 pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, t
);
9424 pBagProto
= pBag
->GetProto();
9426 // special bag already checked
9427 if( pBagProto
&& (pBagProto
->Class
!= ITEM_CLASS_CONTAINER
|| pBagProto
->SubClass
!= ITEM_SUBCLASS_CONTAINER
))
9430 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
9432 if( inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] == 0 )
9434 inv_bags
[t
-INVENTORY_SLOT_BAG_START
][j
] = 1;
9442 // no free slot found?
9444 return EQUIP_ERR_INVENTORY_FULL
;
9447 return EQUIP_ERR_OK
;
9450 //////////////////////////////////////////////////////////////////////////
9451 uint8
Player::CanEquipNewItem( uint8 slot
, uint16
&dest
, uint32 item
, bool swap
) const
9454 Item
*pItem
= Item::CreateItem( item
, 1, this );
9457 uint8 result
= CanEquipItem(slot
, dest
, pItem
, swap
);
9462 return EQUIP_ERR_ITEM_NOT_FOUND
;
9465 uint8
Player::CanEquipItem( uint8 slot
, uint16
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
9470 sLog
.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot
, pItem
->GetEntry(), pItem
->GetCount());
9471 ItemPrototype
const *pProto
= pItem
->GetProto();
9474 if(pItem
->IsBindedNotWith(GetGUID()))
9475 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9477 // check count of items (skip for auto move for same player from bank)
9478 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9479 if(res
!= EQUIP_ERR_OK
)
9482 // check this only in game
9485 // May be here should be more stronger checks; STUNNED checked
9486 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9487 if (hasUnitState(UNIT_STAT_STUNNED
))
9488 return EQUIP_ERR_YOU_ARE_STUNNED
;
9490 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9492 // - in-progress arenas
9493 if( !pProto
->CanChangeEquipStateInCombat() )
9496 return EQUIP_ERR_NOT_IN_COMBAT
;
9498 if(BattleGround
* bg
= GetBattleGround())
9499 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
9500 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
9503 if(isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
!= 0)
9504 return EQUIP_ERR_CANT_DO_RIGHT_NOW
; // maybe exist better err
9506 if(IsNonMeleeSpellCasted(false))
9507 return EQUIP_ERR_CANT_DO_RIGHT_NOW
;
9510 uint8 eslot
= FindEquipSlot( pProto
, slot
, swap
);
9511 if( eslot
== NULL_SLOT
)
9512 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9514 uint8 msg
= CanUseItem( pItem
, not_loading
);
9515 if( msg
!= EQUIP_ERR_OK
)
9517 if( !swap
&& GetItemByPos( INVENTORY_SLOT_BAG_0
, eslot
) )
9518 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE
;
9520 // if swap ignore item (equipped also)
9521 if(uint8 res
= CanEquipUniqueItem(pItem
, swap
? eslot
: NULL_SLOT
))
9524 // check unique-equipped special item classes
9525 if (pProto
->Class
== ITEM_CLASS_QUIVER
)
9527 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; ++i
)
9529 if( Item
* pBag
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
) )
9531 if( ItemPrototype
const* pBagProto
= pBag
->GetProto() )
9533 if( pBagProto
->Class
==pProto
->Class
&& (!swap
|| pBag
->GetSlot() != eslot
) )
9535 if(pBagProto
->SubClass
== ITEM_SUBCLASS_AMMO_POUCH
)
9536 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH
;
9538 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER
;
9545 uint32 type
= pProto
->InventoryType
;
9547 if(eslot
== EQUIPMENT_SLOT_OFFHAND
)
9549 if (type
== INVTYPE_WEAPON
|| type
== INVTYPE_WEAPONOFFHAND
)
9552 return EQUIP_ERR_CANT_DUAL_WIELD
;
9554 else if (type
== INVTYPE_2HWEAPON
)
9556 if(!CanDualWield() || !CanTitanGrip())
9557 return EQUIP_ERR_CANT_DUAL_WIELD
;
9561 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED
;
9564 // equip two-hand weapon case (with possible unequip 2 items)
9565 if( type
== INVTYPE_2HWEAPON
)
9567 if (eslot
== EQUIPMENT_SLOT_OFFHAND
)
9569 if (!CanTitanGrip())
9570 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9572 else if (eslot
!= EQUIPMENT_SLOT_MAINHAND
)
9573 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
;
9575 if (!CanTitanGrip())
9577 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9578 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
9579 ItemPosCountVec off_dest
;
9580 if( offItem
&& (!not_loading
||
9581 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0
) << 8 | EQUIPMENT_SLOT_OFFHAND
,false) != EQUIP_ERR_OK
||
9582 CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false ) != EQUIP_ERR_OK
) )
9583 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_INVENTORY_FULL
;
9586 dest
= ((INVENTORY_SLOT_BAG_0
<< 8) | eslot
);
9587 return EQUIP_ERR_OK
;
9591 return EQUIP_ERR_ITEM_NOT_FOUND
;
9593 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
;
9596 uint8
Player::CanUnequipItem( uint16 pos
, bool swap
) const
9598 // Applied only to equipped items and bank bags
9599 if(!IsEquipmentPos(pos
) && !IsBagPos(pos
))
9600 return EQUIP_ERR_OK
;
9602 Item
* pItem
= GetItemByPos(pos
);
9604 // Applied only to existed equipped item
9606 return EQUIP_ERR_OK
;
9608 sLog
.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos
, pItem
->GetEntry(), pItem
->GetCount());
9610 ItemPrototype
const *pProto
= pItem
->GetProto();
9612 return EQUIP_ERR_ITEM_NOT_FOUND
;
9614 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9616 // - in-progress arenas
9617 if( !pProto
->CanChangeEquipStateInCombat() )
9620 return EQUIP_ERR_NOT_IN_COMBAT
;
9622 if(BattleGround
* bg
= GetBattleGround())
9623 if( bg
->isArena() && bg
->GetStatus() == STATUS_IN_PROGRESS
)
9624 return EQUIP_ERR_NOT_DURING_ARENA_MATCH
;
9627 if(!swap
&& pItem
->IsBag() && !((Bag
*)pItem
)->IsEmpty())
9628 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS
;
9630 return EQUIP_ERR_OK
;
9633 uint8
Player::CanBankItem( uint8 bag
, uint8 slot
, ItemPosCountVec
&dest
, Item
*pItem
, bool swap
, bool not_loading
) const
9636 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
9638 uint32 count
= pItem
->GetCount();
9640 sLog
.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), pItem
->GetCount());
9641 ItemPrototype
const *pProto
= pItem
->GetProto();
9643 return swap
? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
: EQUIP_ERR_ITEM_NOT_FOUND
;
9645 if( pItem
->IsBindedNotWith(GetGUID()) )
9646 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9648 // check count of items (skip for auto move for same player from bank)
9649 uint8 res
= CanTakeMoreSimilarItems(pItem
);
9650 if(res
!= EQUIP_ERR_OK
)
9654 if( bag
!= NULL_BAG
&& slot
!= NULL_SLOT
)
9656 if( slot
>= BANK_SLOT_BAG_START
&& slot
< BANK_SLOT_BAG_END
)
9658 if (!pItem
->IsBag())
9659 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
;
9661 Bag
*pBag
= (Bag
*)pItem
;
9662 if( !HasBankBagSlot( slot
) )
9663 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT
;
9665 if( uint8 cantuse
= CanUseItem( pItem
, not_loading
) != EQUIP_ERR_OK
)
9669 res
= _CanStoreItem_InSpecificSlot(bag
,slot
,dest
,pProto
,count
,swap
,pItem
);
9670 if(res
!=EQUIP_ERR_OK
)
9674 return EQUIP_ERR_OK
;
9677 // not specific slot or have space for partly store only in specific slot
9680 if( bag
!= NULL_BAG
)
9682 if( pProto
->InventoryType
== INVTYPE_BAG
)
9684 Bag
*pBag
= (Bag
*)pItem
;
9685 if( pBag
&& !pBag
->IsEmpty() )
9686 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
;
9689 // search stack in bag for merge to
9690 if( pProto
->Stackable
!= 1 )
9692 if( bag
== INVENTORY_SLOT_BAG_0
)
9694 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9695 if(res
!=EQUIP_ERR_OK
)
9699 return EQUIP_ERR_OK
;
9703 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,false,pItem
,NULL_BAG
,slot
);
9704 if(res
!=EQUIP_ERR_OK
)
9705 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,true,true,pItem
,NULL_BAG
,slot
);
9707 if(res
!=EQUIP_ERR_OK
)
9711 return EQUIP_ERR_OK
;
9715 // search free slot in bag
9716 if( bag
== INVENTORY_SLOT_BAG_0
)
9718 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9719 if(res
!=EQUIP_ERR_OK
)
9723 return EQUIP_ERR_OK
;
9727 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,false,pItem
,NULL_BAG
,slot
);
9728 if(res
!=EQUIP_ERR_OK
)
9729 res
= _CanStoreItem_InBag(bag
,dest
,pProto
,count
,false,true,pItem
,NULL_BAG
,slot
);
9731 if(res
!=EQUIP_ERR_OK
)
9735 return EQUIP_ERR_OK
;
9739 // not specific bag or have space for partly store only in specific bag
9741 // search stack for merge to
9742 if( pProto
->Stackable
!= 1 )
9745 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,true,pItem
,bag
,slot
);
9746 if(res
!=EQUIP_ERR_OK
)
9750 return EQUIP_ERR_OK
;
9753 if( pProto
->BagFamily
)
9755 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
9757 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,false,pItem
,bag
,slot
);
9758 if(res
!=EQUIP_ERR_OK
)
9762 return EQUIP_ERR_OK
;
9766 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
9768 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,true,true,pItem
,bag
,slot
);
9769 if(res
!=EQUIP_ERR_OK
)
9773 return EQUIP_ERR_OK
;
9777 // search free place in special bag
9778 if( pProto
->BagFamily
)
9780 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
9782 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,false,pItem
,bag
,slot
);
9783 if(res
!=EQUIP_ERR_OK
)
9787 return EQUIP_ERR_OK
;
9791 // search free space
9792 res
= _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START
,BANK_SLOT_ITEM_END
,dest
,pProto
,count
,false,pItem
,bag
,slot
);
9793 if(res
!=EQUIP_ERR_OK
)
9797 return EQUIP_ERR_OK
;
9799 for(int i
= BANK_SLOT_BAG_START
; i
< BANK_SLOT_BAG_END
; i
++)
9801 res
= _CanStoreItem_InBag(i
,dest
,pProto
,count
,false,true,pItem
,bag
,slot
);
9802 if(res
!=EQUIP_ERR_OK
)
9806 return EQUIP_ERR_OK
;
9808 return EQUIP_ERR_BANK_FULL
;
9811 uint8
Player::CanUseItem( Item
*pItem
, bool not_loading
) const
9815 sLog
.outDebug( "STORAGE: CanUseItem item = %u", pItem
->GetEntry());
9816 if( !isAlive() && not_loading
)
9817 return EQUIP_ERR_YOU_ARE_DEAD
;
9819 // return EQUIP_ERR_YOU_ARE_STUNNED;
9820 ItemPrototype
const *pProto
= pItem
->GetProto();
9823 if( pItem
->IsBindedNotWith(GetGUID()) )
9824 return EQUIP_ERR_DONT_OWN_THAT_ITEM
;
9825 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
9826 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
9827 if( pItem
->GetSkill() != 0 )
9829 if( GetSkillValue( pItem
->GetSkill() ) == 0 )
9830 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9832 if( pProto
->RequiredSkill
!= 0 )
9834 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
9835 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9836 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
9837 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
9839 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
9840 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9841 if( pProto
->RequiredReputationFaction
&& uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
9842 return EQUIP_ERR_CANT_EQUIP_REPUTATION
;
9843 if( getLevel() < pProto
->RequiredLevel
)
9844 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
9845 return EQUIP_ERR_OK
;
9848 return EQUIP_ERR_ITEM_NOT_FOUND
;
9851 bool Player::CanUseItem( ItemPrototype
const *pProto
)
9853 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
9857 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
9859 if( pProto
->RequiredSkill
!= 0 )
9861 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
9863 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
9866 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
9868 if( getLevel() < pProto
->RequiredLevel
)
9875 uint8
Player::CanUseAmmo( uint32 item
) const
9877 sLog
.outDebug( "STORAGE: CanUseAmmo item = %u", item
);
9879 return EQUIP_ERR_YOU_ARE_DEAD
;
9881 // return EQUIP_ERR_YOU_ARE_STUNNED;
9882 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
9885 if( pProto
->InventoryType
!= INVTYPE_AMMO
)
9886 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE
;
9887 if( (pProto
->AllowableClass
& getClassMask()) == 0 || (pProto
->AllowableRace
& getRaceMask()) == 0 )
9888 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM
;
9889 if( pProto
->RequiredSkill
!= 0 )
9891 if( GetSkillValue( pProto
->RequiredSkill
) == 0 )
9892 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9893 else if( GetSkillValue( pProto
->RequiredSkill
) < pProto
->RequiredSkillRank
)
9894 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL
;
9896 if( pProto
->RequiredSpell
!= 0 && !HasSpell( pProto
->RequiredSpell
) )
9897 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY
;
9898 /*if( GetReputationMgr().GetReputation() < pProto->RequiredReputation )
9899 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9901 if( getLevel() < pProto
->RequiredLevel
)
9902 return EQUIP_ERR_CANT_EQUIP_LEVEL_I
;
9905 if(GetDummyAura(46699))
9906 return EQUIP_ERR_BAG_FULL6
;
9908 return EQUIP_ERR_OK
;
9910 return EQUIP_ERR_ITEM_NOT_FOUND
;
9913 void Player::SetAmmo( uint32 item
)
9919 if( GetUInt32Value(PLAYER_AMMO_ID
) == item
)
9925 uint8 msg
= CanUseAmmo( item
);
9926 if( msg
!= EQUIP_ERR_OK
)
9928 SendEquipError( msg
, NULL
, NULL
);
9933 SetUInt32Value(PLAYER_AMMO_ID
, item
);
9935 _ApplyAmmoBonuses();
9938 void Player::RemoveAmmo()
9940 SetUInt32Value(PLAYER_AMMO_ID
, 0);
9944 if(CanModifyStats())
9945 UpdateDamagePhysical(RANGED_ATTACK
);
9948 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
9949 Item
* Player::StoreNewItem( ItemPosCountVec
const& dest
, uint32 item
, bool update
,int32 randomPropertyId
)
9952 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); ++itr
)
9953 count
+= itr
->count
;
9955 Item
*pItem
= Item::CreateItem( item
, count
, this );
9958 ItemAddedQuestCheck( item
, count
);
9959 if(randomPropertyId
)
9960 pItem
->SetItemRandomProperties(randomPropertyId
);
9961 pItem
= StoreItem( dest
, pItem
, update
);
9966 Item
* Player::StoreItem( ItemPosCountVec
const& dest
, Item
* pItem
, bool update
)
9971 Item
* lastItem
= pItem
;
9973 for(ItemPosCountVec::const_iterator itr
= dest
.begin(); itr
!= dest
.end(); )
9975 uint16 pos
= itr
->pos
;
9976 uint32 count
= itr
->count
;
9980 if(itr
== dest
.end())
9982 lastItem
= _StoreItem(pos
,pItem
,count
,false,update
);
9986 lastItem
= _StoreItem(pos
,pItem
,count
,true,update
);
9992 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
9993 Item
* Player::_StoreItem( uint16 pos
, Item
*pItem
, uint32 count
, bool clone
, bool update
)
9998 uint8 bag
= pos
>> 8;
9999 uint8 slot
= pos
& 255;
10001 sLog
.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag
, slot
, pItem
->GetEntry(), count
);
10003 Item
*pItem2
= GetItemByPos( bag
, slot
);
10008 pItem
= pItem
->CloneItem(count
,this);
10010 pItem
->SetCount(count
);
10015 if( pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10016 pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10017 pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
) )
10018 pItem
->SetBinding( true );
10020 if( bag
== INVENTORY_SLOT_BAG_0
)
10022 m_items
[slot
] = pItem
;
10023 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), pItem
->GetGUID() );
10024 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10025 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10027 pItem
->SetSlot( slot
);
10028 pItem
->SetContainer( NULL
);
10030 // need update known currency
10031 if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)
10032 UpdateKnownCurrencies(pItem
->GetEntry(),true);
10034 if( IsInWorld() && update
)
10036 pItem
->AddToWorld();
10037 pItem
->SendUpdateToPlayer( this );
10040 pItem
->SetState(ITEM_CHANGED
, this);
10044 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
10047 pBag
->StoreItem( slot
, pItem
, update
);
10048 if( IsInWorld() && update
)
10050 pItem
->AddToWorld();
10051 pItem
->SendUpdateToPlayer( this );
10053 pItem
->SetState(ITEM_CHANGED
, this);
10054 pBag
->SetState(ITEM_CHANGED
, this);
10058 AddEnchantmentDurations(pItem
);
10059 AddItemDurations(pItem
);
10065 if( pItem2
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
||
10066 pItem2
->GetProto()->Bonding
== BIND_QUEST_ITEM
||
10067 pItem2
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
&& IsBagPos(pos
) )
10068 pItem2
->SetBinding( true );
10070 pItem2
->SetCount( pItem2
->GetCount() + count
);
10071 if( IsInWorld() && update
)
10072 pItem2
->SendUpdateToPlayer( this );
10076 // delete item (it not in any slot currently)
10077 if( IsInWorld() && update
)
10079 pItem
->RemoveFromWorld();
10080 pItem
->DestroyForPlayer( this );
10083 RemoveEnchantmentDurations(pItem
);
10084 RemoveItemDurations(pItem
);
10086 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10087 pItem
->SetState(ITEM_REMOVED
, this);
10089 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10090 AddEnchantmentDurations(pItem2
);
10092 pItem2
->SetState(ITEM_CHANGED
, this);
10098 Item
* Player::EquipNewItem( uint16 pos
, uint32 item
, bool update
)
10100 Item
*pItem
= Item::CreateItem( item
, 1, this );
10103 ItemAddedQuestCheck( item
, 1 );
10104 Item
* retItem
= EquipItem( pos
, pItem
, update
);
10111 Item
* Player::EquipItem( uint16 pos
, Item
*pItem
, bool update
)
10115 AddEnchantmentDurations(pItem
);
10116 AddItemDurations(pItem
);
10118 uint8 bag
= pos
>> 8;
10119 uint8 slot
= pos
& 255;
10121 Item
*pItem2
= GetItemByPos( bag
, slot
);
10125 VisualizeItem( slot
, pItem
);
10129 ItemPrototype
const *pProto
= pItem
->GetProto();
10131 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10132 if(pProto
&& pProto
->ItemSet
)
10133 AddItemsSetItem(this,pItem
);
10135 _ApplyItemMods(pItem
, slot
, true);
10137 if(pProto
&& isInCombat()&& pProto
->Class
== ITEM_CLASS_WEAPON
&& m_weaponChangeTimer
== 0)
10139 uint32 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s
;
10141 if (getClass() == CLASS_ROGUE
)
10142 cooldownSpell
= SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s
;
10144 SpellEntry
const* spellProto
= sSpellStore
.LookupEntry(cooldownSpell
);
10147 sLog
.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell
);
10150 m_weaponChangeTimer
= spellProto
->StartRecoveryTime
;
10152 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+4);
10153 data
<< uint64(GetGUID());
10155 data
<< uint32(cooldownSpell
);
10157 GetSession()->SendPacket(&data
);
10162 if( IsInWorld() && update
)
10164 pItem
->AddToWorld();
10165 pItem
->SendUpdateToPlayer( this );
10168 ApplyEquipCooldown(pItem
);
10170 if( slot
== EQUIPMENT_SLOT_MAINHAND
)
10171 UpdateExpertise(BASE_ATTACK
);
10172 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10173 UpdateExpertise(OFF_ATTACK
);
10177 pItem2
->SetCount( pItem2
->GetCount() + pItem
->GetCount() );
10178 if( IsInWorld() && update
)
10179 pItem2
->SendUpdateToPlayer( this );
10181 // delete item (it not in any slot currently)
10182 //pItem->DeleteFromDB();
10183 if( IsInWorld() && update
)
10185 pItem
->RemoveFromWorld();
10186 pItem
->DestroyForPlayer( this );
10189 RemoveEnchantmentDurations(pItem
);
10190 RemoveItemDurations(pItem
);
10192 pItem
->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10193 pItem
->SetState(ITEM_REMOVED
, this);
10194 pItem2
->SetState(ITEM_CHANGED
, this);
10196 ApplyEquipCooldown(pItem2
);
10202 // only for full equip instead adding to stack
10203 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM
, pItem
->GetEntry());
10207 void Player::QuickEquipItem( uint16 pos
, Item
*pItem
)
10211 AddEnchantmentDurations(pItem
);
10212 AddItemDurations(pItem
);
10214 uint8 slot
= pos
& 255;
10215 VisualizeItem( slot
, pItem
);
10219 pItem
->AddToWorld();
10220 pItem
->SendUpdateToPlayer( this );
10225 void Player::SetVisibleItemSlot(uint8 slot
, Item
*pItem
)
10227 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10228 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10229 // entry // Size: 1
10230 // inspected enchantments // Size: 6
10232 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10233 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10238 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), pItem
->GetUInt64Value(ITEM_FIELD_CREATOR
));
10240 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
10241 SetUInt32Value(VisibleBase
+ 0, pItem
->GetEntry());
10243 for(int i
= 0; i
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++i
)
10244 SetUInt32Value(VisibleBase
+ 1 + i
, pItem
->GetEnchantmentId(EnchantmentSlot(i
)));
10246 // Use SetInt16Value to prevent set high part to FFFF for negative value
10247 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0, pItem
->GetItemRandomPropertyId());
10248 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), pItem
->GetItemSuffixFactor());
10252 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10254 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (slot
* MAX_VISIBLE_ITEM_OFFSET
);
10255 SetUInt32Value(VisibleBase
+ 0, 0);
10257 for(int i
= 0; i
< MAX_INSPECTED_ENCHANTMENT_SLOT
; ++i
)
10258 SetUInt32Value(VisibleBase
+ 1 + i
, 0);
10260 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 0 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10261 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES
+ 1 + (slot
* MAX_VISIBLE_ITEM_OFFSET
), 0);
10265 void Player::VisualizeItem( uint8 slot
, Item
*pItem
)
10270 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10271 if( pItem
->GetProto()->Bonding
== BIND_WHEN_EQUIPED
|| pItem
->GetProto()->Bonding
== BIND_WHEN_PICKED_UP
|| pItem
->GetProto()->Bonding
== BIND_QUEST_ITEM
)
10272 pItem
->SetBinding( true );
10274 sLog
.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot
, pItem
->GetEntry());
10276 m_items
[slot
] = pItem
;
10277 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), pItem
->GetGUID() );
10278 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, GetGUID() );
10279 pItem
->SetUInt64Value( ITEM_FIELD_OWNER
, GetGUID() );
10280 pItem
->SetSlot( slot
);
10281 pItem
->SetContainer( NULL
);
10283 if( slot
< EQUIPMENT_SLOT_END
)
10284 SetVisibleItemSlot(slot
,pItem
);
10286 pItem
->SetState(ITEM_CHANGED
, this);
10289 void Player::RemoveItem( uint8 bag
, uint8 slot
, bool update
)
10291 // note: removeitem does not actually change the item
10292 // it only takes the item out of storage temporarily
10293 // note2: if removeitem is to be used for delinking
10294 // the item must be removed from the player's updatequeue
10296 Item
*pItem
= GetItemByPos( bag
, slot
);
10299 sLog
.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10301 RemoveEnchantmentDurations(pItem
);
10302 RemoveItemDurations(pItem
);
10304 if( bag
== INVENTORY_SLOT_BAG_0
)
10306 if ( slot
< INVENTORY_SLOT_BAG_END
)
10308 ItemPrototype
const *pProto
= pItem
->GetProto();
10309 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10311 if(pProto
&& pProto
->ItemSet
)
10312 RemoveItemsSetItem(this,pProto
);
10314 _ApplyItemMods(pItem
, slot
, false);
10316 // remove item dependent auras and casts (only weapon and armor slots)
10317 if(slot
< EQUIPMENT_SLOT_END
)
10319 RemoveItemDependentAurasAndCasts(pItem
);
10321 // remove held enchantments, update expertise
10322 if ( slot
== EQUIPMENT_SLOT_MAINHAND
)
10324 if (pItem
->GetItemSuffixFactor())
10326 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3
);
10327 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4
);
10331 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0
);
10332 pItem
->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1
);
10335 UpdateExpertise(BASE_ATTACK
);
10337 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10338 UpdateExpertise(OFF_ATTACK
);
10341 // need update known currency
10342 else if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)
10343 UpdateKnownCurrencies(pItem
->GetEntry(),false);
10345 m_items
[slot
] = NULL
;
10346 SetUInt64Value((uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
*2)), 0);
10348 if ( slot
< EQUIPMENT_SLOT_END
)
10349 SetVisibleItemSlot(slot
,NULL
);
10353 Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
);
10355 pBag
->RemoveItem(slot
, update
);
10357 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10358 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10359 pItem
->SetSlot( NULL_SLOT
);
10360 if( IsInWorld() && update
)
10361 pItem
->SendUpdateToPlayer( this );
10365 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10366 void Player::MoveItemFromInventory(uint8 bag
, uint8 slot
, bool update
)
10368 if(Item
* it
= GetItemByPos(bag
,slot
))
10370 ItemRemovedQuestCheck(it
->GetEntry(),it
->GetCount());
10371 RemoveItem( bag
,slot
,update
);
10372 it
->RemoveFromUpdateQueueOf(this);
10373 if(it
->IsInWorld())
10375 it
->RemoveFromWorld();
10376 it
->DestroyForPlayer( this );
10381 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10382 void Player::MoveItemToInventory(ItemPosCountVec
const& dest
, Item
* pItem
, bool update
, bool in_characterInventoryDB
)
10384 // update quest counters
10385 ItemAddedQuestCheck(pItem
->GetEntry(),pItem
->GetCount());
10388 Item
* pLastItem
= StoreItem( dest
, pItem
, update
);
10390 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10391 if(pLastItem
==pItem
)
10393 // update owner for last item (this can be original item with wrong owner
10394 if(pLastItem
->GetOwnerGUID() != GetGUID())
10395 pLastItem
->SetOwnerGUID(GetGUID());
10397 // if this original item then it need create record in inventory
10398 // in case trade we already have item in other player inventory
10399 pLastItem
->SetState(in_characterInventoryDB
? ITEM_CHANGED
: ITEM_NEW
, this);
10403 void Player::DestroyItem( uint8 bag
, uint8 slot
, bool update
)
10405 Item
*pItem
= GetItemByPos( bag
, slot
);
10408 sLog
.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag
, slot
, pItem
->GetEntry());
10410 // start from destroy contained items (only equipped bag can have its)
10411 if (pItem
->IsBag() && pItem
->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10413 for (int i
= 0; i
< MAX_BAG_SIZE
; i
++)
10414 DestroyItem(slot
,i
,update
);
10417 if(pItem
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_WRAPPED
))
10418 CharacterDatabase
.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem
->GetGUIDLow());
10420 RemoveEnchantmentDurations(pItem
);
10421 RemoveItemDurations(pItem
);
10423 ItemRemovedQuestCheck( pItem
->GetEntry(), pItem
->GetCount() );
10425 if( bag
== INVENTORY_SLOT_BAG_0
)
10427 SetUInt64Value((uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
*2)), 0);
10429 // equipment and equipped bags can have applied bonuses
10430 if ( slot
< INVENTORY_SLOT_BAG_END
)
10432 ItemPrototype
const *pProto
= pItem
->GetProto();
10434 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10435 if(pProto
&& pProto
->ItemSet
)
10436 RemoveItemsSetItem(this,pProto
);
10438 _ApplyItemMods(pItem
, slot
, false);
10441 if ( slot
< EQUIPMENT_SLOT_END
)
10443 // remove item dependent auras and casts (only weapon and armor slots)
10444 RemoveItemDependentAurasAndCasts(pItem
);
10446 // update expertise
10447 if ( slot
== EQUIPMENT_SLOT_MAINHAND
)
10448 UpdateExpertise(BASE_ATTACK
);
10449 else if( slot
== EQUIPMENT_SLOT_OFFHAND
)
10450 UpdateExpertise(OFF_ATTACK
);
10452 // equipment visual show
10453 SetVisibleItemSlot(slot
,NULL
);
10455 // need update known currency
10456 else if (slot
>= CURRENCYTOKEN_SLOT_START
&& slot
< CURRENCYTOKEN_SLOT_END
)
10457 UpdateKnownCurrencies(pItem
->GetEntry(),false);
10459 m_items
[slot
] = NULL
;
10461 else if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, bag
))
10462 pBag
->RemoveItem(slot
, update
);
10464 if( IsInWorld() && update
)
10466 pItem
->RemoveFromWorld();
10467 pItem
->DestroyForPlayer(this);
10470 //pItem->SetOwnerGUID(0);
10471 pItem
->SetUInt64Value( ITEM_FIELD_CONTAINED
, 0 );
10472 pItem
->SetSlot( NULL_SLOT
);
10473 pItem
->SetState(ITEM_REMOVED
, this);
10477 void Player::DestroyItemCount( uint32 item
, uint32 count
, bool update
, bool unequip_check
)
10479 sLog
.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item
, count
);
10480 uint32 remcount
= 0;
10483 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
10485 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10487 if (pItem
->GetEntry() == item
)
10489 if (pItem
->GetCount() + remcount
<= count
)
10491 // all items in inventory can unequipped
10492 remcount
+= pItem
->GetCount();
10493 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10495 if (remcount
>=count
)
10500 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10501 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10502 if (IsInWorld() & update
)
10503 pItem
->SendUpdateToPlayer( this );
10504 pItem
->SetState(ITEM_CHANGED
, this);
10511 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
10513 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10515 if (pItem
->GetEntry() == item
)
10517 if (pItem
->GetCount() + remcount
<= count
)
10519 // all keys can be unequipped
10520 remcount
+= pItem
->GetCount();
10521 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10523 if (remcount
>=count
)
10528 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10529 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10530 if (IsInWorld() & update
)
10531 pItem
->SendUpdateToPlayer( this );
10532 pItem
->SetState(ITEM_CHANGED
, this);
10539 // in inventory bags
10540 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10542 if(Bag
*pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10544 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
10546 if(Item
* pItem
= pBag
->GetItemByPos(j
))
10548 if (pItem
->GetEntry() == item
)
10550 // all items in bags can be unequipped
10551 if (pItem
->GetCount() + remcount
<= count
)
10553 remcount
+= pItem
->GetCount();
10554 DestroyItem( i
, j
, update
);
10556 if (remcount
>=count
)
10561 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10562 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10563 if (IsInWorld() && update
)
10564 pItem
->SendUpdateToPlayer( this );
10565 pItem
->SetState(ITEM_CHANGED
, this);
10574 // in equipment and bag list
10575 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10577 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10579 if (pItem
&& pItem
->GetEntry() == item
)
10581 if (pItem
->GetCount() + remcount
<= count
)
10583 if (!unequip_check
|| CanUnequipItem(INVENTORY_SLOT_BAG_0
<< 8 | i
,false) == EQUIP_ERR_OK
)
10585 remcount
+= pItem
->GetCount();
10586 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10588 if (remcount
>=count
)
10594 ItemRemovedQuestCheck( pItem
->GetEntry(), count
- remcount
);
10595 pItem
->SetCount( pItem
->GetCount() - count
+ remcount
);
10596 if (IsInWorld() & update
)
10597 pItem
->SendUpdateToPlayer( this );
10598 pItem
->SetState(ITEM_CHANGED
, this);
10606 void Player::DestroyZoneLimitedItem( bool update
, uint32 new_zone
)
10608 sLog
.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone
);
10611 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
10612 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10613 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
))
10614 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10616 for(int i
= KEYRING_SLOT_START
; i
< QUESTBAG_SLOT_END
; i
++)
10617 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10618 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
))
10619 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10621 // in inventory bags
10622 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10623 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10624 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
10625 if (Item
* pItem
= pBag
->GetItemByPos(j
))
10626 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
))
10627 DestroyItem( i
, j
, update
);
10629 // in equipment and bag list
10630 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10631 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10632 if (pItem
->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone
))
10633 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10636 void Player::DestroyConjuredItems( bool update
)
10638 // used when entering arena
10639 // destroys all conjured items
10640 sLog
.outDebug( "STORAGE: DestroyConjuredItems" );
10643 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
10644 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10645 if (pItem
->IsConjuredConsumable())
10646 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10648 // in inventory bags
10649 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10650 if (Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10651 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
10652 if (Item
* pItem
= pBag
->GetItemByPos(j
))
10653 if (pItem
->IsConjuredConsumable())
10654 DestroyItem( i
, j
, update
);
10656 // in equipment and bag list
10657 for(int i
= EQUIPMENT_SLOT_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
10658 if (Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
10659 if (pItem
->IsConjuredConsumable())
10660 DestroyItem( INVENTORY_SLOT_BAG_0
, i
, update
);
10663 void Player::DestroyItemCount( Item
* pItem
, uint32
&count
, bool update
)
10668 sLog
.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem
->GetGUIDLow(),pItem
->GetEntry(), count
);
10670 if( pItem
->GetCount() <= count
)
10672 count
-= pItem
->GetCount();
10674 DestroyItem( pItem
->GetBagSlot(),pItem
->GetSlot(), update
);
10678 ItemRemovedQuestCheck( pItem
->GetEntry(), count
);
10679 pItem
->SetCount( pItem
->GetCount() - count
);
10681 if( IsInWorld() & update
)
10682 pItem
->SendUpdateToPlayer( this );
10683 pItem
->SetState(ITEM_CHANGED
, this);
10687 void Player::SplitItem( uint16 src
, uint16 dst
, uint32 count
)
10689 uint8 srcbag
= src
>> 8;
10690 uint8 srcslot
= src
& 255;
10692 uint8 dstbag
= dst
>> 8;
10693 uint8 dstslot
= dst
& 255;
10695 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
10698 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
10702 // not let split all items (can be only at cheating)
10703 if(pSrcItem
->GetCount() == count
)
10705 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
10709 // not let split more existed items (can be only at cheating)
10710 if(pSrcItem
->GetCount() < count
)
10712 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT
, pSrcItem
, NULL
);
10716 if(pSrcItem
->m_lootGenerated
) // prevent split looting item (item
10718 //best error message found for attempting to split while looting
10719 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS
, pSrcItem
, NULL
);
10723 sLog
.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag
, dstslot
, pSrcItem
->GetEntry(), count
);
10724 Item
*pNewItem
= pSrcItem
->CloneItem( count
, this );
10727 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, pSrcItem
, NULL
);
10731 if( IsInventoryPos( dst
) )
10733 // change item amount before check (for unique max count check)
10734 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
10736 ItemPosCountVec dest
;
10737 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pNewItem
, false );
10738 if( msg
!= EQUIP_ERR_OK
)
10741 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
10742 SendEquipError( msg
, pSrcItem
, NULL
);
10747 pSrcItem
->SendUpdateToPlayer( this );
10748 pSrcItem
->SetState(ITEM_CHANGED
, this);
10749 StoreItem( dest
, pNewItem
, true);
10751 else if( IsBankPos ( dst
) )
10753 // change item amount before check (for unique max count check)
10754 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
10756 ItemPosCountVec dest
;
10757 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pNewItem
, false );
10758 if( msg
!= EQUIP_ERR_OK
)
10761 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
10762 SendEquipError( msg
, pSrcItem
, NULL
);
10767 pSrcItem
->SendUpdateToPlayer( this );
10768 pSrcItem
->SetState(ITEM_CHANGED
, this);
10769 BankItem( dest
, pNewItem
, true);
10771 else if( IsEquipmentPos ( dst
) )
10773 // change item amount before check (for unique max count check), provide space for splitted items
10774 pSrcItem
->SetCount( pSrcItem
->GetCount() - count
);
10777 uint8 msg
= CanEquipItem( dstslot
, dest
, pNewItem
, false );
10778 if( msg
!= EQUIP_ERR_OK
)
10781 pSrcItem
->SetCount( pSrcItem
->GetCount() + count
);
10782 SendEquipError( msg
, pSrcItem
, NULL
);
10787 pSrcItem
->SendUpdateToPlayer( this );
10788 pSrcItem
->SetState(ITEM_CHANGED
, this);
10789 EquipItem( dest
, pNewItem
, true);
10790 AutoUnequipOffhandIfNeed();
10794 void Player::SwapItem( uint16 src
, uint16 dst
)
10796 uint8 srcbag
= src
>> 8;
10797 uint8 srcslot
= src
& 255;
10799 uint8 dstbag
= dst
>> 8;
10800 uint8 dstslot
= dst
& 255;
10802 Item
*pSrcItem
= GetItemByPos( srcbag
, srcslot
);
10803 Item
*pDstItem
= GetItemByPos( dstbag
, dstslot
);
10808 sLog
.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag
, dstslot
, pSrcItem
->GetEntry());
10812 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD
, pSrcItem
, pDstItem
);
10818 if(pSrcItem
->m_lootGenerated
) // prevent swap looting item
10820 //best error message found for attempting to swap while looting
10821 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pSrcItem
, NULL
);
10825 // check unequip potability for equipped items and bank bags
10826 if(IsEquipmentPos ( src
) || IsBagPos ( src
))
10828 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10829 uint8 msg
= CanUnequipItem( src
, !IsBagPos ( src
) || IsBagPos ( dst
) || pDstItem
&& pDstItem
->IsBag() && ((Bag
*)pDstItem
)->IsEmpty());
10830 if(msg
!= EQUIP_ERR_OK
)
10832 SendEquipError( msg
, pSrcItem
, pDstItem
);
10837 // prevent put equipped/bank bag in self
10838 if( IsBagPos ( src
) && srcslot
== dstbag
)
10840 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
10848 if(pDstItem
->m_lootGenerated
) // prevent swap looting item
10850 //best error message found for attempting to swap while looting
10851 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW
, pDstItem
, NULL
);
10855 // check unequip potability for equipped items and bank bags
10856 if(IsEquipmentPos ( dst
) || IsBagPos ( dst
))
10858 // bags can be swapped with empty bag slots, or with empty bag (items move possibility checked later)
10859 uint8 msg
= CanUnequipItem( dst
, !IsBagPos ( dst
) || IsBagPos ( src
) || pSrcItem
->IsBag() && ((Bag
*)pSrcItem
)->IsEmpty());
10860 if(msg
!= EQUIP_ERR_OK
)
10862 SendEquipError( msg
, pSrcItem
, pDstItem
);
10868 // NOW this is or item move (swap with empty), or swap with another item (including bags in bag possitions)
10869 // or swap empty bag with another empty or not empty bag (with items exchange)
10874 if( IsInventoryPos( dst
) )
10876 ItemPosCountVec dest
;
10877 uint8 msg
= CanStoreItem( dstbag
, dstslot
, dest
, pSrcItem
, false );
10878 if( msg
!= EQUIP_ERR_OK
)
10880 SendEquipError( msg
, pSrcItem
, NULL
);
10884 RemoveItem(srcbag
, srcslot
, true);
10885 StoreItem( dest
, pSrcItem
, true);
10887 else if( IsBankPos ( dst
) )
10889 ItemPosCountVec dest
;
10890 uint8 msg
= CanBankItem( dstbag
, dstslot
, dest
, pSrcItem
, false);
10891 if( msg
!= EQUIP_ERR_OK
)
10893 SendEquipError( msg
, pSrcItem
, NULL
);
10897 RemoveItem(srcbag
, srcslot
, true);
10898 BankItem( dest
, pSrcItem
, true);
10900 else if( IsEquipmentPos ( dst
) )
10903 uint8 msg
= CanEquipItem( dstslot
, dest
, pSrcItem
, false );
10904 if( msg
!= EQUIP_ERR_OK
)
10906 SendEquipError( msg
, pSrcItem
, NULL
);
10910 RemoveItem(srcbag
, srcslot
, true);
10911 EquipItem( dest
, pSrcItem
, true);
10912 AutoUnequipOffhandIfNeed();
10918 // attempt merge to / fill target item
10919 if(!pSrcItem
->IsBag() && !pDstItem
->IsBag())
10922 ItemPosCountVec sDest
;
10924 if( IsInventoryPos( dst
) )
10925 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
10926 else if( IsBankPos ( dst
) )
10927 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, false );
10928 else if( IsEquipmentPos ( dst
) )
10929 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, false );
10933 // can be merge/fill
10934 if(msg
== EQUIP_ERR_OK
)
10936 if( pSrcItem
->GetCount() + pDstItem
->GetCount() <= pSrcItem
->GetProto()->GetMaxStackSize())
10938 RemoveItem(srcbag
, srcslot
, true);
10940 if( IsInventoryPos( dst
) )
10941 StoreItem( sDest
, pSrcItem
, true);
10942 else if( IsBankPos ( dst
) )
10943 BankItem( sDest
, pSrcItem
, true);
10944 else if( IsEquipmentPos ( dst
) )
10946 EquipItem( eDest
, pSrcItem
, true);
10947 AutoUnequipOffhandIfNeed();
10952 pSrcItem
->SetCount( pSrcItem
->GetCount() + pDstItem
->GetCount() - pSrcItem
->GetProto()->GetMaxStackSize());
10953 pDstItem
->SetCount( pSrcItem
->GetProto()->GetMaxStackSize());
10954 pSrcItem
->SetState(ITEM_CHANGED
, this);
10955 pDstItem
->SetState(ITEM_CHANGED
, this);
10958 pSrcItem
->SendUpdateToPlayer( this );
10959 pDstItem
->SendUpdateToPlayer( this );
10966 // impossible merge/fill, do real swap
10969 // check src->dest move possibility
10970 ItemPosCountVec sDest
;
10972 if( IsInventoryPos( dst
) )
10973 msg
= CanStoreItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
10974 else if( IsBankPos( dst
) )
10975 msg
= CanBankItem( dstbag
, dstslot
, sDest
, pSrcItem
, true );
10976 else if( IsEquipmentPos( dst
) )
10978 msg
= CanEquipItem( dstslot
, eDest
, pSrcItem
, true );
10979 if( msg
== EQUIP_ERR_OK
)
10980 msg
= CanUnequipItem( eDest
, true );
10983 if( msg
!= EQUIP_ERR_OK
)
10985 SendEquipError( msg
, pSrcItem
, pDstItem
);
10989 // check dest->src move possibility
10990 ItemPosCountVec sDest2
;
10992 if( IsInventoryPos( src
) )
10993 msg
= CanStoreItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
10994 else if( IsBankPos( src
) )
10995 msg
= CanBankItem( srcbag
, srcslot
, sDest2
, pDstItem
, true );
10996 else if( IsEquipmentPos( src
) )
10998 msg
= CanEquipItem( srcslot
, eDest2
, pDstItem
, true);
10999 if( msg
== EQUIP_ERR_OK
)
11000 msg
= CanUnequipItem( eDest2
, true);
11003 if( msg
!= EQUIP_ERR_OK
)
11005 SendEquipError( msg
, pDstItem
, pSrcItem
);
11009 // Check bag swap with item exchange (one from empty in not bag possition (equipped (not possible in fact) or store)
11010 if(pSrcItem
->IsBag() && pDstItem
->IsBag())
11012 Bag
* emptyBag
= NULL
;
11013 Bag
* fullBag
= NULL
;
11014 if(((Bag
*)pSrcItem
)->IsEmpty() && !IsBagPos(src
))
11016 emptyBag
= (Bag
*)pSrcItem
;
11017 fullBag
= (Bag
*)pDstItem
;
11019 else if(((Bag
*)pDstItem
)->IsEmpty() && !IsBagPos(dst
))
11021 emptyBag
= (Bag
*)pDstItem
;
11022 fullBag
= (Bag
*)pSrcItem
;
11025 // bag swap (with items exchange) case
11026 if(emptyBag
&& fullBag
)
11028 ItemPrototype
const* emotyProto
= emptyBag
->GetProto();
11032 for(int i
=0; i
< fullBag
->GetBagSize(); ++i
)
11034 Item
*bagItem
= fullBag
->GetItemByPos(i
);
11038 ItemPrototype
const* bagItemProto
= bagItem
->GetProto();
11039 if (!bagItemProto
|| !ItemCanGoIntoBag(bagItemProto
, emotyProto
))
11041 // one from items not go to empry target bag
11042 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG
, pSrcItem
, pDstItem
);
11050 if (count
> emptyBag
->GetBagSize())
11052 // too small targeted bag
11053 SendEquipError( EQUIP_ERR_ITEMS_CANT_BE_SWAPPED
, pSrcItem
, pDstItem
);
11058 count
= 0; // will pos in new bag
11059 for(int i
=0; i
< fullBag
->GetBagSize(); ++i
)
11061 Item
*bagItem
= fullBag
->GetItemByPos(i
);
11065 fullBag
->RemoveItem(i
, true);
11066 emptyBag
->StoreItem(count
, bagItem
, true);
11067 bagItem
->SetState(ITEM_CHANGED
, this);
11074 // now do moves, remove...
11075 RemoveItem(dstbag
, dstslot
, false);
11076 RemoveItem(srcbag
, srcslot
, false);
11079 if( IsInventoryPos( dst
) )
11080 StoreItem(sDest
, pSrcItem
, true);
11081 else if( IsBankPos( dst
) )
11082 BankItem(sDest
, pSrcItem
, true);
11083 else if( IsEquipmentPos( dst
) )
11084 EquipItem(eDest
, pSrcItem
, true);
11087 if( IsInventoryPos( src
) )
11088 StoreItem(sDest2
, pDstItem
, true);
11089 else if( IsBankPos( src
) )
11090 BankItem(sDest2
, pDstItem
, true);
11091 else if( IsEquipmentPos( src
) )
11092 EquipItem(eDest2
, pDstItem
, true);
11094 AutoUnequipOffhandIfNeed();
11097 void Player::AddItemToBuyBackSlot( Item
*pItem
)
11101 uint32 slot
= m_currentBuybackSlot
;
11102 // if current back slot non-empty search oldest or free
11105 uint32 oldest_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
);
11106 uint32 oldest_slot
= BUYBACK_SLOT_START
;
11108 for(uint32 i
= BUYBACK_SLOT_START
+1; i
< BUYBACK_SLOT_END
; ++i
)
11117 uint32 i_time
= GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ i
- BUYBACK_SLOT_START
);
11119 if(oldest_time
> i_time
)
11121 oldest_time
= i_time
;
11127 slot
= oldest_slot
;
11130 RemoveItemFromBuyBackSlot( slot
, true );
11131 sLog
.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem
->GetEntry(), slot
);
11133 m_items
[slot
] = pItem
;
11134 time_t base
= time(NULL
);
11135 uint32 etime
= uint32(base
- m_logintime
+ (30 * 3600));
11136 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11138 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ eslot
* 2, pItem
->GetGUID() );
11139 ItemPrototype
const *pProto
= pItem
->GetProto();
11141 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, pProto
->SellPrice
* pItem
->GetCount() );
11143 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11144 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, (uint32
)etime
);
11146 // move to next (for non filled list is move most optimized choice)
11147 if(m_currentBuybackSlot
< BUYBACK_SLOT_END
-1)
11148 ++m_currentBuybackSlot
;
11152 Item
* Player::GetItemFromBuyBackSlot( uint32 slot
)
11154 sLog
.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot
);
11155 if( slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11156 return m_items
[slot
];
11160 void Player::RemoveItemFromBuyBackSlot( uint32 slot
, bool del
)
11162 sLog
.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot
);
11163 if( slot
>= BUYBACK_SLOT_START
&& slot
< BUYBACK_SLOT_END
)
11165 Item
*pItem
= m_items
[slot
];
11168 pItem
->RemoveFromWorld();
11169 if(del
) pItem
->SetState(ITEM_REMOVED
, this);
11172 m_items
[slot
] = NULL
;
11174 uint32 eslot
= slot
- BUYBACK_SLOT_START
;
11175 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1
+ eslot
* 2, 0 );
11176 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1
+ eslot
, 0 );
11177 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1
+ eslot
, 0 );
11179 // if current backslot is filled set to now free slot
11180 if(m_items
[m_currentBuybackSlot
])
11181 m_currentBuybackSlot
= slot
;
11185 void Player::SendEquipError( uint8 msg
, Item
* pItem
, Item
*pItem2
)
11187 sLog
.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg
);
11188 WorldPacket
data( SMSG_INVENTORY_CHANGE_FAILURE
, (msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
? 22 : 18) );
11189 data
<< uint8(msg
);
11193 data
<< uint64(pItem
? pItem
->GetGUID() : 0);
11194 data
<< uint64(pItem2
? pItem2
->GetGUID() : 0);
11195 data
<< uint8(0); // not 0 there...
11197 if(msg
== EQUIP_ERR_CANT_EQUIP_LEVEL_I
)
11202 if(ItemPrototype
const* proto
= pItem
->GetProto())
11203 level
= proto
->RequiredLevel
;
11205 data
<< uint32(level
); // new 2.4.0
11208 GetSession()->SendPacket(&data
);
11211 void Player::SendBuyError( uint8 msg
, Creature
* pCreature
, uint32 item
, uint32 param
)
11213 sLog
.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11214 WorldPacket
data( SMSG_BUY_FAILED
, (8+4+4+1) );
11215 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11216 data
<< uint32(item
);
11218 data
<< uint32(param
);
11219 data
<< uint8(msg
);
11220 GetSession()->SendPacket(&data
);
11223 void Player::SendSellError( uint8 msg
, Creature
* pCreature
, uint64 guid
, uint32 param
)
11225 sLog
.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11226 WorldPacket
data( SMSG_SELL_ITEM
,(8+8+(param
?4:0)+1)); // last check 2.0.10
11227 data
<< uint64(pCreature
? pCreature
->GetGUID() : 0);
11228 data
<< uint64(guid
);
11230 data
<< uint32(param
);
11231 data
<< uint8(msg
);
11232 GetSession()->SendPacket(&data
);
11235 void Player::ClearTrade()
11238 acceptTrade
= false;
11239 for(int i
= 0; i
< TRADE_SLOT_COUNT
; i
++)
11240 tradeItems
[i
] = NULL_SLOT
;
11243 void Player::TradeCancel(bool sendback
)
11247 // send yellow "Trade canceled" message to both traders
11251 ws
->SendCancelTrade();
11252 ws
= pTrader
->GetSession();
11253 if(!ws
->PlayerLogout())
11254 ws
->SendCancelTrade();
11258 pTrader
->ClearTrade();
11259 // prevent loss of reference
11260 pTrader
->pTrader
= NULL
;
11265 void Player::UpdateItemDuration(uint32 time
, bool realtimeonly
)
11267 if(m_itemDuration
.empty())
11270 sLog
.outDebug("Player::UpdateItemDuration(%u,%u)", time
,realtimeonly
);
11272 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); )
11275 ++itr
; // current element can be erased in UpdateDuration
11277 if (realtimeonly
&& item
->GetProto()->Duration
< 0 || !realtimeonly
)
11278 item
->UpdateDuration(this,time
);
11282 void Player::UpdateEnchantTime(uint32 time
)
11284 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11288 if(!itr
->item
->GetEnchantmentId(itr
->slot
))
11290 next
= m_enchantDuration
.erase(itr
);
11292 else if(itr
->leftduration
<= time
)
11294 ApplyEnchantment(itr
->item
,itr
->slot
,false,false);
11295 itr
->item
->ClearEnchantment(itr
->slot
);
11296 next
= m_enchantDuration
.erase(itr
);
11298 else if(itr
->leftduration
> time
)
11300 itr
->leftduration
-= time
;
11306 void Player::AddEnchantmentDurations(Item
*item
)
11308 for(int x
=0;x
<MAX_ENCHANTMENT_SLOT
;++x
)
11310 if(!item
->GetEnchantmentId(EnchantmentSlot(x
)))
11313 uint32 duration
= item
->GetEnchantmentDuration(EnchantmentSlot(x
));
11315 AddEnchantmentDuration(item
,EnchantmentSlot(x
),duration
);
11319 void Player::RemoveEnchantmentDurations(Item
*item
)
11321 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();)
11323 if(itr
->item
== item
)
11325 // save duration in item
11326 item
->SetEnchantmentDuration(EnchantmentSlot(itr
->slot
),itr
->leftduration
);
11327 itr
= m_enchantDuration
.erase(itr
);
11334 void Player::RemoveAllEnchantments(EnchantmentSlot slot
)
11336 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11337 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin(),next
;itr
!= m_enchantDuration
.end();itr
=next
)
11340 if(itr
->slot
==slot
)
11342 if(itr
->item
&& itr
->item
->GetEnchantmentId(slot
))
11344 // remove from stats
11345 ApplyEnchantment(itr
->item
,slot
,false,false);
11347 itr
->item
->ClearEnchantment(slot
);
11349 // remove from update list
11350 next
= m_enchantDuration
.erase(itr
);
11356 // remove enchants from inventory items
11357 // NOTE: no need to remove these from stats, since these aren't equipped
11359 for(int i
= INVENTORY_SLOT_ITEM_START
; i
< INVENTORY_SLOT_ITEM_END
; i
++)
11361 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11362 if( pItem
&& pItem
->GetEnchantmentId(slot
) )
11363 pItem
->ClearEnchantment(slot
);
11366 // in inventory bags
11367 for(int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
; i
++)
11369 Bag
* pBag
= (Bag
*)GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
11372 for(uint32 j
= 0; j
< pBag
->GetBagSize(); j
++)
11374 Item
* pItem
= pBag
->GetItemByPos(j
);
11375 if( pItem
&& pItem
->GetEnchantmentId(slot
) )
11376 pItem
->ClearEnchantment(slot
);
11382 // duration == 0 will remove item enchant
11383 void Player::AddEnchantmentDuration(Item
*item
,EnchantmentSlot slot
,uint32 duration
)
11388 if(slot
>= MAX_ENCHANTMENT_SLOT
)
11391 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
11393 if(itr
->item
== item
&& itr
->slot
== slot
)
11395 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
11396 m_enchantDuration
.erase(itr
);
11400 if(item
&& duration
> 0 )
11402 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item
->GetGUID(),slot
,uint32(duration
/1000));
11403 m_enchantDuration
.push_back(EnchantDuration(item
,slot
,duration
));
11407 void Player::ApplyEnchantment(Item
*item
,bool apply
)
11409 for(uint32 slot
= 0; slot
< MAX_ENCHANTMENT_SLOT
; ++slot
)
11410 ApplyEnchantment(item
, EnchantmentSlot(slot
), apply
);
11413 void Player::ApplyEnchantment(Item
*item
,EnchantmentSlot slot
,bool apply
, bool apply_dur
, bool ignore_condition
)
11418 if(!item
->IsEquipped())
11421 if(slot
>= MAX_ENCHANTMENT_SLOT
)
11424 uint32 enchant_id
= item
->GetEnchantmentId(slot
);
11428 SpellItemEnchantmentEntry
const *pEnchant
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
11432 if(!ignore_condition
&& pEnchant
->EnchantmentCondition
&& !((Player
*)this)->EnchantmentFitsRequirements(pEnchant
->EnchantmentCondition
, -1))
11435 for (int s
=0; s
<3; s
++)
11437 uint32 enchant_display_type
= pEnchant
->type
[s
];
11438 uint32 enchant_amount
= pEnchant
->amount
[s
];
11439 uint32 enchant_spell_id
= pEnchant
->spellid
[s
];
11441 switch(enchant_display_type
)
11443 case ITEM_ENCHANTMENT_TYPE_NONE
:
11445 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL
:
11446 // processed in Player::CastItemCombatSpell
11448 case ITEM_ENCHANTMENT_TYPE_DAMAGE
:
11449 if (item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
11450 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11451 else if (item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
11452 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11453 else if (item
->GetSlot() == EQUIPMENT_SLOT_RANGED
)
11454 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11456 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL
:
11457 if(enchant_spell_id
)
11461 int32 basepoints
= 0;
11462 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11463 if (item
->GetItemRandomPropertyId())
11465 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11468 // Search enchant_amount
11469 for (int k
=0; k
<3; k
++)
11471 if(item_rand
->enchant_id
[k
] == enchant_id
)
11473 basepoints
= int32((item_rand
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11479 // Cast custom spell vs all equal basepoints getted from enchant_amount
11481 CastCustomSpell(this,enchant_spell_id
,&basepoints
,&basepoints
,&basepoints
,true,item
);
11483 CastSpell(this,enchant_spell_id
,true,item
);
11486 RemoveAurasDueToItemSpell(item
,enchant_spell_id
);
11489 case ITEM_ENCHANTMENT_TYPE_RESISTANCE
:
11490 if (!enchant_amount
)
11492 ItemRandomSuffixEntry
const *item_rand
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11495 for (int k
=0; k
<3; k
++)
11497 if(item_rand
->enchant_id
[k
] == enchant_id
)
11499 enchant_amount
= uint32((item_rand
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11506 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START
+ enchant_spell_id
), TOTAL_VALUE
, float(enchant_amount
), apply
);
11508 case ITEM_ENCHANTMENT_TYPE_STAT
:
11510 if (!enchant_amount
)
11512 ItemRandomSuffixEntry
const *item_rand_suffix
= sItemRandomSuffixStore
.LookupEntry(abs(item
->GetItemRandomPropertyId()));
11513 if(item_rand_suffix
)
11515 for (int k
=0; k
<3; k
++)
11517 if(item_rand_suffix
->enchant_id
[k
] == enchant_id
)
11519 enchant_amount
= uint32((item_rand_suffix
->prefix
[k
]*item
->GetItemSuffixFactor()) / 10000 );
11526 sLog
.outDebug("Adding %u to stat nb %u",enchant_amount
,enchant_spell_id
);
11527 switch (enchant_spell_id
)
11529 case ITEM_MOD_AGILITY
:
11530 sLog
.outDebug("+ %u AGILITY",enchant_amount
);
11531 HandleStatModifier(UNIT_MOD_STAT_AGILITY
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11532 ApplyStatBuffMod(STAT_AGILITY
, enchant_amount
, apply
);
11534 case ITEM_MOD_STRENGTH
:
11535 sLog
.outDebug("+ %u STRENGTH",enchant_amount
);
11536 HandleStatModifier(UNIT_MOD_STAT_STRENGTH
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11537 ApplyStatBuffMod(STAT_STRENGTH
, enchant_amount
, apply
);
11539 case ITEM_MOD_INTELLECT
:
11540 sLog
.outDebug("+ %u INTELLECT",enchant_amount
);
11541 HandleStatModifier(UNIT_MOD_STAT_INTELLECT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11542 ApplyStatBuffMod(STAT_INTELLECT
, enchant_amount
, apply
);
11544 case ITEM_MOD_SPIRIT
:
11545 sLog
.outDebug("+ %u SPIRIT",enchant_amount
);
11546 HandleStatModifier(UNIT_MOD_STAT_SPIRIT
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11547 ApplyStatBuffMod(STAT_SPIRIT
, enchant_amount
, apply
);
11549 case ITEM_MOD_STAMINA
:
11550 sLog
.outDebug("+ %u STAMINA",enchant_amount
);
11551 HandleStatModifier(UNIT_MOD_STAT_STAMINA
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11552 ApplyStatBuffMod(STAT_STAMINA
, enchant_amount
, apply
);
11554 case ITEM_MOD_DEFENSE_SKILL_RATING
:
11555 ((Player
*)this)->ApplyRatingMod(CR_DEFENSE_SKILL
, enchant_amount
, apply
);
11556 sLog
.outDebug("+ %u DEFENCE", enchant_amount
);
11558 case ITEM_MOD_DODGE_RATING
:
11559 ((Player
*)this)->ApplyRatingMod(CR_DODGE
, enchant_amount
, apply
);
11560 sLog
.outDebug("+ %u DODGE", enchant_amount
);
11562 case ITEM_MOD_PARRY_RATING
:
11563 ((Player
*)this)->ApplyRatingMod(CR_PARRY
, enchant_amount
, apply
);
11564 sLog
.outDebug("+ %u PARRY", enchant_amount
);
11566 case ITEM_MOD_BLOCK_RATING
:
11567 ((Player
*)this)->ApplyRatingMod(CR_BLOCK
, enchant_amount
, apply
);
11568 sLog
.outDebug("+ %u SHIELD_BLOCK", enchant_amount
);
11570 case ITEM_MOD_HIT_MELEE_RATING
:
11571 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
11572 sLog
.outDebug("+ %u MELEE_HIT", enchant_amount
);
11574 case ITEM_MOD_HIT_RANGED_RATING
:
11575 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
11576 sLog
.outDebug("+ %u RANGED_HIT", enchant_amount
);
11578 case ITEM_MOD_HIT_SPELL_RATING
:
11579 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
11580 sLog
.outDebug("+ %u SPELL_HIT", enchant_amount
);
11582 case ITEM_MOD_CRIT_MELEE_RATING
:
11583 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
11584 sLog
.outDebug("+ %u MELEE_CRIT", enchant_amount
);
11586 case ITEM_MOD_CRIT_RANGED_RATING
:
11587 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
11588 sLog
.outDebug("+ %u RANGED_CRIT", enchant_amount
);
11590 case ITEM_MOD_CRIT_SPELL_RATING
:
11591 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
11592 sLog
.outDebug("+ %u SPELL_CRIT", enchant_amount
);
11594 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11596 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11597 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11599 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11600 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11602 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11603 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11605 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11606 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11608 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11609 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11611 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11612 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11614 // case ITEM_MOD_HASTE_MELEE_RATING:
11615 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11617 // case ITEM_MOD_HASTE_RANGED_RATING:
11618 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11620 case ITEM_MOD_HASTE_SPELL_RATING
:
11621 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
11623 case ITEM_MOD_HIT_RATING
:
11624 ((Player
*)this)->ApplyRatingMod(CR_HIT_MELEE
, enchant_amount
, apply
);
11625 ((Player
*)this)->ApplyRatingMod(CR_HIT_RANGED
, enchant_amount
, apply
);
11626 ((Player
*)this)->ApplyRatingMod(CR_HIT_SPELL
, enchant_amount
, apply
);
11627 sLog
.outDebug("+ %u HIT", enchant_amount
);
11629 case ITEM_MOD_CRIT_RATING
:
11630 ((Player
*)this)->ApplyRatingMod(CR_CRIT_MELEE
, enchant_amount
, apply
);
11631 ((Player
*)this)->ApplyRatingMod(CR_CRIT_RANGED
, enchant_amount
, apply
);
11632 ((Player
*)this)->ApplyRatingMod(CR_CRIT_SPELL
, enchant_amount
, apply
);
11633 sLog
.outDebug("+ %u CRITICAL", enchant_amount
);
11635 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11636 // case ITEM_MOD_HIT_TAKEN_RATING:
11637 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11638 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11639 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11641 // case ITEM_MOD_CRIT_TAKEN_RATING:
11642 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11643 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11644 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11646 case ITEM_MOD_RESILIENCE_RATING
:
11647 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE
, enchant_amount
, apply
);
11648 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED
, enchant_amount
, apply
);
11649 ((Player
*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL
, enchant_amount
, apply
);
11650 sLog
.outDebug("+ %u RESILIENCE", enchant_amount
);
11652 case ITEM_MOD_HASTE_RATING
:
11653 ((Player
*)this)->ApplyRatingMod(CR_HASTE_MELEE
, enchant_amount
, apply
);
11654 ((Player
*)this)->ApplyRatingMod(CR_HASTE_RANGED
, enchant_amount
, apply
);
11655 ((Player
*)this)->ApplyRatingMod(CR_HASTE_SPELL
, enchant_amount
, apply
);
11656 sLog
.outDebug("+ %u HASTE", enchant_amount
);
11658 case ITEM_MOD_EXPERTISE_RATING
:
11659 ((Player
*)this)->ApplyRatingMod(CR_EXPERTISE
, enchant_amount
, apply
);
11660 sLog
.outDebug("+ %u EXPERTISE", enchant_amount
);
11662 case ITEM_MOD_ATTACK_POWER
:
11663 HandleStatModifier(UNIT_MOD_ATTACK_POWER
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11664 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11665 sLog
.outDebug("+ %u ATTACK_POWER", enchant_amount
);
11667 case ITEM_MOD_RANGED_ATTACK_POWER
:
11668 HandleStatModifier(UNIT_MOD_ATTACK_POWER_RANGED
, TOTAL_VALUE
, float(enchant_amount
), apply
);
11669 sLog
.outDebug("+ %u RANGED_ATTACK_POWER", enchant_amount
);
11671 case ITEM_MOD_FERAL_ATTACK_POWER
:
11672 ((Player
*)this)->ApplyFeralAPBonus(enchant_amount
, apply
);
11673 sLog
.outDebug("+ %u FERAL_ATTACK_POWER", enchant_amount
);
11675 case ITEM_MOD_SPELL_HEALING_DONE
:
11676 ((Player
*)this)->ApplySpellHealingBonus(enchant_amount
, apply
);
11677 sLog
.outDebug("+ %u SPELL_HEALING_DONE", enchant_amount
);
11679 case ITEM_MOD_SPELL_DAMAGE_DONE
:
11680 ((Player
*)this)->ApplySpellDamageBonus(enchant_amount
, apply
);
11681 sLog
.outDebug("+ %u SPELL_DAMAGE_DONE", enchant_amount
);
11683 case ITEM_MOD_MANA_REGENERATION
:
11684 ((Player
*)this)->ApplyManaRegenBonus(enchant_amount
, apply
);
11685 sLog
.outDebug("+ %u MANA_REGENERATION", enchant_amount
);
11687 case ITEM_MOD_ARMOR_PENETRATION_RATING
:
11688 ((Player
*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION
, enchant_amount
, apply
);
11689 sLog
.outDebug("+ %u ARMOR PENETRATION", enchant_amount
);
11691 case ITEM_MOD_SPELL_POWER
:
11692 ((Player
*)this)->ApplySpellHealingBonus(enchant_amount
, apply
);
11693 ((Player
*)this)->ApplySpellDamageBonus(enchant_amount
, apply
);
11694 sLog
.outDebug("+ %u SPELL_POWER", enchant_amount
);
11701 case ITEM_ENCHANTMENT_TYPE_TOTEM
: // Shaman Rockbiter Weapon
11703 if(getClass() == CLASS_SHAMAN
)
11705 float addValue
= 0.0f
;
11706 if(item
->GetSlot() == EQUIPMENT_SLOT_MAINHAND
)
11708 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/1000.0f
);
11709 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND
, TOTAL_VALUE
, addValue
, apply
);
11711 else if(item
->GetSlot() == EQUIPMENT_SLOT_OFFHAND
)
11713 addValue
= float(enchant_amount
* item
->GetProto()->Delay
/1000.0f
);
11714 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND
, TOTAL_VALUE
, addValue
, apply
);
11719 case ITEM_ENCHANTMENT_TYPE_USE_SPELL
:
11720 // processed in Player::CastItemUseSpell
11722 case ITEM_ENCHANTMENT_TYPE_PRISMATIC_SOCKET
:
11726 sLog
.outError("Unknown item enchantment (id = %d) display type: %d", enchant_id
, enchant_display_type
);
11728 } /*switch(enchant_display_type)*/
11731 // visualize enchantment at player and equipped items
11732 if(slot
< MAX_INSPECTED_ENCHANTMENT_SLOT
)
11734 int VisibleBase
= PLAYER_VISIBLE_ITEM_1_0
+ (item
->GetSlot() * MAX_VISIBLE_ITEM_OFFSET
);
11735 SetUInt32Value(VisibleBase
+ 1 + slot
, apply
? item
->GetEnchantmentId(slot
) : 0);
11743 uint32 duration
= item
->GetEnchantmentDuration(slot
);
11745 AddEnchantmentDuration(item
,slot
,duration
);
11749 // duration == 0 will remove EnchantDuration
11750 AddEnchantmentDuration(item
,slot
,0);
11755 void Player::SendEnchantmentDurations()
11757 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
11759 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr
->item
->GetGUID(),itr
->slot
,uint32(itr
->leftduration
)/1000);
11763 void Player::SendItemDurations()
11765 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end();++itr
)
11767 (*itr
)->SendTimeUpdate(this);
11771 void Player::SendNewItem(Item
*item
, uint32 count
, bool received
, bool created
, bool broadcast
)
11773 if(!item
) // prevent crash
11776 // last check 2.0.10
11777 WorldPacket
data( SMSG_ITEM_PUSH_RESULT
, (8+4+4+4+1+4+4+4+4+4) );
11778 data
<< GetGUID(); // player GUID
11779 data
<< uint32(received
); // 0=looted, 1=from npc
11780 data
<< uint32(created
); // 0=received, 1=created
11781 data
<< uint32(1); // always 0x01 (probably meant to be count of listed items)
11782 data
<< (uint8
)item
->GetBagSlot(); // bagslot
11783 // item slot, but when added to stack: 0xFFFFFFFF
11784 data
<< (uint32
) ((item
->GetCount()==count
) ? item
->GetSlot() : -1);
11785 data
<< uint32(item
->GetEntry()); // item id
11786 data
<< uint32(item
->GetItemSuffixFactor()); // SuffixFactor
11787 data
<< uint32(item
->GetItemRandomPropertyId()); // random item property id
11788 data
<< uint32(count
); // count of items
11789 data
<< GetItemCount(item
->GetEntry()); // count of items in inventory
11791 if (broadcast
&& GetGroup())
11792 GetGroup()->BroadcastPacket(&data
, true);
11794 GetSession()->SendPacket(&data
);
11797 /*********************************************************/
11798 /*** QUEST SYSTEM ***/
11799 /*********************************************************/
11801 void Player::PrepareQuestMenu( uint64 guid
)
11804 QuestRelations
* pObjectQR
;
11805 QuestRelations
* pObjectQIR
;
11806 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
11809 pObject
= (Object
*)pCreature
;
11810 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
11811 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
11815 GameObject
*pGameObject
= ObjectAccessor::GetGameObject(*this, guid
);
11818 pObject
= (Object
*)pGameObject
;
11819 pObjectQR
= &objmgr
.mGOQuestRelations
;
11820 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
11826 QuestMenu
&qm
= PlayerTalkClass
->GetQuestMenu();
11829 for(QuestRelations::const_iterator i
= pObjectQIR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQIR
->upper_bound(pObject
->GetEntry()); ++i
)
11831 uint32 quest_id
= i
->second
;
11832 QuestStatus status
= GetQuestStatus( quest_id
);
11833 if ( status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus( quest_id
) )
11834 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_REWARD_REP
);
11835 else if ( status
== QUEST_STATUS_INCOMPLETE
)
11836 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_INCOMPLETE
);
11837 else if (status
== QUEST_STATUS_AVAILABLE
)
11838 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_CHAT
);
11841 for(QuestRelations::const_iterator i
= pObjectQR
->lower_bound(pObject
->GetEntry()); i
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++i
)
11843 uint32 quest_id
= i
->second
;
11844 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
11845 if(!pQuest
) continue;
11847 QuestStatus status
= GetQuestStatus( quest_id
);
11849 if (pQuest
->IsAutoComplete() && CanTakeQuest(pQuest
, false))
11850 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_REWARD_REP
);
11851 else if ( status
== QUEST_STATUS_NONE
&& CanTakeQuest( pQuest
, false ) )
11852 qm
.AddMenuItem(quest_id
, DIALOG_STATUS_AVAILABLE
);
11856 void Player::SendPreparedQuest( uint64 guid
)
11858 QuestMenu
& questMenu
= PlayerTalkClass
->GetQuestMenu();
11859 if( questMenu
.Empty() )
11862 QuestMenuItem
const& qmi0
= questMenu
.GetItem( 0 );
11864 uint32 status
= qmi0
.m_qIcon
;
11866 // single element case
11867 if ( questMenu
.MenuItemCount() == 1 )
11869 // Auto open -- maybe also should verify there is no greeting
11870 uint32 quest_id
= qmi0
.m_qId
;
11871 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
11874 if( status
== DIALOG_STATUS_REWARD_REP
&& !GetQuestRewardStatus( quest_id
) )
11875 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, CanRewardQuest(pQuest
,false), true );
11876 else if( status
== DIALOG_STATUS_INCOMPLETE
)
11877 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, false, true );
11878 // Send completable on repeatable quest if player don't have quest
11879 else if( pQuest
->IsRepeatable() && !pQuest
->IsDaily() )
11880 PlayerTalkClass
->SendQuestGiverRequestItems( pQuest
, guid
, CanCompleteRepeatableQuest(pQuest
), true );
11882 PlayerTalkClass
->SendQuestGiverQuestDetails( pQuest
, guid
, true );
11885 // multiply entries
11891 std::string title
= "";
11892 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
11895 uint32 textid
= pCreature
->GetNpcTextId();
11896 GossipText
const* gossiptext
= objmgr
.GetGossipText(textid
);
11899 qe
._Delay
= 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
11900 qe
._Emote
= 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
11905 qe
= gossiptext
->Options
[0].Emotes
[0];
11907 if(!gossiptext
->Options
[0].Text_0
.empty())
11909 title
= gossiptext
->Options
[0].Text_0
;
11911 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
11914 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
11917 if (nl
->Text_0
[0].size() > loc_idx
&& !nl
->Text_0
[0][loc_idx
].empty())
11918 title
= nl
->Text_0
[0][loc_idx
];
11924 title
= gossiptext
->Options
[0].Text_1
;
11926 int loc_idx
= GetSession()->GetSessionDbLocaleIndex();
11929 NpcTextLocale
const *nl
= objmgr
.GetNpcTextLocale(textid
);
11932 if (nl
->Text_1
[0].size() > loc_idx
&& !nl
->Text_1
[0][loc_idx
].empty())
11933 title
= nl
->Text_1
[0][loc_idx
];
11939 PlayerTalkClass
->SendQuestGiverQuestList( qe
, title
, guid
);
11943 bool Player::IsActiveQuest( uint32 quest_id
) const
11945 QuestStatusMap::const_iterator itr
= mQuestStatus
.find(quest_id
);
11947 return itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
;
11950 Quest
const * Player::GetNextQuest( uint64 guid
, Quest
const *pQuest
)
11953 QuestRelations
* pObjectQR
;
11954 QuestRelations
* pObjectQIR
;
11956 Creature
*pCreature
= ObjectAccessor::GetCreature(*this, guid
);
11959 pObject
= (Object
*)pCreature
;
11960 pObjectQR
= &objmgr
.mCreatureQuestRelations
;
11961 pObjectQIR
= &objmgr
.mCreatureQuestInvolvedRelations
;
11965 GameObject
*pGameObject
= ObjectAccessor::GetGameObject(*this, guid
);
11968 pObject
= (Object
*)pGameObject
;
11969 pObjectQR
= &objmgr
.mGOQuestRelations
;
11970 pObjectQIR
= &objmgr
.mGOQuestInvolvedRelations
;
11976 uint32 nextQuestID
= pQuest
->GetNextQuestInChain();
11977 for(QuestRelations::const_iterator itr
= pObjectQR
->lower_bound(pObject
->GetEntry()); itr
!= pObjectQR
->upper_bound(pObject
->GetEntry()); ++itr
)
11979 if (itr
->second
== nextQuestID
)
11980 return objmgr
.GetQuestTemplate(nextQuestID
);
11986 bool Player::CanSeeStartQuest( Quest
const *pQuest
)
11988 if( SatisfyQuestRace( pQuest
, false ) && SatisfyQuestSkillOrClass( pQuest
, false ) &&
11989 SatisfyQuestExclusiveGroup( pQuest
, false ) && SatisfyQuestReputation( pQuest
, false ) &&
11990 SatisfyQuestPreviousQuest( pQuest
, false ) && SatisfyQuestNextChain( pQuest
, false ) &&
11991 SatisfyQuestPrevChain( pQuest
, false ) && SatisfyQuestDay( pQuest
, false ) )
11993 return getLevel() + sWorld
.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF
) >= pQuest
->GetMinLevel();
11999 bool Player::CanTakeQuest( Quest
const *pQuest
, bool msg
)
12001 return SatisfyQuestStatus( pQuest
, msg
) && SatisfyQuestExclusiveGroup( pQuest
, msg
)
12002 && SatisfyQuestRace( pQuest
, msg
) && SatisfyQuestLevel( pQuest
, msg
)
12003 && SatisfyQuestSkillOrClass( pQuest
, msg
) && SatisfyQuestReputation( pQuest
, msg
)
12004 && SatisfyQuestPreviousQuest( pQuest
, msg
) && SatisfyQuestTimed( pQuest
, msg
)
12005 && SatisfyQuestNextChain( pQuest
, msg
) && SatisfyQuestPrevChain( pQuest
, msg
)
12006 && SatisfyQuestDay( pQuest
, msg
);
12009 bool Player::CanAddQuest( Quest
const *pQuest
, bool msg
)
12011 if( !SatisfyQuestLog( msg
) )
12014 uint32 srcitem
= pQuest
->GetSrcItemId();
12017 uint32 count
= pQuest
->GetSrcItemCount();
12018 ItemPosCountVec dest
;
12019 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
12021 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12022 if( msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
12024 else if( msg
!= EQUIP_ERR_OK
)
12026 SendEquipError( msg
, NULL
, NULL
);
12033 bool Player::CanCompleteQuest( uint32 quest_id
)
12037 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12038 if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
12039 return false; // not allow re-complete quest
12041 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12046 // auto complete quest
12047 if (qInfo
->IsAutoComplete() && CanTakeQuest(qInfo
, false))
12050 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
12053 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12055 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12057 if( qInfo
->ReqItemCount
[i
]!= 0 && q_status
.m_itemcount
[i
] < qInfo
->ReqItemCount
[i
] )
12062 if ( qInfo
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
12064 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12066 if( qInfo
->ReqCreatureOrGOId
[i
] == 0 )
12069 if( qInfo
->ReqCreatureOrGOCount
[i
] != 0 && q_status
.m_creatureOrGOcount
[i
] < qInfo
->ReqCreatureOrGOCount
[i
] )
12074 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT
) && !q_status
.m_explored
)
12077 if ( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && q_status
.m_timer
== 0 )
12080 if ( qInfo
->GetRewOrReqMoney() < 0 )
12082 if ( GetMoney() < uint32(-qInfo
->GetRewOrReqMoney()) )
12086 uint32 repFacId
= qInfo
->GetRepObjectiveFaction();
12087 if ( repFacId
&& GetReputationMgr().GetReputation(repFacId
) < qInfo
->GetRepObjectiveValue() )
12096 bool Player::CanCompleteRepeatableQuest( Quest
const *pQuest
)
12098 // Solve problem that player don't have the quest and try complete it.
12099 // if repeatable she must be able to complete event if player don't have it.
12100 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12101 if( !CanTakeQuest(pQuest
, false) )
12104 if (pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12105 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12106 if( pQuest
->ReqItemId
[i
] && pQuest
->ReqItemCount
[i
] && !HasItemCount(pQuest
->ReqItemId
[i
],pQuest
->ReqItemCount
[i
]) )
12109 if( !CanRewardQuest(pQuest
, false) )
12115 bool Player::CanRewardQuest( Quest
const *pQuest
, bool msg
)
12117 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12118 if(!pQuest
->IsAutoComplete() && GetQuestStatus(pQuest
->GetQuestId()) != QUEST_STATUS_COMPLETE
)
12121 // daily quest can't be rewarded (25 daily quest already completed)
12122 if(!SatisfyQuestDay(pQuest
,true))
12125 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12126 if(GetQuestRewardStatus(pQuest
->GetQuestId()))
12129 // prevent receive reward with quest items in bank
12130 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12132 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++)
12134 if( pQuest
->ReqItemCount
[i
]!= 0 &&
12135 GetItemCount(pQuest
->ReqItemId
[i
]) < pQuest
->ReqItemCount
[i
] )
12138 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND
, NULL
, NULL
);
12144 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12145 if(pQuest
->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest
->GetRewOrReqMoney()) )
12151 bool Player::CanRewardQuest( Quest
const *pQuest
, uint32 reward
, bool msg
)
12153 // prevent receive reward with quest items in bank or for not completed quest
12154 if(!CanRewardQuest(pQuest
,msg
))
12157 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
12159 if( pQuest
->RewChoiceItemId
[reward
] )
12161 ItemPosCountVec dest
;
12162 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] );
12163 if( res
!= EQUIP_ERR_OK
)
12165 SendEquipError( res
, NULL
, NULL
);
12171 if ( pQuest
->GetRewItemsCount() > 0 )
12173 for (uint32 i
= 0; i
< pQuest
->GetRewItemsCount(); ++i
)
12175 if( pQuest
->RewItemId
[i
] )
12177 ItemPosCountVec dest
;
12178 uint8 res
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] );
12179 if( res
!= EQUIP_ERR_OK
)
12181 SendEquipError( res
, NULL
, NULL
);
12191 void Player::AddQuest( Quest
const *pQuest
, Object
*questGiver
)
12193 uint16 log_slot
= FindQuestSlot( 0 );
12194 assert(log_slot
< MAX_QUEST_LOG_SIZE
);
12196 uint32 quest_id
= pQuest
->GetQuestId();
12198 // if not exist then created with set uState==NEW and rewarded=false
12199 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
12201 // check for repeatable quests status reset
12202 questStatusData
.m_status
= QUEST_STATUS_INCOMPLETE
;
12203 questStatusData
.m_explored
= false;
12205 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
12207 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12208 questStatusData
.m_itemcount
[i
] = 0;
12211 if ( pQuest
->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
12213 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
12214 questStatusData
.m_creatureOrGOcount
[i
] = 0;
12217 GiveQuestSourceItem( pQuest
);
12218 AdjustQuestReqItemCount( pQuest
, questStatusData
);
12220 if( pQuest
->GetRepObjectiveFaction() )
12221 if(FactionEntry
const* factionEntry
= sFactionStore
.LookupEntry(pQuest
->GetRepObjectiveFaction()))
12222 GetReputationMgr().SetVisible(factionEntry
);
12225 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
12227 uint32 limittime
= pQuest
->GetLimitTime();
12229 // shared timed quest
12230 if(questGiver
&& questGiver
->GetTypeId()==TYPEID_PLAYER
)
12231 limittime
= ((Player
*)questGiver
)->getQuestStatusMap()[quest_id
].m_timer
/ IN_MILISECONDS
;
12233 AddTimedQuest( quest_id
);
12234 questStatusData
.m_timer
= limittime
* IN_MILISECONDS
;
12235 qtime
= static_cast<uint32
>(time(NULL
)) + limittime
;
12238 questStatusData
.m_timer
= 0;
12240 SetQuestSlot(log_slot
, quest_id
, qtime
);
12242 if (questStatusData
.uState
!= QUEST_NEW
)
12243 questStatusData
.uState
= QUEST_CHANGED
;
12245 //starting initial quest script
12246 if(questGiver
&& pQuest
->GetQuestStartScript()!=0)
12247 sWorld
.ScriptsStart(sQuestStartScripts
, pQuest
->GetQuestStartScript(), questGiver
, this);
12249 // Some spells applied at quest activation
12250 SpellAreaForQuestMapBounds saBounds
= spellmgr
.GetSpellAreaForQuestMapBounds(quest_id
,true);
12251 if(saBounds
.first
!= saBounds
.second
)
12254 GetZoneAndAreaId(zone
,area
);
12256 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
12257 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,zone
,area
))
12258 if( !HasAura(itr
->second
->spellId
,0) )
12259 CastSpell(this,itr
->second
->spellId
,true);
12262 UpdateForQuestsGO();
12265 void Player::CompleteQuest( uint32 quest_id
)
12269 SetQuestStatus( quest_id
, QUEST_STATUS_COMPLETE
);
12271 uint16 log_slot
= FindQuestSlot( quest_id
);
12272 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12273 SetQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
12275 if(Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
))
12277 if( qInfo
->HasFlag(QUEST_FLAGS_AUTO_REWARDED
) )
12278 RewardQuest(qInfo
,0,this,false);
12280 SendQuestComplete( quest_id
);
12285 void Player::IncompleteQuest( uint32 quest_id
)
12289 SetQuestStatus( quest_id
, QUEST_STATUS_INCOMPLETE
);
12291 uint16 log_slot
= FindQuestSlot( quest_id
);
12292 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12293 RemoveQuestSlotState(log_slot
,QUEST_STATE_COMPLETE
);
12297 void Player::RewardQuest( Quest
const *pQuest
, uint32 reward
, Object
* questGiver
, bool announce
)
12299 uint32 quest_id
= pQuest
->GetQuestId();
12301 for (int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; i
++ )
12303 if ( pQuest
->ReqItemId
[i
] )
12304 DestroyItemCount( pQuest
->ReqItemId
[i
], pQuest
->ReqItemCount
[i
], true);
12307 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12308 // SetTimedQuest( 0 );
12309 m_timedquests
.erase(pQuest
->GetQuestId());
12311 if ( pQuest
->GetRewChoiceItemsCount() > 0 )
12313 if( pQuest
->RewChoiceItemId
[reward
] )
12315 ItemPosCountVec dest
;
12316 if( CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewChoiceItemId
[reward
], pQuest
->RewChoiceItemCount
[reward
] ) == EQUIP_ERR_OK
)
12318 Item
* item
= StoreNewItem( dest
, pQuest
->RewChoiceItemId
[reward
], true);
12319 SendNewItem(item
, pQuest
->RewChoiceItemCount
[reward
], true, false);
12324 if ( pQuest
->GetRewItemsCount() > 0 )
12326 for (uint32 i
=0; i
< pQuest
->GetRewItemsCount(); ++i
)
12328 if( pQuest
->RewItemId
[i
] )
12330 ItemPosCountVec dest
;
12331 if( CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, pQuest
->RewItemId
[i
], pQuest
->RewItemCount
[i
] ) == EQUIP_ERR_OK
)
12333 Item
* item
= StoreNewItem( dest
, pQuest
->RewItemId
[i
], true);
12334 SendNewItem(item
, pQuest
->RewItemCount
[i
], true, false);
12340 RewardReputation( pQuest
);
12342 if( pQuest
->GetRewSpellCast() > 0 )
12343 CastSpell( this, pQuest
->GetRewSpellCast(), true);
12344 else if( pQuest
->GetRewSpell() > 0)
12345 CastSpell( this, pQuest
->GetRewSpell(), true);
12347 uint16 log_slot
= FindQuestSlot( quest_id
);
12348 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12349 SetQuestSlot(log_slot
,0);
12351 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12353 // Not give XP in case already completed once repeatable quest
12354 uint32 XP
= q_status
.m_rewarded
? 0 : uint32(pQuest
->XPValue( this )*sWorld
.getRate(RATE_XP_QUEST
));
12356 if ( getLevel() < sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
12357 GiveXP( XP
, NULL
);
12360 uint32 money
= uint32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getRate(RATE_DROP_MONEY
));
12361 ModifyMoney( money
);
12362 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD
, money
);
12365 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12366 if(pQuest
->GetRewOrReqMoney())
12368 ModifyMoney( pQuest
->GetRewOrReqMoney() );
12370 if(pQuest
->GetRewOrReqMoney() > 0)
12371 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD
, pQuest
->GetRewOrReqMoney());
12375 if(pQuest
->GetRewHonorableKills())
12376 RewardHonor(NULL
, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorableKills()));
12379 if(pQuest
->GetCharTitleId())
12381 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
12382 SetTitle(titleEntry
);
12385 if(pQuest
->GetBonusTalents())
12387 m_questRewardTalentCount
+=pQuest
->GetBonusTalents();
12388 InitTalentForLevel();
12391 // Send reward mail
12392 if(pQuest
->GetRewMailTemplateId())
12394 MailMessageType mailType
;
12395 uint32 senderGuidOrEntry
;
12396 switch(questGiver
->GetTypeId())
12399 mailType
= MAIL_CREATURE
;
12400 senderGuidOrEntry
= questGiver
->GetEntry();
12402 case TYPEID_GAMEOBJECT
:
12403 mailType
= MAIL_GAMEOBJECT
;
12404 senderGuidOrEntry
= questGiver
->GetEntry();
12407 mailType
= MAIL_ITEM
;
12408 senderGuidOrEntry
= questGiver
->GetEntry();
12410 case TYPEID_PLAYER
:
12411 mailType
= MAIL_NORMAL
;
12412 senderGuidOrEntry
= questGiver
->GetGUIDLow();
12415 mailType
= MAIL_NORMAL
;
12416 senderGuidOrEntry
= GetGUIDLow();
12420 Loot questMailLoot
;
12422 questMailLoot
.FillLoot(pQuest
->GetQuestId(), LootTemplates_QuestMail
, this,true);
12425 MailItemsInfo mi
; // item list preparing
12427 uint32 max_slot
= questMailLoot
.GetMaxSlotInLootFor(this);
12428 for(uint32 i
= 0; mi
.size() < MAX_MAIL_ITEMS
&& i
< max_slot
; ++i
)
12430 if(LootItem
* lootitem
= questMailLoot
.LootItemInSlot(i
,this))
12432 if(Item
* item
= Item::CreateItem(lootitem
->itemid
,lootitem
->count
,this))
12434 item
->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12435 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
12440 WorldSession::SendMailTo(this, mailType
, MAIL_STATIONERY_NORMAL
, senderGuidOrEntry
, GetGUIDLow(), "", 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
,pQuest
->GetRewMailDelaySecs(),pQuest
->GetRewMailTemplateId());
12443 if(pQuest
->IsDaily())
12445 SetDailyQuestStatus(quest_id
);
12446 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST
, 1);
12449 if ( !pQuest
->IsRepeatable() )
12450 SetQuestStatus(quest_id
, QUEST_STATUS_COMPLETE
);
12452 SetQuestStatus(quest_id
, QUEST_STATUS_NONE
);
12454 q_status
.m_rewarded
= true;
12457 SendQuestReward( pQuest
, XP
, questGiver
);
12459 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12460 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT
);
12461 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST
);
12466 // remove auras from spells with quest reward state limitations
12467 SpellAreaForQuestMapBounds saEndBounds
= spellmgr
.GetSpellAreaForQuestEndMapBounds(quest_id
);
12468 if(saEndBounds
.first
!= saEndBounds
.second
)
12470 GetZoneAndAreaId(zone
,area
);
12472 for(SpellAreaForAreaMap::const_iterator itr
= saEndBounds
.first
; itr
!= saEndBounds
.second
; ++itr
)
12473 if(!itr
->second
->IsFitToRequirements(this,zone
,area
))
12474 RemoveAurasDueToSpell(itr
->second
->spellId
);
12477 // Some spells applied at quest reward
12478 SpellAreaForQuestMapBounds saBounds
= spellmgr
.GetSpellAreaForQuestMapBounds(quest_id
,false);
12479 if(saBounds
.first
!= saBounds
.second
)
12482 GetZoneAndAreaId(zone
,area
);
12484 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
12485 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,zone
,area
))
12486 if( !HasAura(itr
->second
->spellId
,0) )
12487 CastSpell(this,itr
->second
->spellId
,true);
12491 void Player::FailQuest( uint32 quest_id
)
12495 IncompleteQuest( quest_id
);
12497 uint16 log_slot
= FindQuestSlot( quest_id
);
12498 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12500 SetQuestSlotTimer(log_slot
, 1 );
12501 SetQuestSlotState(log_slot
,QUEST_STATE_FAIL
);
12503 SendQuestFailed( quest_id
);
12507 void Player::FailTimedQuest( uint32 quest_id
)
12511 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12513 q_status
.m_timer
= 0;
12514 if (q_status
.uState
!= QUEST_NEW
)
12515 q_status
.uState
= QUEST_CHANGED
;
12517 IncompleteQuest( quest_id
);
12519 uint16 log_slot
= FindQuestSlot( quest_id
);
12520 if( log_slot
< MAX_QUEST_LOG_SIZE
)
12522 SetQuestSlotTimer(log_slot
, 1 );
12523 SetQuestSlotState(log_slot
,QUEST_STATE_FAIL
);
12525 SendQuestTimerFailed( quest_id
);
12529 bool Player::SatisfyQuestSkillOrClass( Quest
const* qInfo
, bool msg
)
12531 int32 zoneOrSort
= qInfo
->GetZoneOrSort();
12532 int32 skillOrClass
= qInfo
->GetSkillOrClass();
12534 // skip zone zoneOrSort and 0 case skillOrClass
12535 if( zoneOrSort
>= 0 && skillOrClass
== 0 )
12538 int32 questSort
= -zoneOrSort
;
12539 uint8 reqSortClass
= ClassByQuestSort(questSort
);
12541 // check class sort cases in zoneOrSort
12542 if( reqSortClass
!= 0 && getClass() != reqSortClass
)
12545 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12550 if( skillOrClass
< 0 )
12552 uint8 reqClass
= -int32(skillOrClass
);
12553 if(getClass() != reqClass
)
12556 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12561 else if( skillOrClass
> 0 )
12563 uint32 reqSkill
= skillOrClass
;
12564 if( GetSkillValue( reqSkill
) < qInfo
->GetRequiredSkillValue() )
12567 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12575 bool Player::SatisfyQuestLevel( Quest
const* qInfo
, bool msg
)
12577 if( getLevel() < qInfo
->GetMinLevel() )
12580 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12586 bool Player::SatisfyQuestLog( bool msg
)
12589 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE
)
12594 WorldPacket
data( SMSG_QUESTLOG_FULL
, 0 );
12595 GetSession()->SendPacket( &data
);
12596 sLog
.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12601 bool Player::SatisfyQuestPreviousQuest( Quest
const* qInfo
, bool msg
)
12603 // No previous quest (might be first quest in a series)
12604 if( qInfo
->prevQuests
.empty())
12607 for(Quest::PrevQuests::const_iterator iter
= qInfo
->prevQuests
.begin(); iter
!= qInfo
->prevQuests
.end(); ++iter
)
12609 uint32 prevId
= abs(*iter
);
12611 QuestStatusMap::iterator i_prevstatus
= mQuestStatus
.find( prevId
);
12612 Quest
const* qPrevInfo
= objmgr
.GetQuestTemplate(prevId
);
12614 if( qPrevInfo
&& i_prevstatus
!= mQuestStatus
.end() )
12616 // If any of the positive previous quests completed, return true
12617 if( *iter
> 0 && i_prevstatus
->second
.m_rewarded
)
12619 // skip one-from-all exclusive group
12620 if(qPrevInfo
->GetExclusiveGroup() >= 0)
12623 // each-from-all exclusive group ( < 0)
12624 // can be start if only all quests in prev quest exclusive group completed and rewarded
12625 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
12626 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
12628 assert(iter
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
12630 for(; iter
!= end
; ++iter
)
12632 uint32 exclude_Id
= iter
->second
;
12634 // skip checked quest id, only state of other quests in group is interesting
12635 if(exclude_Id
== prevId
)
12638 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12640 // alternative quest from group also must be completed and rewarded(reported)
12641 if( i_exstatus
== mQuestStatus
.end() || !i_exstatus
->second
.m_rewarded
)
12644 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12650 // If any of the negative previous quests active, return true
12651 if( *iter
< 0 && (i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
12652 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
))))
12654 // skip one-from-all exclusive group
12655 if(qPrevInfo
->GetExclusiveGroup() >= 0)
12658 // each-from-all exclusive group ( < 0)
12659 // can be start if only all quests in prev quest exclusive group active
12660 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qPrevInfo
->GetExclusiveGroup());
12661 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qPrevInfo
->GetExclusiveGroup());
12663 assert(iter
!=end
); // always must be found if qPrevInfo->ExclusiveGroup != 0
12665 for(; iter
!= end
; ++iter
)
12667 uint32 exclude_Id
= iter
->second
;
12669 // skip checked quest id, only state of other quests in group is interesting
12670 if(exclude_Id
== prevId
)
12673 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12675 // alternative quest from group also must be active
12676 if( i_exstatus
== mQuestStatus
.end() ||
12677 i_exstatus
->second
.m_status
!= QUEST_STATUS_INCOMPLETE
&&
12678 (i_prevstatus
->second
.m_status
!= QUEST_STATUS_COMPLETE
|| GetQuestRewardStatus(prevId
)) )
12681 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12690 // Has only positive prev. quests in non-rewarded state
12691 // and negative prev. quests in non-active state
12693 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12698 bool Player::SatisfyQuestRace( Quest
const* qInfo
, bool msg
)
12700 uint32 reqraces
= qInfo
->GetRequiredRaces();
12701 if ( reqraces
== 0 )
12703 if( (reqraces
& getRaceMask()) == 0 )
12706 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE
);
12712 bool Player::SatisfyQuestReputation( Quest
const* qInfo
, bool msg
)
12714 uint32 fIdMin
= qInfo
->GetRequiredMinRepFaction(); //Min required rep
12715 if(fIdMin
&& GetReputationMgr().GetReputation(fIdMin
) < qInfo
->GetRequiredMinRepValue())
12718 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12722 uint32 fIdMax
= qInfo
->GetRequiredMaxRepFaction(); //Max required rep
12723 if(fIdMax
&& GetReputationMgr().GetReputation(fIdMax
) >= qInfo
->GetRequiredMaxRepValue())
12726 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12733 bool Player::SatisfyQuestStatus( Quest
const* qInfo
, bool msg
)
12735 QuestStatusMap::iterator itr
= mQuestStatus
.find( qInfo
->GetQuestId() );
12736 if ( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
)
12739 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON
);
12745 bool Player::SatisfyQuestTimed( Quest
const* qInfo
, bool msg
)
12747 if ( (find(m_timedquests
.begin(), m_timedquests
.end(), qInfo
->GetQuestId()) != m_timedquests
.end()) && qInfo
->HasFlag(QUEST_MANGOS_FLAGS_TIMED
) )
12750 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED
);
12756 bool Player::SatisfyQuestExclusiveGroup( Quest
const* qInfo
, bool msg
)
12758 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12759 if(qInfo
->GetExclusiveGroup() <= 0)
12762 ObjectMgr::ExclusiveQuestGroups::iterator iter
= objmgr
.mExclusiveQuestGroups
.lower_bound(qInfo
->GetExclusiveGroup());
12763 ObjectMgr::ExclusiveQuestGroups::iterator end
= objmgr
.mExclusiveQuestGroups
.upper_bound(qInfo
->GetExclusiveGroup());
12765 assert(iter
!=end
); // always must be found if qInfo->ExclusiveGroup != 0
12767 for(; iter
!= end
; ++iter
)
12769 uint32 exclude_Id
= iter
->second
;
12771 // skip checked quest id, only state of other quests in group is interesting
12772 if(exclude_Id
== qInfo
->GetQuestId())
12775 // not allow have daily quest if daily quest from exclusive group already recently completed
12776 Quest
const* Nquest
= objmgr
.GetQuestTemplate(exclude_Id
);
12777 if( !SatisfyQuestDay(Nquest
, false) )
12780 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12784 QuestStatusMap::iterator i_exstatus
= mQuestStatus
.find( exclude_Id
);
12786 // alternative quest already started or completed
12787 if( i_exstatus
!= mQuestStatus
.end()
12788 && (i_exstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
|| i_exstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
12791 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12798 bool Player::SatisfyQuestNextChain( Quest
const* qInfo
, bool msg
)
12800 if(!qInfo
->GetNextQuestInChain())
12803 // next quest in chain already started or completed
12804 QuestStatusMap::iterator itr
= mQuestStatus
.find( qInfo
->GetNextQuestInChain() );
12805 if( itr
!= mQuestStatus
.end()
12806 && (itr
->second
.m_status
== QUEST_STATUS_COMPLETE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
) )
12809 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12813 // check for all quests further up the chain
12814 // only necessary if there are quest chains with more than one quest that can be skipped
12815 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12819 bool Player::SatisfyQuestPrevChain( Quest
const* qInfo
, bool msg
)
12821 // No previous quest in chain
12822 if( qInfo
->prevChainQuests
.empty())
12825 for(Quest::PrevChainQuests::const_iterator iter
= qInfo
->prevChainQuests
.begin(); iter
!= qInfo
->prevChainQuests
.end(); ++iter
)
12827 uint32 prevId
= *iter
;
12829 QuestStatusMap::iterator i_prevstatus
= mQuestStatus
.find( prevId
);
12831 if( i_prevstatus
!= mQuestStatus
.end() )
12833 // If any of the previous quests in chain active, return false
12834 if( i_prevstatus
->second
.m_status
== QUEST_STATUS_INCOMPLETE
12835 || (i_prevstatus
->second
.m_status
== QUEST_STATUS_COMPLETE
&& !GetQuestRewardStatus(prevId
)))
12838 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ
);
12843 // check for all quests further down the chain
12844 // only necessary if there are quest chains with more than one quest that can be skipped
12845 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12849 // No previous quest in chain active
12853 bool Player::SatisfyQuestDay( Quest
const* qInfo
, bool msg
)
12855 if(!qInfo
->IsDaily())
12858 bool have_slot
= false;
12859 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
12861 uint32 id
= GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
);
12862 if(qInfo
->GetQuestId()==id
)
12872 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING
);
12879 bool Player::GiveQuestSourceItem( Quest
const *pQuest
)
12881 uint32 srcitem
= pQuest
->GetSrcItemId();
12884 uint32 count
= pQuest
->GetSrcItemCount();
12888 ItemPosCountVec dest
;
12889 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, srcitem
, count
);
12890 if( msg
== EQUIP_ERR_OK
)
12892 Item
* item
= StoreNewItem(dest
, srcitem
, true);
12893 SendNewItem(item
, count
, true, false);
12896 // player already have max amount required item, just report success
12897 else if( msg
== EQUIP_ERR_CANT_CARRY_MORE_OF_THIS
)
12900 SendEquipError( msg
, NULL
, NULL
);
12907 bool Player::TakeQuestSourceItem( uint32 quest_id
, bool msg
)
12909 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12912 uint32 srcitem
= qInfo
->GetSrcItemId();
12915 uint32 count
= qInfo
->GetSrcItemCount();
12919 // exist one case when destroy source quest item not possible:
12920 // non un-equippable item (equipped non-empty bag, for example)
12921 uint8 res
= CanUnequipItems(srcitem
,count
);
12922 if(res
!= EQUIP_ERR_OK
)
12925 SendEquipError( res
, NULL
, NULL
);
12929 DestroyItemCount(srcitem
, count
, true, true);
12935 bool Player::GetQuestRewardStatus( uint32 quest_id
) const
12937 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12940 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
12941 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
12942 if( itr
!= mQuestStatus
.end() && itr
->second
.m_status
!= QUEST_STATUS_NONE
12943 && !qInfo
->IsRepeatable() )
12944 return itr
->second
.m_rewarded
;
12951 QuestStatus
Player::GetQuestStatus( uint32 quest_id
) const
12955 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
12956 if( itr
!= mQuestStatus
.end() )
12957 return itr
->second
.m_status
;
12959 return QUEST_STATUS_NONE
;
12962 bool Player::CanShareQuest(uint32 quest_id
) const
12964 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12965 if( qInfo
&& qInfo
->HasFlag(QUEST_FLAGS_SHARABLE
) )
12967 QuestStatusMap::const_iterator itr
= mQuestStatus
.find( quest_id
);
12968 if( itr
!= mQuestStatus
.end() )
12969 return itr
->second
.m_status
== QUEST_STATUS_NONE
|| itr
->second
.m_status
== QUEST_STATUS_INCOMPLETE
;
12974 void Player::SetQuestStatus( uint32 quest_id
, QuestStatus status
)
12976 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
12979 if( status
== QUEST_STATUS_NONE
|| status
== QUEST_STATUS_INCOMPLETE
|| status
== QUEST_STATUS_COMPLETE
)
12981 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) )
12982 m_timedquests
.erase(qInfo
->GetQuestId());
12985 QuestStatusData
& q_status
= mQuestStatus
[quest_id
];
12987 q_status
.m_status
= status
;
12988 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
12991 UpdateForQuestsGO();
12994 // not used in MaNGOS, but used in scripting code
12995 uint32
Player::GetReqKillOrCastCurrentCount(uint32 quest_id
, int32 entry
)
12997 Quest
const* qInfo
= objmgr
.GetQuestTemplate(quest_id
);
13001 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; ++j
)
13002 if ( qInfo
->ReqCreatureOrGOId
[j
] == entry
)
13003 return mQuestStatus
[quest_id
].m_creatureOrGOcount
[j
];
13008 void Player::AdjustQuestReqItemCount( Quest
const* pQuest
, QuestStatusData
& questStatusData
)
13010 if ( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13012 for(int i
= 0; i
< QUEST_OBJECTIVES_COUNT
; ++i
)
13014 uint32 reqitemcount
= pQuest
->ReqItemCount
[i
];
13015 if( reqitemcount
!= 0 )
13017 uint32 quest_id
= pQuest
->GetQuestId();
13018 uint32 curitemcount
= GetItemCount(pQuest
->ReqItemId
[i
],true);
13020 questStatusData
.m_itemcount
[i
] = std::min(curitemcount
, reqitemcount
);
13021 if (questStatusData
.uState
!= QUEST_NEW
) questStatusData
.uState
= QUEST_CHANGED
;
13027 uint16
Player::FindQuestSlot( uint32 quest_id
) const
13029 for ( uint16 i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13030 if ( GetQuestSlotQuestId(i
) == quest_id
)
13033 return MAX_QUEST_LOG_SIZE
;
13036 void Player::AreaExploredOrEventHappens( uint32 questId
)
13040 uint16 log_slot
= FindQuestSlot( questId
);
13041 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13043 QuestStatusData
& q_status
= mQuestStatus
[questId
];
13045 if(!q_status
.m_explored
)
13047 q_status
.m_explored
= true;
13048 if (q_status
.uState
!= QUEST_NEW
)
13049 q_status
.uState
= QUEST_CHANGED
;
13052 if( CanCompleteQuest( questId
) )
13053 CompleteQuest( questId
);
13057 //not used in mangosd, function for external script library
13058 void Player::GroupEventHappens( uint32 questId
, WorldObject
const* pEventObject
)
13060 if( Group
*pGroup
= GetGroup() )
13062 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
13064 Player
*pGroupGuy
= itr
->getSource();
13066 // for any leave or dead (with not released body) group member at appropriate distance
13067 if( pGroupGuy
&& pGroupGuy
->IsAtGroupRewardDistance(pEventObject
) && !pGroupGuy
->GetCorpse() )
13068 pGroupGuy
->AreaExploredOrEventHappens(questId
);
13072 AreaExploredOrEventHappens(questId
);
13075 void Player::ItemAddedQuestCheck( uint32 entry
, uint32 count
)
13077 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13079 uint32 questid
= GetQuestSlotQuestId(i
);
13080 if ( questid
== 0 )
13083 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13085 if ( q_status
.m_status
!= QUEST_STATUS_INCOMPLETE
)
13088 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13089 if( !qInfo
|| !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13092 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13094 uint32 reqitem
= qInfo
->ReqItemId
[j
];
13095 if ( reqitem
== entry
)
13097 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
13098 uint32 curitemcount
= q_status
.m_itemcount
[j
];
13099 if ( curitemcount
< reqitemcount
)
13101 uint32 additemcount
= ( curitemcount
+ count
<= reqitemcount
? count
: reqitemcount
- curitemcount
);
13102 q_status
.m_itemcount
[j
] += additemcount
;
13103 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13105 SendQuestUpdateAddItem( qInfo
, j
, additemcount
);
13107 if ( CanCompleteQuest( questid
) )
13108 CompleteQuest( questid
);
13113 UpdateForQuestsGO();
13114 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM
, entry
);
13117 void Player::ItemRemovedQuestCheck( uint32 entry
, uint32 count
)
13119 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13121 uint32 questid
= GetQuestSlotQuestId(i
);
13124 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13127 if( !qInfo
->HasFlag( QUEST_MANGOS_FLAGS_DELIVER
) )
13130 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13132 uint32 reqitem
= qInfo
->ReqItemId
[j
];
13133 if ( reqitem
== entry
)
13135 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13137 uint32 reqitemcount
= qInfo
->ReqItemCount
[j
];
13138 uint32 curitemcount
;
13139 if( q_status
.m_status
!= QUEST_STATUS_COMPLETE
)
13140 curitemcount
= q_status
.m_itemcount
[j
];
13142 curitemcount
= GetItemCount(entry
,true);
13143 if ( curitemcount
< reqitemcount
+ count
)
13145 uint32 remitemcount
= ( curitemcount
<= reqitemcount
? count
: count
+ reqitemcount
- curitemcount
);
13146 q_status
.m_itemcount
[j
] = curitemcount
- remitemcount
;
13147 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13149 IncompleteQuest( questid
);
13155 UpdateForQuestsGO();
13158 void Player::KilledMonster( uint32 entry
, uint64 guid
)
13160 uint32 addkillcount
= 1;
13161 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE
, entry
, addkillcount
);
13162 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13164 uint32 questid
= GetQuestSlotQuestId(i
);
13168 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13171 // just if !ingroup || !noraidgroup || raidgroup
13172 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13173 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
&& (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo
->GetType() == QUEST_TYPE_RAID
))
13175 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
13177 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13179 // skip GO activate objective or none
13180 if(qInfo
->ReqCreatureOrGOId
[j
] <=0)
13183 // skip Cast at creature objective
13184 if(qInfo
->ReqSpell
[j
] !=0 )
13187 uint32 reqkill
= qInfo
->ReqCreatureOrGOId
[j
];
13189 if ( reqkill
== entry
)
13191 uint32 reqkillcount
= qInfo
->ReqCreatureOrGOCount
[j
];
13192 uint32 curkillcount
= q_status
.m_creatureOrGOcount
[j
];
13193 if ( curkillcount
< reqkillcount
)
13195 q_status
.m_creatureOrGOcount
[j
] = curkillcount
+ addkillcount
;
13196 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13198 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curkillcount
, addkillcount
);
13200 if ( CanCompleteQuest( questid
) )
13201 CompleteQuest( questid
);
13203 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13212 void Player::CastedCreatureOrGO( uint32 entry
, uint64 guid
, uint32 spell_id
)
13214 bool isCreature
= IS_CREATURE_GUID(guid
);
13216 uint32 addCastCount
= 1;
13217 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13219 uint32 questid
= GetQuestSlotQuestId(i
);
13223 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13227 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13229 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13231 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
) )
13233 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13235 // skip kill creature objective (0) or wrong spell casts
13236 if(qInfo
->ReqSpell
[j
] != spell_id
)
13239 uint32 reqTarget
= 0;
13243 // creature activate objectives
13244 if(qInfo
->ReqCreatureOrGOId
[j
] > 0)
13245 // checked at quest_template loading
13246 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
13250 // GO activate objective
13251 if(qInfo
->ReqCreatureOrGOId
[j
] < 0)
13252 // checked at quest_template loading
13253 reqTarget
= - qInfo
->ReqCreatureOrGOId
[j
];
13256 // other not this creature/GO related objectives
13257 if( reqTarget
!= entry
)
13260 uint32 reqCastCount
= qInfo
->ReqCreatureOrGOCount
[j
];
13261 uint32 curCastCount
= q_status
.m_creatureOrGOcount
[j
];
13262 if ( curCastCount
< reqCastCount
)
13264 q_status
.m_creatureOrGOcount
[j
] = curCastCount
+ addCastCount
;
13265 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13267 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curCastCount
, addCastCount
);
13270 if ( CanCompleteQuest( questid
) )
13271 CompleteQuest( questid
);
13273 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13281 void Player::TalkedToCreature( uint32 entry
, uint64 guid
)
13283 uint32 addTalkCount
= 1;
13284 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13286 uint32 questid
= GetQuestSlotQuestId(i
);
13290 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13294 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13296 if ( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13298 if( qInfo
->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST
| QUEST_MANGOS_FLAGS_SPEAKTO
) )
13300 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13302 // skip spell casts and Gameobject objectives
13303 if(qInfo
->ReqSpell
[j
] > 0 || qInfo
->ReqCreatureOrGOId
[j
] < 0)
13306 uint32 reqTarget
= 0;
13308 if(qInfo
->ReqCreatureOrGOId
[j
] > 0) // creature activate objectives
13309 // checked at quest_template loading
13310 reqTarget
= qInfo
->ReqCreatureOrGOId
[j
];
13314 if ( reqTarget
== entry
)
13316 uint32 reqTalkCount
= qInfo
->ReqCreatureOrGOCount
[j
];
13317 uint32 curTalkCount
= q_status
.m_creatureOrGOcount
[j
];
13318 if ( curTalkCount
< reqTalkCount
)
13320 q_status
.m_creatureOrGOcount
[j
] = curTalkCount
+ addTalkCount
;
13321 if (q_status
.uState
!= QUEST_NEW
) q_status
.uState
= QUEST_CHANGED
;
13323 SendQuestUpdateAddCreatureOrGo( qInfo
, guid
, j
, curTalkCount
, addTalkCount
);
13325 if ( CanCompleteQuest( questid
) )
13326 CompleteQuest( questid
);
13328 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13337 void Player::MoneyChanged( uint32 count
)
13339 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13341 uint32 questid
= GetQuestSlotQuestId(i
);
13345 Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
);
13346 if( qInfo
&& qInfo
->GetRewOrReqMoney() < 0 )
13348 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13350 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13352 if(int32(count
) >= -qInfo
->GetRewOrReqMoney())
13354 if ( CanCompleteQuest( questid
) )
13355 CompleteQuest( questid
);
13358 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
13360 if(int32(count
) < -qInfo
->GetRewOrReqMoney())
13361 IncompleteQuest( questid
);
13367 void Player::ReputationChanged(FactionEntry
const* factionEntry
)
13369 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13371 if(uint32 questid
= GetQuestSlotQuestId(i
))
13373 if(Quest
const* qInfo
= objmgr
.GetQuestTemplate(questid
))
13375 if(qInfo
->GetRepObjectiveFaction() == factionEntry
->ID
)
13377 QuestStatusData
& q_status
= mQuestStatus
[questid
];
13378 if( q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13380 if(GetReputationMgr().GetReputation(factionEntry
) >= qInfo
->GetRepObjectiveValue())
13381 if ( CanCompleteQuest( questid
) )
13382 CompleteQuest( questid
);
13384 else if( q_status
.m_status
== QUEST_STATUS_COMPLETE
)
13386 if(GetReputationMgr().GetReputation(factionEntry
) < qInfo
->GetRepObjectiveValue())
13387 IncompleteQuest( questid
);
13395 bool Player::HasQuestForItem( uint32 itemid
) const
13397 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
13399 uint32 questid
= GetQuestSlotQuestId(i
);
13400 if ( questid
== 0 )
13403 QuestStatusMap::const_iterator qs_itr
= mQuestStatus
.find(questid
);
13404 if(qs_itr
== mQuestStatus
.end())
13407 QuestStatusData
const& q_status
= qs_itr
->second
;
13409 if (q_status
.m_status
== QUEST_STATUS_INCOMPLETE
)
13411 Quest
const* qinfo
= objmgr
.GetQuestTemplate(questid
);
13415 // hide quest if player is in raid-group and quest is no raid quest
13416 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
13419 // There should be no mixed ReqItem/ReqSource drop
13420 // This part for ReqItem drop
13421 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
13423 if(itemid
== qinfo
->ReqItemId
[j
] && q_status
.m_itemcount
[j
] < qinfo
->ReqItemCount
[j
] )
13426 // This part - for ReqSource
13427 for (int j
= 0; j
< QUEST_SOURCE_ITEM_IDS_COUNT
; j
++)
13429 // examined item is a source item
13430 if (qinfo
->ReqSourceId
[j
] == itemid
)
13432 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype(itemid
);
13435 if (pProto
->MaxCount
&& GetItemCount(itemid
,true) < pProto
->MaxCount
)
13438 // allows custom amount drop when not 0
13439 if (qinfo
->ReqSourceCount
[j
])
13441 if (GetItemCount(itemid
,true) < qinfo
->ReqSourceCount
[j
])
13443 } else if (GetItemCount(itemid
,true) < pProto
->Stackable
)
13452 void Player::SendQuestComplete( uint32 quest_id
)
13456 WorldPacket
data( SMSG_QUESTUPDATE_COMPLETE
, 4 );
13457 data
<< uint32(quest_id
);
13458 GetSession()->SendPacket( &data
);
13459 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id
);
13463 void Player::SendQuestReward( Quest
const *pQuest
, uint32 XP
, Object
* questGiver
)
13465 uint32 questid
= pQuest
->GetQuestId();
13466 sLog
.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid
);
13467 WorldPacket
data( SMSG_QUESTGIVER_QUEST_COMPLETE
, (4+4+4+4+4) );
13468 data
<< uint32(questid
);
13470 if ( getLevel() < sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
) )
13472 data
<< uint32(XP
);
13473 data
<< uint32(pQuest
->GetRewOrReqMoney());
13478 data
<< uint32(pQuest
->GetRewOrReqMoney() + int32(pQuest
->GetRewMoneyMaxLevel() * sWorld
.getRate(RATE_DROP_MONEY
)));
13481 data
<< uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest
->GetRewHonorableKills()));
13482 data
<< uint32(pQuest
->GetBonusTalents()); // bonus talents
13483 GetSession()->SendPacket( &data
);
13485 if (pQuest
->GetQuestCompleteScript() != 0)
13486 sWorld
.ScriptsStart(sQuestEndScripts
, pQuest
->GetQuestCompleteScript(), questGiver
, this);
13489 void Player::SendQuestFailed( uint32 quest_id
)
13493 WorldPacket
data( SMSG_QUESTGIVER_QUEST_FAILED
, 4+4 );
13495 data
<< uint32(0); // failed reason (4 for inventory is full)
13496 GetSession()->SendPacket( &data
);
13497 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13501 void Player::SendQuestTimerFailed( uint32 quest_id
)
13505 WorldPacket
data( SMSG_QUESTUPDATE_FAILEDTIMER
, 4 );
13507 GetSession()->SendPacket( &data
);
13508 sLog
.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13512 void Player::SendCanTakeQuestResponse( uint32 msg
)
13514 WorldPacket
data( SMSG_QUESTGIVER_QUEST_INVALID
, 4 );
13515 data
<< uint32(msg
);
13516 GetSession()->SendPacket( &data
);
13517 sLog
.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13520 void Player::SendPushToPartyResponse( Player
*pPlayer
, uint32 msg
)
13524 WorldPacket
data( MSG_QUEST_PUSH_RESULT
, (8+1) );
13525 data
<< uint64(pPlayer
->GetGUID());
13526 data
<< uint8(msg
); // valid values: 0-8
13527 GetSession()->SendPacket( &data
);
13528 sLog
.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13532 void Player::SendQuestUpdateAddItem( Quest
const* pQuest
, uint32 item_idx
, uint32 count
)
13534 WorldPacket
data( SMSG_QUESTUPDATE_ADD_ITEM
, 0 );
13535 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13536 //data << pQuest->ReqItemId[item_idx];
13538 GetSession()->SendPacket( &data
);
13541 void Player::SendQuestUpdateAddCreatureOrGo( Quest
const* pQuest
, uint64 guid
, uint32 creatureOrGO_idx
, uint32 old_count
, uint32 add_count
)
13543 assert(old_count
+ add_count
< 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13545 int32 entry
= pQuest
->ReqCreatureOrGOId
[ creatureOrGO_idx
];
13547 // client expected gameobject template id in form (id|0x80000000)
13548 entry
= (-entry
) | 0x80000000;
13550 WorldPacket
data( SMSG_QUESTUPDATE_ADD_KILL
, (4*4+8) );
13551 sLog
.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13552 data
<< uint32(pQuest
->GetQuestId());
13553 data
<< uint32(entry
);
13554 data
<< uint32(old_count
+ add_count
);
13555 data
<< uint32(pQuest
->ReqCreatureOrGOCount
[ creatureOrGO_idx
]);
13556 data
<< uint64(guid
);
13557 GetSession()->SendPacket(&data
);
13559 uint16 log_slot
= FindQuestSlot( pQuest
->GetQuestId() );
13560 if( log_slot
< MAX_QUEST_LOG_SIZE
)
13561 SetQuestSlotCounter(log_slot
,creatureOrGO_idx
,GetQuestSlotCounter(log_slot
,creatureOrGO_idx
)+add_count
);
13564 /*********************************************************/
13565 /*** LOAD SYSTEM ***/
13566 /*********************************************************/
13568 bool Player::MinimalLoadFromDB( QueryResult
*result
, uint32 guid
)
13570 bool delete_result
= true;
13573 // 0 1 2 3 4 5 6 7 8 9
13574 result
= CharacterDatabase
.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid
);
13575 if(!result
) return false;
13577 else delete_result
= false;
13579 Field
*fields
= result
->Fetch();
13581 if(!LoadValues( fields
[1].GetString()))
13583 sLog
.outError("Player #%d have broken data in `data` field. Can't be loaded for character list.",GUID_LOPART(guid
));
13584 if(delete_result
) delete result
;
13588 // overwrite possible wrong/corrupted guid
13589 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
13591 m_name
= fields
[2].GetCppString();
13593 Relocate(fields
[3].GetFloat(),fields
[4].GetFloat(),fields
[5].GetFloat());
13594 SetMapId(fields
[6].GetUInt32());
13595 // the instance id is not needed at character enum
13597 m_Played_time
[0] = fields
[7].GetUInt32();
13598 m_Played_time
[1] = fields
[8].GetUInt32();
13600 m_atLoginFlags
= fields
[9].GetUInt32();
13602 // I don't see these used anywhere ..
13605 _LoadBoundInstances();*/
13607 if (delete_result
) delete result
;
13609 for (int i
= 0; i
< PLAYER_SLOTS_COUNT
; i
++)
13612 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
13613 m_deathState
= DEAD
;
13618 void Player::_LoadDeclinedNames(QueryResult
* result
)
13624 delete m_declinedname
;
13626 m_declinedname
= new DeclinedName
;
13627 Field
*fields
= result
->Fetch();
13628 for(int i
= 0; i
< MAX_DECLINED_NAME_CASES
; ++i
)
13629 m_declinedname
->name
[i
] = fields
[i
].GetCppString();
13634 void Player::_LoadArenaTeamInfo(QueryResult
*result
)
13636 // arenateamid, played_week, played_season, personal_rating
13637 memset((void*)&m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
], 0, sizeof(uint32
)*18);
13643 Field
*fields
= result
->Fetch();
13645 uint32 arenateamid
= fields
[0].GetUInt32();
13646 uint32 played_week
= fields
[1].GetUInt32();
13647 uint32 played_season
= fields
[2].GetUInt32();
13648 uint32 personal_rating
= fields
[3].GetUInt32();
13650 ArenaTeam
* aTeam
= objmgr
.GetArenaTeamById(arenateamid
);
13653 sLog
.outError("Player::_LoadArenaTeamInfo: couldn't load arenateam %u, week %u, season %u, rating %u", arenateamid
, played_week
, played_season
, personal_rating
);
13656 uint8 arenaSlot
= aTeam
->GetSlot();
13658 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6] = arenateamid
; // TeamID
13659 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 1] = ((aTeam
->GetCaptain() == GetGUID()) ? (uint32
)0 : (uint32
)1); // Captain 0, member 1
13660 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 2] = played_week
; // Played Week
13661 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 3] = played_season
; // Played Season
13662 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 4] = 0; // Unk
13663 m_uint32Values
[PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arenaSlot
* 6 + 5] = personal_rating
; // Personal Rating
13665 }while (result
->NextRow());
13669 bool Player::LoadPositionFromDB(uint32
& mapid
, float& x
,float& y
,float& z
,float& o
, bool& in_flight
, uint64 guid
)
13671 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid
));
13675 Field
*fields
= result
->Fetch();
13677 x
= fields
[0].GetFloat();
13678 y
= fields
[1].GetFloat();
13679 z
= fields
[2].GetFloat();
13680 o
= fields
[3].GetFloat();
13681 mapid
= fields
[4].GetUInt32();
13682 in_flight
= !fields
[5].GetCppString().empty();
13688 bool Player::LoadValuesArrayFromDB(Tokens
& data
, uint64 guid
)
13690 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid
));
13694 Field
*fields
= result
->Fetch();
13696 data
= StrSplit(fields
[0].GetCppString(), " ");
13703 uint32
Player::GetUInt32ValueFromArray(Tokens
const& data
, uint16 index
)
13705 if(index
>= data
.size())
13708 return (uint32
)atoi(data
[index
].c_str());
13711 float Player::GetFloatValueFromArray(Tokens
const& data
, uint16 index
)
13714 uint32 temp
= Player::GetUInt32ValueFromArray(data
,index
);
13715 memcpy(&result
, &temp
, sizeof(result
));
13720 uint32
Player::GetUInt32ValueFromDB(uint16 index
, uint64 guid
)
13723 if(!LoadValuesArrayFromDB(data
,guid
))
13726 return GetUInt32ValueFromArray(data
,index
);
13729 float Player::GetFloatValueFromDB(uint16 index
, uint64 guid
)
13732 uint32 temp
= Player::GetUInt32ValueFromDB(index
, guid
);
13733 memcpy(&result
, &temp
, sizeof(result
));
13738 bool Player::LoadFromDB( uint32 guid
, SqlQueryHolder
*holder
)
13740 //// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 [28] [29] 30 31 32 33 34 35 36 37 38 39 40
13741 //QueryResult *result = CharacterDatabase.PQuery("SELECT guid, account, data, name, race, class, position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, dungeon_difficulty, arena_pending_points,bgid,bgteam,bgmap,bgx,bgy,bgz,bgo FROM characters WHERE guid = '%u'", guid);
13742 QueryResult
*result
= holder
->GetResult(PLAYER_LOGIN_QUERY_LOADFROM
);
13746 sLog
.outError("Player (GUID: %u) not found in table `characters`, can't load. ",guid
);
13750 Field
*fields
= result
->Fetch();
13752 uint32 dbAccountId
= fields
[1].GetUInt32();
13754 // check if the character's account in the db and the logged in account match.
13755 // player should be able to load/delete character only with correct account!
13756 if( dbAccountId
!= GetSession()->GetAccountId() )
13758 sLog
.outError("Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid
,GetSession()->GetAccountId(),dbAccountId
);
13763 Object::_Create( guid
, 0, HIGHGUID_PLAYER
);
13765 m_name
= fields
[3].GetCppString();
13767 // check name limitations
13768 if(!ObjectMgr::IsValidName(m_name
) || GetSession()->GetSecurity() == SEC_PLAYER
&& objmgr
.IsReservedName(m_name
))
13771 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME
),guid
);
13775 if(!LoadValues( fields
[2].GetString()))
13777 sLog
.outError("Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid
));
13782 // overwrite possible wrong/corrupted guid
13783 SetUInt64Value(OBJECT_FIELD_GUID
, MAKE_NEW_GUID(guid
, 0, HIGHGUID_PLAYER
));
13785 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13786 for(uint8 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
13788 SetUInt64Value( (uint16
)(PLAYER_FIELD_INV_SLOT_HEAD
+ (slot
* 2) ), 0 );
13789 SetVisibleItemSlot(slot
,NULL
);
13793 delete m_items
[slot
];
13794 m_items
[slot
] = NULL
;
13798 // update money limits
13799 if(GetMoney() > MAX_MONEY_AMOUNT
)
13800 SetMoney(MAX_MONEY_AMOUNT
);
13802 sLog
.outDebug("Load Basic value of player %s is: ", m_name
.c_str());
13805 m_race
= fields
[4].GetUInt8();
13806 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13807 //Other way is to saves m_team into characters table.
13808 setFactionForRace(m_race
);
13811 m_class
= fields
[5].GetUInt8();
13813 // load home bind and check in same time class/race pair, it used later for restore broken positions
13814 if(!_LoadHomeBind(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND
)))
13817 InitPrimaryProffesions(); // to max set before any spell loaded
13819 // init saved position, and fix it later if problematic
13820 uint32 transGUID
= fields
[24].GetUInt32();
13821 Relocate(fields
[6].GetFloat(),fields
[7].GetFloat(),fields
[8].GetFloat(),fields
[10].GetFloat());
13822 SetMapId(fields
[9].GetUInt32());
13823 SetDifficulty(fields
[32].GetUInt32()); // may be changed in _LoadGroup
13825 _LoadGroup(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP
));
13827 _LoadArenaTeamInfo(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADARENAINFO
));
13829 uint32 arena_currency
= GetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
) + fields
[33].GetUInt32();
13830 if (arena_currency
> sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
))
13831 arena_currency
= sWorld
.getConfig(CONFIG_MAX_ARENA_POINTS
);
13833 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY
, arena_currency
);
13835 // check arena teams integrity
13836 for(uint32 arena_slot
= 0; arena_slot
< MAX_ARENA_SLOT
; ++arena_slot
)
13838 uint32 arena_team_id
= GetArenaTeamId(arena_slot
);
13842 if(ArenaTeam
* at
= objmgr
.GetArenaTeamById(arena_team_id
))
13843 if(at
->HaveMember(GetGUID()))
13846 // arena team not exist or not member, cleanup fields
13847 for(int j
=0; j
< 6; ++j
)
13848 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ arena_slot
* 6 + j
, 0);
13851 _LoadBoundInstances(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES
));
13853 if(!IsPositionValid())
13855 sLog
.outError("Player (guidlow %d) have invalid coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",guid
,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
13856 RelocateToHomebind();
13860 m_movementInfo
.t_x
= 0.0f
;
13861 m_movementInfo
.t_y
= 0.0f
;
13862 m_movementInfo
.t_z
= 0.0f
;
13863 m_movementInfo
.t_o
= 0.0f
;
13866 uint32 bgid
= fields
[34].GetUInt32();
13867 uint32 bgteam
= fields
[35].GetUInt32();
13869 if(bgid
) //saved in BattleGround
13871 SetBattleGroundEntryPoint(fields
[36].GetUInt32(),fields
[37].GetFloat(),fields
[38].GetFloat(),fields
[39].GetFloat(),fields
[40].GetFloat());
13873 // check entry point and fix to homebind if need
13874 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(m_bgEntryPoint
.mapid
);
13875 if(!mapEntry
|| mapEntry
->Instanceable() || !MapManager::IsValidMapCoord(m_bgEntryPoint
))
13876 SetBattleGroundEntryPoint(m_homebindMapId
,m_homebindX
,m_homebindY
,m_homebindZ
,0.0f
);
13878 BattleGround
*currentBg
= sBattleGroundMgr
.GetBattleGround(bgid
, BATTLEGROUND_TYPE_NONE
);
13880 if(currentBg
&& currentBg
->IsPlayerInBattleGround(GetGUID()))
13882 BattleGroundQueueTypeId bgQueueTypeId
= sBattleGroundMgr
.BGQueueTypeId(currentBg
->GetTypeID(), currentBg
->GetArenaType());
13883 uint32 queueSlot
= AddBattleGroundQueueId(bgQueueTypeId
);
13885 SetBattleGroundId(currentBg
->GetInstanceID(), currentBg
->GetTypeID());
13888 //join player to battleground group
13889 currentBg
->EventPlayerLoggedIn(this, GetGUID());
13890 currentBg
->AddOrSetPlayerToCorrectBgGroup(this, GetGUID(), bgteam
);
13892 SetInviteForBattleGroundQueueType(bgQueueTypeId
,currentBg
->GetInstanceID());
13896 Relocate(GetBattleGroundEntryPoint());
13897 //RemoveArenaAuras(true);
13902 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(GetMapId());
13903 // if server restart after player save in BG or area
13904 // player can have current coordinates in to BG/Arean map, fix this
13905 if(!mapEntry
|| mapEntry
->IsBattleGroundOrArena())
13907 // return to BG master
13908 SetMapId(fields
[36].GetUInt32());
13909 Relocate(fields
[37].GetFloat(),fields
[38].GetFloat(),fields
[39].GetFloat(),fields
[40].GetFloat());
13911 // check entry point and fix to homebind if need
13912 mapEntry
= sMapStore
.LookupEntry(GetMapId());
13913 if(!mapEntry
|| mapEntry
->IsBattleGroundOrArena() || !IsPositionValid())
13914 RelocateToHomebind();
13918 if (transGUID
!= 0)
13920 m_movementInfo
.t_x
= fields
[20].GetFloat();
13921 m_movementInfo
.t_y
= fields
[21].GetFloat();
13922 m_movementInfo
.t_z
= fields
[22].GetFloat();
13923 m_movementInfo
.t_o
= fields
[23].GetFloat();
13925 if( !MaNGOS::IsValidMapCoord(
13926 GetPositionX()+m_movementInfo
.t_x
,GetPositionY()+m_movementInfo
.t_y
,
13927 GetPositionZ()+m_movementInfo
.t_z
,GetOrientation()+m_movementInfo
.t_o
) ||
13928 // transport size limited
13929 m_movementInfo
.t_x
> 50 || m_movementInfo
.t_y
> 50 || m_movementInfo
.t_z
> 50 )
13931 sLog
.outError("Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
13932 guid
,GetPositionX()+m_movementInfo
.t_x
,GetPositionY()+m_movementInfo
.t_y
,
13933 GetPositionZ()+m_movementInfo
.t_z
,GetOrientation()+m_movementInfo
.t_o
);
13935 RelocateToHomebind();
13937 m_movementInfo
.t_x
= 0.0f
;
13938 m_movementInfo
.t_y
= 0.0f
;
13939 m_movementInfo
.t_z
= 0.0f
;
13940 m_movementInfo
.t_o
= 0.0f
;
13946 if (transGUID
!= 0)
13948 for (MapManager::TransportSet::iterator iter
= MapManager::Instance().m_Transports
.begin(); iter
!= MapManager::Instance().m_Transports
.end(); ++iter
)
13950 if( (*iter
)->GetGUIDLow() == transGUID
)
13952 MapEntry
const* transMapEntry
= sMapStore
.LookupEntry((*iter
)->GetMapId());
13953 // client without expansion support
13954 if(GetSession()->Expansion() < transMapEntry
->Expansion())
13956 sLog
.outDebug("Player %s using client without required expansion tried login at transport at non accessible map %u", GetName(), (*iter
)->GetMapId());
13960 m_transport
= *iter
;
13961 m_transport
->AddPassenger(this);
13962 SetMapId(m_transport
->GetMapId());
13969 sLog
.outError("Player (guidlow %d) have problems with transport guid (%u). Teleport to default race/class locations.",
13972 RelocateToHomebind();
13974 m_movementInfo
.t_x
= 0.0f
;
13975 m_movementInfo
.t_y
= 0.0f
;
13976 m_movementInfo
.t_z
= 0.0f
;
13977 m_movementInfo
.t_o
= 0.0f
;
13982 else // not transport case
13984 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(GetMapId());
13985 // client without expansion support
13986 if(GetSession()->Expansion() < mapEntry
->Expansion())
13988 sLog
.outDebug("Player %s using client without required expansion tried login at non accessible map %u", GetName(), GetMapId());
13989 RelocateToHomebind();
13993 // NOW player must have valid map
13994 // load the player's map here if it's not already loaded
13995 Map
*map
= GetMap();
13997 // since the player may not be bound to the map yet, make sure subsequent
13998 // getmap calls won't create new maps
13999 SetInstanceId(map
->GetInstanceId());
14001 // if the player is in an instance and it has been reset in the meantime teleport him to the entrance
14002 if(GetInstanceId() && !sInstanceSaveManager
.GetInstanceSave(GetInstanceId()))
14004 AreaTrigger
const* at
= objmgr
.GetMapEntranceTrigger(GetMapId());
14006 Relocate(at
->target_X
, at
->target_Y
, at
->target_Z
, at
->target_Orientation
);
14008 sLog
.outError("Player %s(GUID: %u) logged in to a reset instance (map: %u) and there is no aretrigger leading to this map. Thus he can't be ported back to the entrance. This _might_ be an exploit attempt.", GetName(), GetGUIDLow(), GetMapId());
14011 SaveRecallPosition();
14013 time_t now
= time(NULL
);
14014 time_t logoutTime
= time_t(fields
[16].GetUInt64());
14016 // since last logout (in seconds)
14017 uint64 time_diff
= uint64(now
- logoutTime
);
14019 // set value, including drunk invisibility detection
14020 // calculate sobering. after 15 minutes logged out, the player will be sober again
14022 if(time_diff
> 15*MINUTE
)
14025 soberFactor
= 1-time_diff
/(15.0f
*MINUTE
);
14026 uint16 newDrunkenValue
= uint16(soberFactor
*(GetUInt32Value(PLAYER_BYTES_3
) & 0xFFFE));
14027 SetDrunkValue(newDrunkenValue
);
14029 m_rest_bonus
= fields
[15].GetFloat();
14030 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
14031 float bubble0
= 0.031;
14032 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
14033 float bubble1
= 0.125;
14035 if((int32
)fields
[16].GetUInt32() > 0)
14037 float bubble
= fields
[17].GetUInt32() > 0
14038 ? bubble1
*sWorld
.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY
)
14039 : bubble0
*sWorld
.getRate(RATE_REST_OFFLINE_IN_WILDERNESS
);
14041 SetRestBonus(GetRestBonus()+ time_diff
*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)/72000)*bubble
);
14044 m_cinematic
= fields
[12].GetUInt32();
14045 m_Played_time
[0]= fields
[13].GetUInt32();
14046 m_Played_time
[1]= fields
[14].GetUInt32();
14048 m_resetTalentsCost
= fields
[18].GetUInt32();
14049 m_resetTalentsTime
= time_t(fields
[19].GetUInt64());
14051 // reserve some flags
14052 uint32 old_safe_flags
= GetUInt32Value(PLAYER_FLAGS
) & ( PLAYER_FLAGS_HIDE_CLOAK
| PLAYER_FLAGS_HIDE_HELM
);
14054 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GM
) )
14055 SetUInt32Value(PLAYER_FLAGS
, 0 | old_safe_flags
);
14057 m_taxi
.LoadTaxiMask( fields
[11].GetString() ); // must be before InitTaxiNodesForLevel
14059 uint32 extraflags
= fields
[25].GetUInt32();
14061 m_stableSlots
= fields
[26].GetUInt32();
14062 if(m_stableSlots
> 4)
14064 sLog
.outError("Player can have not more 4 stable slots, but have in DB %u",uint32(m_stableSlots
));
14068 m_atLoginFlags
= fields
[27].GetUInt32();
14071 // Update Honor kills data
14072 m_lastHonorUpdateTime
= logoutTime
;
14073 UpdateHonorFields();
14075 m_deathExpireTime
= (time_t)fields
[30].GetUInt64();
14076 if(m_deathExpireTime
> now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
)
14077 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
-1;
14079 std::string taxi_nodes
= fields
[31].GetCppString();
14083 // clear channel spell data (if saved at channel spell casting)
14084 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT
, 0);
14085 SetUInt32Value(UNIT_CHANNEL_SPELL
,0);
14087 // clear charm/summon related fields
14094 // reset some aura modifiers before aura apply
14095 SetFarSightGUID(0);
14096 SetUInt32Value(PLAYER_TRACK_CREATURES
, 0 );
14097 SetUInt32Value(PLAYER_TRACK_RESOURCES
, 0 );
14101 // make sure the unit is considered out of combat for proper loading
14104 // make sure the unit is considered not in duel for proper loading
14105 SetUInt64Value(PLAYER_DUEL_ARBITER
, 0);
14106 SetUInt32Value(PLAYER_DUEL_TEAM
, 0);
14108 // remember loaded power/health values to restore after stats initialization and modifier applying
14109 uint32 savedHealth
= GetHealth();
14110 uint32 savedPower
[MAX_POWERS
];
14111 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
14112 savedPower
[i
] = GetPower(Powers(i
));
14114 // reset stats before loading any modifiers
14115 InitStatsForLevel();
14116 InitTaxiNodesForLevel();
14117 InitGlyphsForLevel();
14120 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14122 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14125 _LoadAuras(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS
), time_diff
);
14128 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14129 if( HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_GHOST
) )
14130 m_deathState
= DEAD
;
14132 _LoadSpells(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS
));
14134 // after spell load, learn rewarded spell if need also
14135 _LoadQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS
));
14136 _LoadDailyQuestStatus(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS
));
14138 // after spell and quest load
14139 InitTalentForLevel();
14140 learnDefaultSpells();
14142 _LoadTutorials(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS
));
14144 // must be before inventory (some items required reputation check)
14145 m_reputationMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION
));
14147 _LoadInventory(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY
), time_diff
);
14149 // update items with duration and realtime
14150 UpdateItemDuration(time_diff
, true);
14152 _LoadActions(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS
));
14154 // unread mails and next delivery time, actual mails not loaded
14155 _LoadMailInit(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT
), holder
->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE
));
14157 m_social
= sSocialMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST
), GetGUIDLow());
14159 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14160 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14161 if(uint32 curTitle
= GetUInt32Value(PLAYER_CHOSEN_TITLE
))
14163 if(!HasTitle(curTitle
))
14164 SetUInt32Value(PLAYER_CHOSEN_TITLE
,0);
14167 // Not finish taxi flight path
14168 if(!m_taxi
.LoadTaxiDestinationsFromString(taxi_nodes
,GetTeam()))
14170 // problems with taxi path loading
14171 TaxiNodesEntry
const* nodeEntry
= NULL
;
14172 if(uint32 node_id
= m_taxi
.GetTaxiSource())
14173 nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
14175 if(!nodeEntry
) // don't know taxi start node, to homebind
14177 sLog
.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14178 RelocateToHomebind();
14179 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14181 else // have start node, to it
14183 sLog
.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14184 SetMapId(nodeEntry
->map_id
);
14185 Relocate(nodeEntry
->x
, nodeEntry
->y
, nodeEntry
->z
,0.0f
);
14186 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14188 m_taxi
.ClearTaxiDestinations();
14190 else if(uint32 node_id
= m_taxi
.GetTaxiSource())
14192 // save source node as recall coord to prevent recall and fall from sky
14193 TaxiNodesEntry
const* nodeEntry
= sTaxiNodesStore
.LookupEntry(node_id
);
14194 assert(nodeEntry
); // checked in m_taxi.LoadTaxiDestinationsFromString
14195 m_recallMap
= nodeEntry
->map_id
;
14196 m_recallX
= nodeEntry
->x
;
14197 m_recallY
= nodeEntry
->y
;
14198 m_recallZ
= nodeEntry
->z
;
14200 // flight will started later
14203 // has to be called after last Relocate() in Player::LoadFromDB
14204 SetFallInformation(0, GetPositionZ());
14206 _LoadSpellCooldowns(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS
));
14208 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14209 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14211 RemoveAllAurasOnDeath();
14213 //apply all stat bonuses from items and auras
14214 SetCanModifyStats(true);
14217 // restore remembered power/health values (but not more max values)
14218 SetHealth(savedHealth
> GetMaxHealth() ? GetMaxHealth() : savedHealth
);
14219 for(uint32 i
= 0; i
< MAX_POWERS
; ++i
)
14220 SetPower(Powers(i
),savedPower
[i
] > GetMaxPower(Powers(i
)) ? GetMaxPower(Powers(i
)) : savedPower
[i
]);
14222 sLog
.outDebug("The value of player %s after load item and aura is: ", m_name
.c_str());
14226 if(GetSession()->GetSecurity() > SEC_PLAYER
)
14228 switch(sWorld
.getConfig(CONFIG_GM_LOGIN_STATE
))
14231 case 0: break; // disable
14232 case 1: SetGameMaster(true); break; // enable
14233 case 2: // save state
14234 if(extraflags
& PLAYER_EXTRA_GM_ON
)
14235 SetGameMaster(true);
14239 switch(sWorld
.getConfig(CONFIG_GM_VISIBLE_STATE
))
14242 case 0: SetGMVisible(false); break; // invisible
14243 case 1: break; // visible
14244 case 2: // save state
14245 if(extraflags
& PLAYER_EXTRA_GM_INVISIBLE
)
14246 SetGMVisible(false);
14250 switch(sWorld
.getConfig(CONFIG_GM_ACCEPT_TICKETS
))
14253 case 0: break; // disable
14254 case 1: SetAcceptTicket(true); break; // enable
14255 case 2: // save state
14256 if(extraflags
& PLAYER_EXTRA_GM_ACCEPT_TICKETS
)
14257 SetAcceptTicket(true);
14261 switch(sWorld
.getConfig(CONFIG_GM_CHAT
))
14264 case 0: break; // disable
14265 case 1: SetGMChat(true); break; // enable
14266 case 2: // save state
14267 if(extraflags
& PLAYER_EXTRA_GM_CHAT
)
14272 switch(sWorld
.getConfig(CONFIG_GM_WISPERING_TO
))
14275 case 0: break; // disable
14276 case 1: SetAcceptWhispers(true); break; // enable
14277 case 2: // save state
14278 if(extraflags
& PLAYER_EXTRA_ACCEPT_WHISPERS
)
14279 SetAcceptWhispers(true);
14284 _LoadDeclinedNames(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES
));
14286 m_achievementMgr
.LoadFromDB(holder
->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS
), holder
->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS
));
14287 m_achievementMgr
.CheckAllAchievementCriteria();
14291 bool Player::isAllowedToLoot(Creature
* creature
)
14293 if(Player
* recipient
= creature
->GetLootRecipient())
14295 if (recipient
== this)
14297 if( Group
* otherGroup
= recipient
->GetGroup())
14299 Group
* thisGroup
= GetGroup();
14302 return thisGroup
== otherGroup
;
14307 // prevent other players from looting if the recipient got disconnected
14308 return !creature
->hasLootRecipient();
14311 void Player::_LoadActions(QueryResult
*result
)
14313 m_actionButtons
.clear();
14315 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14321 Field
*fields
= result
->Fetch();
14323 uint8 button
= fields
[0].GetUInt8();
14325 if(addActionButton(button
, fields
[1].GetUInt16(), fields
[2].GetUInt8(), fields
[3].GetUInt8()))
14326 m_actionButtons
[button
].uState
= ACTIONBUTTON_UNCHANGED
;
14329 sLog
.outError( " ...at loading, and will deleted in DB also");
14331 // Will deleted in DB at next save (it can create data until save but marked as deleted)
14332 m_actionButtons
[button
].uState
= ACTIONBUTTON_DELETED
;
14335 while( result
->NextRow() );
14341 void Player::_LoadAuras(QueryResult
*result
, uint32 timediff
)
14344 for (int i
= 0; i
< TOTAL_AURAS
; i
++)
14345 m_modAuras
[i
].clear();
14347 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14353 Field
*fields
= result
->Fetch();
14354 uint64 caster_guid
= fields
[0].GetUInt64();
14355 uint32 spellid
= fields
[1].GetUInt32();
14356 uint32 effindex
= fields
[2].GetUInt32();
14357 uint32 stackcount
= fields
[3].GetUInt32();
14358 int32 damage
= (int32
)fields
[4].GetUInt32();
14359 int32 maxduration
= (int32
)fields
[5].GetUInt32();
14360 int32 remaintime
= (int32
)fields
[6].GetUInt32();
14361 int32 remaincharges
= (int32
)fields
[7].GetUInt32();
14363 SpellEntry
const* spellproto
= sSpellStore
.LookupEntry(spellid
);
14366 sLog
.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid
,effindex
);
14372 sLog
.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid
,effindex
);
14376 // negative effects should continue counting down after logout
14377 if (remaintime
!= -1 && !IsPositiveEffect(spellid
, effindex
))
14379 if(remaintime
<= int32(timediff
))
14382 remaintime
-= timediff
;
14385 // prevent wrong values of remaincharges
14386 if(spellproto
->procCharges
)
14388 if(remaincharges
<= 0 || remaincharges
> spellproto
->procCharges
)
14389 remaincharges
= spellproto
->procCharges
;
14395 for(uint32 i
=0; i
<stackcount
; i
++)
14397 Aura
* aura
= CreateAura(spellproto
, effindex
, NULL
, this, NULL
);
14399 damage
= aura
->GetModifier()->m_amount
;
14401 // reset stolen single target auras
14402 if (caster_guid
!= GetGUID() && aura
->IsSingleTarget())
14403 aura
->SetIsSingleTarget(false);
14405 aura
->SetLoadedState(caster_guid
,damage
,maxduration
,remaintime
,remaincharges
);
14407 sLog
.outDetail("Added aura spellid %u, effect %u", spellproto
->Id
, effindex
);
14410 while( result
->NextRow() );
14415 if(m_class
== CLASS_WARRIOR
)
14416 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE
,true);
14419 void Player::_LoadGlyphAuras()
14421 for (uint8 i
= 0; i
< MAX_GLYPH_SLOT_INDEX
; ++i
)
14423 if (uint32 glyph
= GetGlyph(i
))
14425 if (GlyphPropertiesEntry
const *gp
= sGlyphPropertiesStore
.LookupEntry(glyph
))
14427 if (GlyphSlotEntry
const *gs
= sGlyphSlotStore
.LookupEntry(GetGlyphSlot(i
)))
14429 if(gp
->TypeFlags
== gs
->TypeFlags
)
14431 CastSpell(this, gp
->SpellId
, true);
14435 sLog
.outError("Player %s has glyph with typeflags %u in slot with typeflags %u, removing.", m_name
.c_str(), gp
->TypeFlags
, gs
->TypeFlags
);
14438 sLog
.outError("Player %s has not existing glyph slot entry %u on index %u", m_name
.c_str(), GetGlyphSlot(i
), i
);
14441 sLog
.outError("Player %s has not existing glyph entry %u on index %u", m_name
.c_str(), glyph
, i
);
14443 // On any error remove glyph
14449 void Player::LoadCorpse()
14453 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14457 if(Corpse
*corpse
= GetCorpse())
14459 ApplyModFlag(PLAYER_FIELD_BYTES
, PLAYER_FIELD_BYTE_RELEASE_TIMER
, corpse
&& !sMapStore
.LookupEntry(corpse
->GetMapId())->Instanceable() );
14463 //Prevent Dead Player login without corpse
14464 ResurrectPlayer(0.5f
);
14469 void Player::_LoadInventory(QueryResult
*result
, uint32 timediff
)
14471 //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());
14472 std::map
<uint64
, Bag
*> bagMap
; // fast guid lookup for bags
14473 //NOTE: the "order by `bag`" is important because it makes sure
14474 //the bagMap is filled before items in the bags are loaded
14475 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14476 //expected to be equipped before offhand items (TODO: fixme)
14478 uint32 zone
= GetZoneId();
14482 std::list
<Item
*> problematicItems
;
14484 // prevent items from being added to the queue when stored
14485 m_itemUpdateQueueBlocked
= true;
14488 Field
*fields
= result
->Fetch();
14489 uint32 bag_guid
= fields
[1].GetUInt32();
14490 uint8 slot
= fields
[2].GetUInt8();
14491 uint32 item_guid
= fields
[3].GetUInt32();
14492 uint32 item_id
= fields
[4].GetUInt32();
14494 ItemPrototype
const * proto
= objmgr
.GetItemPrototype(item_id
);
14498 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14499 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid
);
14500 sLog
.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id
);
14504 Item
*item
= NewItemOrBag(proto
);
14506 if(!item
->LoadFromDB(item_guid
, GetGUID(), result
))
14508 sLog
.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id
);
14509 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14510 item
->FSetState(ITEM_REMOVED
);
14511 item
->SaveToDB(); // it also deletes item object !
14515 // not allow have in alive state item limited to another map/zone
14516 if(isAlive() && item
->IsLimitedToAnotherMapOrZone(GetMapId(),zone
) )
14518 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14519 item
->FSetState(ITEM_REMOVED
);
14520 item
->SaveToDB(); // it also deletes item object !
14524 // "Conjured items disappear if you are logged out for more than 15 minutes"
14525 if ((timediff
> 15*60) && (item
->HasFlag(ITEM_FIELD_FLAGS
, ITEM_FLAGS_CONJURED
)))
14527 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14528 item
->FSetState(ITEM_REMOVED
);
14529 item
->SaveToDB(); // it also deletes item object !
14533 bool success
= true;
14537 // the item is not in a bag
14538 item
->SetContainer( NULL
);
14539 item
->SetSlot(slot
);
14541 if( IsInventoryPos( INVENTORY_SLOT_BAG_0
, slot
) )
14543 ItemPosCountVec dest
;
14544 if( CanStoreItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false ) == EQUIP_ERR_OK
)
14545 item
= StoreItem(dest
, item
, true);
14549 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0
, slot
) )
14552 if( CanEquipItem( slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
14553 QuickEquipItem(dest
, item
);
14557 else if( IsBankPos( INVENTORY_SLOT_BAG_0
, slot
) )
14559 ItemPosCountVec dest
;
14560 if( CanBankItem( INVENTORY_SLOT_BAG_0
, slot
, dest
, item
, false, false ) == EQUIP_ERR_OK
)
14561 item
= BankItem(dest
, item
, true);
14568 // store bags that may contain items in them
14569 if(item
->IsBag() && IsBagPos(item
->GetPos()))
14570 bagMap
[item_guid
] = (Bag
*)item
;
14575 item
->SetSlot(NULL_SLOT
);
14576 // the item is in a bag, find the bag
14577 std::map
<uint64
, Bag
*>::iterator itr
= bagMap
.find(bag_guid
);
14578 if(itr
!= bagMap
.end())
14579 itr
->second
->StoreItem(slot
, item
, true );
14584 // item's state may have changed after stored
14586 item
->SetState(ITEM_UNCHANGED
, this);
14589 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
);
14590 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid
);
14591 problematicItems
.push_back(item
);
14593 } while (result
->NextRow());
14596 m_itemUpdateQueueBlocked
= false;
14598 // send by mail problematic items
14599 while(!problematicItems
.empty())
14602 MailItemsInfo mi
; // item list preparing
14604 for(int i
= 0; !problematicItems
.empty() && i
< MAX_MAIL_ITEMS
; ++i
)
14606 Item
* item
= problematicItems
.front();
14607 problematicItems
.pop_front();
14609 mi
.AddItem(item
->GetGUIDLow(), item
->GetEntry(), item
);
14612 std::string subject
= GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM
);
14614 WorldSession::SendMailTo(this, MAIL_NORMAL
, MAIL_STATIONERY_GM
, GetGUIDLow(), GetGUIDLow(), subject
, 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
);
14618 _ApplyAllItemMods();
14621 // load mailed item which should receive current player
14622 void Player::_LoadMailedItems(Mail
*mail
)
14624 // data needs to be at first place for Item::LoadFromDB
14625 QueryResult
* result
= CharacterDatabase
.PQuery("SELECT data, item_guid, item_template FROM mail_items JOIN item_instance ON item_guid = guid WHERE mail_id='%u'", mail
->messageID
);
14631 Field
*fields
= result
->Fetch();
14632 uint32 item_guid_low
= fields
[1].GetUInt32();
14633 uint32 item_template
= fields
[2].GetUInt32();
14635 mail
->AddItem(item_guid_low
, item_template
);
14637 ItemPrototype
const *proto
= objmgr
.GetItemPrototype(item_template
);
14641 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
);
14642 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
14643 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low
);
14647 Item
*item
= NewItemOrBag(proto
);
14649 if(!item
->LoadFromDB(item_guid_low
, 0, result
))
14651 sLog
.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail
->messageID
, item_guid_low
);
14652 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low
);
14653 item
->FSetState(ITEM_REMOVED
);
14654 item
->SaveToDB(); // it also deletes item object !
14659 } while (result
->NextRow());
14664 void Player::_LoadMailInit(QueryResult
*resultUnread
, QueryResult
*resultDelivery
)
14666 //set a count of unread mails
14667 //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);
14670 Field
*fieldMail
= resultUnread
->Fetch();
14671 unReadMails
= fieldMail
[0].GetUInt8();
14672 delete resultUnread
;
14675 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14676 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14677 if (resultDelivery
)
14679 Field
*fieldMail
= resultDelivery
->Fetch();
14680 m_nextMailDelivereTime
= (time_t)fieldMail
[0].GetUInt64();
14681 delete resultDelivery
;
14685 void Player::_LoadMail()
14688 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14689 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());
14694 Field
*fields
= result
->Fetch();
14695 Mail
*m
= new Mail
;
14696 m
->messageID
= fields
[0].GetUInt32();
14697 m
->messageType
= fields
[1].GetUInt8();
14698 m
->sender
= fields
[2].GetUInt32();
14699 m
->receiver
= fields
[3].GetUInt32();
14700 m
->subject
= fields
[4].GetCppString();
14701 m
->itemTextId
= fields
[5].GetUInt32();
14702 bool has_items
= fields
[6].GetBool();
14703 m
->expire_time
= (time_t)fields
[7].GetUInt64();
14704 m
->deliver_time
= (time_t)fields
[8].GetUInt64();
14705 m
->money
= fields
[9].GetUInt32();
14706 m
->COD
= fields
[10].GetUInt32();
14707 m
->checked
= fields
[11].GetUInt32();
14708 m
->stationery
= fields
[12].GetUInt8();
14709 m
->mailTemplateId
= fields
[13].GetInt16();
14711 if(m
->mailTemplateId
&& !sMailTemplateStore
.LookupEntry(m
->mailTemplateId
))
14713 sLog
.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m
->messageID
, m
->mailTemplateId
);
14714 m
->mailTemplateId
= 0;
14717 m
->state
= MAIL_STATE_UNCHANGED
;
14720 _LoadMailedItems(m
);
14722 m_mail
.push_back(m
);
14723 } while( result
->NextRow() );
14726 m_mailsLoaded
= true;
14729 void Player::LoadPet()
14731 //fixme: the pet should still be loaded if the player is not in world
14732 // just not added to the map
14735 Pet
*pet
= new Pet
;
14736 if(!pet
->LoadPetFromDB(this,0,0,true))
14741 void Player::_LoadQuestStatus(QueryResult
*result
)
14743 mQuestStatus
.clear();
14747 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14748 //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());
14754 Field
*fields
= result
->Fetch();
14756 uint32 quest_id
= fields
[0].GetUInt32();
14757 // used to be new, no delete?
14758 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
14762 QuestStatusData
& questStatusData
= mQuestStatus
[quest_id
];
14764 uint32 qstatus
= fields
[1].GetUInt32();
14765 if(qstatus
< MAX_QUEST_STATUS
)
14766 questStatusData
.m_status
= QuestStatus(qstatus
);
14769 questStatusData
.m_status
= QUEST_STATUS_NONE
;
14770 sLog
.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id
,qstatus
);
14773 questStatusData
.m_rewarded
= ( fields
[2].GetUInt8() > 0 );
14774 questStatusData
.m_explored
= ( fields
[3].GetUInt8() > 0 );
14776 time_t quest_time
= time_t(fields
[4].GetUInt64());
14778 if( pQuest
->HasFlag( QUEST_MANGOS_FLAGS_TIMED
) && !GetQuestRewardStatus(quest_id
) && questStatusData
.m_status
!= QUEST_STATUS_NONE
)
14780 AddTimedQuest( quest_id
);
14782 if (quest_time
<= sWorld
.GetGameTime())
14783 questStatusData
.m_timer
= 1;
14785 questStatusData
.m_timer
= (quest_time
- sWorld
.GetGameTime()) * IN_MILISECONDS
;
14790 questStatusData
.m_creatureOrGOcount
[0] = fields
[5].GetUInt32();
14791 questStatusData
.m_creatureOrGOcount
[1] = fields
[6].GetUInt32();
14792 questStatusData
.m_creatureOrGOcount
[2] = fields
[7].GetUInt32();
14793 questStatusData
.m_creatureOrGOcount
[3] = fields
[8].GetUInt32();
14794 questStatusData
.m_itemcount
[0] = fields
[9].GetUInt32();
14795 questStatusData
.m_itemcount
[1] = fields
[10].GetUInt32();
14796 questStatusData
.m_itemcount
[2] = fields
[11].GetUInt32();
14797 questStatusData
.m_itemcount
[3] = fields
[12].GetUInt32();
14799 questStatusData
.uState
= QUEST_UNCHANGED
;
14801 // add to quest log
14802 if( slot
< MAX_QUEST_LOG_SIZE
&&
14803 ( questStatusData
.m_status
==QUEST_STATUS_INCOMPLETE
||
14804 questStatusData
.m_status
==QUEST_STATUS_COMPLETE
&&
14805 (!questStatusData
.m_rewarded
|| pQuest
->IsDaily()) ) )
14807 SetQuestSlot(slot
,quest_id
,quest_time
);
14809 if(questStatusData
.m_status
== QUEST_STATUS_COMPLETE
)
14810 SetQuestSlotState(slot
,QUEST_STATE_COMPLETE
);
14812 for(uint8 idx
= 0; idx
< QUEST_OBJECTIVES_COUNT
; ++idx
)
14813 if(questStatusData
.m_creatureOrGOcount
[idx
])
14814 SetQuestSlotCounter(slot
,idx
,questStatusData
.m_creatureOrGOcount
[idx
]);
14819 if(questStatusData
.m_rewarded
)
14821 // learn rewarded spell if unknown
14822 learnQuestRewardedSpells(pQuest
);
14824 // set rewarded title if any
14825 if(pQuest
->GetCharTitleId())
14827 if(CharTitlesEntry
const* titleEntry
= sCharTitlesStore
.LookupEntry(pQuest
->GetCharTitleId()))
14828 SetTitle(titleEntry
);
14831 if(pQuest
->GetBonusTalents())
14832 m_questRewardTalentCount
+=pQuest
->GetBonusTalents();
14835 sLog
.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData
.m_status
, quest_id
, GetGUIDLow());
14838 while( result
->NextRow() );
14843 // clear quest log tail
14844 for ( uint16 i
= slot
; i
< MAX_QUEST_LOG_SIZE
; ++i
)
14848 void Player::_LoadDailyQuestStatus(QueryResult
*result
)
14850 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
14851 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
14853 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14857 uint32 quest_daily_idx
= 0;
14861 if(quest_daily_idx
>= PLAYER_MAX_DAILY_QUESTS
) // max amount with exist data in query
14863 sLog
.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
14867 Field
*fields
= result
->Fetch();
14869 uint32 quest_id
= fields
[0].GetUInt32();
14871 // save _any_ from daily quest times (it must be after last reset anyway)
14872 m_lastDailyQuestTime
= (time_t)fields
[1].GetUInt64();
14874 Quest
const* pQuest
= objmgr
.GetQuestTemplate(quest_id
);
14878 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
14881 sLog
.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id
, GetGUIDLow());
14883 while( result
->NextRow() );
14888 m_DailyQuestChanged
= false;
14891 void Player::_LoadSpells(QueryResult
*result
)
14893 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,active,disabled FROM character_spell WHERE guid = '%u'",GetGUIDLow());
14899 Field
*fields
= result
->Fetch();
14901 addSpell(fields
[0].GetUInt16(), fields
[1].GetBool(), false, false, fields
[2].GetBool());
14903 while( result
->NextRow() );
14909 void Player::_LoadTutorials(QueryResult
*result
)
14911 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
14917 Field
*fields
= result
->Fetch();
14919 for (int iI
=0; iI
<8; iI
++)
14920 m_Tutorials
[iI
] = fields
[iI
].GetUInt32();
14922 while( result
->NextRow() );
14927 m_TutorialsChanged
= false;
14930 void Player::_LoadGroup(QueryResult
*result
)
14932 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
14935 uint64 leaderGuid
= MAKE_NEW_GUID((*result
)[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
14937 Group
* group
= objmgr
.GetGroupByLeader(leaderGuid
);
14940 uint8 subgroup
= group
->GetMemberGroup(GetGUID());
14941 SetGroup(group
, subgroup
);
14942 if(getLevel() >= LEVELREQUIREMENT_HEROIC
)
14944 // the group leader may change the instance difficulty while the player is offline
14945 SetDifficulty(group
->GetDifficulty());
14951 void Player::_LoadBoundInstances(QueryResult
*result
)
14953 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
14954 m_boundInstances
[i
].clear();
14956 Group
*group
= GetGroup();
14958 //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));
14963 Field
*fields
= result
->Fetch();
14964 bool perm
= fields
[1].GetBool();
14965 uint32 mapId
= fields
[2].GetUInt32();
14966 uint32 instanceId
= fields
[0].GetUInt32();
14967 uint8 difficulty
= fields
[3].GetUInt8();
14968 time_t resetTime
= (time_t)fields
[4].GetUInt64();
14969 // the resettime for normal instances is only saved when the InstanceSave is unloaded
14970 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
14971 // and in that case it is not used
14973 MapEntry
const* mapEntry
= sMapStore
.LookupEntry(mapId
);
14974 if(!mapEntry
|| !mapEntry
->IsDungeon())
14976 sLog
.outError("_LoadBoundInstances: player %s(%d) has bind to not existed or not dungeon map %d", GetName(), GetGUIDLow(), mapId
);
14977 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
14983 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
);
14984 CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId
);
14988 // since non permanent binds are always solo bind, they can always be reset
14989 InstanceSave
*save
= sInstanceSaveManager
.AddInstanceSave(mapId
, instanceId
, difficulty
, resetTime
, !perm
, true);
14990 if(save
) BindToInstance(save
, perm
, true);
14991 } while(result
->NextRow());
14996 InstancePlayerBind
* Player::GetBoundInstance(uint32 mapid
, uint8 difficulty
)
14998 // some instances only have one difficulty
14999 const MapEntry
* entry
= sMapStore
.LookupEntry(mapid
);
15000 if(!entry
|| !entry
->SupportsHeroicMode()) difficulty
= DIFFICULTY_NORMAL
;
15002 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
15003 if(itr
!= m_boundInstances
[difficulty
].end())
15004 return &itr
->second
;
15009 void Player::UnbindInstance(uint32 mapid
, uint8 difficulty
, bool unload
)
15011 BoundInstancesMap::iterator itr
= m_boundInstances
[difficulty
].find(mapid
);
15012 UnbindInstance(itr
, difficulty
, unload
);
15015 void Player::UnbindInstance(BoundInstancesMap::iterator
&itr
, uint8 difficulty
, bool unload
)
15017 if(itr
!= m_boundInstances
[difficulty
].end())
15019 if(!unload
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr
->second
.save
->GetInstanceId());
15020 itr
->second
.save
->RemovePlayer(this); // save can become invalid
15021 m_boundInstances
[difficulty
].erase(itr
++);
15025 InstancePlayerBind
* Player::BindToInstance(InstanceSave
*save
, bool permanent
, bool load
)
15029 InstancePlayerBind
& bind
= m_boundInstances
[save
->GetDifficulty()][save
->GetMapId()];
15032 // update the save when the group kills a boss
15033 if(permanent
!= bind
.perm
|| save
!= bind
.save
)
15034 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());
15037 if(!load
) CharacterDatabase
.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save
->GetInstanceId(), permanent
);
15039 if(bind
.save
!= save
)
15041 if(bind
.save
) bind
.save
->RemovePlayer(this);
15042 save
->AddPlayer(this);
15045 if(permanent
) save
->SetCanReset(false);
15048 bind
.perm
= permanent
;
15049 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());
15056 void Player::SendRaidInfo()
15058 uint32 counter
= 0;
15060 WorldPacket
data(SMSG_RAID_INSTANCE_INFO
, 4);
15062 size_t p_counter
= data
.wpos();
15063 data
<< uint32(counter
); // placeholder
15065 for(int i
= 0; i
< TOTAL_DIFFICULTIES
; ++i
)
15067 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15069 if(itr
->second
.perm
)
15071 InstanceSave
*save
= itr
->second
.save
;
15072 data
<< uint32(save
->GetMapId());
15073 data
<< uint32(save
->GetResetTime() - time(NULL
));
15074 data
<< uint32(save
->GetInstanceId());
15075 data
<< uint32(save
->GetDifficulty());
15080 data
.put
<uint32
>(p_counter
,counter
);
15081 GetSession()->SendPacket(&data
);
15085 - called on every successful teleportation to a map
15087 void Player::SendSavedInstances()
15089 bool hasBeenSaved
= false;
15092 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15094 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15096 if(itr
->second
.perm
) // only permanent binds are sent
15098 hasBeenSaved
= true;
15104 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15105 data
.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP
);
15106 data
<< uint32(hasBeenSaved
);
15107 GetSession()->SendPacket(&data
);
15112 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15114 for (BoundInstancesMap::iterator itr
= m_boundInstances
[i
].begin(); itr
!= m_boundInstances
[i
].end(); ++itr
)
15116 if(itr
->second
.perm
)
15118 data
.Initialize(SMSG_UPDATE_LAST_INSTANCE
);
15119 data
<< uint32(itr
->second
.save
->GetMapId());
15120 GetSession()->SendPacket(&data
);
15126 /// convert the player's binds to the group
15127 void Player::ConvertInstancesToGroup(Player
*player
, Group
*group
, uint64 player_guid
)
15129 bool has_binds
= false;
15130 bool has_solo
= false;
15132 if(player
) { player_guid
= player
->GetGUID(); if(!group
) group
= player
->GetGroup(); }
15133 assert(player_guid
);
15135 // copy all binds to the group, when changing leader it's assumed the character
15136 // will not have any solo binds
15140 for(uint8 i
= 0; i
< TOTAL_DIFFICULTIES
; i
++)
15142 for (BoundInstancesMap::iterator itr
= player
->m_boundInstances
[i
].begin(); itr
!= player
->m_boundInstances
[i
].end();)
15145 if(group
) group
->BindToInstance(itr
->second
.save
, itr
->second
.perm
, true);
15146 // permanent binds are not removed
15147 if(!itr
->second
.perm
)
15149 player
->UnbindInstance(itr
, i
, true); // increments itr
15158 // if the player's not online we don't know what binds it has
15159 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
));
15160 // the following should not get executed when changing leaders
15161 if(!player
|| has_solo
) CharacterDatabase
.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid
));
15164 bool Player::_LoadHomeBind(QueryResult
*result
)
15166 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(), getClass());
15169 sLog
.outError("Player have incorrect race/class pair. Can't be loaded.");
15174 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15177 Field
*fields
= result
->Fetch();
15178 m_homebindMapId
= fields
[0].GetUInt32();
15179 m_homebindZoneId
= fields
[1].GetUInt16();
15180 m_homebindX
= fields
[2].GetFloat();
15181 m_homebindY
= fields
[3].GetFloat();
15182 m_homebindZ
= fields
[4].GetFloat();
15185 MapEntry
const* bindMapEntry
= sMapStore
.LookupEntry(m_homebindMapId
);
15187 // accept saved data only for valid position (and non instanceable), and accessable
15188 if( MapManager::IsValidMapCoord(m_homebindMapId
,m_homebindX
,m_homebindY
,m_homebindZ
) &&
15189 !bindMapEntry
->Instanceable() && GetSession()->Expansion() >= bindMapEntry
->Expansion())
15194 CharacterDatabase
.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15199 m_homebindMapId
= info
->mapId
;
15200 m_homebindZoneId
= info
->zoneId
;
15201 m_homebindX
= info
->positionX
;
15202 m_homebindY
= info
->positionY
;
15203 m_homebindZ
= info
->positionZ
;
15205 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
);
15208 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f",
15209 m_homebindMapId
, m_homebindZoneId
, m_homebindX
, m_homebindY
, m_homebindZ
);
15214 /*********************************************************/
15215 /*** SAVE SYSTEM ***/
15216 /*********************************************************/
15218 void Player::SaveToDB()
15220 // delay auto save at any saves (manual, in code, or autosave)
15221 m_nextSave
= sWorld
.getConfig(CONFIG_INTERVAL_SAVE
);
15223 // first save/honor gain after midnight will also update the player's honor fields
15224 UpdateHonorFields();
15226 int is_save_resting
= HasFlag(PLAYER_FLAGS
, PLAYER_FLAGS_RESTING
) ? 1 : 0;
15227 //save, far from tavern/city
15228 //save, but in tavern/city
15229 sLog
.outDebug("The value of player %s at save: ", m_name
.c_str());
15232 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15233 uint32 tmp_bytes
= GetUInt32Value(UNIT_FIELD_BYTES_1
);
15234 uint32 tmp_bytes2
= GetUInt32Value(UNIT_FIELD_BYTES_2
);
15235 uint32 tmp_flags
= GetUInt32Value(UNIT_FIELD_FLAGS
);
15236 uint32 tmp_pflags
= GetUInt32Value(PLAYER_FLAGS
);
15237 uint32 tmp_displayid
= GetDisplayId();
15239 // Set player sit state to standing on save, also stealth and shifted form
15240 SetByteValue(UNIT_FIELD_BYTES_1
, 0, UNIT_STAND_STATE_STAND
);
15241 SetByteValue(UNIT_FIELD_BYTES_2
, 3, 0); // shapeshift
15242 RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_STUNNED
);
15243 SetDisplayId(GetNativeDisplayId());
15245 bool inworld
= IsInWorld();
15247 CharacterDatabase
.BeginTransaction();
15249 CharacterDatabase
.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15251 std::string sql_name
= m_name
;
15252 CharacterDatabase
.escape_string(sql_name
);
15254 std::ostringstream ss
;
15255 ss
<< "INSERT INTO characters (guid,account,name,race,class,"
15256 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15257 "taximask, online, cinematic, "
15258 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15259 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15260 "death_expire_time, taxi_path, arena_pending_points, bgid, bgteam, bgmap, bgx, bgy, bgz, bgo) VALUES ("
15261 << GetGUIDLow() << ", "
15262 << GetSession()->GetAccountId() << ", '"
15263 << sql_name
<< "', "
15265 << m_class
<< ", ";
15267 if(!IsBeingTeleported())
15269 ss
<< GetMapId() << ", "
15270 << (uint32
)GetDifficulty() << ", "
15271 << finiteAlways(GetPositionX()) << ", "
15272 << finiteAlways(GetPositionY()) << ", "
15273 << finiteAlways(GetPositionZ()) << ", "
15274 << finiteAlways(GetOrientation()) << ", '";
15278 ss
<< GetTeleportDest().mapid
<< ", "
15279 << (uint32
)GetDifficulty() << ", "
15280 << finiteAlways(GetTeleportDest().x
) << ", "
15281 << finiteAlways(GetTeleportDest().y
) << ", "
15282 << finiteAlways(GetTeleportDest().z
) << ", "
15283 << finiteAlways(GetTeleportDest().o
) << ", '";
15287 for( i
= 0; i
< m_valuesCount
; i
++ )
15289 ss
<< GetUInt32Value(i
) << " ";
15294 ss
<< m_taxi
; // string with TaxiMaskSize numbers
15297 ss
<< (inworld
? 1 : 0);
15303 ss
<< m_Played_time
[0];
15305 ss
<< m_Played_time
[1];
15308 ss
<< finiteAlways(m_rest_bonus
);
15310 ss
<< (uint64
)time(NULL
);
15312 ss
<< is_save_resting
;
15314 ss
<< m_resetTalentsCost
;
15316 ss
<< (uint64
)m_resetTalentsTime
;
15319 ss
<< finiteAlways(m_movementInfo
.t_x
);
15321 ss
<< finiteAlways(m_movementInfo
.t_y
);
15323 ss
<< finiteAlways(m_movementInfo
.t_z
);
15325 ss
<< finiteAlways(m_movementInfo
.t_o
);
15328 ss
<< m_transport
->GetGUIDLow();
15333 ss
<< m_ExtraFlags
;
15336 ss
<< uint32(m_stableSlots
); // to prevent save uint8 as char
15339 ss
<< uint32(m_atLoginFlags
);
15345 ss
<< (uint64
)m_deathExpireTime
;
15348 ss
<< m_taxi
.SaveTaxiDestinationsToString();
15350 ss
<< GetBattleGroundId();
15354 ss
<< m_bgEntryPoint
.mapid
<< ", "
15355 << finiteAlways(m_bgEntryPoint
.x
) << ", "
15356 << finiteAlways(m_bgEntryPoint
.y
) << ", "
15357 << finiteAlways(m_bgEntryPoint
.z
) << ", "
15358 << finiteAlways(m_bgEntryPoint
.o
);
15361 CharacterDatabase
.Execute( ss
.str().c_str() );
15363 if(m_mailsUpdated
) //save mails only when needed
15367 _SaveQuestStatus();
15368 _SaveDailyQuestStatus();
15371 _SaveSpellCooldowns();
15374 m_achievementMgr
.SaveToDB();
15375 m_reputationMgr
.SaveToDB();
15377 CharacterDatabase
.CommitTransaction();
15379 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15380 SetDisplayId(tmp_displayid
);
15381 SetUInt32Value(UNIT_FIELD_BYTES_1
, tmp_bytes
);
15382 SetUInt32Value(UNIT_FIELD_BYTES_2
, tmp_bytes2
);
15383 SetUInt32Value(UNIT_FIELD_FLAGS
, tmp_flags
);
15384 SetUInt32Value(PLAYER_FLAGS
, tmp_pflags
);
15386 // save pet (hunter pet level and experience and all type pets health/mana).
15387 if(Pet
* pet
= GetPet())
15388 pet
->SavePetToDB(PET_SAVE_AS_CURRENT
);
15391 // fast save function for item/money cheating preventing - save only inventory and money state
15392 void Player::SaveInventoryAndGoldToDB()
15395 //money is in data field
15396 SaveDataFieldToDB();
15399 void Player::_SaveActions()
15401 for(ActionButtonList::iterator itr
= m_actionButtons
.begin(); itr
!= m_actionButtons
.end(); )
15403 switch (itr
->second
.uState
)
15405 case ACTIONBUTTON_NEW
:
15406 CharacterDatabase
.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15407 GetGUIDLow(), (uint32
)itr
->first
, (uint32
)itr
->second
.action
, (uint32
)itr
->second
.type
, (uint32
)itr
->second
.misc
);
15408 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
15411 case ACTIONBUTTON_CHANGED
:
15412 CharacterDatabase
.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15413 (uint32
)itr
->second
.action
, (uint32
)itr
->second
.type
, (uint32
)itr
->second
.misc
, GetGUIDLow(), (uint32
)itr
->first
);
15414 itr
->second
.uState
= ACTIONBUTTON_UNCHANGED
;
15417 case ACTIONBUTTON_DELETED
:
15418 CharacterDatabase
.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32
)itr
->first
);
15419 m_actionButtons
.erase(itr
++);
15428 void Player::_SaveAuras()
15430 CharacterDatabase
.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15432 AuraMap
const& auras
= GetAuras();
15437 spellEffectPair lastEffectPair
= auras
.begin()->first
;
15438 uint32 stackCounter
= 1;
15440 for(AuraMap::const_iterator itr
= auras
.begin(); ; ++itr
)
15442 if(itr
== auras
.end() || lastEffectPair
!= itr
->first
)
15444 AuraMap::const_iterator itr2
= itr
;
15445 // save previous spellEffectPair to db
15448 SpellEntry
const *spellInfo
= itr2
->second
->GetSpellProto();
15450 //skip all auras from spells that are passive or need a shapeshift
15451 if (!(itr2
->second
->IsPassive() || itr2
->second
->IsRemovedOnShapeLost()))
15453 //do not save single target auras (unless they were cast by the player)
15454 if (!(itr2
->second
->GetCasterGUID() != GetGUID() && itr2
->second
->IsSingleTarget()))
15457 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15458 for (i
= 0; i
< 3; i
++)
15459 if (spellInfo
->EffectApplyAuraName
[i
] == SPELL_AURA_MOD_SHAPESHIFT
||
15460 spellInfo
->EffectApplyAuraName
[i
] == SPELL_AURA_MOD_STEALTH
)
15465 CharacterDatabase
.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15466 "VALUES ('%u', '" I64FMTD
"' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15467 GetGUIDLow(), itr2
->second
->GetCasterGUID(), (uint32
)itr2
->second
->GetId(), (uint32
)itr2
->second
->GetEffIndex(), stackCounter
, itr2
->second
->GetModifier()->m_amount
,int(itr2
->second
->GetAuraMaxDuration()),int(itr2
->second
->GetAuraDuration()),int(itr2
->second
->GetAuraCharges()));
15472 if(itr
== auras
.end())
15476 if (lastEffectPair
== itr
->first
)
15480 lastEffectPair
= itr
->first
;
15486 void Player::_SaveInventory()
15488 // force items in buyback slots to new state
15489 // and remove those that aren't already
15490 for (uint8 i
= BUYBACK_SLOT_START
; i
< BUYBACK_SLOT_END
; i
++)
15492 Item
*item
= m_items
[i
];
15493 if (!item
|| item
->GetState() == ITEM_NEW
) continue;
15494 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
15495 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item
->GetGUIDLow());
15496 m_items
[i
]->FSetState(ITEM_NEW
);
15499 // update enchantment durations
15500 for(EnchantDurationList::iterator itr
= m_enchantDuration
.begin();itr
!= m_enchantDuration
.end();++itr
)
15502 itr
->item
->SetEnchantmentDuration(itr
->slot
,itr
->leftduration
);
15506 if (m_itemUpdateQueue
.empty()) return;
15508 // do not save if the update queue is corrupt
15509 bool error
= false;
15510 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); i
++)
15512 Item
*item
= m_itemUpdateQueue
[i
];
15513 if(!item
|| item
->GetState() == ITEM_REMOVED
) continue;
15514 Item
*test
= GetItemByPos( item
->GetBagSlot(), item
->GetSlot());
15518 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());
15521 else if (test
!= item
)
15523 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());
15530 sLog
.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15531 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED
);
15535 for(size_t i
= 0; i
< m_itemUpdateQueue
.size(); i
++)
15537 Item
*item
= m_itemUpdateQueue
[i
];
15538 if(!item
) continue;
15540 Bag
*container
= item
->GetContainer();
15541 uint32 bag_guid
= container
? container
->GetGUIDLow() : 0;
15543 switch(item
->GetState())
15546 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());
15549 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());
15552 CharacterDatabase
.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item
->GetGUIDLow());
15554 case ITEM_UNCHANGED
:
15558 item
->SaveToDB(); // item have unchanged inventory record and can be save standalone
15560 m_itemUpdateQueue
.clear();
15563 void Player::_SaveMail()
15565 if (!m_mailsLoaded
)
15568 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); ++itr
)
15571 if (m
->state
== MAIL_STATE_CHANGED
)
15573 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'",
15574 m
->itemTextId
, m
->HasItems() ? 1 : 0, (uint64
)m
->expire_time
, (uint64
)m
->deliver_time
, m
->money
, m
->COD
, m
->checked
, m
->messageID
);
15575 if(m
->removedItems
.size())
15577 for(std::vector
<uint32
>::iterator itr2
= m
->removedItems
.begin(); itr2
!= m
->removedItems
.end(); ++itr2
)
15578 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2
);
15579 m
->removedItems
.clear();
15581 m
->state
= MAIL_STATE_UNCHANGED
;
15583 else if (m
->state
== MAIL_STATE_DELETED
)
15586 for(std::vector
<MailItemInfo
>::iterator itr2
= m
->items
.begin(); itr2
!= m
->items
.end(); ++itr2
)
15587 CharacterDatabase
.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2
->item_guid
);
15589 CharacterDatabase
.PExecute("DELETE FROM item_text WHERE id = '%u'", m
->itemTextId
);
15590 CharacterDatabase
.PExecute("DELETE FROM mail WHERE id = '%u'", m
->messageID
);
15591 CharacterDatabase
.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m
->messageID
);
15595 //deallocate deleted mails...
15596 for (PlayerMails::iterator itr
= m_mail
.begin(); itr
!= m_mail
.end(); )
15598 if ((*itr
)->state
== MAIL_STATE_DELETED
)
15603 itr
= m_mail
.begin();
15609 m_mailsUpdated
= false;
15612 void Player::_SaveQuestStatus()
15614 // we don't need transactions here.
15615 for( QuestStatusMap::iterator i
= mQuestStatus
.begin( ); i
!= mQuestStatus
.end( ); ++i
)
15617 switch (i
->second
.uState
)
15620 CharacterDatabase
.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15621 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD
"', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15622 GetGUIDLow(), i
->first
, i
->second
.m_status
, i
->second
.m_rewarded
, i
->second
.m_explored
, uint64(i
->second
.m_timer
/ IN_MILISECONDS
+ sWorld
.GetGameTime()), i
->second
.m_creatureOrGOcount
[0], i
->second
.m_creatureOrGOcount
[1], i
->second
.m_creatureOrGOcount
[2], i
->second
.m_creatureOrGOcount
[3], i
->second
.m_itemcount
[0], i
->second
.m_itemcount
[1], i
->second
.m_itemcount
[2], i
->second
.m_itemcount
[3]);
15624 case QUEST_CHANGED
:
15625 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' ",
15626 i
->second
.m_status
, i
->second
.m_rewarded
, i
->second
.m_explored
, uint64(i
->second
.m_timer
/ IN_MILISECONDS
+ sWorld
.GetGameTime()), i
->second
.m_creatureOrGOcount
[0], i
->second
.m_creatureOrGOcount
[1], i
->second
.m_creatureOrGOcount
[2], i
->second
.m_creatureOrGOcount
[3], i
->second
.m_itemcount
[0], i
->second
.m_itemcount
[1], i
->second
.m_itemcount
[2], i
->second
.m_itemcount
[3], GetGUIDLow(), i
->first
);
15628 case QUEST_UNCHANGED
:
15631 i
->second
.uState
= QUEST_UNCHANGED
;
15635 void Player::_SaveDailyQuestStatus()
15637 if(!m_DailyQuestChanged
)
15640 m_DailyQuestChanged
= false;
15642 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15644 // we don't need transactions here.
15645 CharacterDatabase
.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15646 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
15647 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
15648 CharacterDatabase
.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD
"')",
15649 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
),uint64(m_lastDailyQuestTime
));
15652 void Player::_SaveSpells()
15654 for (PlayerSpellMap::iterator itr
= m_spells
.begin(), next
= m_spells
.begin(); itr
!= m_spells
.end();)
15656 if (itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->second
->state
== PLAYERSPELL_CHANGED
)
15657 CharacterDatabase
.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr
->first
);
15659 // add only changed/new not dependent spells
15660 if (!itr
->second
->dependent
&& (itr
->second
->state
== PLAYERSPELL_NEW
|| itr
->second
->state
== PLAYERSPELL_CHANGED
))
15661 CharacterDatabase
.PExecute("INSERT INTO character_spell (guid,spell,active,disabled) VALUES ('%u', '%u', '%u', '%u')", GetGUIDLow(), itr
->first
, itr
->second
->active
? 1 : 0,itr
->second
->disabled
? 1 : 0);
15663 if (itr
->second
->state
== PLAYERSPELL_REMOVED
)
15665 delete itr
->second
;
15666 m_spells
.erase(itr
++);
15670 itr
->second
->state
= PLAYERSPELL_UNCHANGED
;
15677 void Player::_SaveTutorials()
15679 if(!m_TutorialsChanged
)
15683 // it's better than rebuilding indexes multiple times
15684 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID
);
15687 Rows
= result
->Fetch()[0].GetUInt32();
15693 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'",
15694 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
);
15698 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]);
15701 m_TutorialsChanged
= false;
15704 void Player::outDebugValues() const
15706 if(!sLog
.IsOutDebug()) // optimize disabled debug output
15709 sLog
.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA
));
15710 sLog
.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY
), GetStat(STAT_STRENGTH
));
15711 sLog
.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT
), GetStat(STAT_SPIRIT
));
15712 sLog
.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA
), GetStat(STAT_SPIRIT
));
15713 sLog
.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE
));
15714 sLog
.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY
), GetResistance(SPELL_SCHOOL_FIRE
));
15715 sLog
.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE
), GetResistance(SPELL_SCHOOL_FROST
));
15716 sLog
.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW
), GetResistance(SPELL_SCHOOL_ARCANE
));
15717 sLog
.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE
), GetFloatValue(UNIT_FIELD_MAXDAMAGE
));
15718 sLog
.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE
));
15719 sLog
.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE
), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE
));
15720 sLog
.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK
), GetAttackTime(RANGED_ATTACK
));
15723 /*********************************************************/
15724 /*** FLOOD FILTER SYSTEM ***/
15725 /*********************************************************/
15727 void Player::UpdateSpeakTime()
15729 // ignore chat spam protection for GMs in any mode
15730 if(GetSession()->GetSecurity() > SEC_PLAYER
)
15733 time_t current
= time (NULL
);
15734 if(m_speakTime
> current
)
15736 uint32 max_count
= sWorld
.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT
);
15741 if(m_speakCount
>= max_count
)
15743 // prevent overwrite mute time, if message send just before mutes set, for example.
15744 time_t new_mute
= current
+ sWorld
.getConfig(CONFIG_CHATFLOOD_MUTE_TIME
);
15745 if(GetSession()->m_muteTime
< new_mute
)
15746 GetSession()->m_muteTime
= new_mute
;
15754 m_speakTime
= current
+ sWorld
.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY
);
15757 bool Player::CanSpeak() const
15759 return GetSession()->m_muteTime
<= time (NULL
);
15762 /*********************************************************/
15763 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15764 /*********************************************************/
15766 void Player::SendAttackSwingNotInRange()
15768 WorldPacket
data(SMSG_ATTACKSWING_NOTINRANGE
, 0);
15769 GetSession()->SendPacket( &data
);
15772 void Player::SavePositionInDB(uint32 mapid
, float x
,float y
,float z
,float o
,uint32 zone
,uint64 guid
)
15774 std::ostringstream ss
;
15775 ss
<< "UPDATE characters SET position_x='"<<x
<<"',position_y='"<<y
15776 << "',position_z='"<<z
<<"',orientation='"<<o
<<"',map='"<<mapid
15777 << "',zone='"<<zone
<<"',trans_x='0',trans_y='0',trans_z='0',"
15778 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
15779 sLog
.outDebug(ss
.str().c_str());
15780 CharacterDatabase
.Execute(ss
.str().c_str());
15783 void Player::SaveDataFieldToDB()
15785 std::ostringstream ss
;
15786 ss
<<"UPDATE characters SET data='";
15788 for(uint16 i
= 0; i
< m_valuesCount
; i
++ )
15790 ss
<< GetUInt32Value(i
) << " ";
15792 ss
<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
15794 CharacterDatabase
.Execute(ss
.str().c_str());
15797 bool Player::SaveValuesArrayInDB(Tokens
const& tokens
, uint64 guid
)
15799 std::ostringstream ss2
;
15800 ss2
<<"UPDATE characters SET data='";
15802 for (Tokens::const_iterator iter
= tokens
.begin(); iter
!= tokens
.end(); ++iter
, ++i
)
15804 ss2
<<tokens
[i
]<<" ";
15806 ss2
<<"' WHERE guid='"<< GUID_LOPART(guid
) <<"'";
15808 return CharacterDatabase
.Execute(ss2
.str().c_str());
15811 void Player::SetUInt32ValueInArray(Tokens
& tokens
,uint16 index
, uint32 value
)
15814 snprintf(buf
,11,"%u",value
);
15816 if(index
>= tokens
.size())
15819 tokens
[index
] = buf
;
15822 void Player::SetUInt32ValueInDB(uint16 index
, uint32 value
, uint64 guid
)
15825 if(!LoadValuesArrayFromDB(tokens
,guid
))
15828 if(index
>= tokens
.size())
15832 snprintf(buf
,11,"%u",value
);
15833 tokens
[index
] = buf
;
15835 SaveValuesArrayInDB(tokens
,guid
);
15838 void Player::SetFloatValueInDB(uint16 index
, float value
, uint64 guid
)
15841 memcpy(&temp
, &value
, sizeof(value
));
15842 Player::SetUInt32ValueInDB(index
, temp
, guid
);
15845 void Player::Customize(uint64 guid
, uint8 gender
, uint8 skin
, uint8 face
, uint8 hairStyle
, uint8 hairColor
, uint8 facialHair
)
15848 if(!LoadValuesArrayFromDB(tokens
, guid
))
15851 uint32 unit_bytes0
= GetUInt32ValueFromArray(tokens
, UNIT_FIELD_BYTES_0
);
15852 uint8 race
= unit_bytes0
& 0xFF;
15853 uint8 class_
= (unit_bytes0
>> 8) & 0xFF;
15855 PlayerInfo
const* info
= objmgr
.GetPlayerInfo(race
, class_
);
15859 unit_bytes0
&= ~(0xFF << 16);
15860 unit_bytes0
|= (gender
<< 16);
15861 SetUInt32ValueInArray(tokens
, UNIT_FIELD_BYTES_0
, unit_bytes0
);
15863 SetUInt32ValueInArray(tokens
, UNIT_FIELD_DISPLAYID
, gender
? info
->displayId_f
: info
->displayId_m
);
15864 SetUInt32ValueInArray(tokens
, UNIT_FIELD_NATIVEDISPLAYID
, gender
? info
->displayId_f
: info
->displayId_m
);
15866 SetUInt32ValueInArray(tokens
, PLAYER_BYTES
, (skin
| (face
<< 8) | (hairStyle
<< 16) | (hairColor
<< 24)));
15868 uint32 player_bytes2
= GetUInt32ValueFromArray(tokens
, PLAYER_BYTES_2
);
15869 player_bytes2
&= ~0xFF;
15870 player_bytes2
|= facialHair
;
15871 SetUInt32ValueInArray(tokens
, PLAYER_BYTES_2
, player_bytes2
);
15873 uint32 player_bytes3
= GetUInt32ValueFromArray(tokens
, PLAYER_BYTES_3
);
15874 player_bytes3
&= ~0xFF;
15875 player_bytes3
|= gender
;
15876 SetUInt32ValueInArray(tokens
, PLAYER_BYTES_3
, player_bytes3
);
15878 SaveValuesArrayInDB(tokens
, guid
);
15881 void Player::SendAttackSwingNotStanding()
15883 WorldPacket
data(SMSG_ATTACKSWING_NOTSTANDING
, 0);
15884 GetSession()->SendPacket( &data
);
15887 void Player::SendAttackSwingDeadTarget()
15889 WorldPacket
data(SMSG_ATTACKSWING_DEADTARGET
, 0);
15890 GetSession()->SendPacket( &data
);
15893 void Player::SendAttackSwingCantAttack()
15895 WorldPacket
data(SMSG_ATTACKSWING_CANT_ATTACK
, 0);
15896 GetSession()->SendPacket( &data
);
15899 void Player::SendAttackSwingCancelAttack()
15901 WorldPacket
data(SMSG_CANCEL_COMBAT
, 0);
15902 GetSession()->SendPacket( &data
);
15905 void Player::SendAttackSwingBadFacingAttack()
15907 WorldPacket
data(SMSG_ATTACKSWING_BADFACING
, 0);
15908 GetSession()->SendPacket( &data
);
15911 void Player::SendAutoRepeatCancel()
15913 WorldPacket
data(SMSG_CANCEL_AUTO_REPEAT
, GetPackGUID().size());
15914 data
.append(GetPackGUID()); // may be it's target guid
15915 GetSession()->SendPacket( &data
);
15918 void Player::SendExplorationExperience(uint32 Area
, uint32 Experience
)
15920 WorldPacket
data( SMSG_EXPLORATION_EXPERIENCE
, 8 );
15922 data
<< Experience
;
15923 GetSession()->SendPacket(&data
);
15926 void Player::SendDungeonDifficulty(bool IsInGroup
)
15928 uint8 val
= 0x00000001;
15929 WorldPacket
data(MSG_SET_DUNGEON_DIFFICULTY
, 12);
15930 data
<< (uint32
)GetDifficulty();
15931 data
<< uint32(val
);
15932 data
<< uint32(IsInGroup
);
15933 GetSession()->SendPacket(&data
);
15936 void Player::SendResetFailedNotify(uint32 mapid
)
15938 WorldPacket
data(SMSG_RESET_FAILED_NOTIFY
, 4);
15939 data
<< uint32(mapid
);
15940 GetSession()->SendPacket(&data
);
15943 /// Reset all solo instances and optionally send a message on success for each
15944 void Player::ResetInstances(uint8 method
)
15946 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
15948 // we assume that when the difficulty changes, all instances that can be reset will be
15949 uint8 dif
= GetDifficulty();
15951 for (BoundInstancesMap::iterator itr
= m_boundInstances
[dif
].begin(); itr
!= m_boundInstances
[dif
].end();)
15953 InstanceSave
*p
= itr
->second
.save
;
15954 const MapEntry
*entry
= sMapStore
.LookupEntry(itr
->first
);
15955 if(!entry
|| !p
->CanReset())
15961 if(method
== INSTANCE_RESET_ALL
)
15963 // the "reset all instances" method can only reset normal maps
15964 if(dif
== DIFFICULTY_HEROIC
|| entry
->map_type
== MAP_RAID
)
15971 // if the map is loaded, reset it
15972 Map
*map
= MapManager::Instance().FindMap(p
->GetMapId(), p
->GetInstanceId());
15973 if(map
&& map
->IsDungeon())
15974 ((InstanceMap
*)map
)->Reset(method
);
15976 // since this is a solo instance there should not be any players inside
15977 if(method
== INSTANCE_RESET_ALL
|| method
== INSTANCE_RESET_CHANGE_DIFFICULTY
)
15978 SendResetInstanceSuccess(p
->GetMapId());
15981 m_boundInstances
[dif
].erase(itr
++);
15983 // the following should remove the instance save from the manager and delete it as well
15984 p
->RemovePlayer(this);
15988 void Player::SendResetInstanceSuccess(uint32 MapId
)
15990 WorldPacket
data(SMSG_INSTANCE_RESET
, 4);
15992 GetSession()->SendPacket(&data
);
15995 void Player::SendResetInstanceFailed(uint32 reason
, uint32 MapId
)
15997 // TODO: find what other fail reasons there are besides players in the instance
15998 WorldPacket
data(SMSG_INSTANCE_RESET_FAILED
, 4);
16001 GetSession()->SendPacket(&data
);
16004 /*********************************************************/
16005 /*** Update timers ***/
16006 /*********************************************************/
16008 ///checks the 15 afk reports per 5 minutes limit
16009 void Player::UpdateAfkReport(time_t currTime
)
16011 if(m_bgAfkReportedTimer
<= currTime
)
16013 m_bgAfkReportedCount
= 0;
16014 m_bgAfkReportedTimer
= currTime
+5*MINUTE
;
16018 void Player::UpdateContestedPvP(uint32 diff
)
16020 if(!m_contestedPvPTimer
||isInCombat())
16022 if(m_contestedPvPTimer
<= diff
)
16024 ResetContestedPvP();
16027 m_contestedPvPTimer
-= diff
;
16030 void Player::UpdatePvPFlag(time_t currTime
)
16034 if(pvpInfo
.endTimer
== 0 || currTime
< (pvpInfo
.endTimer
+ 300))
16040 void Player::UpdateDuelFlag(time_t currTime
)
16042 if(!duel
|| duel
->startTimer
== 0 ||currTime
< duel
->startTimer
+ 3)
16045 SetUInt32Value(PLAYER_DUEL_TEAM
, 1);
16046 duel
->opponent
->SetUInt32Value(PLAYER_DUEL_TEAM
, 2);
16048 duel
->startTimer
= 0;
16049 duel
->startTime
= currTime
;
16050 duel
->opponent
->duel
->startTimer
= 0;
16051 duel
->opponent
->duel
->startTime
= currTime
;
16054 void Player::RemovePet(Pet
* pet
, PetSaveMode mode
, bool returnreagent
)
16059 if(returnreagent
&& (pet
|| m_temporaryUnsummonedPetNumber
))
16061 //returning of reagents only for players, so best done here
16062 uint32 spellId
= pet
? pet
->GetUInt32Value(UNIT_CREATED_BY_SPELL
) : m_oldpetspell
;
16063 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spellId
);
16067 for(uint32 i
= 0; i
< 7; ++i
)
16069 if(spellInfo
->Reagent
[i
] > 0)
16071 ItemPosCountVec dest
; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16072 uint8 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
, dest
, spellInfo
->Reagent
[i
], spellInfo
->ReagentCount
[i
] );
16073 if( msg
== EQUIP_ERR_OK
)
16075 Item
* item
= StoreNewItem( dest
, spellInfo
->Reagent
[i
], true);
16077 SendNewItem(item
,spellInfo
->ReagentCount
[i
],true,false);
16082 m_temporaryUnsummonedPetNumber
= 0;
16085 if(!pet
|| pet
->GetOwnerGUID()!=GetGUID())
16088 // only if current pet in slot
16089 switch(pet
->getPetType())
16095 m_guardianPets
.erase(pet
->GetGUID());
16098 if(GetPetGUID() == pet
->GetGUID())
16107 switch(pet
->GetEntry())
16109 //warlock pets except imp are removed(?) when logging out
16114 mode
= PET_SAVE_NOT_IN_SLOT
;
16119 pet
->SavePetToDB(mode
);
16121 pet
->CleanupsBeforeDelete();
16122 pet
->AddObjectToRemoveList();
16123 pet
->m_removed
= true;
16125 if(pet
->isControlled())
16127 WorldPacket
data(SMSG_PET_SPELLS
, 8+4);
16130 GetSession()->SendPacket(&data
);
16133 SetGroupUpdateFlag(GROUP_UPDATE_PET
);
16137 void Player::RemoveMiniPet()
16139 if(Pet
* pet
= GetMiniPet())
16141 pet
->Remove(PET_SAVE_AS_DELETED
);
16146 Pet
* Player::GetMiniPet()
16150 return ObjectAccessor::GetPet(m_miniPet
);
16153 void Player::RemoveGuardians()
16155 while(!m_guardianPets
.empty())
16157 uint64 guid
= *m_guardianPets
.begin();
16158 if(Pet
* pet
= ObjectAccessor::GetPet(guid
))
16159 pet
->Remove(PET_SAVE_AS_DELETED
);
16161 m_guardianPets
.erase(guid
);
16165 bool Player::HasGuardianWithEntry(uint32 entry
)
16167 // pet guid middle part is entry (and creature also)
16168 // and in guardian list must be guardians with same entry _always_
16169 for(GuardianPetList::const_iterator itr
= m_guardianPets
.begin(); itr
!= m_guardianPets
.end(); ++itr
)
16170 if(GUID_ENPART(*itr
)==entry
)
16176 void Player::Uncharm()
16178 Unit
* charm
= GetCharm();
16182 charm
->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM
);
16183 charm
->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS
);
16186 void Player::BuildPlayerChat(WorldPacket
*data
, uint8 msgtype
, const std::string
& text
, uint32 language
) const
16188 *data
<< (uint8
)msgtype
;
16189 *data
<< (uint32
)language
;
16190 *data
<< (uint64
)GetGUID();
16191 *data
<< (uint32
)language
; //language 2.1.0 ?
16192 *data
<< (uint64
)GetGUID();
16193 *data
<< (uint32
)(text
.length()+1);
16195 *data
<< (uint8
)chatTag();
16198 void Player::Say(const std::string
& text
, const uint32 language
)
16200 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16201 BuildPlayerChat(&data
, CHAT_MSG_SAY
, text
, language
);
16202 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_SAY
),true);
16205 void Player::Yell(const std::string
& text
, const uint32 language
)
16207 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16208 BuildPlayerChat(&data
, CHAT_MSG_YELL
, text
, language
);
16209 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_YELL
),true);
16212 void Player::TextEmote(const std::string
& text
)
16214 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16215 BuildPlayerChat(&data
, CHAT_MSG_EMOTE
, text
, LANG_UNIVERSAL
);
16216 SendMessageToSetInRange(&data
,sWorld
.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE
),true, !sWorld
.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT
) );
16219 void Player::Whisper(const std::string
& text
, uint32 language
,uint64 receiver
)
16221 if (language
!= LANG_ADDON
) // if not addon data
16222 language
= LANG_UNIVERSAL
; // whispers should always be readable
16224 Player
*rPlayer
= objmgr
.GetPlayer(receiver
);
16226 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16227 if(!rPlayer
->isDND() || isGameMaster())
16229 WorldPacket
data(SMSG_MESSAGECHAT
, 200);
16230 BuildPlayerChat(&data
, CHAT_MSG_WHISPER
, text
, language
);
16231 rPlayer
->GetSession()->SendPacket(&data
);
16233 data
.Initialize(SMSG_MESSAGECHAT
, 200);
16234 rPlayer
->BuildPlayerChat(&data
, CHAT_MSG_REPLY
, text
, language
);
16235 GetSession()->SendPacket(&data
);
16239 // announce to player that player he is whispering to is dnd and cannot receive his message
16240 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND
, rPlayer
->GetName(), rPlayer
->dndMsg
.c_str());
16243 if(!isAcceptWhispers())
16245 SetAcceptWhispers(true);
16246 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON
);
16249 // announce to player that player he is whispering to is afk
16250 if(rPlayer
->isAFK())
16251 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK
, rPlayer
->GetName(), rPlayer
->afkMsg
.c_str());
16253 // if player whisper someone, auto turn of dnd to be able to receive an answer
16254 if(isDND() && !rPlayer
->isGameMaster())
16258 void Player::PetSpellInitialize()
16260 Pet
* pet
= GetPet();
16265 sLog
.outDebug("Pet Spells Groups");
16267 CharmInfo
*charmInfo
= pet
->GetCharmInfo();
16269 WorldPacket
data(SMSG_PET_SPELLS
, 8+4+4+4+10*4);
16270 data
<< uint64(pet
->GetGUID());
16271 data
<< uint32(pet
->GetCreatureInfo()->family
); // creature family (required for pet talents)
16273 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState()) << uint16(0);
16276 for(uint32 i
= 0; i
< 10; i
++)
16278 data
<< uint32(charmInfo
->GetActionBarEntry(i
)->Raw
);
16281 size_t spellsCountPos
= data
.wpos();
16285 data
<< uint8(addlist
); // placeholder
16287 if(pet
->isControlled() && ((pet
->getPetType() == HUNTER_PET
) || ((pet
->GetCreatureInfo()->type
== CREATURE_TYPE_DEMON
) && (getClass() == CLASS_WARLOCK
))))
16290 for (PetSpellMap::iterator itr
= pet
->m_spells
.begin(); itr
!= pet
->m_spells
.end(); ++itr
)
16292 if(itr
->second
->state
== PETSPELL_REMOVED
)
16295 data
<< uint16(itr
->first
);
16296 data
<< uint16(itr
->second
->active
); // pet spell active state isn't boolean
16301 data
.put
<uint8
>(spellsCountPos
, addlist
);
16303 uint8 cooldownsCount
= pet
->m_CreatureSpellCooldowns
.size() + pet
->m_CreatureCategoryCooldowns
.size();
16304 data
<< uint8(cooldownsCount
);
16306 time_t curTime
= time(NULL
);
16308 for(CreatureSpellCooldowns::const_iterator itr
= pet
->m_CreatureSpellCooldowns
.begin(); itr
!= pet
->m_CreatureSpellCooldowns
.end(); ++itr
)
16310 time_t cooldown
= 0;
16312 if(itr
->second
> curTime
)
16313 cooldown
= (itr
->second
- curTime
) * IN_MILISECONDS
;
16315 data
<< uint16(itr
->first
); // spellid
16316 data
<< uint16(0); // spell category?
16317 data
<< uint32(itr
->second
); // cooldown
16318 data
<< uint32(0); // category cooldown
16321 for(CreatureSpellCooldowns::const_iterator itr
= pet
->m_CreatureCategoryCooldowns
.begin(); itr
!= pet
->m_CreatureCategoryCooldowns
.end(); ++itr
)
16323 time_t cooldown
= 0;
16325 if(itr
->second
> curTime
)
16326 cooldown
= (itr
->second
- curTime
) * IN_MILISECONDS
;
16328 data
<< uint16(itr
->first
); // spellid
16329 data
<< uint16(0); // spell category?
16330 data
<< uint32(0); // cooldown
16331 data
<< uint32(itr
->second
); // category cooldown
16334 GetSession()->SendPacket(&data
);
16337 void Player::PossessSpellInitialize()
16339 Unit
* charm
= GetCharm();
16344 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
16348 sLog
.outError("Player::PossessSpellInitialize(): charm ("I64FMTD
") has no charminfo!", charm
->GetGUID());
16353 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);// first line + actionbar + spellcount + spells + last adds
16356 data
<< uint64(charm
->GetGUID());
16357 data
<< uint32(0x00000000);
16361 for(uint32 i
= 0; i
< 10; i
++) //40
16363 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
16366 data
<< uint8(addlist
); //1
16369 data
<< uint8(count
); // cooldowns count
16371 GetSession()->SendPacket(&data
);
16374 void Player::CharmSpellInitialize()
16376 Unit
* charm
= GetCharm();
16381 CharmInfo
*charmInfo
= charm
->GetCharmInfo();
16384 sLog
.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD
") has no charminfo!", charm
->GetGUID());
16390 if(charm
->GetTypeId() != TYPEID_PLAYER
)
16392 CreatureInfo
const *cinfo
= ((Creature
*)charm
)->GetCreatureInfo();
16394 if(cinfo
&& cinfo
->type
== CREATURE_TYPE_DEMON
&& getClass() == CLASS_WARLOCK
)
16396 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
16398 if(charmInfo
->GetCharmSpell(i
)->spellId
)
16404 WorldPacket
data(SMSG_PET_SPELLS
, 16+40+1+4*addlist
+25);// first line + actionbar + spellcount + spells + last adds
16406 data
<< uint64(charm
->GetGUID());
16407 data
<< uint32(0x00000000);
16409 if(charm
->GetTypeId() != TYPEID_PLAYER
)
16410 data
<< uint8(charmInfo
->GetReactState()) << uint8(charmInfo
->GetCommandState());
16412 data
<< uint8(0) << uint8(0);
16415 for(uint32 i
= 0; i
< 10; i
++) //40
16417 data
<< uint16(charmInfo
->GetActionBarEntry(i
)->SpellOrAction
) << uint16(charmInfo
->GetActionBarEntry(i
)->Type
);
16420 data
<< uint8(addlist
); //1
16424 for(uint32 i
= 0; i
< CREATURE_MAX_SPELLS
; ++i
)
16426 CharmSpellEntry
*cspell
= charmInfo
->GetCharmSpell(i
);
16427 if(cspell
->spellId
)
16429 data
<< uint16(cspell
->spellId
);
16430 data
<< uint16(cspell
->active
);
16436 data
<< uint8(count
); // cooldowns count
16438 GetSession()->SendPacket(&data
);
16441 bool Player::IsAffectedBySpellmod(SpellEntry
const *spellInfo
, SpellModifier
*mod
, Spell
const* spell
)
16443 if (!mod
|| !spellInfo
)
16446 if(mod
->charges
== -1 && mod
->lastAffected
) // marked as expired but locked until spell casting finish
16448 // prevent apply to any spell except spell that trigger expire
16451 if(mod
->lastAffected
!= spell
)
16454 else if(mod
->lastAffected
!= FindCurrentSpellBySpellId(spellInfo
->Id
))
16458 return spellmgr
.IsAffectedByMod(spellInfo
, mod
);
16461 void Player::AddSpellMod(SpellModifier
* mod
, bool apply
)
16463 uint16 Opcode
= (mod
->type
== SPELLMOD_FLAT
) ? SMSG_SET_FLAT_SPELL_MODIFIER
: SMSG_SET_PCT_SPELL_MODIFIER
;
16465 for(int eff
=0;eff
<96;++eff
)
16469 if (eff
<64) _mask
= uint64(1) << (eff
- 0);
16470 else _mask2
= uint64(1) << (eff
-64);
16471 if ( mod
->mask
& _mask
|| mod
->mask2
& _mask2
)
16474 for (SpellModList::iterator itr
= m_spellMods
[mod
->op
].begin(); itr
!= m_spellMods
[mod
->op
].end(); ++itr
)
16476 if ((*itr
)->type
== mod
->type
&& ((*itr
)->mask
& _mask
|| (*itr
)->mask2
& _mask2
))
16477 val
+= (*itr
)->value
;
16479 val
+= apply
? mod
->value
: -(mod
->value
);
16480 WorldPacket
data(Opcode
, (1+1+4));
16481 data
<< uint8(eff
);
16482 data
<< uint8(mod
->op
);
16483 data
<< int32(val
);
16484 SendDirectMessage(&data
);
16489 m_spellMods
[mod
->op
].push_back(mod
);
16492 if (mod
->charges
== -1)
16493 --m_SpellModRemoveCount
;
16494 m_spellMods
[mod
->op
].remove(mod
);
16499 void Player::RemoveSpellMods(Spell
const* spell
)
16501 if(!spell
|| (m_SpellModRemoveCount
== 0))
16504 for(int i
=0;i
<MAX_SPELLMOD
;++i
)
16506 for (SpellModList::iterator itr
= m_spellMods
[i
].begin(); itr
!= m_spellMods
[i
].end();)
16508 SpellModifier
*mod
= *itr
;
16511 if (mod
&& mod
->charges
== -1 && (mod
->lastAffected
== spell
|| mod
->lastAffected
==NULL
))
16513 RemoveAurasDueToSpell(mod
->spellId
);
16514 if (m_spellMods
[i
].empty())
16517 itr
= m_spellMods
[i
].begin();
16523 // send Proficiency
16524 void Player::SendProficiency(uint8 pr1
, uint32 pr2
)
16526 WorldPacket
data(SMSG_SET_PROFICIENCY
, 8);
16527 data
<< pr1
<< pr2
;
16528 GetSession()->SendPacket (&data
);
16531 void Player::RemovePetitionsAndSigns(uint64 guid
, uint32 type
)
16533 QueryResult
*result
= NULL
;
16535 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
16537 result
= CharacterDatabase
.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16540 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.
16541 { // and SendPetitionQueryOpcode reads data from the DB
16542 Field
*fields
= result
->Fetch();
16543 uint64 ownerguid
= MAKE_NEW_GUID(fields
[0].GetUInt32(), 0, HIGHGUID_PLAYER
);
16544 uint64 petitionguid
= MAKE_NEW_GUID(fields
[1].GetUInt32(), 0, HIGHGUID_ITEM
);
16546 // send update if charter owner in game
16547 Player
* owner
= objmgr
.GetPlayer(ownerguid
);
16549 owner
->GetSession()->SendPetitionQueryOpcode(petitionguid
);
16551 } while ( result
->NextRow() );
16556 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid
));
16558 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16561 CharacterDatabase
.BeginTransaction();
16564 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid
));
16565 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid
));
16569 CharacterDatabase
.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16570 CharacterDatabase
.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid
), type
);
16572 CharacterDatabase
.CommitTransaction();
16575 void Player::LeaveAllArenaTeams(uint64 guid
)
16577 QueryResult
*result
= CharacterDatabase
.PQuery("SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid='%u'", GUID_LOPART(guid
));
16583 Field
*fields
= result
->Fetch();
16584 uint32 at_id
= fields
[0].GetUInt32();
16587 ArenaTeam
* at
= objmgr
.GetArenaTeamById(at_id
);
16589 at
->DelMember(guid
);
16591 } while (result
->NextRow());
16596 void Player::SetRestBonus (float rest_bonus_new
)
16598 // Prevent resting on max level
16599 if(getLevel() >= sWorld
.getConfig(CONFIG_MAX_PLAYER_LEVEL
))
16600 rest_bonus_new
= 0;
16602 if(rest_bonus_new
< 0)
16603 rest_bonus_new
= 0;
16605 float rest_bonus_max
= (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP
)*1.5/2;
16607 if(rest_bonus_new
> rest_bonus_max
)
16608 m_rest_bonus
= rest_bonus_max
;
16610 m_rest_bonus
= rest_bonus_new
;
16612 // update data for client
16613 if(m_rest_bonus
>10)
16614 SetByteValue(PLAYER_BYTES_2
, 3, 0x01); // Set Reststate = Rested
16615 else if(m_rest_bonus
<=1)
16616 SetByteValue(PLAYER_BYTES_2
, 3, 0x02); // Set Reststate = Normal
16619 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE
, uint32(m_rest_bonus
));
16622 void Player::HandleStealthedUnitsDetection()
16624 std::list
<Unit
*> stealthedUnits
;
16626 CellPair
p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16628 cell
.data
.Part
.reserved
= ALL_DISTRICT
;
16629 cell
.SetNoCreate();
16631 MaNGOS::AnyStealthedCheck u_check
;
16632 MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
> searcher(this,stealthedUnits
, u_check
);
16634 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, WorldTypeMapContainer
> world_unit_searcher(searcher
);
16635 TypeContainerVisitor
<MaNGOS::UnitListSearcher
<MaNGOS::AnyStealthedCheck
>, GridTypeMapContainer
> grid_unit_searcher(searcher
);
16637 CellLock
<GridReadGuard
> cell_lock(cell
, p
);
16638 cell_lock
->Visit(cell_lock
, world_unit_searcher
, *GetMap());
16639 cell_lock
->Visit(cell_lock
, grid_unit_searcher
, *GetMap());
16641 for (std::list
<Unit
*>::iterator i
= stealthedUnits
.begin(); i
!= stealthedUnits
.end();)
16645 i
= stealthedUnits
.erase(i
);
16649 if ((*i
)->isVisibleForOrDetect(this,true))
16652 (*i
)->SendUpdateToPlayer(this);
16653 m_clientGUIDs
.insert((*i
)->GetGUID());
16655 #ifdef MANGOS_DEBUG
16656 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
16657 sLog
.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i
)->GetGUIDLow(),(*i
)->GetTypeId(),GetGUIDLow(),GetDistance(*i
));
16660 // target aura duration for caster show only if target exist at caster client
16661 // send data at target visibility change (adding to client)
16662 if((*i
)!=this && (*i
)->isType(TYPEMASK_UNIT
))
16663 SendAurasForTarget(*i
);
16665 i
= stealthedUnits
.erase(i
);
16673 bool Player::ActivateTaxiPathTo(std::vector
<uint32
> const& nodes
, uint32 mount_id
, Creature
* npc
)
16675 if(nodes
.size() < 2)
16678 // not let cheating with start flight mounted
16681 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16682 data
<< uint32(ERR_TAXIPLAYERALREADYMOUNTED
);
16683 GetSession()->SendPacket(&data
);
16687 if( m_ShapeShiftFormSpellId
&& m_form
!= FORM_BATTLESTANCE
&& m_form
!= FORM_BERSERKERSTANCE
&& m_form
!= FORM_DEFENSIVESTANCE
&& m_form
!= FORM_SHADOW
)
16689 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16690 data
<< uint32(ERR_TAXIPLAYERSHAPESHIFTED
);
16691 GetSession()->SendPacket(&data
);
16695 // 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
16696 if(GetSession()->isLogingOut() ||
16697 (!m_currentSpells
[CURRENT_GENERIC_SPELL
] ||
16698 m_currentSpells
[CURRENT_GENERIC_SPELL
]->m_spellInfo
->Effect
[0] != SPELL_EFFECT_SEND_TAXI
)&&
16699 IsNonMeleeSpellCasted(false) ||
16702 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16703 data
<< uint32(ERR_TAXIPLAYERBUSY
);
16704 GetSession()->SendPacket(&data
);
16708 if(HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_DISABLE_MOVE
))
16711 uint32 sourcenode
= nodes
[0];
16713 // starting node too far away (cheat?)
16714 TaxiNodesEntry
const* node
= sTaxiNodesStore
.LookupEntry(sourcenode
);
16715 if( !node
|| node
->map_id
!= GetMapId() ||
16716 (node
->x
- GetPositionX())*(node
->x
- GetPositionX())+
16717 (node
->y
- GetPositionY())*(node
->y
- GetPositionY())+
16718 (node
->z
- GetPositionZ())*(node
->z
- GetPositionZ()) >
16719 (2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
)*(2*INTERACTION_DISTANCE
) )
16721 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16722 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
16723 GetSession()->SendPacket(&data
);
16727 // Prepare to flight start now
16729 // stop combat at start taxi flight if any
16732 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16735 // clean not finished taxi path if any
16736 m_taxi
.ClearTaxiDestinations();
16738 // 0 element current node
16739 m_taxi
.AddTaxiDestination(sourcenode
);
16741 // fill destinations path tail
16742 uint32 sourcepath
= 0;
16743 uint32 totalcost
= 0;
16745 uint32 prevnode
= sourcenode
;
16746 uint32 lastnode
= 0;
16748 for(uint32 i
= 1; i
< nodes
.size(); ++i
)
16752 lastnode
= nodes
[i
];
16753 objmgr
.GetTaxiPath(prevnode
, lastnode
, path
, cost
);
16757 m_taxi
.ClearTaxiDestinations();
16763 if(prevnode
== sourcenode
)
16766 m_taxi
.AddTaxiDestination(lastnode
);
16768 prevnode
= lastnode
;
16771 if(!mount_id
) // if not provide then attempt use default.
16772 mount_id
= objmgr
.GetTaxiMount(sourcenode
, GetTeam());
16774 if (mount_id
== 0 || sourcepath
== 0)
16776 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16777 data
<< uint32(ERR_TAXIUNSPECIFIEDSERVERERROR
);
16778 GetSession()->SendPacket(&data
);
16779 m_taxi
.ClearTaxiDestinations();
16783 uint32 money
= GetMoney();
16787 totalcost
= (uint32
)ceil(totalcost
*GetReputationPriceDiscount(npc
));
16790 if(money
< totalcost
)
16792 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16793 data
<< uint32(ERR_TAXINOTENOUGHMONEY
);
16794 GetSession()->SendPacket(&data
);
16795 m_taxi
.ClearTaxiDestinations();
16799 //Checks and preparations done, DO FLIGHT
16800 ModifyMoney(-(int32
)totalcost
);
16801 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING
, totalcost
);
16803 // prevent stealth flight
16804 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH
);
16806 WorldPacket
data(SMSG_ACTIVATETAXIREPLY
, 4);
16807 data
<< uint32(ERR_TAXIOK
);
16808 GetSession()->SendPacket(&data
);
16810 sLog
.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16812 GetSession()->SendDoFlight(mount_id
, sourcepath
);
16817 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask
, uint32 unTimeMs
)
16819 // last check 2.0.10
16820 WorldPacket
data(SMSG_SPELL_COOLDOWN
, 8+1+m_spells
.size()*8);
16822 data
<< uint8(0x0); // flags (0x1, 0x2)
16823 time_t curTime
= time(NULL
);
16824 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
16826 if (itr
->second
->state
== PLAYERSPELL_REMOVED
)
16828 uint32 unSpellId
= itr
->first
;
16829 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(unSpellId
);
16836 // Not send cooldown for this spells
16837 if (spellInfo
->Attributes
& SPELL_ATTR_DISABLED_WHILE_ACTIVE
)
16840 if((idSchoolMask
& GetSpellSchoolMask(spellInfo
)) && GetSpellCooldownDelay(unSpellId
) < unTimeMs
)
16843 data
<< unTimeMs
; // in m.secs
16844 AddSpellCooldown(unSpellId
, 0, curTime
+ unTimeMs
/IN_MILISECONDS
);
16847 GetSession()->SendPacket(&data
);
16850 void Player::InitDataForForm(bool reapplyMods
)
16852 SpellShapeshiftEntry
const* ssEntry
= sSpellShapeshiftStore
.LookupEntry(m_form
);
16853 if(ssEntry
&& ssEntry
->attackSpeed
)
16855 SetAttackTime(BASE_ATTACK
,ssEntry
->attackSpeed
);
16856 SetAttackTime(OFF_ATTACK
,ssEntry
->attackSpeed
);
16857 SetAttackTime(RANGED_ATTACK
, BASE_ATTACK_TIME
);
16860 SetRegularAttackTime();
16866 if(getPowerType()!=POWER_ENERGY
)
16867 setPowerType(POWER_ENERGY
);
16871 case FORM_DIREBEAR
:
16873 if(getPowerType()!=POWER_RAGE
)
16874 setPowerType(POWER_RAGE
);
16877 default: // 0, for example
16879 ChrClassesEntry
const* cEntry
= sChrClassesStore
.LookupEntry(getClass());
16880 if(cEntry
&& cEntry
->powerType
< MAX_POWERS
&& uint32(getPowerType()) != cEntry
->powerType
)
16881 setPowerType(Powers(cEntry
->powerType
));
16886 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
16888 UpdateEquipSpellsAtFormChange();
16890 UpdateAttackPowerAndDamage();
16891 UpdateAttackPowerAndDamage(true);
16894 // Return true is the bought item has a max count to force refresh of window by caller
16895 bool Player::BuyItemFromVendor(uint64 vendorguid
, uint32 item
, uint8 count
, uint64 bagguid
, uint8 slot
)
16897 // cheating attempt
16898 if(count
< 1) count
= 1;
16903 ItemPrototype
const *pProto
= objmgr
.GetItemPrototype( item
);
16906 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, NULL
, item
, 0);
16910 Creature
*pCreature
= ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid
,UNIT_NPC_FLAG_VENDOR
);
16913 sLog
.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid
)) );
16914 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR
, NULL
, item
, 0);
16918 VendorItemData
const* vItems
= pCreature
->GetVendorItems();
16919 if(!vItems
|| vItems
->Empty())
16921 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
16925 size_t vendor_slot
= vItems
->FindItemSlot(item
);
16926 if(vendor_slot
>= vItems
->GetItemCount())
16928 SendBuyError( BUY_ERR_CANT_FIND_ITEM
, pCreature
, item
, 0);
16932 VendorItem
const* crItem
= vItems
->m_items
[vendor_slot
];
16934 // check current item amount if it limited
16935 if( crItem
->maxcount
!= 0 )
16937 if(pCreature
->GetVendorItemCurrentCount(crItem
) < pProto
->BuyCount
* count
)
16939 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD
, pCreature
, item
, 0);
16944 if( uint32(GetReputationRank(pProto
->RequiredReputationFaction
)) < pProto
->RequiredReputationRank
)
16946 SendBuyError( BUY_ERR_REPUTATION_REQUIRE
, pCreature
, item
, 0);
16950 if(crItem
->ExtendedCost
)
16952 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
16955 sLog
.outError("Item %u have wrong ExtendedCost field value %u", pProto
->ItemId
, crItem
->ExtendedCost
);
16959 // honor points price
16960 if(GetHonorPoints() < (iece
->reqhonorpoints
* count
))
16962 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS
, NULL
, NULL
);
16966 // arena points price
16967 if(GetArenaPoints() < (iece
->reqarenapoints
* count
))
16969 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS
, NULL
, NULL
);
16974 for (uint8 i
= 0; i
< 5; ++i
)
16976 if(iece
->reqitem
[i
] && !HasItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
)))
16978 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS
, NULL
, NULL
);
16983 // check for personal arena rating requirement
16984 if( GetMaxPersonalArenaRatingRequirement() < iece
->reqpersonalarenarating
)
16986 // probably not the proper equip err
16987 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK
,NULL
,NULL
);
16992 uint32 price
= pProto
->BuyPrice
* count
;
16994 // reputation discount
16995 price
= uint32(floor(price
* GetReputationPriceDiscount(pCreature
)));
16997 if( GetMoney() < price
)
16999 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY
, pCreature
, item
, 0);
17003 uint8 bag
= 0; // init for case invalid bagGUID
17005 if (bagguid
!= NULL_BAG
&& slot
!= NULL_SLOT
)
17008 if( bagguid
== GetGUID() )
17010 bag
= INVENTORY_SLOT_BAG_0
;
17014 for (int i
= INVENTORY_SLOT_BAG_START
; i
< INVENTORY_SLOT_BAG_END
;i
++)
17016 pBag
= (Bag
*)GetItemByPos(INVENTORY_SLOT_BAG_0
,i
);
17019 if( bagguid
== pBag
->GetGUID() )
17029 if( IsInventoryPos( bag
, slot
) || (bagguid
== NULL_BAG
&& slot
== NULL_SLOT
) )
17031 ItemPosCountVec dest
;
17032 uint8 msg
= CanStoreNewItem( bag
, slot
, dest
, item
, pProto
->BuyCount
* count
);
17033 if( msg
!= EQUIP_ERR_OK
)
17035 SendEquipError( msg
, NULL
, NULL
);
17039 ModifyMoney( -(int32
)price
);
17040 if(crItem
->ExtendedCost
) // case for new honor system
17042 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
17043 if(iece
->reqhonorpoints
)
17044 ModifyHonorPoints( - int32(iece
->reqhonorpoints
* count
));
17045 if(iece
->reqarenapoints
)
17046 ModifyArenaPoints( - int32(iece
->reqarenapoints
* count
));
17047 for (uint8 i
= 0; i
< 5; ++i
)
17049 if(iece
->reqitem
[i
])
17050 DestroyItemCount(iece
->reqitem
[i
], (iece
->reqitemcount
[i
] * count
), true);
17054 if(Item
*it
= StoreNewItem( dest
, item
, true ))
17056 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
17058 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
17059 data
<< pCreature
->GetGUID();
17060 data
<< (uint32
)(vendor_slot
+1); // numbered from 1 at client
17061 data
<< (uint32
)(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
17062 data
<< (uint32
)count
;
17063 GetSession()->SendPacket(&data
);
17065 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
17068 else if( IsEquipmentPos( bag
, slot
) )
17070 if(pProto
->BuyCount
* count
!= 1)
17072 SendEquipError( EQUIP_ERR_ITEM_CANT_BE_EQUIPPED
, NULL
, NULL
);
17077 uint8 msg
= CanEquipNewItem( slot
, dest
, item
, false );
17078 if( msg
!= EQUIP_ERR_OK
)
17080 SendEquipError( msg
, NULL
, NULL
);
17084 ModifyMoney( -(int32
)price
);
17085 if(crItem
->ExtendedCost
) // case for new honor system
17087 ItemExtendedCostEntry
const* iece
= sItemExtendedCostStore
.LookupEntry(crItem
->ExtendedCost
);
17088 if(iece
->reqhonorpoints
)
17089 ModifyHonorPoints( - int32(iece
->reqhonorpoints
));
17090 if(iece
->reqarenapoints
)
17091 ModifyArenaPoints( - int32(iece
->reqarenapoints
));
17092 for (uint8 i
= 0; i
< 5; ++i
)
17094 if(iece
->reqitem
[i
])
17095 DestroyItemCount(iece
->reqitem
[i
], iece
->reqitemcount
[i
], true);
17099 if(Item
*it
= EquipNewItem( dest
, item
, true ))
17101 uint32 new_count
= pCreature
->UpdateVendorItemCurrentCount(crItem
,pProto
->BuyCount
* count
);
17103 WorldPacket
data(SMSG_BUY_ITEM
, (8+4+4+4));
17104 data
<< pCreature
->GetGUID();
17105 data
<< (uint32
)(vendor_slot
+1); // numbered from 1 at client
17106 data
<< (uint32
)(crItem
->maxcount
> 0 ? new_count
: 0xFFFFFFFF);
17107 data
<< (uint32
)count
;
17108 GetSession()->SendPacket(&data
);
17110 SendNewItem(it
, pProto
->BuyCount
*count
, true, false, false);
17112 AutoUnequipOffhandIfNeed();
17117 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT
, NULL
, NULL
);
17121 return crItem
->maxcount
!=0;
17124 uint32
Player::GetMaxPersonalArenaRatingRequirement()
17126 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17127 // the personal rating of the arena team must match the required limit as well
17128 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17129 uint32 max_personal_rating
= 0;
17130 for(int i
= 0; i
< MAX_ARENA_SLOT
; ++i
)
17132 if(ArenaTeam
* at
= objmgr
.GetArenaTeamById(GetArenaTeamId(i
)))
17134 uint32 p_rating
= GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1
+ (i
* 6) + 5);
17135 uint32 t_rating
= at
->GetRating();
17136 p_rating
= p_rating
<t_rating
? p_rating
: t_rating
;
17137 if(max_personal_rating
< p_rating
)
17138 max_personal_rating
= p_rating
;
17141 return max_personal_rating
;
17144 void Player::UpdateHomebindTime(uint32 time
)
17146 // GMs never get homebind timer online
17147 if (m_InstanceValid
|| isGameMaster())
17149 if(m_HomebindTimer
) // instance valid, but timer not reset
17152 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
17155 GetSession()->SendPacket(&data
);
17157 // instance is valid, reset homebind timer
17158 m_HomebindTimer
= 0;
17160 else if (m_HomebindTimer
> 0)
17162 if (time
>= m_HomebindTimer
)
17164 // teleport to homebind location
17165 TeleportTo(m_homebindMapId
, m_homebindX
, m_homebindY
, m_homebindZ
, GetOrientation());
17168 m_HomebindTimer
-= time
;
17172 // instance is invalid, start homebind timer
17173 m_HomebindTimer
= 60000;
17174 // send message to player
17175 WorldPacket
data(SMSG_RAID_GROUP_ONLY
, 4+4);
17176 data
<< m_HomebindTimer
;
17178 GetSession()->SendPacket(&data
);
17179 sLog
.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17183 void Player::UpdatePvP(bool state
, bool ovrride
)
17185 if(!state
|| ovrride
)
17188 if(Pet
* pet
= GetPet())
17189 pet
->SetPvP(state
);
17190 if(Unit
* charmed
= GetCharm())
17191 charmed
->SetPvP(state
);
17193 pvpInfo
.endTimer
= 0;
17197 if(pvpInfo
.endTimer
!= 0)
17198 pvpInfo
.endTimer
= time(NULL
);
17203 if(Pet
* pet
= GetPet())
17204 pet
->SetPvP(state
);
17205 if(Unit
* charmed
= GetCharm())
17206 charmed
->SetPvP(state
);
17211 void Player::AddSpellAndCategoryCooldowns(SpellEntry
const* spellInfo
, uint32 itemId
, Spell
* spell
, bool infinityCooldown
)
17213 // init cooldown values
17218 // some special item spells without correct cooldown in SpellInfo
17219 // cooldown information stored in item prototype
17220 // This used in same way in WorldSession::HandleItemQuerySingleOpcode data sending to client.
17224 if(ItemPrototype
const* proto
= ObjectMgr::GetItemPrototype(itemId
))
17226 for(int idx
= 0; idx
< 5; ++idx
)
17228 if(proto
->Spells
[idx
].SpellId
== spellInfo
->Id
)
17230 cat
= proto
->Spells
[idx
].SpellCategory
;
17231 rec
= proto
->Spells
[idx
].SpellCooldown
;
17232 catrec
= proto
->Spells
[idx
].SpellCategoryCooldown
;
17239 // if no cooldown found above then base at DBC data
17240 if(rec
< 0 && catrec
< 0)
17242 cat
= spellInfo
->Category
;
17243 rec
= spellInfo
->RecoveryTime
;
17244 catrec
= spellInfo
->CategoryRecoveryTime
;
17247 time_t curTime
= time(NULL
);
17252 // overwrite time for selected category
17253 if(infinityCooldown
)
17255 // use +MONTH as infinity mark for spell cooldown (will checked as MONTH/2 at save ans skipped)
17256 // but not allow ignore until reset or re-login
17257 catrecTime
= catrec
> 0 ? curTime
+MONTH
: 0;
17258 recTime
= rec
> 0 ? curTime
+MONTH
: catrecTime
;
17262 // shoot spells used equipped item cooldown values already assigned in GetAttackTime(RANGED_ATTACK)
17263 // prevent 0 cooldowns set by another way
17264 if (rec
<= 0 && catrec
<= 0 && (cat
== 76 || IsAutoRepeatRangedSpell(spellInfo
) && spellInfo
->Id
!= SPELL_ID_AUTOSHOT
))
17265 rec
= GetAttackTime(RANGED_ATTACK
);
17267 // Now we have cooldown data (if found any), time to apply mods
17269 ApplySpellMod(spellInfo
->Id
, SPELLMOD_COOLDOWN
, rec
, spell
);
17272 ApplySpellMod(spellInfo
->Id
, SPELLMOD_COOLDOWN
, catrec
, spell
);
17274 // replace negative cooldowns by 0
17275 if (rec
< 0) rec
= 0;
17276 if (catrec
< 0) catrec
= 0;
17278 // no cooldown after applying spell mods
17279 if( rec
== 0 && catrec
== 0)
17282 catrecTime
= catrec
? curTime
+catrec
/IN_MILISECONDS
: 0;
17283 recTime
= rec
? curTime
+rec
/IN_MILISECONDS
: catrecTime
;
17286 // self spell cooldown
17288 AddSpellCooldown(spellInfo
->Id
, itemId
, recTime
);
17291 if (cat
&& catrec
> 0)
17293 SpellCategoryStore::const_iterator i_scstore
= sSpellCategoryStore
.find(cat
);
17294 if(i_scstore
!= sSpellCategoryStore
.end())
17296 for(SpellCategorySet::const_iterator i_scset
= i_scstore
->second
.begin(); i_scset
!= i_scstore
->second
.end(); ++i_scset
)
17298 if(*i_scset
== spellInfo
->Id
) // skip main spell, already handled above
17301 AddSpellCooldown(*i_scset
, itemId
, catrecTime
);
17307 void Player::AddSpellCooldown(uint32 spellid
, uint32 itemid
, time_t end_time
)
17311 sc
.itemid
= itemid
;
17312 m_spellCooldowns
[spellid
] = sc
;
17315 void Player::SendCooldownEvent(SpellEntry
const *spellInfo
, uint32 itemId
, Spell
* spell
)
17317 // start cooldowns at server side, if any
17318 AddSpellAndCategoryCooldowns(spellInfo
,itemId
,spell
);
17320 // Send activate cooldown timer (possible 0) at client side
17321 WorldPacket
data(SMSG_COOLDOWN_EVENT
, (4+8));
17322 data
<< spellInfo
->Id
;
17324 SendDirectMessage(&data
);
17327 void Player::UpdatePotionCooldown(Spell
* spell
)
17329 // no potion used i combat or still in combat
17330 if(!m_lastPotionId
|| isInCombat())
17333 // Call not from spell cast, send cooldown event for item spells if no in combat
17336 // spell/item pair let set proper cooldown (except not existed charged spell cooldown spellmods for potions)
17337 if(ItemPrototype
const* proto
= ObjectMgr::GetItemPrototype(m_lastPotionId
))
17338 for(int idx
= 0; idx
< 5; ++idx
)
17339 if(proto
->Spells
[idx
].SpellId
&& proto
->Spells
[idx
].SpellTrigger
== ITEM_SPELLTRIGGER_ON_USE
)
17340 if(SpellEntry
const* spellInfo
= sSpellStore
.LookupEntry(proto
->Spells
[idx
].SpellId
))
17341 SendCooldownEvent(spellInfo
,m_lastPotionId
);
17343 // from spell cases (m_lastPotionId set in Spell::SendSpellCooldown)
17345 SendCooldownEvent(spell
->m_spellInfo
,m_lastPotionId
,spell
);
17347 m_lastPotionId
= 0;
17350 //slot to be excluded while counting
17351 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition
, int8 slot
)
17353 if(!enchantmentcondition
)
17356 SpellItemEnchantmentConditionEntry
const *Condition
= sSpellItemEnchantmentConditionStore
.LookupEntry(enchantmentcondition
);
17361 uint8 curcount
[4] = {0, 0, 0, 0};
17363 //counting current equipped gem colors
17364 for(uint8 i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_END
; ++i
)
17368 Item
*pItem2
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
);
17369 if(pItem2
&& pItem2
->GetProto()->Socket
[0].Color
)
17371 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17373 uint32 enchant_id
= pItem2
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17377 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17381 uint32 gemid
= enchantEntry
->GemID
;
17385 ItemPrototype
const* gemProto
= sItemStorage
.LookupEntry
<ItemPrototype
>(gemid
);
17389 GemPropertiesEntry
const* gemProperty
= sGemPropertiesStore
.LookupEntry(gemProto
->GemProperties
);
17393 uint8 GemColor
= gemProperty
->color
;
17395 for(uint8 b
= 0, tmpcolormask
= 1; b
< 4; b
++, tmpcolormask
<<= 1)
17397 if(tmpcolormask
& GemColor
)
17404 bool activate
= true;
17406 for(int i
= 0; i
< 5; i
++)
17408 if(!Condition
->Color
[i
])
17411 uint32 _cur_gem
= curcount
[Condition
->Color
[i
] - 1];
17413 // if have <CompareColor> use them as count, else use <value> from Condition
17414 uint32 _cmp_gem
= Condition
->CompareColor
[i
] ? curcount
[Condition
->CompareColor
[i
] - 1]: Condition
->Value
[i
];
17416 switch(Condition
->Comparator
[i
])
17418 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17419 activate
&= (_cur_gem
< _cmp_gem
) ? true : false;
17421 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17422 activate
&= (_cur_gem
> _cmp_gem
) ? true : false;
17424 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17425 activate
&= (_cur_gem
>= _cmp_gem
) ? true : false;
17430 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");
17435 void Player::CorrectMetaGemEnchants(uint8 exceptslot
, bool apply
)
17437 //cycle all equipped items
17438 for(uint32 slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
17440 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17441 if(slot
== exceptslot
)
17444 Item
* pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
17446 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
)
17449 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17451 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17455 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17459 uint32 condition
= enchantEntry
->EnchantmentCondition
;
17462 //was enchant active with/without item?
17463 bool wasactive
= EnchantmentFitsRequirements(condition
, apply
? exceptslot
: -1);
17464 //should it now be?
17465 if(wasactive
^ EnchantmentFitsRequirements(condition
, apply
? -1 : exceptslot
))
17467 // ignore item gem conditions
17468 //if state changed, (dis)apply enchant
17469 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
),!wasactive
,true,true);
17476 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17477 void Player::ToggleMetaGemsActive(uint8 exceptslot
, bool apply
)
17479 //cycle all equipped items
17480 for(int slot
= EQUIPMENT_SLOT_START
; slot
< EQUIPMENT_SLOT_END
; ++slot
)
17482 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17483 if(slot
== exceptslot
)
17486 Item
*pItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, slot
);
17488 if(!pItem
|| !pItem
->GetProto()->Socket
[0].Color
) //if item has no sockets or no item is equipped go to next item
17491 //cycle all (gem)enchants
17492 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
17494 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
17495 if(!enchant_id
) //if no enchant go to next enchant(slot)
17498 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
17502 //only metagems to be (de)activated, so only enchants with condition
17503 uint32 condition
= enchantEntry
->EnchantmentCondition
;
17505 ApplyEnchantment(pItem
,EnchantmentSlot(enchant_slot
), apply
);
17510 void Player::LeaveBattleground(bool teleportToEntryPoint
)
17512 if(BattleGround
*bg
= GetBattleGround())
17514 bg
->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint
, true);
17516 // call after remove to be sure that player resurrected for correct cast
17517 if( bg
->isBattleGround() && sWorld
.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER
) )
17519 if( bg
->GetStatus() == STATUS_IN_PROGRESS
|| bg
->GetStatus() == STATUS_WAIT_JOIN
)
17520 CastSpell(this, 26013, true); // Deserter
17525 bool Player::CanJoinToBattleground() const
17527 // check Deserter debuff
17528 if(GetDummyAura(26013))
17534 bool Player::CanReportAfkDueToLimit()
17536 // a player can complain about 15 people per 5 minutes
17537 if(m_bgAfkReportedCount
>= 15)
17539 ++m_bgAfkReportedCount
;
17543 ///This player has been blamed to be inactive in a battleground
17544 void Player::ReportedAfkBy(Player
* reporter
)
17546 BattleGround
*bg
= GetBattleGround();
17547 if(!bg
|| bg
!= reporter
->GetBattleGround() || GetTeam() != reporter
->GetTeam())
17550 // check if player has 'Idle' or 'Inactive' debuff
17551 if(m_bgAfkReporter
.find(reporter
->GetGUIDLow())==m_bgAfkReporter
.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter
->CanReportAfkDueToLimit())
17553 m_bgAfkReporter
.insert(reporter
->GetGUIDLow());
17554 // 3 players have to complain to apply debuff
17555 if(m_bgAfkReporter
.size() >= 3)
17557 // cast 'Idle' spell
17558 CastSpell(this, 43680, true);
17559 m_bgAfkReporter
.clear();
17564 bool Player::IsVisibleInGridForPlayer( Player
* pl
) const
17566 // gamemaster in GM mode see all, including ghosts
17567 if(pl
->isGameMaster() && GetSession()->GetSecurity() <= pl
->GetSession()->GetSecurity())
17570 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17571 if (InBattleGround())
17573 if (!(isAlive() || m_deathTimer
> 0) && !IsFriendlyTo(pl
) )
17578 // Live player see live player or dead player with not realized corpse
17579 if(pl
->isAlive() || pl
->m_deathTimer
> 0)
17581 return isAlive() || m_deathTimer
> 0;
17584 // Ghost see other friendly ghosts, that's for sure
17585 if(!(isAlive() || m_deathTimer
> 0) && IsFriendlyTo(pl
))
17588 // Dead player see live players near own corpse
17591 Corpse
*corpse
= pl
->GetCorpse();
17594 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17595 if(corpse
->IsWithinDistInMap(this,(20+25)*sWorld
.getRate(RATE_CREATURE_AGGRO
)))
17600 // and not see any other
17604 bool Player::IsVisibleGloballyFor( Player
* u
) const
17609 // Always can see self
17613 // Visible units, always are visible for all players
17614 if (GetVisibility() == VISIBILITY_ON
)
17617 // GMs are visible for higher gms (or players are visible for gms)
17618 if (u
->GetSession()->GetSecurity() > SEC_PLAYER
)
17619 return GetSession()->GetSecurity() <= u
->GetSession()->GetSecurity();
17621 // non faction visibility non-breakable for non-GMs
17622 if (GetVisibility() == VISIBILITY_OFF
)
17625 // non-gm stealth/invisibility not hide from global player lists
17629 void Player::UpdateVisibilityOf(WorldObject
* target
)
17631 if(HaveAtClient(target
))
17633 if(!target
->isVisibleForInState(this,true))
17635 target
->DestroyForPlayer(this);
17636 m_clientGUIDs
.erase(target
->GetGUID());
17638 #ifdef MANGOS_DEBUG
17639 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17640 sLog
.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
17646 if(target
->isVisibleForInState(this,false))
17648 target
->SendUpdateToPlayer(this);
17649 if(target
->GetTypeId()!=TYPEID_GAMEOBJECT
||!((GameObject
*)target
)->IsTransport())
17650 m_clientGUIDs
.insert(target
->GetGUID());
17652 #ifdef MANGOS_DEBUG
17653 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17654 sLog
.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target
->GetGUIDLow(),target
->GetTypeId(),GetGUIDLow(),GetDistance(target
));
17657 // target aura duration for caster show only if target exist at caster client
17658 // send data at target visibility change (adding to client)
17659 if(target
!=this && target
->isType(TYPEMASK_UNIT
))
17660 SendAurasForTarget((Unit
*)target
);
17662 if(target
->GetTypeId()==TYPEID_UNIT
&& ((Creature
*)target
)->isAlive())
17663 ((Creature
*)target
)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17669 inline void UpdateVisibilityOf_helper(std::set
<uint64
>& s64
, T
* target
)
17671 s64
.insert(target
->GetGUID());
17675 inline void UpdateVisibilityOf_helper(std::set
<uint64
>& s64
, GameObject
* target
)
17677 if(!target
->IsTransport())
17678 s64
.insert(target
->GetGUID());
17682 void Player::UpdateVisibilityOf(T
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
)
17684 if(HaveAtClient(target
))
17686 if(!target
->isVisibleForInState(this,true))
17688 target
->BuildOutOfRangeUpdateBlock(&data
);
17689 m_clientGUIDs
.erase(target
->GetGUID());
17691 #ifdef MANGOS_DEBUG
17692 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17693 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
));
17699 if(target
->isVisibleForInState(this,false))
17701 visibleNow
.insert(target
);
17702 target
->BuildUpdate(data_updates
);
17703 target
->BuildCreateUpdateBlockForPlayer(&data
, this);
17704 UpdateVisibilityOf_helper(m_clientGUIDs
,target
);
17706 #ifdef MANGOS_DEBUG
17707 if((sLog
.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES
)==0)
17708 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
));
17714 template void Player::UpdateVisibilityOf(Player
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17715 template void Player::UpdateVisibilityOf(Creature
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17716 template void Player::UpdateVisibilityOf(Corpse
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17717 template void Player::UpdateVisibilityOf(GameObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17718 template void Player::UpdateVisibilityOf(DynamicObject
* target
, UpdateData
& data
, UpdateDataMapType
& data_updates
, std::set
<WorldObject
*>& visibleNow
);
17720 void Player::InitPrimaryProffesions()
17722 SetFreePrimaryProffesions(sWorld
.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL
));
17725 void Player::SendComboPoints()
17727 Unit
*combotarget
= ObjectAccessor::GetUnit(*this, m_comboTarget
);
17730 WorldPacket
data(SMSG_UPDATE_COMBO_POINTS
, combotarget
->GetPackGUID().size()+1);
17731 data
.append(combotarget
->GetPackGUID());
17732 data
<< uint8(m_comboPoints
);
17733 GetSession()->SendPacket(&data
);
17737 void Player::AddComboPoints(Unit
* target
, int8 count
)
17742 // without combo points lost (duration checked in aura)
17743 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
17745 if(target
->GetGUID() == m_comboTarget
)
17747 m_comboPoints
+= count
;
17752 if(Unit
* target
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
17753 target
->RemoveComboPointHolder(GetGUIDLow());
17755 m_comboTarget
= target
->GetGUID();
17756 m_comboPoints
= count
;
17758 target
->AddComboPointHolder(GetGUIDLow());
17761 if (m_comboPoints
> 5) m_comboPoints
= 5;
17762 if (m_comboPoints
< 0) m_comboPoints
= 0;
17767 void Player::ClearComboPoints()
17772 // without combopoints lost (duration checked in aura)
17773 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS
);
17779 if(Unit
* target
= ObjectAccessor::GetUnit(*this,m_comboTarget
))
17780 target
->RemoveComboPointHolder(GetGUIDLow());
17785 void Player::SetGroup(Group
*group
, int8 subgroup
)
17791 // never use SetGroup without a subgroup unless you specify NULL for group
17792 assert(subgroup
>= 0);
17793 m_group
.link(group
, this);
17794 m_group
.setSubGroup((uint8
)subgroup
);
17798 void Player::SendInitialPacketsBeforeAddToMap()
17800 WorldPacket
data(SMSG_SET_REST_START_OBSOLETE
, 4);
17801 data
<< uint32(0); // unknown, may be rest state time or experience
17802 GetSession()->SendPacket(&data
);
17805 data
.Initialize(SMSG_BINDPOINTUPDATE
, 5*4);
17806 data
<< m_homebindX
<< m_homebindY
<< m_homebindZ
;
17807 data
<< (uint32
) m_homebindMapId
;
17808 data
<< (uint32
) m_homebindZoneId
;
17809 GetSession()->SendPacket(&data
);
17811 // SMSG_SET_PROFICIENCY
17812 // SMSG_UPDATE_AURA_DURATION
17815 data
.Initialize(SMSG_TUTORIAL_FLAGS
, 8*4);
17816 for (int i
= 0; i
< 8; ++i
)
17817 data
<< uint32( GetTutorialInt(i
) );
17818 GetSession()->SendPacket(&data
);
17820 SendInitialSpells();
17822 data
.Initialize(SMSG_SEND_UNLEARN_SPELLS
, 4);
17823 data
<< uint32(0); // count, for(count) uint32;
17824 GetSession()->SendPacket(&data
);
17826 SendInitialActionButtons();
17827 m_reputationMgr
.SendInitialReputations();
17828 m_achievementMgr
.SendAllAchievementData();
17831 uint32 newzone
, newarea
;
17832 GetZoneAndAreaId(newzone
,newarea
);
17833 UpdateZone(newzone
,newarea
); // also call SendInitWorldStates();
17835 // SMSG_SET_AURA_SINGLE
17837 data
.Initialize(SMSG_LOGIN_SETTIMESPEED
, 8);
17838 data
<< uint32(secsToTimeBitFields(sWorld
.GetGameTime()));
17839 data
<< (float)0.01666667f
; // game speed
17840 GetSession()->SendPacket( &data
);
17842 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17843 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
) || isInFlight())
17844 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2
);
17849 void Player::SendInitialPacketsAfterAddToMap()
17851 WorldPacket
data(SMSG_TIME_SYNC_REQ
, 4); // new 2.0.x, enable movement
17852 data
<< uint32(0x00000000); // on blizz it increments periodically
17853 GetSession()->SendPacket(&data
);
17855 CastSpell(this, 836, true); // LOGINEFFECT
17857 // set some aura effects that send packet to player client after add player to map
17858 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17859 // same auras state lost at far teleport, send it one more time in this case also
17860 static const AuraType auratypes
[] =
17862 SPELL_AURA_MOD_FEAR
, SPELL_AURA_TRANSFORM
, SPELL_AURA_WATER_WALK
,
17863 SPELL_AURA_FEATHER_FALL
, SPELL_AURA_HOVER
, SPELL_AURA_SAFE_FALL
,
17864 SPELL_AURA_FLY
, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
, SPELL_AURA_NONE
17866 for(AuraType
const* itr
= &auratypes
[0]; itr
&& itr
[0] != SPELL_AURA_NONE
; ++itr
)
17868 Unit::AuraList
const& auraList
= GetAurasByType(*itr
);
17869 if(!auraList
.empty())
17870 auraList
.front()->ApplyModifier(true,true);
17873 if(HasAuraType(SPELL_AURA_MOD_STUN
))
17874 SetMovement(MOVE_ROOT
);
17876 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17877 if(HasAuraType(SPELL_AURA_MOD_ROOT
))
17879 WorldPacket
data(SMSG_FORCE_MOVE_ROOT
, 10);
17880 data
.append(GetPackGUID());
17882 SendMessageToSet(&data
,true);
17885 SendAurasForTarget(this);
17886 SendEnchantmentDurations(); // must be after add to map
17887 SendItemDurations(); // must be after add to map
17890 void Player::SendUpdateToOutOfRangeGroupMembers()
17892 if (m_groupUpdateMask
== GROUP_UPDATE_FLAG_NONE
)
17894 if(Group
* group
= GetGroup())
17895 group
->UpdatePlayerOutOfRange(this);
17897 m_groupUpdateMask
= GROUP_UPDATE_FLAG_NONE
;
17898 m_auraUpdateMask
= 0;
17899 if(Pet
*pet
= GetPet())
17900 pet
->ResetAuraUpdateMask();
17903 void Player::SendTransferAborted(uint32 mapid
, uint8 reason
, uint8 arg
)
17905 WorldPacket
data(SMSG_TRANSFER_ABORTED
, 4+2);
17906 data
<< uint32(mapid
);
17907 data
<< uint8(reason
); // transfer abort reason
17910 case TRANSFER_ABORT_INSUF_EXPAN_LVL
:
17911 case TRANSFER_ABORT_DIFFICULTY
:
17912 case TRANSFER_ABORT_UNIQUE_MESSAGE
:
17913 data
<< uint8(arg
);
17916 GetSession()->SendPacket(&data
);
17919 void Player::SendInstanceResetWarning(uint32 mapid
, uint32 time
)
17921 // type of warning, based on the time remaining until reset
17924 type
= RAID_INSTANCE_WELCOME
;
17925 else if(time
> 900 && time
<= 3600)
17926 type
= RAID_INSTANCE_WARNING_HOURS
;
17927 else if(time
> 300 && time
<= 900)
17928 type
= RAID_INSTANCE_WARNING_MIN
;
17930 type
= RAID_INSTANCE_WARNING_MIN_SOON
;
17931 WorldPacket
data(SMSG_RAID_INSTANCE_MESSAGE
, 4+4+4);
17932 data
<< uint32(type
);
17933 data
<< uint32(mapid
);
17934 data
<< uint32(time
);
17935 GetSession()->SendPacket(&data
);
17938 void Player::ApplyEquipCooldown( Item
* pItem
)
17940 for(int i
= 0; i
< MAX_ITEM_PROTO_SPELLS
; ++i
)
17942 _Spell
const& spellData
= pItem
->GetProto()->Spells
[i
];
17945 if( !spellData
.SpellId
)
17948 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
17949 if( spellData
.SpellTrigger
!= ITEM_SPELLTRIGGER_ON_USE
)
17952 AddSpellCooldown(spellData
.SpellId
, pItem
->GetEntry(), time(NULL
) + 30);
17954 WorldPacket
data(SMSG_ITEM_COOLDOWN
, 12);
17955 data
<< pItem
->GetGUID();
17956 data
<< uint32(spellData
.SpellId
);
17957 GetSession()->SendPacket(&data
);
17961 void Player::resetSpells()
17963 // not need after this call
17964 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS
))
17966 m_atLoginFlags
= m_atLoginFlags
& ~AT_LOGIN_RESET_SPELLS
;
17967 CharacterDatabase
.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS
), GetGUIDLow());
17970 // make full copy of map (spells removed and marked as deleted at another spell remove
17971 // and we can't use original map for safe iterative with visit each spell at loop end
17972 PlayerSpellMap smap
= GetSpellMap();
17974 for(PlayerSpellMap::const_iterator iter
= smap
.begin();iter
!= smap
.end(); ++iter
)
17975 removeSpell(iter
->first
); // only iter->first can be accessed, object by iter->second can be deleted already
17977 learnDefaultSpells();
17978 learnQuestRewardedSpells();
17981 void Player::learnDefaultSpells()
17983 // learn default race/class spells
17984 PlayerInfo
const *info
= objmgr
.GetPlayerInfo(getRace(),getClass());
17985 for (PlayerCreateInfoSpells::const_iterator itr
= info
->spell
.begin(); itr
!=info
->spell
.end(); ++itr
)
17987 uint32 tspell
= *itr
;
17988 sLog
.outDebug("PLAYER (Class: %u Race: %u): Adding initial spell, id = %u",uint32(getClass()),uint32(getRace()), tspell
);
17989 if(!IsInWorld()) // will send in INITIAL_SPELLS in list anyway at map add
17990 addSpell(tspell
,true,true,true,false);
17991 else // but send in normal spell in game learn case
17992 learnSpell(tspell
,true);
17996 void Player::learnQuestRewardedSpells(Quest
const* quest
)
17998 uint32 spell_id
= quest
->GetRewSpellCast();
18000 // skip quests without rewarded spell
18004 SpellEntry
const *spellInfo
= sSpellStore
.LookupEntry(spell_id
);
18008 // check learned spells state
18009 bool found
= false;
18010 for(int i
=0; i
< 3; ++i
)
18012 if(spellInfo
->Effect
[i
] == SPELL_EFFECT_LEARN_SPELL
&& !HasSpell(spellInfo
->EffectTriggerSpell
[i
]))
18019 // skip quests with not teaching spell or already known spell
18023 // prevent learn non first rank unknown profession and second specialization for same profession)
18024 uint32 learned_0
= spellInfo
->EffectTriggerSpell
[0];
18025 if( spellmgr
.GetSpellRank(learned_0
) > 1 && !HasSpell(learned_0
) )
18027 // not have first rank learned (unlearned prof?)
18028 uint32 first_spell
= spellmgr
.GetFirstSpellInChain(learned_0
);
18029 if( !HasSpell(first_spell
) )
18032 SpellEntry
const *learnedInfo
= sSpellStore
.LookupEntry(learned_0
);
18037 if(learnedInfo
->Effect
[0]==SPELL_EFFECT_TRADE_SKILL
&& learnedInfo
->Effect
[1]==0)
18039 // search other specialization for same prof
18040 for(PlayerSpellMap::const_iterator itr
= m_spells
.begin(); itr
!= m_spells
.end(); ++itr
)
18042 if(itr
->second
->state
== PLAYERSPELL_REMOVED
|| itr
->first
==learned_0
)
18045 SpellEntry
const *itrInfo
= sSpellStore
.LookupEntry(itr
->first
);
18049 // compare only specializations
18050 if(itrInfo
->Effect
[0]!=SPELL_EFFECT_TRADE_SKILL
|| itrInfo
->Effect
[1]!=0)
18053 // compare same chain spells
18054 if(spellmgr
.GetFirstSpellInChain(itr
->first
) != first_spell
)
18057 // now we have 2 specialization, learn possible only if found is lesser specialization rank
18058 if(!spellmgr
.IsHighRankOfSpell(learned_0
,itr
->first
))
18064 CastSpell( this, spell_id
, true);
18067 void Player::learnQuestRewardedSpells()
18069 // learn spells received from quest completing
18070 for(QuestStatusMap::const_iterator itr
= mQuestStatus
.begin(); itr
!= mQuestStatus
.end(); ++itr
)
18072 // skip no rewarded quests
18073 if(!itr
->second
.m_rewarded
)
18076 Quest
const* quest
= objmgr
.GetQuestTemplate(itr
->first
);
18080 learnQuestRewardedSpells(quest
);
18084 void Player::learnSkillRewardedSpells(uint32 skill_id
, uint32 skill_value
)
18086 uint32 raceMask
= getRaceMask();
18087 uint32 classMask
= getClassMask();
18088 for (uint32 j
=0; j
<sSkillLineAbilityStore
.GetNumRows(); ++j
)
18090 SkillLineAbilityEntry
const *pAbility
= sSkillLineAbilityStore
.LookupEntry(j
);
18091 if (!pAbility
|| pAbility
->skillId
!=skill_id
|| pAbility
->learnOnGetSkill
!= ABILITY_LEARNED_ON_GET_PROFESSION_SKILL
)
18093 // Check race if set
18094 if (pAbility
->racemask
&& !(pAbility
->racemask
& raceMask
))
18096 // Check class if set
18097 if (pAbility
->classmask
&& !(pAbility
->classmask
& classMask
))
18100 if (sSpellStore
.LookupEntry(pAbility
->spellId
))
18102 // need unlearn spell
18103 if (skill_value
< pAbility
->req_skill_value
)
18104 removeSpell(pAbility
->spellId
);
18106 else if (!IsInWorld())
18107 addSpell(pAbility
->spellId
,true,true,true,false);
18109 learnSpell(pAbility
->spellId
,true);
18114 void Player::SendAurasForTarget(Unit
*target
)
18116 if(target
->GetVisibleAuras()->empty()) // speedup things
18119 WorldPacket
data(SMSG_AURA_UPDATE_ALL
);
18120 data
.append(target
->GetPackGUID());
18122 Unit::VisibleAuraMap
const *visibleAuras
= target
->GetVisibleAuras();
18123 for(Unit::VisibleAuraMap::const_iterator itr
= visibleAuras
->begin(); itr
!= visibleAuras
->end(); ++itr
)
18125 for(uint32 j
= 0; j
< 3; ++j
)
18127 if(Aura
*aura
= target
->GetAura(itr
->second
, j
))
18129 data
<< uint8(aura
->GetAuraSlot());
18130 data
<< uint32(aura
->GetId());
18134 uint8 auraFlags
= aura
->GetAuraFlags();
18136 data
<< uint8(auraFlags
);
18138 data
<< uint8(aura
->GetAuraLevel());
18140 data
<< uint8(aura
->GetAuraCharges());
18142 if(!(auraFlags
& AFLAG_NOT_CASTER
))
18144 data
<< uint8(0); // packed GUID of someone (caster?)
18147 if(auraFlags
& AFLAG_DURATION
) // include aura duration
18149 data
<< uint32(aura
->GetAuraMaxDuration());
18150 data
<< uint32(aura
->GetAuraDuration());
18158 GetSession()->SendPacket(&data
);
18161 void Player::SetDailyQuestStatus( uint32 quest_id
)
18163 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
18165 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
))
18167 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,quest_id
);
18168 m_lastDailyQuestTime
= time(NULL
); // last daily quest time
18169 m_DailyQuestChanged
= true;
18175 void Player::ResetDailyQuestStatus()
18177 for(uint32 quest_daily_idx
= 0; quest_daily_idx
< PLAYER_MAX_DAILY_QUESTS
; ++quest_daily_idx
)
18178 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1
+quest_daily_idx
,0);
18180 // DB data deleted in caller
18181 m_DailyQuestChanged
= false;
18182 m_lastDailyQuestTime
= 0;
18185 BattleGround
* Player::GetBattleGround() const
18187 if(GetBattleGroundId()==0)
18190 return sBattleGroundMgr
.GetBattleGround(GetBattleGroundId(), m_bgTypeID
);
18193 bool Player::InArena() const
18195 BattleGround
*bg
= GetBattleGround();
18196 if(!bg
|| !bg
->isArena())
18202 bool Player::GetBGAccessByLevel(BattleGroundTypeId bgTypeId
) const
18204 // get a template bg instead of running one
18205 BattleGround
*bg
= sBattleGroundMgr
.GetBattleGroundTemplate(bgTypeId
);
18209 if(getLevel() < bg
->GetMinLevel() || getLevel() > bg
->GetMaxLevel())
18215 BGQueueIdBasedOnLevel
Player::GetBattleGroundQueueIdFromLevel(BattleGroundTypeId bgTypeId
) const
18217 //returned to hardcoded version of this function, because there is no way to code it dynamic
18218 uint32 level
= getLevel();
18219 if( bgTypeId
== BATTLEGROUND_AV
)
18222 uint32 queue_id
= (level
/ 10) - 1; // for ranges 0 - 19, 20 - 29, 30 - 39, 40 - 49, 50 - 59, 60 - 69, 70 -79, 80
18223 if( queue_id
>= MAX_BATTLEGROUND_QUEUES
)
18225 sLog
.outError("BattleGround: too high queue_id %u this shouldn't happen", queue_id
);
18226 return QUEUE_ID_MAX_LEVEL_80
;
18228 return BGQueueIdBasedOnLevel(queue_id
);
18231 float Player::GetReputationPriceDiscount( Creature
const* pCreature
) const
18233 FactionTemplateEntry
const* vendor_faction
= pCreature
->getFactionTemplateEntry();
18234 if(!vendor_faction
|| !vendor_faction
->faction
)
18237 ReputationRank rank
= GetReputationRank(vendor_faction
->faction
);
18238 if(rank
<= REP_NEUTRAL
)
18241 return 1.0f
- 0.05f
* (rank
- REP_NEUTRAL
);
18244 bool Player::IsSpellFitByClassAndRace( uint32 spell_id
) const
18246 uint32 racemask
= getRaceMask();
18247 uint32 classmask
= getClassMask();
18249 SkillLineAbilityMap::const_iterator lower
= spellmgr
.GetBeginSkillLineAbilityMap(spell_id
);
18250 SkillLineAbilityMap::const_iterator upper
= spellmgr
.GetEndSkillLineAbilityMap(spell_id
);
18254 for(SkillLineAbilityMap::const_iterator _spell_idx
= lower
; _spell_idx
!= upper
; ++_spell_idx
)
18256 // skip wrong race skills
18257 if( _spell_idx
->second
->racemask
&& (_spell_idx
->second
->racemask
& racemask
) == 0)
18260 // skip wrong class skills
18261 if( _spell_idx
->second
->classmask
&& (_spell_idx
->second
->classmask
& classmask
) == 0)
18270 bool Player::HasQuestForGO(int32 GOId
) const
18272 for( int i
= 0; i
< MAX_QUEST_LOG_SIZE
; ++i
)
18274 uint32 questid
= GetQuestSlotQuestId(i
);
18275 if ( questid
== 0 )
18278 QuestStatusMap::const_iterator qs_itr
= mQuestStatus
.find(questid
);
18279 if(qs_itr
== mQuestStatus
.end())
18282 QuestStatusData
const& qs
= qs_itr
->second
;
18284 if (qs
.m_status
== QUEST_STATUS_INCOMPLETE
)
18286 Quest
const* qinfo
= objmgr
.GetQuestTemplate(questid
);
18290 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo
->GetType() != QUEST_TYPE_RAID
)
18293 for (int j
= 0; j
< QUEST_OBJECTIVES_COUNT
; j
++)
18295 if (qinfo
->ReqCreatureOrGOId
[j
]>=0) //skip non GO case
18298 if((-1)*GOId
== qinfo
->ReqCreatureOrGOId
[j
] && qs
.m_creatureOrGOcount
[j
] < qinfo
->ReqCreatureOrGOCount
[j
])
18306 void Player::UpdateForQuestsGO()
18308 if(m_clientGUIDs
.empty())
18312 WorldPacket packet
;
18313 for(ClientGUIDs::iterator itr
=m_clientGUIDs
.begin(); itr
!=m_clientGUIDs
.end(); ++itr
)
18315 if(IS_GAMEOBJECT_GUID(*itr
))
18317 GameObject
*obj
= HashMapHolder
<GameObject
>::Find(*itr
);
18319 obj
->BuildValuesUpdateBlockForPlayer(&udata
,this);
18322 udata
.BuildPacket(&packet
);
18323 GetSession()->SendPacket(&packet
);
18326 void Player::SummonIfPossible(bool agree
)
18330 m_summon_expire
= 0;
18334 // expire and auto declined
18335 if(m_summon_expire
< time(NULL
))
18338 // stop taxi flight at summon
18341 GetMotionMaster()->MovementExpired();
18342 m_taxi
.ClearTaxiDestinations();
18345 // drop flag at summon
18346 // this code can be reached only when GM is summoning player who carries flag, because player should be immune to summoning spells when he carries flag
18347 if(BattleGround
*bg
= GetBattleGround())
18348 bg
->EventPlayerDroppedFlag(this);
18350 m_summon_expire
= 0;
18352 TeleportTo(m_summon_mapid
, m_summon_x
, m_summon_y
, m_summon_z
,GetOrientation());
18355 void Player::RemoveItemDurations( Item
*item
)
18357 for(ItemDurationList::iterator itr
= m_itemDuration
.begin();itr
!= m_itemDuration
.end(); ++itr
)
18361 m_itemDuration
.erase(itr
);
18367 void Player::AddItemDurations( Item
*item
)
18369 if(item
->GetUInt32Value(ITEM_FIELD_DURATION
))
18371 m_itemDuration
.push_back(item
);
18372 item
->SendTimeUpdate(this);
18376 void Player::AutoUnequipOffhandIfNeed()
18378 Item
*offItem
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
);
18382 // need unequip offhand for 2h-weapon without TitanGrip (in any from hands)
18383 if (CanTitanGrip() || (offItem
->GetProto()->InventoryType
!= INVTYPE_2HWEAPON
&& !IsTwoHandUsed()))
18386 ItemPosCountVec off_dest
;
18387 uint8 off_msg
= CanStoreItem( NULL_BAG
, NULL_SLOT
, off_dest
, offItem
, false );
18388 if( off_msg
== EQUIP_ERR_OK
)
18390 RemoveItem(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
, true);
18391 StoreItem( off_dest
, offItem
, true );
18396 mi
.AddItem(offItem
->GetGUIDLow(), offItem
->GetEntry(), offItem
);
18397 MoveItemFromInventory(INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
, true);
18398 CharacterDatabase
.BeginTransaction();
18399 offItem
->DeleteFromInventoryDB(); // deletes item from character's inventory
18400 offItem
->SaveToDB(); // recursive and not have transaction guard into self, item not in inventory and can be save standalone
18401 CharacterDatabase
.CommitTransaction();
18403 std::string subject
= GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM
);
18404 WorldSession::SendMailTo(this, MAIL_NORMAL
, MAIL_STATIONERY_GM
, GetGUIDLow(), GetGUIDLow(), subject
, 0, &mi
, 0, 0, MAIL_CHECK_MASK_NONE
);
18408 bool Player::HasItemFitToSpellReqirements(SpellEntry
const* spellInfo
, Item
const* ignoreItem
)
18410 if(spellInfo
->EquippedItemClass
< 0)
18413 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18414 // for optimize check 2 used cases only
18415 switch(spellInfo
->EquippedItemClass
)
18417 case ITEM_CLASS_WEAPON
:
18419 for(int i
= EQUIPMENT_SLOT_MAINHAND
; i
< EQUIPMENT_SLOT_TABARD
; ++i
)
18420 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
18421 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18425 case ITEM_CLASS_ARMOR
:
18427 // tabard not have dependent spells
18428 for(int i
= EQUIPMENT_SLOT_START
; i
< EQUIPMENT_SLOT_MAINHAND
; ++i
)
18429 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, i
))
18430 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18433 // shields can be equipped to offhand slot
18434 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_OFFHAND
))
18435 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18438 // ranged slot can have some armor subclasses
18439 if(Item
*item
= GetItemByPos( INVENTORY_SLOT_BAG_0
, EQUIPMENT_SLOT_RANGED
))
18440 if(item
!=ignoreItem
&& item
->IsFitToSpellRequirements(spellInfo
))
18446 sLog
.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo
->EquippedItemClass
);
18453 bool Player::CanNoReagentCast(SpellEntry
const* spellInfo
) const
18455 // don't take reagents for spells with SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
18456 if (spellInfo
->AttributesEx5
& SPELL_ATTR_EX5_NO_REAGENT_WHILE_PREP
&&
18457 HasFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_PREPARATION
))
18460 // Check no reagent use mask
18461 uint64 noReagentMask_0_1
= GetUInt64Value(PLAYER_NO_REAGENT_COST_1
);
18462 uint32 noReagentMask_2
= GetUInt64Value(PLAYER_NO_REAGENT_COST_1
+2);
18463 if (spellInfo
->SpellFamilyFlags
& noReagentMask_0_1
||
18464 spellInfo
->SpellFamilyFlags2
& noReagentMask_2
)
18470 void Player::RemoveItemDependentAurasAndCasts( Item
* pItem
)
18472 AuraMap
& auras
= GetAuras();
18473 for(AuraMap::iterator itr
= auras
.begin(); itr
!= auras
.end(); )
18475 Aura
* aura
= itr
->second
;
18477 // skip passive (passive item dependent spells work in another way) and not self applied auras
18478 SpellEntry
const* spellInfo
= aura
->GetSpellProto();
18479 if(aura
->IsPassive() || aura
->GetCasterGUID()!=GetGUID())
18485 // skip if not item dependent or have alternative item
18486 if(HasItemFitToSpellReqirements(spellInfo
,pItem
))
18492 // no alt item, remove aura, restart check
18493 RemoveAurasDueToSpell(aura
->GetId());
18494 itr
= auras
.begin();
18497 // currently casted spells can be dependent from item
18498 for (uint32 i
= 0; i
< CURRENT_MAX_SPELL
; i
++)
18500 if( m_currentSpells
[i
] && m_currentSpells
[i
]->getState()!=SPELL_STATE_DELAYED
&&
18501 !HasItemFitToSpellReqirements(m_currentSpells
[i
]->m_spellInfo
,pItem
) )
18506 uint32
Player::GetResurrectionSpellId()
18508 // search priceless resurrection possibilities
18510 uint32 spell_id
= 0;
18511 AuraList
const& dummyAuras
= GetAurasByType(SPELL_AURA_DUMMY
);
18512 for(AuraList::const_iterator itr
= dummyAuras
.begin(); itr
!= dummyAuras
.end(); ++itr
)
18514 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18515 if( prio
< 2 && (*itr
)->GetSpellProto()->SpellVisual
[0] == 99 && (*itr
)->GetSpellProto()->SpellIconID
== 92 )
18517 switch((*itr
)->GetId())
18519 case 20707: spell_id
= 3026; break; // rank 1
18520 case 20762: spell_id
= 20758; break; // rank 2
18521 case 20763: spell_id
= 20759; break; // rank 3
18522 case 20764: spell_id
= 20760; break; // rank 4
18523 case 20765: spell_id
= 20761; break; // rank 5
18524 case 27239: spell_id
= 27240; break; // rank 6
18525 case 47883: spell_id
= 47882; break; // rank 7
18527 sLog
.outError("Unhandled spell %%u: S.Resurrection",(*itr
)->GetId());
18533 // Twisting Nether // prio: 2 (max)
18534 else if((*itr
)->GetId()==23701 && roll_chance_i(10))
18541 // Reincarnation (passive spell) // prio: 1
18542 if(prio
< 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18548 // Used in triggers for check "Only to targets that grant experience or honor" req
18549 bool Player::isHonorOrXPTarget(Unit
* pVictim
)
18551 uint32 v_level
= pVictim
->getLevel();
18552 uint32 k_grey
= MaNGOS::XP::GetGrayLevel(getLevel());
18554 // Victim level less gray level
18555 if(v_level
<=k_grey
)
18558 if(pVictim
->GetTypeId() == TYPEID_UNIT
)
18560 if (((Creature
*)pVictim
)->isTotem() ||
18561 ((Creature
*)pVictim
)->isPet() ||
18562 ((Creature
*)pVictim
)->GetCreatureInfo()->flags_extra
& CREATURE_FLAG_EXTRA_NO_XP_AT_KILL
)
18568 bool Player::RewardPlayerAndGroupAtKill(Unit
* pVictim
)
18570 bool PvP
= pVictim
->isCharmedOwnedByPlayerOrPlayer();
18572 // prepare data for near group iteration (PvP and !PvP cases)
18574 bool honored_kill
= false;
18576 if(Group
*pGroup
= GetGroup())
18579 uint32 sum_level
= 0;
18580 Player
* member_with_max_level
= NULL
;
18581 Player
* not_gray_member_with_max_level
= NULL
;
18583 pGroup
->GetDataForXPAtKill(pVictim
,count
,sum_level
,member_with_max_level
,not_gray_member_with_max_level
);
18585 if(member_with_max_level
)
18587 /// not get Xp in PvP or no not gray players in group
18588 xp
= (PvP
|| !not_gray_member_with_max_level
) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level
, pVictim
);
18590 /// skip in check PvP case (for speed, not used)
18591 bool is_raid
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsRaid() && pGroup
->isRaidGroup();
18592 bool is_dungeon
= PvP
? false : sMapStore
.LookupEntry(GetMapId())->IsDungeon();
18593 float group_rate
= MaNGOS::XP::xp_in_group_rate(count
,is_raid
);
18595 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
18597 Player
* pGroupGuy
= itr
->getSource();
18601 if(!pGroupGuy
->IsAtGroupRewardDistance(pVictim
))
18602 continue; // member (alive or dead) or his corpse at req. distance
18604 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18605 if(pGroupGuy
->isAlive() && pGroupGuy
->RewardHonor(pVictim
,count
) && pGroupGuy
==this)
18606 honored_kill
= true;
18608 // xp and reputation only in !PvP case
18611 float rate
= group_rate
* float(pGroupGuy
->getLevel()) / sum_level
;
18613 // if is in dungeon then all receive full reputation at kill
18614 // rewarded any alive/dead/near_corpse group member
18615 pGroupGuy
->RewardReputation(pVictim
,is_dungeon
? 1.0f
: rate
);
18617 // XP updated only for alive group member
18618 if(pGroupGuy
->isAlive() && not_gray_member_with_max_level
&&
18619 pGroupGuy
->getLevel() <= not_gray_member_with_max_level
->getLevel())
18621 uint32 itr_xp
= (member_with_max_level
== not_gray_member_with_max_level
) ? uint32(xp
*rate
) : uint32((xp
*rate
/2)+1);
18623 pGroupGuy
->GiveXP(itr_xp
, pVictim
);
18624 if(Pet
* pet
= pGroupGuy
->GetPet())
18625 pet
->GivePetXP(itr_xp
/2);
18628 // quest objectives updated only for alive group member or dead but with not released body
18629 if(pGroupGuy
->isAlive()|| !pGroupGuy
->GetCorpse())
18631 // normal creature (not pet/etc) can be only in !PvP case
18632 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
18633 pGroupGuy
->KilledMonster(pVictim
->GetEntry(), pVictim
->GetGUID());
18639 else // if (!pGroup)
18641 xp
= PvP
? 0 : MaNGOS::XP::Gain(this, pVictim
);
18643 // honor can be in PvP and !PvP (racial leader) cases
18644 if(RewardHonor(pVictim
,1))
18645 honored_kill
= true;
18647 // xp and reputation only in !PvP case
18650 RewardReputation(pVictim
,1);
18651 GiveXP(xp
, pVictim
);
18653 if(Pet
* pet
= GetPet())
18654 pet
->GivePetXP(xp
);
18656 // normal creature (not pet/etc) can be only in !PvP case
18657 if(pVictim
->GetTypeId()==TYPEID_UNIT
)
18658 KilledMonster(pVictim
->GetEntry(),pVictim
->GetGUID());
18661 return xp
|| honored_kill
;
18664 void Player::RewardPlayerAndGroupAtEvent(uint32 creature_id
, WorldObject
* pRewardSource
)
18666 uint64 creature_guid
= pRewardSource
->GetTypeId()==TYPEID_UNIT
? pRewardSource
->GetGUID() : uint64(0);
18668 // prepare data for near group iteration
18669 if(Group
*pGroup
= GetGroup())
18671 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
18673 Player
* pGroupGuy
= itr
->getSource();
18677 if(!pGroupGuy
->IsAtGroupRewardDistance(pRewardSource
))
18678 continue; // member (alive or dead) or his corpse at req. distance
18680 // quest objectives updated only for alive group member or dead but with not released body
18681 if(pGroupGuy
->isAlive()|| !pGroupGuy
->GetCorpse())
18682 pGroupGuy
->KilledMonster(creature_id
, creature_guid
);
18685 else // if (!pGroup)
18686 KilledMonster(creature_id
, creature_guid
);
18689 bool Player::IsAtGroupRewardDistance(WorldObject
const* pRewardSource
) const
18691 if(pRewardSource
->GetDistance(this) <= sWorld
.getConfig(CONFIG_GROUP_XP_DISTANCE
))
18697 Corpse
* corpse
= GetCorpse();
18701 return pRewardSource
->GetDistance(corpse
) <= sWorld
.getConfig(CONFIG_GROUP_XP_DISTANCE
);
18704 uint32
Player::GetBaseWeaponSkillValue (WeaponAttackType attType
) const
18706 Item
* item
= GetWeaponForAttack(attType
,true);
18708 // unarmed only with base attack
18709 if(attType
!= BASE_ATTACK
&& !item
)
18712 // weapon skill or (unarmed for base attack)
18713 uint32 skill
= item
? item
->GetSkill() : SKILL_UNARMED
;
18714 return GetBaseSkillValue(skill
);
18717 void Player::ResurectUsingRequestData()
18719 /// Teleport before resurrecting, otherwise the player might get attacked from creatures near his corpse
18720 TeleportTo(m_resurrectMap
, m_resurrectX
, m_resurrectY
, m_resurrectZ
, GetOrientation());
18722 ResurrectPlayer(0.0f
,false);
18724 if(GetMaxHealth() > m_resurrectHealth
)
18725 SetHealth( m_resurrectHealth
);
18727 SetHealth( GetMaxHealth() );
18729 if(GetMaxPower(POWER_MANA
) > m_resurrectMana
)
18730 SetPower(POWER_MANA
, m_resurrectMana
);
18732 SetPower(POWER_MANA
, GetMaxPower(POWER_MANA
) );
18734 SetPower(POWER_RAGE
, 0 );
18736 SetPower(POWER_ENERGY
, GetMaxPower(POWER_ENERGY
) );
18738 SpawnCorpseBones();
18741 void Player::SetClientControl(Unit
* target
, uint8 allowMove
)
18743 WorldPacket
data(SMSG_CLIENT_CONTROL_UPDATE
, target
->GetPackGUID().size()+1);
18744 data
.append(target
->GetPackGUID());
18745 data
<< uint8(allowMove
);
18746 GetSession()->SendPacket(&data
);
18749 void Player::UpdateZoneDependentAuras( uint32 newZone
)
18751 // remove new continent flight forms
18752 if( !IsAllowUseFlyMountsHere() )
18754 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED
);
18755 RemoveSpellsCausingAura(SPELL_AURA_FLY
);
18758 // Some spells applied at enter into zone (with subzones), aura removed in UpdateAreaDependentAuras that called always at zone->area update
18759 SpellAreaForAreaMapBounds saBounds
= spellmgr
.GetSpellAreaForAreaMapBounds(newZone
);
18760 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
18761 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,newZone
,0))
18762 if( !HasAura(itr
->second
->spellId
,0) )
18763 CastSpell(this,itr
->second
->spellId
,true);
18766 void Player::UpdateAreaDependentAuras( uint32 newArea
)
18768 // remove auras from spells with area limitations
18769 for(AuraMap::iterator iter
= m_Auras
.begin(); iter
!= m_Auras
.end();)
18771 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18772 if(spellmgr
.GetSpellAllowedInLocationError(iter
->second
->GetSpellProto(),GetMapId(),m_zoneUpdateId
,newArea
,this) != SPELL_CAST_OK
)
18778 // some auras applied at subzone enter
18779 SpellAreaForAreaMapBounds saBounds
= spellmgr
.GetSpellAreaForAreaMapBounds(newArea
);
18780 for(SpellAreaForAreaMap::const_iterator itr
= saBounds
.first
; itr
!= saBounds
.second
; ++itr
)
18781 if(itr
->second
->autocast
&& itr
->second
->IsFitToRequirements(this,m_zoneUpdateId
,newArea
))
18782 if( !HasAura(itr
->second
->spellId
,0) )
18783 CastSpell(this,itr
->second
->spellId
,true);
18786 uint32
Player::GetCorpseReclaimDelay(bool pvp
) const
18788 if( pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18789 !pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18791 return copseReclaimDelay
[0];
18794 time_t now
= time(NULL
);
18795 // 0..2 full period
18796 uint32 count
= (now
< m_deathExpireTime
) ? (m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
: 0;
18797 return copseReclaimDelay
[count
];
18800 void Player::UpdateCorpseReclaimDelay()
18802 bool pvp
= m_ExtraFlags
& PLAYER_EXTRA_PVP_DEATH
;
18804 if( pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18805 !pvp
&& !sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18808 time_t now
= time(NULL
);
18809 if(now
< m_deathExpireTime
)
18811 // full and partly periods 1..3
18812 uint32 count
= (m_deathExpireTime
- now
)/DEATH_EXPIRE_STEP
+1;
18813 if(count
< MAX_DEATH_COUNT
)
18814 m_deathExpireTime
= now
+(count
+1)*DEATH_EXPIRE_STEP
;
18816 m_deathExpireTime
= now
+MAX_DEATH_COUNT
*DEATH_EXPIRE_STEP
;
18819 m_deathExpireTime
= now
+DEATH_EXPIRE_STEP
;
18822 void Player::SendCorpseReclaimDelay(bool load
)
18824 Corpse
* corpse
= GetCorpse();
18831 if(corpse
->GetGhostTime() > m_deathExpireTime
)
18834 bool pvp
= corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
;
18837 if( pvp
&& sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP
) ||
18838 !pvp
&& sWorld
.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE
) )
18840 count
= (m_deathExpireTime
-corpse
->GetGhostTime())/DEATH_EXPIRE_STEP
;
18841 if(count
>=MAX_DEATH_COUNT
)
18842 count
= MAX_DEATH_COUNT
-1;
18847 time_t expected_time
= corpse
->GetGhostTime()+copseReclaimDelay
[count
];
18849 time_t now
= time(NULL
);
18850 if(now
>= expected_time
)
18853 delay
= expected_time
-now
;
18856 delay
= GetCorpseReclaimDelay(corpse
->GetType()==CORPSE_RESURRECTABLE_PVP
);
18858 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
18859 WorldPacket
data(SMSG_CORPSE_RECLAIM_DELAY
, 4);
18860 data
<< uint32(delay
*IN_MILISECONDS
);
18861 GetSession()->SendPacket( &data
);
18864 Player
* Player::GetNextRandomRaidMember(float radius
)
18866 Group
*pGroup
= GetGroup();
18870 std::vector
<Player
*> nearMembers
;
18871 nearMembers
.reserve(pGroup
->GetMembersCount());
18873 for(GroupReference
*itr
= pGroup
->GetFirstMember(); itr
!= NULL
; itr
= itr
->next())
18875 Player
* Target
= itr
->getSource();
18877 // IsHostileTo check duel and controlled by enemy
18878 if( Target
&& Target
!= this && IsWithinDistInMap(Target
, radius
) &&
18879 !Target
->HasInvisibilityAura() && !IsHostileTo(Target
) )
18880 nearMembers
.push_back(Target
);
18883 if (nearMembers
.empty())
18886 uint32 randTarget
= urand(0,nearMembers
.size()-1);
18887 return nearMembers
[randTarget
];
18890 PartyResult
Player::CanUninviteFromGroup() const
18892 const Group
* grp
= GetGroup();
18894 return PARTY_RESULT_YOU_NOT_IN_GROUP
;
18896 if(!grp
->IsLeader(GetGUID()) && !grp
->IsAssistant(GetGUID()))
18897 return PARTY_RESULT_YOU_NOT_LEADER
;
18899 if(InBattleGround())
18900 return PARTY_RESULT_INVITE_RESTRICTED
;
18902 return PARTY_RESULT_OK
;
18905 void Player::SetBattleGroundRaid(Group
* group
, int8 subgroup
)
18907 //we must move references from m_group to m_originalGroup
18908 SetOriginalGroup(GetGroup(), GetSubGroup());
18911 m_group
.link(group
, this);
18912 m_group
.setSubGroup((uint8
)subgroup
);
18915 void Player::RemoveFromBattleGroundRaid()
18917 //remove existing reference
18919 if( Group
* group
= GetOriginalGroup() )
18921 m_group
.link(group
, this);
18922 m_group
.setSubGroup(GetOriginalSubGroup());
18924 SetOriginalGroup(NULL
);
18927 void Player::SetOriginalGroup(Group
*group
, int8 subgroup
)
18929 if( group
== NULL
)
18930 m_originalGroup
.unlink();
18933 // never use SetOriginalGroup without a subgroup unless you specify NULL for group
18934 assert(subgroup
>= 0);
18935 m_originalGroup
.link(group
, this);
18936 m_originalGroup
.setSubGroup((uint8
)subgroup
);
18940 void Player::UpdateUnderwaterState( Map
* m
, float x
, float y
, float z
)
18942 LiquidData liquid_status
;
18943 ZLiquidStatus res
= m
->getLiquidStatus(x
, y
, z
, MAP_ALL_LIQUIDS
, &liquid_status
);
18946 m_MirrorTimerFlags
&= ~(UNDERWATER_INWATER
|UNDERWATER_INLAVA
|UNDERWATER_INSLIME
|UNDERWARER_INDARKWATER
);
18947 // Small hack for enable breath in WMO
18949 m_MirrorTimerFlags
|=UNDERWATER_INWATER
;
18953 // All liquids type - check under water position
18954 if (liquid_status
.type
&(MAP_LIQUID_TYPE_WATER
|MAP_LIQUID_TYPE_OCEAN
|MAP_LIQUID_TYPE_MAGMA
|MAP_LIQUID_TYPE_SLIME
))
18956 if ( res
& LIQUID_MAP_UNDER_WATER
)
18957 m_MirrorTimerFlags
|= UNDERWATER_INWATER
;
18959 m_MirrorTimerFlags
&= ~UNDERWATER_INWATER
;
18962 // Allow travel in dark water on taxi or transport
18963 if (liquid_status
.type
& MAP_LIQUID_TYPE_DARK_WATER
&& !isInFlight() && !(GetUnitMovementFlags()&MOVEMENTFLAG_ONTRANSPORT
))
18964 m_MirrorTimerFlags
|= UNDERWARER_INDARKWATER
;
18966 m_MirrorTimerFlags
&= ~UNDERWARER_INDARKWATER
;
18968 // in lava check, anywhere in lava level
18969 if (liquid_status
.type
&MAP_LIQUID_TYPE_MAGMA
)
18971 if (res
& (LIQUID_MAP_UNDER_WATER
|LIQUID_MAP_IN_WATER
|LIQUID_MAP_WATER_WALK
))
18972 m_MirrorTimerFlags
|= UNDERWATER_INLAVA
;
18974 m_MirrorTimerFlags
&= ~UNDERWATER_INLAVA
;
18976 // in slime check, anywhere in slime level
18977 if (liquid_status
.type
&MAP_LIQUID_TYPE_SLIME
)
18979 if (res
& (LIQUID_MAP_UNDER_WATER
|LIQUID_MAP_IN_WATER
|LIQUID_MAP_WATER_WALK
))
18980 m_MirrorTimerFlags
|= UNDERWATER_INSLIME
;
18982 m_MirrorTimerFlags
&= ~UNDERWATER_INSLIME
;
18986 void Player::SetCanParry( bool value
)
18988 if(m_canParry
==value
)
18991 m_canParry
= value
;
18992 UpdateParryPercentage();
18995 void Player::SetCanBlock( bool value
)
18997 if(m_canBlock
==value
)
19000 m_canBlock
= value
;
19001 UpdateBlockPercentage();
19004 bool ItemPosCount::isContainedIn(ItemPosCountVec
const& vec
) const
19006 for(ItemPosCountVec::const_iterator itr
= vec
.begin(); itr
!= vec
.end();++itr
)
19007 if(itr
->pos
== pos
)
19013 bool Player::CanUseBattleGroundObject()
19015 return ( //InBattleGround() && // in battleground - not need, check in other cases
19016 //!IsMounted() && - not correct, player is dismounted when he clicks on flag
19017 //i'm not sure if these two are correct, because invisible players should get visible when they click on flag
19018 !isTotalImmune() && // not totally immune
19019 !HasStealthAura() && // not stealthed
19020 !HasInvisibilityAura() && // not invisible
19021 !HasAura(SPELL_RECENTLY_DROPPED_FLAG
, 0) && // can't pickup
19022 //TODO player cannot use object when he is invulnerable (immune) - (ice block, divine shield, divine protection, divine intervention ...)
19023 isAlive() // live player
19027 bool Player::CanCaptureTowerPoint()
19029 return ( !HasStealthAura() && // not stealthed
19030 !HasInvisibilityAura() && // not invisible
19031 isAlive() // live player
19035 uint32
Player::GetBarberShopCost(uint8 newhairstyle
, uint8 newhaircolor
, uint8 newfacialhair
)
19037 uint32 level
= getLevel();
19039 if(level
> GT_MAX_LEVEL
)
19040 level
= GT_MAX_LEVEL
; // max level in this dbc
19042 uint8 hairstyle
= GetByteValue(PLAYER_BYTES
, 2);
19043 uint8 haircolor
= GetByteValue(PLAYER_BYTES
, 3);
19044 uint8 facialhair
= GetByteValue(PLAYER_BYTES_2
, 0);
19046 if((hairstyle
== newhairstyle
) && (haircolor
== newhaircolor
) && (facialhair
== newfacialhair
))
19049 GtBarberShopCostBaseEntry
const *bsc
= sGtBarberShopCostBaseStore
.LookupEntry(level
- 1);
19051 if(!bsc
) // shouldn't happen
19056 if(hairstyle
!= newhairstyle
)
19057 cost
+= bsc
->cost
; // full price
19059 if((haircolor
!= newhaircolor
) && (hairstyle
== newhairstyle
))
19060 cost
+= bsc
->cost
* 0.5f
; // +1/2 of price
19062 if(facialhair
!= newfacialhair
)
19063 cost
+= bsc
->cost
* 0.75f
; // +3/4 of price
19065 return uint32(cost
);
19068 void Player::InitGlyphsForLevel()
19070 for(uint32 i
= 0; i
< sGlyphSlotStore
.GetNumRows(); ++i
)
19071 if(GlyphSlotEntry
const * gs
= sGlyphSlotStore
.LookupEntry(i
))
19073 SetGlyphSlot(gs
->Order
- 1, gs
->Id
);
19075 uint32 level
= getLevel();
19078 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
19080 value
|= (0x01 | 0x02);
19090 SetUInt32Value(PLAYER_GLYPHS_ENABLED
, value
);
19093 void Player::EnterVehicle(Vehicle
*vehicle
)
19095 VehicleEntry
const *ve
= sVehicleStore
.LookupEntry(vehicle
->GetVehicleId());
19099 VehicleSeatEntry
const *veSeat
= sVehicleSeatStore
.LookupEntry(ve
->m_seatID
[0]);
19103 vehicle
->SetCharmerGUID(GetGUID());
19104 vehicle
->RemoveFlag(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_SPELLCLICK
);
19105 vehicle
->SetFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_UNK_24
);
19106 vehicle
->setFaction(getFaction());
19108 SetCharm(vehicle
); // charm
19109 SetFarSightGUID(vehicle
->GetGUID()); // set view
19111 SetClientControl(vehicle
, 1); // redirect controls to vehicle
19113 WorldPacket
data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA
, 0);
19114 GetSession()->SendPacket(&data
);
19116 data
.Initialize(MSG_MOVE_TELEPORT_ACK
, 30);
19117 data
.append(GetPackGUID());
19118 data
<< uint32(0); // counter?
19119 data
<< uint32(MOVEMENTFLAG_ONTRANSPORT
); // transport
19120 data
<< uint16(0); // special flags
19121 data
<< uint32(getMSTime()); // time
19122 data
<< vehicle
->GetPositionX(); // x
19123 data
<< vehicle
->GetPositionY(); // y
19124 data
<< vehicle
->GetPositionZ(); // z
19125 data
<< vehicle
->GetOrientation(); // o
19126 // transport part, TODO: load/calculate seat offsets
19127 data
<< uint64(vehicle
->GetGUID()); // transport guid
19128 data
<< float(veSeat
->m_attachmentOffsetX
); // transport offsetX
19129 data
<< float(veSeat
->m_attachmentOffsetY
); // transport offsetY
19130 data
<< float(veSeat
->m_attachmentOffsetZ
); // transport offsetZ
19131 data
<< float(0); // transport orientation
19132 data
<< uint32(getMSTime()); // transport time
19133 data
<< uint8(0); // seat
19134 // end of transport part
19135 data
<< uint32(0); // fall time
19136 GetSession()->SendPacket(&data
);
19138 data
.Initialize(SMSG_PET_SPELLS
, 8+4+4+4+4*10+1+1);
19139 data
<< uint64(vehicle
->GetGUID());
19140 data
<< uint32(0x00000000);
19141 data
<< uint32(0x00000000);
19142 data
<< uint32(0x00000101);
19144 for(uint32 i
= 0; i
< 10; ++i
)
19145 data
<< uint16(0) << uint8(0) << uint8(i
+8);
19149 GetSession()->SendPacket(&data
);
19152 void Player::ExitVehicle(Vehicle
*vehicle
)
19154 vehicle
->SetCharmerGUID(0);
19155 vehicle
->SetFlag(UNIT_NPC_FLAGS
, UNIT_NPC_FLAG_SPELLCLICK
);
19156 vehicle
->RemoveFlag(UNIT_FIELD_FLAGS
, UNIT_FLAG_UNK_24
);
19157 vehicle
->setFaction((GetTeam() == ALLIANCE
) ? vehicle
->GetCreatureInfo()->faction_A
: vehicle
->GetCreatureInfo()->faction_H
);
19160 SetFarSightGUID(0);
19162 SetClientControl(vehicle
, 0);
19164 WorldPacket
data(MSG_MOVE_TELEPORT_ACK
, 30);
19165 data
.append(GetPackGUID());
19166 data
<< uint32(0); // counter?
19167 data
<< uint32(MOVEMENTFLAG_FLY_UNK1
); // fly unk
19168 data
<< uint16(0x40); // special flags
19169 data
<< uint32(getMSTime()); // time
19170 data
<< vehicle
->GetPositionX(); // x
19171 data
<< vehicle
->GetPositionY(); // y
19172 data
<< vehicle
->GetPositionZ(); // z
19173 data
<< vehicle
->GetOrientation(); // o
19174 data
<< uint32(0); // fall time
19175 GetSession()->SendPacket(&data
);
19177 data
.Initialize(SMSG_PET_SPELLS
, 8+4);
19180 GetSession()->SendPacket(&data
);
19182 // only for flyable vehicles?
19183 CastSpell(this, 45472, true); // Parachute
19186 bool Player::isTotalImmune()
19188 AuraList
const& immune
= GetAurasByType(SPELL_AURA_SCHOOL_IMMUNITY
);
19190 uint32 immuneMask
= 0;
19191 for(AuraList::const_iterator itr
= immune
.begin(); itr
!= immune
.end(); ++itr
)
19193 immuneMask
|= (*itr
)->GetModifier()->m_miscvalue
;
19194 if( immuneMask
& SPELL_SCHOOL_MASK_ALL
) // total immunity
19200 bool Player::HasTitle(uint32 bitIndex
)
19202 if (bitIndex
> 128)
19205 uint32 fieldIndexOffset
= bitIndex
/32;
19206 uint32 flag
= 1 << (bitIndex
%32);
19207 return HasFlag(PLAYER__FIELD_KNOWN_TITLES
+fieldIndexOffset
, flag
);
19210 void Player::SetTitle(CharTitlesEntry
const* title
)
19212 uint32 fieldIndexOffset
= title
->bit_index
/32;
19213 uint32 flag
= 1 << (title
->bit_index
%32);
19214 SetFlag(PLAYER__FIELD_KNOWN_TITLES
+fieldIndexOffset
, flag
);
19217 void Player::ConvertRune(uint8 index
, uint8 newType
)
19219 SetCurrentRune(index
, newType
);
19221 WorldPacket
data(SMSG_CONVERT_RUNE
, 2);
19222 data
<< uint8(index
);
19223 data
<< uint8(newType
);
19224 GetSession()->SendPacket(&data
);
19227 void Player::ResyncRunes(uint8 count
)
19229 WorldPacket
data(SMSG_RESYNC_RUNES
, count
* 2);
19230 for(uint32 i
= 0; i
< count
; ++i
)
19232 data
<< uint8(GetCurrentRune(i
)); // rune type
19233 data
<< uint8(255 - (GetRuneCooldown(i
) * 51)); // passed cooldown time (0-255)
19235 GetSession()->SendPacket(&data
);
19238 void Player::AddRunePower(uint8 index
)
19240 WorldPacket
data(SMSG_ADD_RUNE_POWER
, 4);
19241 data
<< uint32(1 << index
); // mask (0x00-0x3F probably)
19242 GetSession()->SendPacket(&data
);
19245 void Player::InitRunes()
19247 if(getClass() != CLASS_DEATH_KNIGHT
)
19250 m_runes
= new Runes
;
19252 m_runes
->runeState
= 0;
19254 for(uint32 i
= 0; i
< MAX_RUNES
; ++i
)
19256 SetBaseRune(i
, i
/ 2); // init base types
19257 SetCurrentRune(i
, i
/ 2); // init current types
19258 SetRuneCooldown(i
, 0); // reset cooldowns
19259 m_runes
->SetRuneState(i
);
19262 for(uint32 i
= 0; i
< NUM_RUNE_TYPES
; ++i
)
19263 SetFloatValue(PLAYER_RUNE_REGEN_1
+ i
, 0.1f
);
19266 void Player::AutoStoreLoot(uint8 bag
, uint8 slot
, uint32 loot_id
, LootStore
const& store
, bool broadcast
)
19269 loot
.FillLoot (loot_id
,store
,this,true);
19271 uint32 max_slot
= loot
.GetMaxSlotInLootFor(this);
19272 for(uint32 i
= 0; i
< max_slot
; ++i
)
19274 LootItem
* lootItem
= loot
.LootItemInSlot(i
,this);
19276 ItemPosCountVec dest
;
19277 uint8 msg
= CanStoreNewItem (bag
,slot
,dest
,lootItem
->itemid
,lootItem
->count
);
19278 if(msg
!= EQUIP_ERR_OK
&& slot
!= NULL_SLOT
)
19279 msg
= CanStoreNewItem( bag
, NULL_SLOT
,dest
,lootItem
->itemid
,lootItem
->count
);
19280 if( msg
!= EQUIP_ERR_OK
&& bag
!= NULL_BAG
)
19281 msg
= CanStoreNewItem( NULL_BAG
, NULL_SLOT
,dest
,lootItem
->itemid
,lootItem
->count
);
19282 if(msg
!= EQUIP_ERR_OK
)
19284 SendEquipError( msg
, NULL
, NULL
);
19288 Item
* pItem
= StoreNewItem (dest
,lootItem
->itemid
,true,lootItem
->randomPropertyId
);
19289 SendNewItem(pItem
, lootItem
->count
, false, false, broadcast
);
19293 uint32
Player::CalculateTalentsPoints() const
19295 uint32 base_talent
= getLevel() < 10 ? 0 : uint32((getLevel()-9)*sWorld
.getRate(RATE_TALENT
));
19297 if(getClass() != CLASS_DEATH_KNIGHT
)
19298 return base_talent
;
19300 uint32 talentPointsForLevel
=
19301 (getLevel() < 56 ? 0 : uint32((getLevel()-55)*sWorld
.getRate(RATE_TALENT
)))
19302 + m_questRewardTalentCount
;
19304 if(talentPointsForLevel
> base_talent
)
19305 talentPointsForLevel
= base_talent
;
19307 return talentPointsForLevel
;
19310 bool Player::IsAllowUseFlyMountsHere() const
19312 if (isGameMaster())
19315 uint32 v_map
= GetVirtualMapForMapAndZone(GetMapId(), GetZoneId());
19316 return v_map
== 530 || v_map
== 571 && HasSpell(54197);
19319 void Player::learnSpellHighRank(uint32 spellid
)
19321 learnSpell(spellid
,false);
19323 SpellChainMapNext
const& nextMap
= spellmgr
.GetSpellChainNext();
19324 for(SpellChainMapNext::const_iterator itr
= nextMap
.lower_bound(spellid
); itr
!= nextMap
.upper_bound(spellid
); ++itr
)
19325 learnSpellHighRank(itr
->second
);
19328 void Player::_LoadSkills()
19330 // Note: skill data itself loaded from `data` field. This is only cleanup part of load
19332 // reset skill modifiers and set correct unlearn flags
19333 for (uint32 i
= 0; i
< PLAYER_MAX_SKILLS
; i
++)
19335 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i
),0);
19337 // set correct unlearn bit
19338 uint32 id
= GetUInt32Value(PLAYER_SKILL_INDEX(i
)) & 0x0000FFFF;
19341 SkillLineEntry
const *pSkill
= sSkillLineStore
.LookupEntry(id
);
19342 if(!pSkill
) continue;
19344 // enable unlearn button for primary professions only
19345 if (pSkill
->categoryId
== SKILL_CATEGORY_PROFESSION
)
19346 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,1));
19348 SetUInt32Value(PLAYER_SKILL_INDEX(i
), MAKE_PAIR32(id
,0));
19350 // set fixed skill ranges
19351 switch(GetSkillRangeType(pSkill
,false))
19353 case SKILL_RANGE_LANGUAGE
: // 300..300
19354 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(300,300));
19356 case SKILL_RANGE_MONO
: // 1..1, grey monolite bar
19357 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
),MAKE_SKILL_VALUE(1,1));
19363 uint32 vskill
= SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i
)));
19364 learnSkillRewardedSpells(id
, vskill
);
19367 // special settings
19368 if(getClass()==CLASS_DEATH_KNIGHT
)
19370 uint32 base_level
= std::min(getLevel(),sWorld
.getConfig (CONFIG_START_HEROIC_PLAYER_LEVEL
));
19373 uint32 base_skill
= (base_level
-1)*5; // 270 at starting level 55
19375 base_skill
= 1; // skill mast be known and then > 0 in any case
19377 if(GetPureSkillValue (SKILL_FIRST_AID
) < base_skill
)
19378 SetSkill(SKILL_FIRST_AID
,base_skill
, base_skill
);
19379 if(GetPureSkillValue (SKILL_AXES
) < base_skill
)
19380 SetSkill(SKILL_AXES
, base_skill
,base_skill
);
19381 if(GetPureSkillValue (SKILL_DEFENSE
) < base_skill
)
19382 SetSkill(SKILL_DEFENSE
, base_skill
,base_skill
);
19383 if(GetPureSkillValue (SKILL_POLEARMS
) < base_skill
)
19384 SetSkill(SKILL_POLEARMS
, base_skill
,base_skill
);
19385 if(GetPureSkillValue (SKILL_SWORDS
) < base_skill
)
19386 SetSkill(SKILL_SWORDS
, base_skill
,base_skill
);
19387 if(GetPureSkillValue (SKILL_2H_AXES
) < base_skill
)
19388 SetSkill(SKILL_2H_AXES
, base_skill
,base_skill
);
19389 if(GetPureSkillValue (SKILL_2H_SWORDS
) < base_skill
)
19390 SetSkill(SKILL_2H_SWORDS
, base_skill
,base_skill
);
19391 if(GetPureSkillValue (SKILL_UNARMED
) < base_skill
)
19392 SetSkill(SKILL_UNARMED
, base_skill
,base_skill
);
19396 uint32
Player::GetPhaseMaskForSpawn() const
19398 uint32 phase
= PHASEMASK_NORMAL
;
19399 if(!isGameMaster())
19400 phase
= GetPhaseMask();
19403 AuraList
const& phases
= GetAurasByType(SPELL_AURA_PHASE
);
19404 if(!phases
.empty())
19405 phase
= phases
.front()->GetMiscValue();
19408 // some aura phases include 1 normal map in addition to phase itself
19409 if(uint32 n_phase
= phase
& ~PHASEMASK_NORMAL
)
19412 return PHASEMASK_NORMAL
;
19415 uint8
Player::CanEquipUniqueItem(Item
* pItem
, uint8 eslot
, uint32 limit_count
) const
19417 ItemPrototype
const* pProto
= pItem
->GetProto();
19419 // proto based limitations
19420 if(uint8 res
= CanEquipUniqueItem(pProto
,eslot
,limit_count
))
19423 // check unique-equipped on gems
19424 for(uint32 enchant_slot
= SOCK_ENCHANTMENT_SLOT
; enchant_slot
< SOCK_ENCHANTMENT_SLOT
+3; ++enchant_slot
)
19426 uint32 enchant_id
= pItem
->GetEnchantmentId(EnchantmentSlot(enchant_slot
));
19429 SpellItemEnchantmentEntry
const* enchantEntry
= sSpellItemEnchantmentStore
.LookupEntry(enchant_id
);
19433 ItemPrototype
const* pGem
= objmgr
.GetItemPrototype(enchantEntry
->GemID
);
19437 // include for check equip another gems with same limit category for not equipped item (and then not counted)
19438 uint32 gem_limit_count
= !pItem
->IsEquipped() && pGem
->ItemLimitCategory
19439 ? pItem
->GetGemCountWithLimitCategory(pGem
->ItemLimitCategory
) : 1;
19441 if(uint8 res
= CanEquipUniqueItem(pGem
, eslot
,gem_limit_count
))
19445 return EQUIP_ERR_OK
;
19448 uint8
Player::CanEquipUniqueItem( ItemPrototype
const* itemProto
, uint8 except_slot
, uint32 limit_count
) const
19450 // check unique-equipped on item
19451 if (itemProto
->Flags
& ITEM_FLAGS_UNIQUE_EQUIPPED
)
19453 // there is an equip limit on this item
19454 if(HasItemOrGemWithIdEquipped(itemProto
->ItemId
,1,except_slot
))
19455 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
19458 // check unique-equipped limit
19459 if (itemProto
->ItemLimitCategory
)
19461 ItemLimitCategoryEntry
const* limitEntry
= sItemLimitCategoryStore
.LookupEntry(itemProto
->ItemLimitCategory
);
19463 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
19465 if(limit_count
> limitEntry
->maxCount
)
19466 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
; // attempt add too many limit category items (gems)
19468 // there is an equip limit on this item
19469 if(HasItemOrGemWithLimitCategoryEquipped(itemProto
->ItemLimitCategory
,limitEntry
->maxCount
-limit_count
+1,except_slot
))
19470 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE
;
19473 return EQUIP_ERR_OK
;
19476 void Player::HandleFall(MovementInfo
const& movementInfo
)
19478 // calculate total z distance of the fall
19479 float z_diff
= m_lastFallZ
- movementInfo
.z
;
19480 sLog
.outDebug("zDiff = %f", z_diff
);
19482 //Players with low fall distance, Feather Fall or physical immunity (charges used) are ignored
19483 // 14.57 can be calculated by resolving damageperc formular below to 0
19484 if (z_diff
>= 14.57f
&& !isDead() && !isGameMaster() &&
19485 !HasAuraType(SPELL_AURA_HOVER
) && !HasAuraType(SPELL_AURA_FEATHER_FALL
) &&
19486 !HasAuraType(SPELL_AURA_FLY
) && !IsImmunedToDamage(SPELL_SCHOOL_MASK_NORMAL
) )
19488 //Safe fall, fall height reduction
19489 int32 safe_fall
= GetTotalAuraModifier(SPELL_AURA_SAFE_FALL
);
19491 float damageperc
= 0.018f
*(z_diff
-safe_fall
)-0.2426f
;
19495 uint32 damage
= (uint32
)(damageperc
* GetMaxHealth()*sWorld
.getRate(RATE_DAMAGE_FALL
));
19497 float height
= movementInfo
.z
;
19498 UpdateGroundPositionZ(movementInfo
.x
,movementInfo
.y
,height
);
19502 //Prevent fall damage from being more than the player maximum health
19503 if (damage
> GetMaxHealth())
19504 damage
= GetMaxHealth();
19507 if (GetDummyAura(43621))
19508 damage
= GetMaxHealth()/2;
19510 EnvironmentalDamage(DAMAGE_FALL
, damage
);
19512 // recheck alive, might have died of EnvironmentalDamage
19514 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING
, uint32(z_diff
*100));
19517 //Z given by moveinfo, LastZ, FallTime, WaterZ, MapZ, Damage, Safefall reduction
19518 DEBUG_LOG("FALLDAMAGE z=%f sz=%f pZ=%f FallTime=%d mZ=%f damage=%d SF=%d" , movementInfo
.z
, height
, GetPositionZ(), movementInfo
.fallTime
, height
, damage
, safe_fall
);
19523 void Player::UpdateAchievementCriteria( AchievementCriteriaTypes type
, uint32 miscvalue1
/*=0*/, uint32 miscvalue2
/*=0*/, Unit
*unit
/*=NULL*/, uint32 time
/*=0*/ )
19525 GetAchievementMgr().UpdateAchievementCriteria(type
, miscvalue1
,miscvalue2
,unit
,time
);
19528 void Player::LearnTalent(uint32 talentId
, uint32 talentRank
)
19530 uint32 CurTalentPoints
= GetFreeTalentPoints();
19532 if(CurTalentPoints
== 0)
19535 if (talentRank
>= MAX_TALENT_RANK
)
19538 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry( talentId
);
19543 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry( talentInfo
->TalentTab
);
19548 // prevent learn talent for different class (cheating)
19549 if( (getClassMask() & talentTabInfo
->ClassMask
) == 0 )
19552 // find current max talent rank
19553 int32 curtalent_maxrank
= 0;
19554 for(int32 k
= MAX_TALENT_RANK
-1; k
> -1; --k
)
19556 if(talentInfo
->RankID
[k
] && HasSpell(talentInfo
->RankID
[k
]))
19558 curtalent_maxrank
= k
+ 1;
19563 // we already have same or higher talent rank learned
19564 if(curtalent_maxrank
>= (talentRank
+ 1))
19567 // check if we have enough talent points
19568 if(CurTalentPoints
< (talentRank
- curtalent_maxrank
+ 1))
19571 // Check if it requires another talent
19572 if (talentInfo
->DependsOn
> 0)
19574 if(TalentEntry
const *depTalentInfo
= sTalentStore
.LookupEntry(talentInfo
->DependsOn
))
19576 bool hasEnoughRank
= false;
19577 for (int i
= talentInfo
->DependsOnRank
; i
< MAX_TALENT_RANK
; i
++)
19579 if (depTalentInfo
->RankID
[i
] != 0)
19580 if (HasSpell(depTalentInfo
->RankID
[i
]))
19581 hasEnoughRank
= true;
19583 if (!hasEnoughRank
)
19588 // Find out how many points we have in this field
19589 uint32 spentPoints
= 0;
19591 uint32 tTab
= talentInfo
->TalentTab
;
19592 if (talentInfo
->Row
> 0)
19594 unsigned int numRows
= sTalentStore
.GetNumRows();
19595 for (unsigned int i
= 0; i
< numRows
; i
++) // Loop through all talents.
19597 // Someday, someone needs to revamp
19598 const TalentEntry
*tmpTalent
= sTalentStore
.LookupEntry(i
);
19599 if (tmpTalent
) // the way talents are tracked
19601 if (tmpTalent
->TalentTab
== tTab
)
19603 for (int j
= 0; j
< MAX_TALENT_RANK
; j
++)
19605 if (tmpTalent
->RankID
[j
] != 0)
19607 if (HasSpell(tmpTalent
->RankID
[j
]))
19609 spentPoints
+= j
+ 1;
19618 // not have required min points spent in talent tree
19619 if(spentPoints
< (talentInfo
->Row
* MAX_TALENT_RANK
))
19622 // spell not set in talent.dbc
19623 uint32 spellid
= talentInfo
->RankID
[talentRank
];
19626 sLog
.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId
, talentRank
);
19631 if(HasSpell(spellid
))
19634 // learn! (other talent ranks will unlearned at learning)
19635 learnSpell(spellid
, false);
19636 sLog
.outDetail("TalentID: %u Rank: %u Spell: %u\n", talentId
, talentRank
, spellid
);
19638 // update free talent points
19639 SetFreeTalentPoints(CurTalentPoints
- (talentRank
- curtalent_maxrank
+ 1));
19642 void Player::LearnPetTalent(uint64 petGuid
, uint32 talentId
, uint32 talentRank
)
19644 Pet
*pet
= GetPet();
19649 if(petGuid
!= pet
->GetGUID())
19652 uint32 CurTalentPoints
= pet
->GetFreeTalentPoints();
19654 if(CurTalentPoints
== 0)
19657 if (talentRank
>= MAX_PET_TALENT_RANK
)
19660 TalentEntry
const *talentInfo
= sTalentStore
.LookupEntry(talentId
);
19665 TalentTabEntry
const *talentTabInfo
= sTalentTabStore
.LookupEntry(talentInfo
->TalentTab
);
19670 CreatureInfo
const *ci
= pet
->GetCreatureInfo();
19675 CreatureFamilyEntry
const *pet_family
= sCreatureFamilyStore
.LookupEntry(ci
->family
);
19680 if(pet_family
->petTalentType
< 0) // not hunter pet
19683 // prevent learn talent for different family (cheating)
19684 if(!((1 << pet_family
->petTalentType
) & talentTabInfo
->petTalentMask
))
19687 // find current max talent rank
19688 int32 curtalent_maxrank
= 0;
19689 for(int32 k
= MAX_TALENT_RANK
-1; k
> -1; --k
)
19691 if(talentInfo
->RankID
[k
] && pet
->HasSpell(talentInfo
->RankID
[k
]))
19693 curtalent_maxrank
= k
+ 1;
19698 // we already have same or higher talent rank learned
19699 if(curtalent_maxrank
>= (talentRank
+ 1))
19702 // check if we have enough talent points
19703 if(CurTalentPoints
< (talentRank
- curtalent_maxrank
+ 1))
19706 // Check if it requires another talent
19707 if (talentInfo
->DependsOn
> 0)
19709 if(TalentEntry
const *depTalentInfo
= sTalentStore
.LookupEntry(talentInfo
->DependsOn
))
19711 bool hasEnoughRank
= false;
19712 for (int i
= talentInfo
->DependsOnRank
; i
< MAX_TALENT_RANK
; i
++)
19714 if (depTalentInfo
->RankID
[i
] != 0)
19715 if (pet
->HasSpell(depTalentInfo
->RankID
[i
]))
19716 hasEnoughRank
= true;
19718 if (!hasEnoughRank
)
19723 // Find out how many points we have in this field
19724 uint32 spentPoints
= 0;
19726 uint32 tTab
= talentInfo
->TalentTab
;
19727 if (talentInfo
->Row
> 0)
19729 unsigned int numRows
= sTalentStore
.GetNumRows();
19730 for (unsigned int i
= 0; i
< numRows
; ++i
) // Loop through all talents.
19732 // Someday, someone needs to revamp
19733 const TalentEntry
*tmpTalent
= sTalentStore
.LookupEntry(i
);
19734 if (tmpTalent
) // the way talents are tracked
19736 if (tmpTalent
->TalentTab
== tTab
)
19738 for (int j
= 0; j
< MAX_TALENT_RANK
; j
++)
19740 if (tmpTalent
->RankID
[j
] != 0)
19742 if (pet
->HasSpell(tmpTalent
->RankID
[j
]))
19744 spentPoints
+= j
+ 1;
19753 // not have required min points spent in talent tree
19754 if(spentPoints
< (talentInfo
->Row
* MAX_PET_TALENT_RANK
))
19757 // spell not set in talent.dbc
19758 uint32 spellid
= talentInfo
->RankID
[talentRank
];
19761 sLog
.outError("Talent.dbc have for talent: %u Rank: %u spell id = 0", talentId
, talentRank
);
19766 if(pet
->HasSpell(spellid
))
19769 // learn! (other talent ranks will unlearned at learning)
19770 pet
->learnSpell(spellid
);
19771 sLog
.outDetail("PetTalentID: %u Rank: %u Spell: %u\n", talentId
, talentRank
, spellid
);
19773 // update free talent points
19774 pet
->SetFreeTalentPoints(CurTalentPoints
- (talentRank
- curtalent_maxrank
+ 1));
19777 void Player::UpdateKnownCurrencies(uint32 itemId
, bool apply
)
19779 if(CurrencyTypesEntry
const* ctEntry
= sCurrencyTypesStore
.LookupEntry(itemId
))
19782 SetFlag64(PLAYER_FIELD_KNOWN_CURRENCIES
,(1LL << (ctEntry
->BitIndex
-1)));
19784 RemoveFlag64(PLAYER_FIELD_KNOWN_CURRENCIES
,(1LL << (ctEntry
->BitIndex
-1)));
19788 void Player::UpdateFallInformationIfNeed( MovementInfo
const& minfo
,uint16 opcode
)
19790 if (m_lastFallTime
>= minfo
.fallTime
|| m_lastFallZ
<=minfo
.z
|| opcode
== MSG_MOVE_FALL_LAND
)
19791 SetFallInformation(minfo
.fallTime
, minfo
.z
);