Use characters.guid instead low guid value from characters.data in charcter enum...
[getmangos.git] / src / game / Player.cpp
blob922e4588405e79c61239f8e9a667c09c9969ce7a
1 /*
2 * Copyright (C) 2005-2008 MaNGOS <http://getmangos.com/>
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #include "Common.h"
20 #include "Language.h"
21 #include "Database/DatabaseEnv.h"
22 #include "Log.h"
23 #include "Opcodes.h"
24 #include "ObjectMgr.h"
25 #include "SpellMgr.h"
26 #include "World.h"
27 #include "WorldPacket.h"
28 #include "WorldSession.h"
29 #include "UpdateMask.h"
30 #include "Player.h"
31 #include "SkillDiscovery.h"
32 #include "QuestDef.h"
33 #include "GossipDef.h"
34 #include "UpdateData.h"
35 #include "Channel.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"
42 #include "CellImpl.h"
43 #include "ObjectMgr.h"
44 #include "ObjectAccessor.h"
45 #include "CreatureAI.h"
46 #include "Formulas.h"
47 #include "Group.h"
48 #include "Guild.h"
49 #include "Pet.h"
50 #include "SpellAuras.h"
51 #include "Util.h"
52 #include "Transports.h"
53 #include "Weather.h"
54 #include "BattleGround.h"
55 #include "BattleGroundMgr.h"
56 #include "ArenaTeam.h"
57 #include "Chat.h"
58 #include "Database/DatabaseImpl.h"
59 #include "Spell.h"
60 #include "SocialMgr.h"
62 #include <cmath>
64 #define ZONE_UPDATE_INTERVAL 1000
66 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
67 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
68 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
70 #define SKILL_VALUE(x) PAIR32_LOPART(x)
71 #define SKILL_MAX(x) PAIR32_HIPART(x)
72 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
74 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
75 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
76 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
78 enum CharacterFlags
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()
125 // Taxi nodes
126 memset(m_taximask, 0, sizeof(m_taximask));
129 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 level)
131 // capital and taxi hub masks
132 switch(race)
134 case RACE_HUMAN: SetTaximaskNode(2); break; // Human
135 case RACE_ORC: SetTaximaskNode(23); break; // Orc
136 case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
137 case RACE_NIGHTELF: SetTaximaskNode(26);
138 SetTaximaskNode(27); break; // Night Elf
139 case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead
140 case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
141 case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
142 case RACE_TROLL: SetTaximaskNode(23); break; // Troll
143 case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
144 case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
146 // new continent starting masks (It will be accessible only at new map)
147 switch(Player::TeamForRace(race))
149 case ALLIANCE: SetTaximaskNode(100); break;
150 case HORDE: SetTaximaskNode(99); break;
152 // level dependent taxi hubs
153 if(level>=68)
154 SetTaximaskNode(213); //Shattered Sun Staging Area
157 void PlayerTaxi::LoadTaxiMask(const char* data)
159 Tokens tokens = StrSplit(data, " ");
161 int index;
162 Tokens::iterator iter;
163 for (iter = tokens.begin(), index = 0;
164 (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
166 // load and set bits only for existed taxi nodes
167 m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str()));
171 void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
173 if(all)
175 for (uint8 i=0; i<TaxiMaskSize; i++)
176 data << sTaxiNodesMask[i]; // all existed nodes
178 else
180 for (uint8 i=0; i<TaxiMaskSize; i++)
181 data << uint32(m_taximask[i]); // known nodes
185 bool PlayerTaxi::LoadTaxiDestinationsFromString( std::string values )
187 ClearTaxiDestinations();
189 Tokens tokens = StrSplit(values," ");
191 for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
193 uint32 node = uint32(atol(iter->c_str()));
194 AddTaxiDestination(node);
197 if(m_TaxiDestinations.empty())
198 return true;
200 // Check integrity
201 if(m_TaxiDestinations.size() < 2)
202 return false;
204 for(size_t i = 1; i < m_TaxiDestinations.size(); ++i)
206 uint32 cost;
207 uint32 path;
208 objmgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i],path,cost);
209 if(!path)
210 return false;
213 return true;
216 std::string PlayerTaxi::SaveTaxiDestinationsToString()
218 if(m_TaxiDestinations.empty())
219 return "";
221 std::ostringstream ss;
223 for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
224 ss << m_TaxiDestinations[i] << " ";
226 return ss.str();
229 uint32 PlayerTaxi::GetCurrentTaxiPath() const
231 if(m_TaxiDestinations.size() < 2)
232 return 0;
234 uint32 path;
235 uint32 cost;
237 objmgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
239 return path;
242 //== Player ====================================================
244 const int32 Player::ReputationRank_Length[MAX_REPUTATION_RANK] = {36000, 3000, 3000, 3000, 6000, 12000, 21000, 1000};
246 UpdateMask Player::updateVisualBits;
248 Player::Player (WorldSession *session): Unit()
250 m_transport = 0;
252 m_speakTime = 0;
253 m_speakCount = 0;
255 m_objectType |= TYPEMASK_PLAYER;
256 m_objectTypeId = TYPEID_PLAYER;
258 m_valuesCount = PLAYER_END;
260 m_session = session;
262 m_divider = 0;
264 m_ExtraFlags = 0;
265 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER)
266 SetAcceptTicket(true);
268 // players always accept
269 if(GetSession()->GetSecurity() == SEC_PLAYER)
270 SetAcceptWhispers(true);
272 m_curSelection = 0;
273 m_lootGuid = 0;
275 m_comboTarget = 0;
276 m_comboPoints = 0;
278 m_usedTalentCount = 0;
280 m_regenTimer = 0;
281 m_weaponChangeTimer = 0;
283 m_zoneUpdateId = 0;
284 m_zoneUpdateTimer = 0;
286 m_areaUpdateId = 0;
288 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
290 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
291 // this must help in case next save after mass player load after server startup
292 m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
294 clearResurrectRequestData();
296 m_SpellModRemoveCount = 0;
298 memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
300 m_social = NULL;
302 // group is initialized in the reference constructor
303 SetGroupInvite(NULL);
304 m_groupUpdateMask = 0;
305 m_auraUpdateMask = 0;
307 duel = NULL;
309 m_GuildIdInvited = 0;
310 m_ArenaTeamIdInvited = 0;
312 m_atLoginFlags = AT_LOGIN_NONE;
314 m_dontMove = false;
316 pTrader = 0;
317 ClearTrade();
319 m_cinematic = 0;
321 PlayerTalkClass = new PlayerMenu( GetSession() );
322 m_currentBuybackSlot = BUYBACK_SLOT_START;
324 for ( int aX = 0 ; aX < 8 ; aX++ )
325 m_Tutorials[ aX ] = 0x00;
326 m_TutorialsChanged = false;
328 m_DailyQuestChanged = false;
329 m_lastDailyQuestTime = 0;
331 m_regenTimer = 0;
332 m_weaponChangeTimer = 0;
333 m_breathTimer = 0;
334 m_isunderwater = 0;
335 m_isInWater = false;
336 m_drunkTimer = 0;
337 m_drunk = 0;
338 m_restTime = 0;
339 m_deathTimer = 0;
340 m_deathExpireTime = 0;
342 m_swingErrorMsg = 0;
344 m_DetectInvTimer = 1000;
346 m_bgBattleGroundID = 0;
347 for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; j++)
349 m_bgBattleGroundQueueID[j].bgType = 0;
350 m_bgBattleGroundQueueID[j].invited = false;
352 m_bgTeam = 0;
354 m_logintime = time(NULL);
355 m_Last_tick = m_logintime;
356 m_WeaponProficiency = 0;
357 m_ArmorProficiency = 0;
358 m_canParry = false;
359 m_canBlock = false;
360 m_canDualWield = false;
361 m_ammoDPS = 0.0f;
363 m_temporaryUnsummonedPetNumber = 0;
364 //cache for UNIT_CREATED_BY_SPELL to allow
365 //returning reagests for temporarily removed pets
366 //when dying/logging out
367 m_oldpetspell = 0;
369 ////////////////////Rest System/////////////////////
370 time_inn_enter=0;
371 inn_pos_mapid=0;
372 inn_pos_x=0;
373 inn_pos_y=0;
374 inn_pos_z=0;
375 m_rest_bonus=0;
376 rest_type=REST_TYPE_NO;
377 ////////////////////Rest System/////////////////////
379 m_mailsLoaded = false;
380 m_mailsUpdated = false;
381 unReadMails = 0;
382 m_nextMailDelivereTime = 0;
384 m_resetTalentsCost = 0;
385 m_resetTalentsTime = 0;
386 m_itemUpdateQueueBlocked = false;
388 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
389 m_forced_speed_changes[i] = 0;
391 m_stableSlots = 0;
393 /////////////////// Instance System /////////////////////
395 m_HomebindTimer = 0;
396 m_InstanceValid = true;
397 m_dungeonDifficulty = DIFFICULTY_NORMAL;
399 for (int i = 0; i < BASEMOD_END; i++)
401 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
402 m_auraBaseMod[i][PCT_MOD] = 1.0f;
405 // Honor System
406 m_lastHonorUpdateTime = time(NULL);
408 // Player summoning
409 m_summon_expire = 0;
410 m_summon_mapid = 0;
411 m_summon_x = 0.0f;
412 m_summon_y = 0.0f;
413 m_summon_z = 0.0f;
415 //Default movement to run mode
416 m_unit_movement_flags = 0;
418 m_miniPet = 0;
419 m_bgAfkReportedTimer = 0;
420 m_contestedPvPTimer = 0;
422 m_declinedname = NULL;
425 Player::~Player ()
427 CleanupsBeforeDelete();
429 // it must be unloaded already in PlayerLogout and accessed only for loggined player
430 //m_social = NULL;
432 // Note: buy back item already deleted from DB when player was saved
433 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
435 if(m_items[i])
436 delete m_items[i];
438 CleanupChannels();
440 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
441 delete itr->second;
443 //all mailed items should be deleted, also all mail should be deallocated
444 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
445 delete *itr;
447 for (ItemMap::iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
448 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
450 delete PlayerTalkClass;
452 if (m_transport)
454 m_transport->RemovePassenger(this);
457 for(size_t x = 0; x < ItemSetEff.size(); x++)
458 if(ItemSetEff[x])
459 delete ItemSetEff[x];
461 // clean up player-instance binds, may unload some instance saves
462 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
463 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
464 itr->second.save->RemovePlayer(this);
466 delete m_declinedname;
469 void Player::CleanupsBeforeDelete()
471 if(m_uint32Values) // only for fully created Object
473 TradeCancel(false);
474 DuelComplete(DUEL_INTERUPTED);
476 Unit::CleanupsBeforeDelete();
479 bool Player::Create( uint32 guidlow, std::string name, uint8 race, uint8 class_, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair, uint8 outfitId )
481 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
483 m_name = name;
485 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
486 if(!info)
488 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
489 return false;
492 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
493 m_items[i] = NULL;
495 //for(int j = BUYBACK_SLOT_START; j < BUYBACK_SLOT_END; j++)
497 // SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1+j*2,0);
498 // SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1+j,0);
499 // SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1+j,0);
502 m_race = race;
503 m_class = class_;
505 SetMapId(info->mapId);
506 Relocate(info->positionX,info->positionY,info->positionZ);
508 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
509 if(!cEntry)
511 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
512 return false;
515 uint8 powertype = cEntry->powerType;
517 uint32 unitfield;
519 switch(powertype)
521 case POWER_ENERGY:
522 case POWER_MANA:
523 unitfield = 0x00000000;
524 break;
525 case POWER_RAGE:
526 unitfield = 0x00110000;
527 break;
528 default:
529 sLog.outError("Invalid default powertype %u for player (class %u)",powertype,class_);
530 return false;
533 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE );
534 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f );
536 switch(gender)
538 case GENDER_FEMALE:
539 SetDisplayId(info->displayId_f );
540 SetNativeDisplayId(info->displayId_f );
541 break;
542 case GENDER_MALE:
543 SetDisplayId(info->displayId_m );
544 SetNativeDisplayId(info->displayId_m );
545 break;
546 default:
547 sLog.outError("Invalid gender %u for player",gender);
548 return false;
549 break;
552 setFactionForRace(m_race);
554 SetUInt32Value(UNIT_FIELD_BYTES_0, ( ( race ) | ( class_ << 8 ) | ( gender << 16 ) | ( powertype << 24 ) ) );
555 SetUInt32Value(UNIT_FIELD_BYTES_1, unitfield);
556 SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_UNK3 | UNIT_BYTE2_FLAG_UNK5 );
557 SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
558 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
560 //-1 is default value
561 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
563 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
564 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
565 SetByteValue(PLAYER_BYTES_3, 0, gender);
567 SetUInt32Value( PLAYER_GUILDID, 0 );
568 SetUInt32Value( PLAYER_GUILDRANK, 0 );
569 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
571 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
572 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
573 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
574 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
575 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
576 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
578 // set starting level
579 SetUInt32Value( UNIT_FIELD_LEVEL, sWorld.getConfig(CONFIG_START_PLAYER_LEVEL) );
581 // Played time
582 m_Last_tick = time(NULL);
583 m_Played_time[0] = 0;
584 m_Played_time[1] = 0;
586 // base stats and related field values
587 InitStatsForLevel();
588 InitTaxiNodesForLevel();
589 InitTalentForLevel();
590 InitPrimaryProffesions(); // to max set before any spell added
592 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
593 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
594 SetHealth(GetMaxHealth());
595 if (getPowerType()==POWER_MANA)
597 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intelect)
598 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
601 learnDefaultSpells(true);
603 std::list<uint16>::const_iterator action_itr[4];
604 for(int i=0; i<4; i++)
605 action_itr[i] = info->action[i].begin();
607 for (; action_itr[0]!=info->action[0].end() && action_itr[1]!=info->action[1].end();)
609 uint16 taction[4];
610 for(int i=0; i<4 ;i++)
611 taction[i] = (*action_itr[i]);
613 addActionButton((uint8)taction[0], taction[1], (uint8)taction[2], (uint8)taction[3]);
615 for(int i=0; i<4 ;i++)
616 ++action_itr[i];
619 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
621 uint32 titem_id = item_id_itr->item_id;
622 uint32 titem_amount = item_id_itr->item_amount;
624 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
626 // attempt equip
627 uint16 eDest;
628 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, titem_amount, false );
629 if( msg == EQUIP_ERR_OK )
631 EquipNewItem( eDest, titem_id, titem_amount, true);
632 AutoUnequipOffhandIfNeed();
633 continue; // equipped, to next
636 // attempt store
637 ItemPosCountVec sDest;
638 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
639 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
640 if( msg == EQUIP_ERR_OK )
642 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
643 continue; // stored, to next
646 // item can't be added
647 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,race,class_,msg);
650 // bags and main-hand weapon must equipped at this moment
651 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
652 // or ammo not equipped in special bag
653 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
655 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
657 uint16 eDest;
658 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
659 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
660 if( msg == EQUIP_ERR_OK )
662 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
663 EquipItem( eDest, pItem, true);
665 // move other items to more appropriate slots (ammo not equipped in special bag)
666 else
668 ItemPosCountVec sDest;
669 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
670 if( msg == EQUIP_ERR_OK )
672 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
673 pItem = StoreItem( sDest, pItem, true);
676 // if this is ammo then use it
677 uint8 msg = CanUseAmmo( pItem->GetProto()->ItemId );
678 if( msg == EQUIP_ERR_OK )
679 SetAmmo( pItem->GetProto()->ItemId );
683 // all item positions resolved
685 return true;
688 void Player::StartMirrorTimer(MirrorTimerType Type, uint32 MaxValue)
690 uint32 BreathRegen = (uint32)-1;
692 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
693 data << (uint32)Type;
694 data << MaxValue;
695 data << MaxValue;
696 data << BreathRegen;
697 data << (uint8)0;
698 data << (uint32)0; // spell id
699 GetSession()->SendPacket(&data);
702 void Player::ModifyMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, uint32 Regen)
704 if(Type==BREATH_TIMER)
705 m_breathTimer = ((MaxValue + 1000) - CurrentValue) / Regen;
707 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
708 data << (uint32)Type;
709 data << CurrentValue;
710 data << MaxValue;
711 data << Regen;
712 data << (uint8)0;
713 data << (uint32)0; // spell id
714 GetSession()->SendPacket( &data );
717 void Player::StopMirrorTimer(MirrorTimerType Type)
719 if(Type==BREATH_TIMER)
720 m_breathTimer = 0;
722 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
723 data << (uint32)Type;
724 GetSession()->SendPacket( &data );
727 void Player::EnvironmentalDamage(uint64 guid, EnviromentalDamage type, uint32 damage)
729 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
730 data << (uint64)guid;
731 data << (uint8)(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
732 data << (uint32)damage;
733 data << (uint32)0;
734 data << (uint32)0;
735 //m_session->SendPacket(&data);
736 //Let other players see that you get damage
737 SendMessageToSet(&data, true);
738 DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
740 if(type==DAMAGE_FALL && !isAlive()) // DealDamage not apply item durability loss at self damage
742 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
743 DurabilityLossAll(0.10f,false);
744 // durability lost message
745 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
746 GetSession()->SendPacket(&data);
750 void Player::HandleDrowning()
752 if(!m_isunderwater)
753 return;
755 //if have water breath , then remove bar
756 if(waterbreath || isGameMaster() || !isAlive())
758 StopMirrorTimer(BREATH_TIMER);
759 m_isunderwater = 0;
760 return;
763 uint32 UnderWaterTime = 1*MINUTE*1000; // default leangthL 1 min
765 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
766 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
767 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
769 if ((m_isunderwater & 0x01) && !(m_isunderwater & 0x80) && isAlive())
771 //single trigger timer
772 if (!(m_isunderwater & 0x02))
774 m_isunderwater|= 0x02;
775 m_breathTimer = UnderWaterTime + 1000;
777 //single trigger "Breathbar"
778 if ( m_breathTimer <= UnderWaterTime && !(m_isunderwater & 0x04))
780 m_isunderwater|= 0x04;
781 StartMirrorTimer(BREATH_TIMER, UnderWaterTime);
783 //continius trigger drowning "Damage"
784 if ((m_breathTimer == 0) && (m_isunderwater & 0x01))
786 //TODO: Check this formula
787 uint64 guid = GetGUID();
788 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
790 EnvironmentalDamage(guid, DAMAGE_DROWNING,damage);
791 m_breathTimer = 2000;
794 //single trigger retract bar
795 else if (!(m_isunderwater & 0x01) && !(m_isunderwater & 0x08) && (m_isunderwater & 0x02) && (m_breathTimer > 0) && isAlive())
797 m_isunderwater = 0x08;
799 uint32 BreathRegen = 10;
800 ModifyMirrorTimer(BREATH_TIMER, UnderWaterTime, m_breathTimer,BreathRegen);
801 m_isunderwater = 0x10;
803 //remove bar
804 else if ((m_breathTimer < 50) && !(m_isunderwater & 0x01) && (m_isunderwater == 0x10))
806 StopMirrorTimer(BREATH_TIMER);
807 m_isunderwater = 0;
811 void Player::HandleLava()
813 bool ValidArea = false;
815 if ((m_isunderwater & 0x80) && isAlive())
817 //Single trigger Set BreathTimer
818 if (!(m_isunderwater & 0x80))
820 m_isunderwater|= 0x04;
821 m_breathTimer = 1000;
823 //Reset BreathTimer and still in the lava
824 if (!m_breathTimer)
826 uint64 guid = GetGUID();
827 uint32 damage = urand(600, 700); // TODO: Get more detailed information about lava damage
828 uint32 dmgZone = GetZoneId(); // TODO: Find correct "lava dealing zone" flag in Area Table
830 // Deal lava damage only in lava zones.
831 switch(dmgZone)
833 case 0x8D:
834 ValidArea = false;
835 break;
836 case 0x94:
837 ValidArea = false;
838 break;
839 case 0x2CE:
840 ValidArea = false;
841 break;
842 case 0x2CF:
843 ValidArea = false;
844 break;
845 default:
846 if (dmgZone / 5 & 0x408)
847 ValidArea = true;
850 // if is valid area and is not gamemaster then deal damage
851 if ( ValidArea && !isGameMaster() )
852 EnvironmentalDamage(guid, DAMAGE_LAVA, damage);
854 m_breathTimer = 1000;
858 //Death timer disabled and WaterFlags reset
859 else if (m_deathState == DEAD)
861 m_breathTimer = 0;
862 m_isunderwater = 0;
866 ///The player sobers by 256 every 10 seconds
867 void Player::HandleSobering()
869 m_drunkTimer = 0;
871 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
872 SetDrunkValue(drunk);
875 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
877 if(value >= 23000)
878 return DRUNKEN_SMASHED;
879 if(value >= 12800)
880 return DRUNKEN_DRUNK;
881 if(value & 0xFFFE)
882 return DRUNKEN_TIPSY;
883 return DRUNKEN_SOBER;
886 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
888 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
890 m_drunk = newDrunkenValue;
891 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
893 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
895 // special drunk invisibility detection
896 if(newDrunkenState >= DRUNKEN_DRUNK)
897 m_detectInvisibilityMask |= (1<<6);
898 else
899 m_detectInvisibilityMask &= ~(1<<6);
901 if(newDrunkenState == oldDrunkenState)
902 return;
904 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
905 data << GetGUID();
906 data << uint32(newDrunkenState);
907 data << uint32(itemId);
909 SendMessageToSet(&data, true);
912 void Player::Update( uint32 p_time )
914 if(!IsInWorld())
915 return;
917 // undelivered mail
918 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
920 SendNewMail();
921 ++unReadMails;
923 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
924 m_nextMailDelivereTime = 0;
927 Unit::Update( p_time );
929 // update player only attacks
930 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
932 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
935 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
937 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
940 time_t now = time (NULL);
942 UpdatePvPFlag(now);
944 UpdateContestedPvP(p_time);
946 UpdateDuelFlag(now);
948 CheckDuelDistance(now);
950 UpdateAfkReport(now);
952 CheckExploreSystem();
954 // Update items that have just a limited lifetime
955 if (now>m_Last_tick)
956 UpdateItemDuration(uint32(now- m_Last_tick));
958 if (!m_timedquests.empty())
960 std::set<uint32>::iterator iter = m_timedquests.begin();
961 while (iter != m_timedquests.end())
963 QuestStatusData& q_status = mQuestStatus[*iter];
964 if( q_status.m_timer <= p_time )
966 uint32 quest_id = *iter;
967 ++iter; // current iter will be removed in FailTimedQuest
968 FailTimedQuest( quest_id );
970 else
972 q_status.m_timer -= p_time;
973 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
974 ++iter;
979 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
981 Unit *pVictim = getVictim();
982 if( !IsNonMeleeSpellCasted(false) && pVictim)
984 // default combat reach 10
985 // TODO add weapon,skill check
987 float pldistance = ATTACK_DISTANCE;
989 if (isAttackReady(BASE_ATTACK))
991 if(!IsWithinDistInMap(pVictim, pldistance))
993 setAttackTimer(BASE_ATTACK,100);
994 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
996 SendAttackSwingNotInRange();
997 m_swingErrorMsg = 1;
1000 //120 degrees of radiant range
1001 else if( !HasInArc( 2*M_PI/3, pVictim ))
1003 setAttackTimer(BASE_ATTACK,100);
1004 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1006 SendAttackSwingBadFacingAttack();
1007 m_swingErrorMsg = 2;
1010 else
1012 m_swingErrorMsg = 0; // reset swing error state
1014 // prevent base and off attack in same time, delay attack at 0.2 sec
1015 if(haveOffhandWeapon())
1017 uint32 off_att = getAttackTimer(OFF_ATTACK);
1018 if(off_att < ATTACK_DISPLAY_DELAY)
1019 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1021 AttackerStateUpdate(pVictim, BASE_ATTACK);
1022 resetAttackTimer(BASE_ATTACK);
1026 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1028 if(!IsWithinDistInMap(pVictim, pldistance))
1030 setAttackTimer(OFF_ATTACK,100);
1032 else if( !HasInArc( 2*M_PI/3, pVictim ))
1034 setAttackTimer(OFF_ATTACK,100);
1036 else
1038 // prevent base and off attack in same time, delay attack at 0.2 sec
1039 uint32 base_att = getAttackTimer(BASE_ATTACK);
1040 if(base_att < ATTACK_DISPLAY_DELAY)
1041 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1042 // do attack
1043 AttackerStateUpdate(pVictim, OFF_ATTACK);
1044 resetAttackTimer(OFF_ATTACK);
1048 Unit *owner = pVictim->GetOwner();
1049 Unit *u = owner ? owner : pVictim;
1050 if(u->IsPvP() && (!duel || duel->opponent != u))
1052 UpdatePvP(true);
1053 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1058 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1060 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1062 int time_inn = time(NULL)-GetTimeInnEnter();
1063 if (time_inn >= 10) //freeze update
1065 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1066 //speed collect rest bonus (section/in hour)
1067 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1068 UpdateInnerTime(time(NULL));
1073 if(m_regenTimer > 0)
1075 if(p_time >= m_regenTimer)
1076 m_regenTimer = 0;
1077 else
1078 m_regenTimer -= p_time;
1081 if (m_weaponChangeTimer > 0)
1083 if(p_time >= m_weaponChangeTimer)
1084 m_weaponChangeTimer = 0;
1085 else
1086 m_weaponChangeTimer -= p_time;
1089 if (m_zoneUpdateTimer > 0)
1091 if(p_time >= m_zoneUpdateTimer)
1093 uint32 newzone = GetZoneId();
1094 if( m_zoneUpdateId != newzone )
1095 UpdateZone(newzone); // also update area
1096 else
1098 // use area updates as well
1099 // needed for free far all arenas for example
1100 uint32 newarea = GetAreaId();
1101 if( m_areaUpdateId != newarea )
1102 UpdateArea(newarea);
1104 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1107 else
1108 m_zoneUpdateTimer -= p_time;
1111 if (isAlive())
1113 RegenerateAll();
1116 if (m_deathState == JUST_DIED)
1118 KillPlayer();
1121 if(m_nextSave > 0)
1123 if(p_time >= m_nextSave)
1125 // m_nextSave reseted in SaveToDB call
1126 SaveToDB();
1127 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1129 else
1131 m_nextSave -= p_time;
1135 //Breathtimer
1136 if(m_breathTimer > 0)
1138 if(p_time >= m_breathTimer)
1139 m_breathTimer = 0;
1140 else
1141 m_breathTimer -= p_time;
1145 //Handle Water/drowning
1146 HandleDrowning();
1148 //Handle lava
1149 HandleLava();
1151 //Handle detect stealth players
1152 if (m_DetectInvTimer > 0)
1154 if (p_time >= m_DetectInvTimer)
1156 m_DetectInvTimer = 3000;
1157 HandleStealthedUnitsDetection();
1159 else
1160 m_DetectInvTimer -= p_time;
1163 // Played time
1164 if (now > m_Last_tick)
1166 uint32 elapsed = uint32(now - m_Last_tick);
1167 m_Played_time[0] += elapsed; // Total played time
1168 m_Played_time[1] += elapsed; // Level played time
1169 m_Last_tick = now;
1172 if (m_drunk)
1174 m_drunkTimer += p_time;
1176 if (m_drunkTimer > 10000)
1177 HandleSobering();
1180 // not auto-free ghost from body in instances
1181 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1183 if(p_time >= m_deathTimer)
1185 m_deathTimer = 0;
1186 BuildPlayerRepop();
1187 RepopAtGraveyard();
1189 else
1190 m_deathTimer -= p_time;
1193 UpdateEnchantTime(p_time);
1194 UpdateHomebindTime(p_time);
1196 // group update
1197 SendUpdateToOutOfRangeGroupMembers();
1199 Pet* pet = GetPet();
1200 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE))
1202 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1203 return;
1207 void Player::setDeathState(DeathState s)
1209 uint32 ressSpellId = 0;
1211 bool cur = isAlive();
1213 if(s == JUST_DIED && cur)
1215 // drunken state is cleared on death
1216 SetDrunkValue(0);
1217 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1218 ClearComboPoints();
1220 clearResurrectRequestData();
1222 // remove form before other mods to prevent incorrect stats calculation
1223 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1225 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1226 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1228 // remove uncontrolled pets
1229 RemoveMiniPet();
1230 RemoveGuardians();
1232 // save value before aura remove in Unit::setDeathState
1233 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1235 // passive spell
1236 if(!ressSpellId)
1237 ressSpellId = GetResurrectionSpellId();
1239 Unit::setDeathState(s);
1241 // restore resurrection spell id for player after aura remove
1242 if(s == JUST_DIED && cur && ressSpellId)
1243 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1245 if(isAlive() && !cur)
1247 //clear aura case after resurrection by another way (spells will be applied before next death)
1248 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1250 // restore default warrior stance
1251 if(getClass()== CLASS_WARRIOR)
1252 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1256 void Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1258 *p_data << GetGUID();
1259 *p_data << m_name;
1261 *p_data << getRace();
1262 uint8 pClass = getClass();
1263 *p_data << pClass;
1264 *p_data << getGender();
1266 uint32 bytes = GetUInt32Value(PLAYER_BYTES);
1267 *p_data << uint8(bytes);
1268 *p_data << uint8(bytes >> 8);
1269 *p_data << uint8(bytes >> 16);
1270 *p_data << uint8(bytes >> 24);
1272 bytes = GetUInt32Value(PLAYER_BYTES_2);
1273 *p_data << uint8(bytes);
1275 *p_data << uint8(getLevel()); // player level
1276 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1277 uint32 zoneId = MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY());
1279 *p_data << zoneId;
1280 *p_data << GetMapId();
1282 *p_data << GetPositionX();
1283 *p_data << GetPositionY();
1284 *p_data << GetPositionZ();
1286 *p_data << GetUInt32Value(PLAYER_GUILDID); // guild id
1288 uint32 char_flags = 0;
1289 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
1290 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1291 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
1292 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1293 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
1294 char_flags |= CHARACTER_FLAG_GHOST;
1295 if(HasAtLoginFlag(AT_LOGIN_RENAME))
1296 char_flags |= CHARACTER_FLAG_RENAME;
1297 // always send the flag if declined names aren't used
1298 // to let the client select a default method of declining the name
1299 if(!sWorld.getConfig(CONFIG_DECLINED_NAMES_USED) || (result && result->Fetch()[13].GetCppString() != ""))
1300 char_flags |= CHARACTER_FLAG_DECLINED;
1302 *p_data << (uint32)char_flags; // character flags
1304 *p_data << (uint8)1; // unknown
1306 // Pets info
1308 uint32 petDisplayId = 0;
1309 uint32 petLevel = 0;
1310 uint32 petFamily = 0;
1312 // show pet at selection character in character list only for non-ghost character
1313 if(result && isAlive() && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER))
1315 Field* fields = result->Fetch();
1317 uint32 entry = fields[10].GetUInt32();
1318 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1319 if(cInfo)
1321 petDisplayId = fields[11].GetUInt32();
1322 petLevel = fields[12].GetUInt32();
1323 petFamily = cInfo->family;
1327 *p_data << (uint32)petDisplayId;
1328 *p_data << (uint32)petLevel;
1329 *p_data << (uint32)petFamily;
1332 /*ItemPrototype const *items[EQUIPMENT_SLOT_END];
1333 for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
1334 items[i] = NULL;
1336 QueryResult *result = CharacterDatabase.PQuery("SELECT slot,item_template FROM character_inventory WHERE guid = '%u' AND bag = 0",GetGUIDLow());
1337 if (result)
1341 Field *fields = result->Fetch();
1342 uint8 slot = fields[0].GetUInt8() & 255;
1343 uint32 item_id = fields[1].GetUInt32();
1344 if( slot >= EQUIPMENT_SLOT_END )
1345 continue;
1347 items[slot] = objmgr.GetItemPrototype(item_id);
1348 if(!items[slot])
1350 sLog.outError( "Player::BuildEnumData: Player %s have unknown item (id: #%u) in inventory, skipped.", GetName(),item_id );
1351 continue;
1353 } while (result->NextRow());
1354 delete result;
1357 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1359 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
1360 uint32 item_id = GetUInt32Value(visualbase);
1361 const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
1362 SpellItemEnchantmentEntry const *enchant = NULL;
1364 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot<=TEMP_ENCHANTMENT_SLOT; enchantSlot++)
1366 uint32 enchantId = GetUInt32Value(visualbase+1+enchantSlot);
1367 if(enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))
1368 break;
1371 if (proto != NULL)
1373 *p_data << (uint32)proto->DisplayInfoID;
1374 *p_data << (uint8)proto->InventoryType;
1375 *p_data << (uint32)(enchant?enchant->aura_id:0);
1377 else
1379 *p_data << (uint32)0;
1380 *p_data << (uint8)0;
1381 *p_data << (uint32)0; // enchant?
1384 *p_data << (uint32)0; // first bag display id
1385 *p_data << (uint8)0; // first bag inventory type
1386 *p_data << (uint32)0; // enchant?
1389 bool Player::ToggleAFK()
1391 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1393 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1395 // afk player not allowed in battleground
1396 if(state && InBattleGround())
1397 LeaveBattleground();
1399 return state;
1402 bool Player::ToggleDND()
1404 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1406 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1409 uint8 Player::chatTag() const
1411 // it's bitmask
1412 // 0x8 - ??
1413 // 0x4 - gm
1414 // 0x2 - dnd
1415 // 0x1 - afk
1416 if(isGMChat())
1417 return 4;
1418 else if(isDND())
1419 return 3;
1420 if(isAFK())
1421 return 1;
1422 else
1423 return 0;
1426 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1428 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1430 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1431 return false;
1434 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1435 Pet* pet = GetPet();
1437 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1439 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1440 if(!InBattleGround() && mEntry->IsBattleGround() && !GetSession()->GetSecurity())
1441 return false;
1443 // client without expansion support
1444 if(GetSession()->Expansion() < mEntry->Expansion())
1446 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessable map %u", GetName(), mapid);
1448 if(GetTransport())
1449 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1451 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL1);
1453 return false; // normal client can't teleport to this map...
1455 else
1457 sLog.outDebug("Player %s will teleported to map %u", GetName(), mapid);
1460 // if we were on a transport, leave
1461 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1463 m_transport->RemovePassenger(this);
1464 m_transport = NULL;
1465 m_movementInfo.t_x = 0.0f;
1466 m_movementInfo.t_y = 0.0f;
1467 m_movementInfo.t_z = 0.0f;
1468 m_movementInfo.t_o = 0.0f;
1469 m_movementInfo.t_time = 0;
1472 SetSemaphoreTeleport(true);
1474 // The player was ported to another map and looses the duel immediatly.
1475 // We have to perform this check before the teleport, otherwise the
1476 // ObjectAccessor won't find the flag.
1477 if (duel && this->GetMapId()!=mapid)
1479 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
1480 if (obj)
1481 DuelComplete(DUEL_FLED);
1484 // reset movement flags at teleport, because player will continue move with these flags after teleport
1485 SetUnitMovementFlags(0);
1487 if ((this->GetMapId() == mapid) && (!m_transport))
1489 // prepare zone change detect
1490 uint32 old_zone = GetZoneId();
1492 // near teleport
1493 if(!GetSession()->PlayerLogout())
1495 WorldPacket data;
1496 BuildTeleportAckMsg(&data, x, y, z, orientation);
1497 GetSession()->SendPacket(&data);
1498 SetPosition( x, y, z, orientation, true);
1500 else
1501 // this will be used instead of the current location in SaveToDB
1502 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1504 //BuildHeartBeatMsg(&data);
1505 //SendMessageToSet(&data, true);
1506 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1508 //same map, only remove pet if out of range
1509 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE))
1511 if(pet->isControlled() && !pet->isTemporarySummoned() )
1512 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1513 else
1514 m_temporaryUnsummonedPetNumber = 0;
1516 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1520 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1521 CombatStop();
1523 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1525 // resummon pet
1526 if(pet && m_temporaryUnsummonedPetNumber)
1528 Pet* NewPet = new Pet;
1529 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
1530 delete NewPet;
1532 m_temporaryUnsummonedPetNumber = 0;
1536 if(!GetSession()->PlayerLogout())
1538 // don't reset teleport semaphore while logging out, otherwise m_teleport_dest won't be used in Player::SaveToDB
1539 SetSemaphoreTeleport(false);
1541 UpdateZone(GetZoneId());
1544 // new zone
1545 if(old_zone != GetZoneId())
1547 // honorless target
1548 if(pvpInfo.inHostileArea)
1549 CastSpell(this, 2479, true);
1552 else
1554 // far teleport to another map
1555 Map* oldmap = IsInWorld() ? MapManager::Instance().GetMap(GetMapId(), this) : NULL;
1556 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1558 // Check enter rights before map getting to avoid creating instance copy for player
1559 // this check not dependent from map instance copy and same for all instance copies of selected map
1560 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1562 SetSemaphoreTeleport(false);
1563 return false;
1566 // If the map is not created, assume it is possible to enter it.
1567 // It will be created in the WorldPortAck.
1568 Map *map = MapManager::Instance().FindMap(mapid);
1569 if (!map || map->CanEnter(this))
1571 SetSelection(0);
1573 CombatStop();
1575 ResetContestedPvP();
1577 // remove player from battleground on far teleport (when changing maps)
1578 if(BattleGround const* bg = GetBattleGround())
1580 // Note: at battleground join battleground id set before teleport
1581 // and we already will found "current" battleground
1582 // just need check that this is targeted map or leave
1583 if(bg->GetMapId() != mapid)
1584 LeaveBattleground(false); // don't teleport to entry point
1587 // remove pet on map change
1588 if (pet)
1590 //leaving map -> delete pet right away (doing this later will cause problems)
1591 if(pet->isControlled() && !pet->isTemporarySummoned())
1592 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1593 else
1594 m_temporaryUnsummonedPetNumber = 0;
1596 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1599 // remove all dyn objects
1600 RemoveAllDynObjects();
1602 // stop spellcasting
1603 // not attempt interrupt teleportation spell at caster teleport
1604 if(!(options & TELE_TO_SPELL))
1605 if(IsNonMeleeSpellCasted(true))
1606 InterruptNonMeleeSpells(true);
1608 if(!GetSession()->PlayerLogout())
1610 // send transfer packets
1611 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1612 data << uint32(mapid);
1613 if (m_transport)
1615 data << m_transport->GetEntry() << GetMapId();
1617 GetSession()->SendPacket(&data);
1619 data.Initialize(SMSG_NEW_WORLD, (20));
1620 if (m_transport)
1622 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1624 else
1626 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1628 GetSession()->SendPacket( &data );
1629 SendSavedInstances();
1631 // remove from old map now
1632 if(oldmap) oldmap->Remove(this, false);
1635 // new final coordinates
1636 float final_x = x;
1637 float final_y = y;
1638 float final_z = z;
1639 float final_o = orientation;
1641 if(m_transport)
1643 final_x += m_movementInfo.t_x;
1644 final_y += m_movementInfo.t_y;
1645 final_z += m_movementInfo.t_z;
1646 final_o += m_movementInfo.t_o;
1649 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1650 // if the player is saved before worldportack (at logout for example)
1651 // this will be used instead of the current location in SaveToDB
1653 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
1655 // move packet sent by client always after far teleport
1656 // SetPosition(final_x, final_y, final_z, final_o, true);
1657 SetDontMove(true);
1659 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1661 else
1662 return false;
1664 return true;
1667 void Player::AddToWorld()
1669 ///- Do not add/remove the player from the object storage
1670 ///- It will crash when updating the ObjectAccessor
1671 ///- The player should only be added when logging in
1672 Unit::AddToWorld();
1674 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1676 if(m_items[i])
1677 m_items[i]->AddToWorld();
1681 void Player::RemoveFromWorld()
1683 // cleanup
1684 if(IsInWorld())
1686 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1687 Uncharm();
1688 UnsummonAllTotems();
1689 RemoveMiniPet();
1690 RemoveGuardians();
1693 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1695 if(m_items[i])
1696 m_items[i]->RemoveFromWorld();
1699 ///- Do not add/remove the player from the object storage
1700 ///- It will crash when updating the ObjectAccessor
1701 ///- The player should only be removed when logging out
1702 Unit::RemoveFromWorld();
1705 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1707 float addRage;
1709 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1711 if(attacker)
1713 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1715 // talent who gave more rage on attack
1716 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1718 else
1720 addRage = damage/rageconversion*2.5;
1722 // Berserker Rage effect
1723 if(HasAura(18499,0))
1724 addRage *= 1.3;
1727 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1729 ModifyPower(POWER_RAGE, uint32(addRage*10));
1732 void Player::RegenerateAll()
1734 if (m_regenTimer != 0)
1735 return;
1736 uint32 regenDelay = 2000;
1738 // Not in combat or they have regeneration
1739 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1740 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1742 RegenerateHealth();
1743 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1744 Regenerate(POWER_RAGE);
1747 Regenerate( POWER_ENERGY );
1749 Regenerate( POWER_MANA );
1751 m_regenTimer = regenDelay;
1754 void Player::Regenerate(Powers power)
1756 uint32 curValue = GetPower(power);
1757 uint32 maxValue = GetMaxPower(power);
1759 float addvalue = 0.0f;
1761 switch (power)
1763 case POWER_MANA:
1765 bool recentCast = IsUnderLastManaUseEffect();
1766 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1767 if (recentCast)
1769 // Mangos Updates Mana in intervals of 2s, which is correct
1770 addvalue = GetFloatValue(PLAYER_FIELD_MOD_MANA_REGEN_INTERRUPT) * ManaIncreaseRate * 2.00f;
1772 else
1774 addvalue = GetFloatValue(PLAYER_FIELD_MOD_MANA_REGEN) * ManaIncreaseRate * 2.00f;
1776 } break;
1777 case POWER_RAGE: // Regenerate rage
1779 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1780 addvalue = 30 * RageDecreaseRate; // 3 rage by tick
1781 } break;
1782 case POWER_ENERGY: // Regenerate energy (rogue)
1783 addvalue = 20;
1784 break;
1785 case POWER_FOCUS:
1786 case POWER_HAPPINESS:
1787 break;
1790 // Mana regen calculated in Player::UpdateManaRegen()
1791 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1792 if(power != POWER_MANA)
1794 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1795 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1796 if ((*i)->GetModifier()->m_miscvalue == power)
1797 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1800 if (power != POWER_RAGE)
1802 curValue += uint32(addvalue);
1803 if (curValue > maxValue)
1804 curValue = maxValue;
1806 else
1808 if(curValue <= uint32(addvalue))
1809 curValue = 0;
1810 else
1811 curValue -= uint32(addvalue);
1813 SetPower(power, curValue);
1816 void Player::RegenerateHealth()
1818 uint32 curValue = GetHealth();
1819 uint32 maxValue = GetMaxHealth();
1821 if (curValue >= maxValue) return;
1823 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
1825 float addvalue = 0.0f;
1827 // polymorphed case
1828 if ( IsPolymorphed() )
1829 addvalue = GetMaxHealth()/3;
1830 // normal regen case (maybe partly in combat case)
1831 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
1833 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
1834 if (!isInCombat())
1836 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
1837 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
1838 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
1840 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
1841 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
1843 if(!IsStandState())
1844 addvalue *= 1.5;
1847 // always regeneration bonus (including combat)
1848 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
1850 if(addvalue < 0)
1851 addvalue = 0;
1853 ModifyHealth(int32(addvalue));
1856 bool Player::CanInteractWithNPCs(bool alive) const
1858 if(alive && !isAlive())
1859 return false;
1860 if(isInFlight())
1861 return false;
1863 return true;
1866 bool Player::IsUnderWater() const
1868 return IsInWater() &&
1869 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
1872 void Player::SetInWater(bool apply)
1874 if(m_isInWater==apply)
1875 return;
1877 //define player in water by opcodes
1878 //move player's guid into HateOfflineList of those mobs
1879 //which can't swim and move guid back into ThreatList when
1880 //on surface.
1881 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
1882 m_isInWater = apply;
1884 // remove auras that need water/land
1885 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
1887 getHostilRefManager().updateThreatTables();
1890 void Player::SetGameMaster(bool on)
1892 if(on)
1894 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
1895 setFaction(35);
1896 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
1898 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
1899 ResetContestedPvP();
1901 getHostilRefManager().setOnlineOfflineState(false);
1902 CombatStop();
1904 else
1906 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
1907 setFactionForRace(getRace());
1908 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
1910 // restore FFA PvP Server state
1911 if(sWorld.IsFFAPvPRealm())
1912 SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
1914 // restore FFA PvP area state, remove not allowed for GM mounts
1915 UpdateArea(m_areaUpdateId);
1917 getHostilRefManager().setOnlineOfflineState(true);
1920 ObjectAccessor::UpdateVisibilityForPlayer(this);
1923 void Player::SetGMVisible(bool on)
1925 if(on)
1927 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
1929 // Reapply stealth/invisibility if active or show if not any
1930 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
1931 SetVisibility(VISIBILITY_GROUP_STEALTH);
1932 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
1933 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
1934 else
1935 SetVisibility(VISIBILITY_ON);
1937 else
1939 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
1941 SetAcceptWhispers(false);
1942 SetGameMaster(true);
1944 SetVisibility(VISIBILITY_OFF);
1948 bool Player::IsGroupVisibleFor(Player* p) const
1950 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
1952 default: return IsInSameGroupWith(p);
1953 case 1: return IsInSameRaidWith(p);
1954 case 2: return GetTeam()==p->GetTeam();
1958 bool Player::IsInSameGroupWith(Player const* p) const
1960 return p==this || GetGroup() != NULL &&
1961 GetGroup() == p->GetGroup() &&
1962 GetGroup()->SameSubGroup((Player*)this, (Player*)p);
1965 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
1966 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
1967 void Player::UninviteFromGroup()
1969 if(GetGroupInvite()) // uninvited invitee
1971 Group* group = GetGroupInvite();
1972 group->RemoveInvite(this);
1974 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
1976 if(group->IsCreated())
1978 group->Disband(true);
1979 objmgr.RemoveGroup(group);
1981 else
1982 group->RemoveAllInvites();
1984 delete group;
1989 void Player::RemoveFromGroup(Group* group, uint64 guid)
1991 if(group)
1993 if (group->RemoveMember(guid, 0) <= 1)
1995 // group->Disband(); already disbanded in RemoveMember
1996 objmgr.RemoveGroup(group);
1997 delete group;
1998 // removemember sets the player's group pointer to NULL
2003 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2005 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2006 data << uint64(victim ? victim->GetGUID() : 0); // guid
2007 data << uint32(GivenXP+RestXP); // given experience
2008 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2009 if(victim)
2011 data << uint32(GivenXP); // experience without rested bonus
2012 data << float(1); // 1 - none 0 - 100% group bonus output
2014 data << uint8(0); // new 2.4.0
2015 GetSession()->SendPacket(&data);
2018 void Player::GiveXP(uint32 xp, Unit* victim)
2020 if ( xp < 1 )
2021 return;
2023 if(!isAlive())
2024 return;
2026 uint32 level = getLevel();
2028 // XP to money conversion processed in Player::RewardQuest
2029 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2030 return;
2032 // handle SPELL_AURA_MOD_XP_PCT auras
2033 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2034 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2035 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2037 // XP resting bonus for kill
2038 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2040 SendLogXPGain(xp,victim,rested_bonus_xp);
2042 uint32 curXP = GetUInt32Value(PLAYER_XP);
2043 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2044 uint32 newXP = curXP + xp + rested_bonus_xp;
2046 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2048 newXP -= nextLvlXP;
2050 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2051 GiveLevel(level + 1);
2053 level = getLevel();
2054 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2057 SetUInt32Value(PLAYER_XP, newXP);
2060 // Update player to next level
2061 // Current player experience not update (must be update by caller)
2062 void Player::GiveLevel(uint32 level)
2064 if ( level == getLevel() )
2065 return;
2067 PlayerLevelInfo info;
2068 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2070 PlayerClassLevelInfo classInfo;
2071 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2073 // send levelup info to client
2074 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2075 data << uint32(level);
2076 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2077 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2078 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2079 data << uint32(0);
2080 data << uint32(0);
2081 data << uint32(0);
2082 data << uint32(0);
2083 // end for
2084 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2085 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2087 GetSession()->SendPacket(&data);
2089 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, MaNGOS::XP::xp_to_level(level));
2091 //update level, max level of skills
2092 if(getLevel()!= level)
2093 m_Played_time[1] = 0; // Level Played Time reset
2094 SetLevel(level);
2095 UpdateMaxSkills();
2097 // save base values (bonuses already included in stored stats
2098 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2099 SetCreateStat(Stats(i), info.stats[i]);
2101 SetCreateHealth(classInfo.basehealth);
2102 SetCreateMana(classInfo.basemana);
2104 InitTalentForLevel();
2105 InitTaxiNodesForLevel();
2107 UpdateAllStats();
2109 // set current level health and mana/energy to maximum after applying all mods.
2110 SetHealth(GetMaxHealth());
2111 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2112 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2113 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2114 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2115 SetPower(POWER_FOCUS, 0);
2116 SetPower(POWER_HAPPINESS, 0);
2118 // give level to summoned pet
2119 Pet* pet = GetPet();
2120 if(pet && pet->getPetType()==SUMMON_PET)
2121 pet->GivePetLevel(level);
2124 void Player::InitTalentForLevel()
2126 uint32 level = getLevel();
2127 // talents base at level diff ( talents = level - 9 but some can be used already)
2128 if(level < 10)
2130 // Remove all talent points
2131 if(m_usedTalentCount > 0) // Free any used talents
2133 resetTalents(true);
2134 SetFreeTalentPoints(0);
2137 else
2139 uint32 talentPointsForLevel = uint32((level-9)*sWorld.getRate(RATE_TALENT));
2140 // if used more that have then reset
2141 if(m_usedTalentCount > talentPointsForLevel)
2143 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2144 resetTalents(true);
2145 else
2146 SetFreeTalentPoints(0);
2148 // else update amount of free points
2149 else
2150 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2154 void Player::InitStatsForLevel(bool reapplyMods)
2156 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2157 _RemoveAllStatBonuses();
2159 PlayerClassLevelInfo classInfo;
2160 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2162 PlayerLevelInfo info;
2163 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2165 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2166 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, MaNGOS::XP::xp_to_level(getLevel()));
2168 UpdateMaxSkills ();
2170 // set default cast time multiplier
2171 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2173 // reset size before reapply auras
2174 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2176 // save base values (bonuses already included in stored stats
2177 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2178 SetCreateStat(Stats(i), info.stats[i]);
2180 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2181 SetStat(Stats(i), info.stats[i]);
2183 SetCreateHealth(classInfo.basehealth);
2185 //set create powers
2186 SetCreateMana(classInfo.basemana);
2188 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2190 InitStatBuffMods();
2192 //reset rating fields values
2193 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2194 SetUInt32Value(index, 0);
2196 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2197 for (int i = 0; i < 7; i++)
2199 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2200 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2201 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2204 //reset attack power, damage and attack speed fields
2205 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2206 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2207 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2209 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2210 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2211 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2212 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2213 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2214 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2216 SetUInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2217 SetUInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2218 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2219 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2220 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2221 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2223 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2224 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2225 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2226 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2228 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2229 for (uint8 i = 0; i < 7; ++i)
2230 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2232 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2233 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2234 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2236 // Dodge percentage
2237 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2239 // set armor (resistance 0) to original value (create_agility*2)
2240 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2241 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2242 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2243 // set other resistance to original value (0)
2244 for (int i = 1; i < MAX_SPELL_SCHOOL; i++)
2246 SetResistance(SpellSchools(i), 0);
2247 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2248 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2251 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2252 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2253 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2255 SetFloatValue(UNIT_FIELD_POWER_COST_MODIFIER+i,0.0f);
2256 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2258 // Init data for form but skip reapply item mods for form
2259 InitDataForForm(reapplyMods);
2261 // save new stats
2262 for (int i = POWER_MANA; i < MAX_POWERS; i++)
2263 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2265 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2267 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2268 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2270 // cleanup unit flags (will be re-applied if need at aura load).
2271 RemoveFlag( UNIT_FIELD_FLAGS,
2272 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2273 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2274 UNIT_FLAG_DISABLE_ROTATE | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2275 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2276 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2277 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2279 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2280 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST | PLAYER_FLAGS_FFA_PVP);
2282 SetByteValue(UNIT_FIELD_BYTES_1, 2, 0x00); // one form stealth modified bytes
2284 // restore if need some important flags
2285 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2287 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2288 _ApplyAllStatBonuses();
2290 // set current level health and mana/energy to maximum after applying all mods.
2291 SetHealth(GetMaxHealth());
2292 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2293 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2294 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2295 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2296 SetPower(POWER_FOCUS, 0);
2297 SetPower(POWER_HAPPINESS, 0);
2300 void Player::SendInitialSpells()
2302 uint16 spellCount = 0;
2304 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2305 data << uint8(0);
2307 size_t countPos = data.wpos();
2308 data << uint16(spellCount); // spell count placeholder
2310 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2312 if(itr->second->state == PLAYERSPELL_REMOVED)
2313 continue;
2315 if(!itr->second->active || itr->second->disabled)
2316 continue;
2318 data << uint16(itr->first);
2319 //data << uint16(itr->second->slotId);
2320 data << uint16(0); // it's not slot id
2322 spellCount +=1;
2325 data.put<uint16>(countPos,spellCount); // write real count value
2327 uint16 spellCooldowns = m_spellCooldowns.size();
2328 data << uint16(spellCooldowns);
2329 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); itr++)
2331 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2332 if(!sEntry)
2333 continue;
2335 data << uint16(itr->first);
2337 time_t cooldown = 0;
2338 time_t curTime = time(NULL);
2339 if(itr->second.end > curTime)
2340 cooldown = (itr->second.end-curTime)*1000;
2342 data << uint16(itr->second.itemid); // cast item id
2343 data << uint16(sEntry->Category); // spell category
2344 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2346 data << uint32(0);
2347 data << uint32(cooldown);
2349 else
2351 data << uint32(cooldown);
2352 data << uint32(0);
2356 GetSession()->SendPacket(&data);
2358 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2361 void Player::RemoveMail(uint32 id)
2363 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2365 if ((*itr)->messageID == id)
2367 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2368 m_mail.erase(itr);
2369 return;
2374 void Player::SendMailResult(uint32 mailId, uint32 mailAction, uint32 mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2376 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_BAG_FULL?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2377 data << (uint32) mailId;
2378 data << (uint32) mailAction;
2379 data << (uint32) mailError;
2380 if ( mailError == MAIL_ERR_BAG_FULL )
2381 data << (uint32) equipError;
2382 else if( mailAction == MAIL_ITEM_TAKEN )
2384 data << (uint32) item_guid; // item guid low?
2385 data << (uint32) item_count; // item count?
2387 GetSession()->SendPacket(&data);
2390 void Player::SendNewMail()
2392 // deliver undelivered mail
2393 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2394 data << (uint32) 0;
2395 GetSession()->SendPacket(&data);
2398 void Player::UpdateNextMailTimeAndUnreads()
2400 // calculate next delivery time (min. from non-delivered mails
2401 // and recalculate unReadMail
2402 time_t cTime = time(NULL);
2403 m_nextMailDelivereTime = 0;
2404 unReadMails = 0;
2405 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2407 if((*itr)->deliver_time > cTime)
2409 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2410 m_nextMailDelivereTime = (*itr)->deliver_time;
2412 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2413 ++unReadMails;
2417 void Player::AddNewMailDeliverTime(time_t deliver_time)
2419 if(deliver_time <= time(NULL)) // ready now
2421 ++unReadMails;
2422 SendNewMail();
2424 else // not ready and no have ready mails
2426 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2427 m_nextMailDelivereTime = deliver_time;
2431 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool loading, uint16 slot_id, bool disabled)
2433 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2434 if (!spellInfo)
2436 // do character spell book cleanup (all characters)
2437 if(loading && !learning) // spell load case
2439 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2440 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2442 else
2443 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2445 return false;
2448 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2450 // do character spell book cleanup (all characters)
2451 if(loading && !learning) // spell load case
2453 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2454 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2456 else
2457 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2459 return false;
2462 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2464 bool disabled_case = false;
2465 bool superceded_old = false;
2467 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2468 if (itr != m_spells.end())
2470 // update active state for known spell
2471 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2473 itr->second->active = active;
2475 // loading && !learning == explicitly load from DB and then exist in it already and set correctly
2476 if(loading && !learning)
2477 itr->second->state = PLAYERSPELL_UNCHANGED;
2478 else if(itr->second->state != PLAYERSPELL_NEW)
2479 itr->second->state = PLAYERSPELL_CHANGED;
2481 if(!active)
2483 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2484 data << uint16(spell_id);
2485 GetSession()->SendPacket(&data);
2487 return active; // learn (show in spell book if active now)
2490 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2492 if(itr->second->state != PLAYERSPELL_NEW)
2493 itr->second->state = PLAYERSPELL_CHANGED;
2494 itr->second->disabled = disabled;
2496 if(disabled)
2497 return false;
2499 disabled_case = true;
2501 else switch(itr->second->state)
2503 case PLAYERSPELL_UNCHANGED: // known saved spell
2504 return false;
2505 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2507 delete itr->second;
2508 m_spells.erase(itr);
2509 state = PLAYERSPELL_CHANGED;
2510 break; // need re-add
2512 default: // known not saved yet spell (new or modified)
2514 // can be in case spell loading but learned at some previous spell loading
2515 if(loading && !learning)
2516 itr->second->state = PLAYERSPELL_UNCHANGED;
2518 return false;
2523 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2525 // talent: unlearn all other talent ranks (high and low)
2526 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2528 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2530 for(int i=0; i <5; ++i)
2532 // skip learning spell and no rank spell case
2533 uint32 rankSpellId = talentInfo->RankID[i];
2534 if(!rankSpellId || rankSpellId==spell_id)
2535 continue;
2537 // skip unknown ranks
2538 if(!HasSpell(rankSpellId))
2539 continue;
2541 removeSpell(rankSpellId);
2545 // non talent spell: learn low ranks (recursive call)
2546 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2548 if(loading) // at spells loading, no output, but allow save
2549 addSpell(prev_spell,active,true,loading,SPELL_WITHOUT_SLOT_ID,disabled);
2550 else // at normal learning
2551 learnSpell(prev_spell);
2554 PlayerSpell *newspell = new PlayerSpell;
2555 newspell->active = active;
2556 newspell->state = state;
2557 newspell->disabled = disabled;
2559 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2560 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2562 for( PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr )
2564 if(itr->second->state == PLAYERSPELL_REMOVED) continue;
2565 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr->first);
2566 if(!i_spellInfo) continue;
2568 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr->first) )
2570 if(itr->second->active)
2572 if(spellmgr.IsHighRankOfSpell(spell_id,itr->first))
2574 if(!loading) // not send spell (re-/over-)learn packets at loading
2576 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2577 data << uint16(itr->first);
2578 data << uint16(spell_id);
2579 GetSession()->SendPacket( &data );
2582 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2583 itr->second->active = false;
2584 itr->second->state = PLAYERSPELL_CHANGED;
2585 superceded_old = true; // new spell replace old in action bars and spell book.
2587 else if(spellmgr.IsHighRankOfSpell(itr->first,spell_id))
2589 if(!loading) // not send spell (re-/over-)learn packets at loading
2591 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2592 data << uint16(spell_id);
2593 data << uint16(itr->first);
2594 GetSession()->SendPacket( &data );
2597 // mark new spell as disable (not learned yet for client and will not learned)
2598 newspell->active = false;
2599 if(newspell->state != PLAYERSPELL_NEW)
2600 newspell->state = PLAYERSPELL_CHANGED;
2607 uint16 tmpslot=slot_id;
2609 if (tmpslot == SPELL_WITHOUT_SLOT_ID)
2611 uint16 maxid = 0;
2612 PlayerSpellMap::iterator itr;
2613 for (itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2615 if(itr->second->state == PLAYERSPELL_REMOVED)
2616 continue;
2617 if (itr->second->slotId > maxid)
2618 maxid = itr->second->slotId;
2620 tmpslot = maxid + 1;
2623 newspell->slotId = tmpslot;
2624 m_spells[spell_id] = newspell;
2626 // return false if spell disabled
2627 if (newspell->disabled)
2628 return false;
2631 uint32 talentCost = GetTalentSpellCost(spell_id);
2633 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2634 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2635 if( talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL) )
2637 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2638 CastSpell(this, spell_id, true);
2640 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2641 else if (IsPassiveSpell(spell_id))
2643 // if spell doesn't require a stance or the player is in the required stance
2644 if( ( !spellInfo->Stances &&
2645 spell_id != 5420 && spell_id != 5419 && spell_id != 7376 &&
2646 spell_id != 7381 && spell_id != 21156 && spell_id != 21009 &&
2647 spell_id != 21178 && spell_id != 33948 && spell_id != 40121 ) ||
2648 m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))) ||
2649 (spell_id == 5420 && m_form == FORM_TREE) ||
2650 (spell_id == 5419 && m_form == FORM_TRAVEL) ||
2651 (spell_id == 7376 && m_form == FORM_DEFENSIVESTANCE) ||
2652 (spell_id == 7381 && m_form == FORM_BERSERKERSTANCE) ||
2653 (spell_id == 21156 && m_form == FORM_BATTLESTANCE)||
2654 (spell_id == 21178 && (m_form == FORM_BEAR || m_form == FORM_DIREBEAR) ) ||
2655 (spell_id == 33948 && m_form == FORM_FLIGHT) ||
2656 (spell_id == 40121 && m_form == FORM_FLIGHT_EPIC) )
2657 //Check CasterAuraStates
2658 if (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)))
2659 CastSpell(this, spell_id, true);
2661 else if( IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP) )
2663 CastSpell(this, spell_id, true);
2664 return false;
2667 // update used talent points count
2668 m_usedTalentCount += talentCost;
2670 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2671 if(uint32 freeProfs = GetFreePrimaryProffesionPoints())
2673 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2674 SetFreePrimaryProffesions(freeProfs-1);
2677 // add dependent skills
2678 uint16 maxskill = GetMaxSkillValueForLevel();
2680 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2682 if(spellLearnSkill)
2684 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
2685 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
2687 if(skill_value < spellLearnSkill->value)
2688 skill_value = spellLearnSkill->value;
2690 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
2692 if(skill_max_value < new_skill_max_value)
2693 skill_max_value = new_skill_max_value;
2695 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
2697 else
2699 // not ranked skills
2700 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2701 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2703 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2705 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2706 if(!pSkill)
2707 continue;
2709 if(HasSkill(pSkill->id))
2710 continue;
2712 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2713 // poison special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2714 pSkill->id==SKILL_POISONS && _spell_idx->second->max_value==0 ||
2715 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2716 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
2718 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
2720 case SKILL_RANGE_LANGUAGE:
2721 SetSkill(pSkill->id, 300, 300 );
2722 break;
2723 case SKILL_RANGE_LEVEL:
2724 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
2725 break;
2726 case SKILL_RANGE_MONO:
2727 SetSkill(pSkill->id, 1, 1 );
2728 break;
2729 default:
2730 break;
2736 // learn dependent spells
2737 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2738 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2740 for(SpellLearnSpellMap::const_iterator itr = spell_begin; itr != spell_end; ++itr)
2742 if(!itr->second.autoLearned)
2744 if(loading) // at spells loading, no output, but allow save
2745 addSpell(itr->second.spell,true,true,loading);
2746 else // at normal learning
2747 learnSpell(itr->second.spell);
2751 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2752 return active && !disabled && !superceded_old;
2755 void Player::learnSpell(uint32 spell_id)
2757 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2759 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
2760 bool active = disabled ? itr->second->active : true;
2762 bool learning = addSpell(spell_id,active);
2764 // learn all disabled higher ranks (recursive)
2765 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2766 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
2768 PlayerSpellMap::iterator iter = m_spells.find(i->second);
2769 if (disabled && iter != m_spells.end() && iter->second->disabled)
2770 learnSpell(i->second);
2773 // prevent duplicated entires in spell book
2774 if(!learning)
2775 return;
2777 WorldPacket data(SMSG_LEARNED_SPELL, 4);
2778 data << uint32(spell_id);
2779 GetSession()->SendPacket(&data);
2782 void Player::removeSpell(uint32 spell_id, bool disabled)
2784 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2785 if (itr == m_spells.end())
2786 return;
2788 if(itr->second->state == PLAYERSPELL_REMOVED || disabled && itr->second->disabled)
2789 return;
2791 // unlearn non talent higher ranks (recursive)
2792 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2793 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
2794 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
2795 removeSpell(itr2->second,disabled);
2797 // removing
2798 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2799 data << uint16(spell_id);
2800 GetSession()->SendPacket(&data);
2802 if (disabled)
2804 itr->second->disabled = disabled;
2805 if(itr->second->state != PLAYERSPELL_NEW)
2806 itr->second->state = PLAYERSPELL_CHANGED;
2808 else
2810 if(itr->second->state == PLAYERSPELL_NEW)
2812 delete itr->second;
2813 m_spells.erase(itr);
2815 else
2816 itr->second->state = PLAYERSPELL_REMOVED;
2819 RemoveAurasDueToSpell(spell_id);
2821 // remove pet auras
2822 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id))
2823 RemovePetAura(petSpell);
2825 // free talent points
2826 uint32 talentCosts = GetTalentSpellCost(spell_id);
2827 if(talentCosts > 0)
2829 if(talentCosts < m_usedTalentCount)
2830 m_usedTalentCount -= talentCosts;
2831 else
2832 m_usedTalentCount = 0;
2835 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
2836 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2838 uint32 freeProfs = GetFreePrimaryProffesionPoints()+1;
2839 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
2840 SetFreePrimaryProffesions(freeProfs);
2843 // remove dependent skill
2844 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2845 if(spellLearnSkill)
2847 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
2848 if(!prev_spell) // first rank, remove skill
2849 SetSkill(spellLearnSkill->skill,0,0);
2850 else
2852 // search prev. skill setting by spell ranks chain
2853 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
2854 while(!prevSkill && prev_spell)
2856 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
2857 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
2860 if(!prevSkill) // not found prev skill setting, remove skill
2861 SetSkill(spellLearnSkill->skill,0,0);
2862 else // set to prev. skill setting values
2864 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
2865 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
2867 if(skill_value > prevSkill->value)
2868 skill_value = prevSkill->value;
2870 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
2872 if(skill_max_value > new_skill_max_value)
2873 skill_max_value = new_skill_max_value;
2875 SetSkill(prevSkill->skill,skill_value,skill_max_value);
2880 else
2882 // not ranked skills
2883 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2884 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2886 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2888 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2889 if(!pSkill)
2890 continue;
2892 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2893 // poison special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2894 pSkill->id==SKILL_POISONS && _spell_idx->second->max_value==0 ||
2895 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2896 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
2898 // not reset skills for professions and racial abilities
2899 if( (pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
2900 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0) )
2901 continue;
2903 SetSkill(pSkill->id, 0, 0 );
2908 // remove dependent spells
2909 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2910 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2912 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
2913 removeSpell(itr2->second.spell, disabled);
2916 void Player::RemoveArenaSpellCooldowns()
2918 // remove cooldowns on spells that has < 15 min CD
2919 SpellCooldowns::iterator itr, next;
2920 // iterate spell cooldowns
2921 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
2923 next = itr;
2924 ++next;
2925 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
2926 // check if spellentry is present and if the cooldown is less than 15 mins
2927 if( entry &&
2928 entry->RecoveryTime <= 15 * MINUTE * 1000 &&
2929 entry->CategoryRecoveryTime <= 15 * MINUTE * 1000 )
2931 // notify player
2932 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
2933 data << uint32(itr->first);
2934 data << GetGUID();
2935 GetSession()->SendPacket(&data);
2936 // remove cooldown
2937 m_spellCooldowns.erase(itr);
2942 void Player::RemoveAllSpellCooldown()
2944 if(!m_spellCooldowns.empty())
2946 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
2948 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
2949 data << uint32(itr->first);
2950 data << uint64(GetGUID());
2951 GetSession()->SendPacket(&data);
2953 m_spellCooldowns.clear();
2957 void Player::_LoadSpellCooldowns(QueryResult *result)
2959 m_spellCooldowns.clear();
2961 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
2963 if(result)
2965 time_t curTime = time(NULL);
2969 Field *fields = result->Fetch();
2971 uint32 spell_id = fields[0].GetUInt32();
2972 uint32 item_id = fields[1].GetUInt32();
2973 time_t db_time = (time_t)fields[2].GetUInt64();
2975 if(!sSpellStore.LookupEntry(spell_id))
2977 sLog.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
2978 continue;
2981 // skip outdated cooldown
2982 if(db_time <= curTime)
2983 continue;
2985 AddSpellCooldown(spell_id, item_id, db_time);
2987 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
2989 while( result->NextRow() );
2991 delete result;
2995 void Player::_SaveSpellCooldowns()
2997 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
2999 time_t curTime = time(NULL);
3001 // remove outdated and save active
3002 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3004 if(itr->second.end <= curTime)
3005 m_spellCooldowns.erase(itr++);
3006 else
3008 CharacterDatabase.PExecute("INSERT INTO character_spell_cooldown (guid,spell,item,time) VALUES ('%u', '%u', '%u', '" I64FMTD "')", GetGUIDLow(), itr->first, itr->second.itemid, uint64(itr->second.end));
3009 ++itr;
3014 uint32 Player::resetTalentsCost() const
3016 // The first time reset costs 1 gold
3017 if(m_resetTalentsCost < 1*GOLD)
3018 return 1*GOLD;
3019 // then 5 gold
3020 else if(m_resetTalentsCost < 5*GOLD)
3021 return 5*GOLD;
3022 // After that it increases in increments of 5 gold
3023 else if(m_resetTalentsCost < 10*GOLD)
3024 return 10*GOLD;
3025 else
3027 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3028 if(months > 0)
3030 // This cost will be reduced by a rate of 5 gold per month
3031 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3032 // to a minimum of 10 gold.
3033 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3035 else
3037 // After that it increases in increments of 5 gold
3038 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3039 // until it hits a cap of 50 gold.
3040 if(new_cost > 50*GOLD)
3041 new_cost = 50*GOLD;
3042 return new_cost;
3047 bool Player::resetTalents(bool no_cost)
3049 // not need after this call
3050 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3052 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_TALENTS;
3053 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS), GetGUIDLow());
3056 uint32 level = getLevel();
3057 uint32 talentPointsForLevel = level < 10 ? 0 : uint32((level-9)*sWorld.getRate(RATE_TALENT));
3059 if (m_usedTalentCount == 0)
3061 SetFreeTalentPoints(talentPointsForLevel);
3062 return false;
3065 uint32 cost = 0;
3067 if(!no_cost)
3069 cost = resetTalentsCost();
3071 if (GetMoney() < cost)
3073 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3074 return false;
3078 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); i++)
3080 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3082 if (!talentInfo) continue;
3084 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3086 if(!talentTabInfo)
3087 continue;
3089 // unlearn only talents for character class
3090 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3091 // to prevent unexpected lost normal learned spell skip another class talents
3092 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3093 continue;
3095 for (int j = 0; j < 5; j++)
3097 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3099 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3101 ++itr;
3102 continue;
3105 // remove learned spells (all ranks)
3106 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3108 // unlearn if first rank is talent or learned by talent
3109 if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3111 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3112 itr = GetSpellMap().begin();
3113 continue;
3115 else
3116 ++itr;
3121 SetFreeTalentPoints(talentPointsForLevel);
3123 if(!no_cost)
3125 ModifyMoney(-(int32)cost);
3127 m_resetTalentsCost = cost;
3128 m_resetTalentsTime = time(NULL);
3131 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3132 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3134 return true;
3137 bool Player::_removeSpell(uint16 spell_id)
3139 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3140 if (itr != m_spells.end())
3142 delete itr->second;
3143 m_spells.erase(itr);
3144 return true;
3146 return false;
3149 Mail* Player::GetMail(uint32 id)
3151 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); itr++)
3153 if ((*itr)->messageID == id)
3155 return (*itr);
3158 return NULL;
3161 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3163 if(target == this)
3165 Object::_SetCreateBits(updateMask, target);
3167 else
3169 for(uint16 index = 0; index < m_valuesCount; index++)
3171 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3172 updateMask->SetBit(index);
3177 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3179 if(target == this)
3181 Object::_SetUpdateBits(updateMask, target);
3183 else
3185 Object::_SetUpdateBits(updateMask, target);
3186 *updateMask &= updateVisualBits;
3190 void Player::InitVisibleBits()
3192 updateVisualBits.SetCount(PLAYER_END);
3194 // TODO: really implement OWNER_ONLY and GROUP_ONLY. Flags can be found in UpdateFields.h
3196 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3197 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3198 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3200 updateVisualBits.SetBit(UNIT_FIELD_CHARM);
3201 updateVisualBits.SetBit(UNIT_FIELD_CHARM+1);
3203 updateVisualBits.SetBit(UNIT_FIELD_SUMMON);
3204 updateVisualBits.SetBit(UNIT_FIELD_SUMMON+1);
3206 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY);
3207 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY+1);
3209 updateVisualBits.SetBit(UNIT_FIELD_TARGET);
3210 updateVisualBits.SetBit(UNIT_FIELD_TARGET+1);
3212 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT);
3213 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT+1);
3215 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3216 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3217 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3218 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3219 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3220 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3222 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3223 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3224 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3225 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3226 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3227 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3229 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3230 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3231 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3232 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3233 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3234 for(uint16 i = UNIT_FIELD_AURA; i < UNIT_FIELD_AURASTATE; ++i)
3235 updateVisualBits.SetBit(i);
3236 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3237 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME);
3238 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3239 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3240 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3241 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3242 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3243 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3244 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3245 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3246 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3247 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3248 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3249 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3250 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3252 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER);
3253 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER+1);
3254 updateVisualBits.SetBit(PLAYER_FLAGS);
3255 updateVisualBits.SetBit(PLAYER_GUILDID);
3256 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3257 updateVisualBits.SetBit(PLAYER_BYTES);
3258 updateVisualBits.SetBit(PLAYER_BYTES_2);
3259 updateVisualBits.SetBit(PLAYER_BYTES_3);
3260 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3261 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3263 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3264 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i+=4)
3265 updateVisualBits.SetBit(i);
3267 //Players visible items are not inventory stuff
3268 //431) = 884 (0x374) = main weapon
3269 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; i++)
3271 // item creator
3272 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + (i*MAX_VISIBLE_ITEM_OFFSET) + 0);
3273 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + (i*MAX_VISIBLE_ITEM_OFFSET) + 1);
3275 uint16 visual_base = PLAYER_VISIBLE_ITEM_1_0 + (i*MAX_VISIBLE_ITEM_OFFSET);
3277 // item entry
3278 updateVisualBits.SetBit(visual_base + 0);
3280 // item enchantment IDs
3281 for(uint8 j = 0; j < MAX_INSPECTED_ENCHANTMENT_SLOT; ++j)
3282 updateVisualBits.SetBit(visual_base + 1 + j);
3284 // random properties
3285 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 0 + (i*MAX_VISIBLE_ITEM_OFFSET));
3286 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (i*MAX_VISIBLE_ITEM_OFFSET));
3289 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3292 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3294 for(int i = 0; i < EQUIPMENT_SLOT_END; i++)
3296 if(m_items[i] == NULL)
3297 continue;
3299 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3302 if(target == this)
3305 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3307 if(m_items[i] == NULL)
3308 continue;
3310 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3312 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3314 if(m_items[i] == NULL)
3315 continue;
3317 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3321 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3324 void Player::DestroyForPlayer( Player *target ) const
3326 Unit::DestroyForPlayer( target );
3328 for(int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
3330 if(m_items[i] == NULL)
3331 continue;
3333 m_items[i]->DestroyForPlayer( target );
3336 if(target == this)
3339 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3341 if(m_items[i] == NULL)
3342 continue;
3344 m_items[i]->DestroyForPlayer( target );
3346 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3348 if(m_items[i] == NULL)
3349 continue;
3351 m_items[i]->DestroyForPlayer( target );
3356 bool Player::HasSpell(uint32 spell) const
3358 PlayerSpellMap::const_iterator itr = m_spells.find((uint16)spell);
3359 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled);
3362 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3364 if (!trainer_spell)
3365 return TRAINER_SPELL_RED;
3367 if (!trainer_spell->spell)
3368 return TRAINER_SPELL_RED;
3370 // known spell
3371 if(HasSpell(trainer_spell->spell))
3372 return TRAINER_SPELL_GRAY;
3374 // check race/class requirement
3375 if(!IsSpellFitByClassAndRace(trainer_spell->spell))
3376 return TRAINER_SPELL_RED;
3378 // check level requirement
3379 if(getLevel() < trainer_spell->reqlevel)
3380 return TRAINER_SPELL_RED;
3382 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->spell))
3384 // check prev.rank requirement
3385 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3386 return TRAINER_SPELL_RED;
3388 // check additional spell requirement
3389 if(spell_chain->req && !HasSpell(spell_chain->req))
3390 return TRAINER_SPELL_RED;
3393 // check skill requirement
3394 if(trainer_spell->reqskill && GetBaseSkillValue(trainer_spell->reqskill) < trainer_spell->reqskillvalue)
3395 return TRAINER_SPELL_RED;
3397 // exist, already checked at loading
3398 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->spell);
3400 // secondary prof. or not prof. spell
3401 uint32 skill = spell->EffectMiscValue[1];
3403 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3404 return TRAINER_SPELL_GREEN;
3406 // check primary prof. limit
3407 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProffesionPoints() == 0)
3408 return TRAINER_SPELL_RED;
3410 return TRAINER_SPELL_GREEN;
3413 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3415 uint32 guid = GUID_LOPART(playerguid);
3417 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3418 // bones will be deleted by corpse/bones deleting thread shortly
3419 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3421 // remove from guild
3422 uint32 guildId = GetGuildIdFromDB(playerguid);
3423 if(guildId != 0)
3425 Guild* guild = objmgr.GetGuildById(guildId);
3426 if(guild)
3427 guild->DelMember(guid);
3430 // the player was uninvited already on logout so just remove from group
3431 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3432 if(resultGroup)
3434 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3435 delete resultGroup;
3436 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3437 if(group)
3439 RemoveFromGroup(group, playerguid);
3443 // remove signs from petitions (also remove petitions if owner);
3444 RemovePetitionsAndSigns(playerguid, 10);
3446 // return back all mails with COD and Item 0 1 2 3 4 5 6
3447 QueryResult *resultMail = CharacterDatabase.PQuery("SELECT id,mailTemplateId,sender,subject,itemTextId,money,has_items FROM mail WHERE receiver='%u' AND has_items<>0 AND cod<>0", guid);
3448 if(resultMail)
3452 Field *fields = resultMail->Fetch();
3454 uint32 mail_id = fields[0].GetUInt32();
3455 uint16 mailTemplateId= fields[1].GetUInt16();
3456 uint32 sender = fields[2].GetUInt32();
3457 std::string subject = fields[3].GetCppString();
3458 uint32 itemTextId = fields[4].GetUInt32();
3459 uint32 money = fields[5].GetUInt32();
3460 bool has_items = fields[6].GetBool();
3462 //we can return mail now
3463 //so firstly delete the old one
3464 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3466 MailItemsInfo mi;
3467 if(has_items)
3469 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", mail_id);
3470 if(resultItems)
3474 Field *fields2 = resultItems->Fetch();
3476 uint32 item_guidlow = fields2[0].GetUInt32();
3477 uint32 item_template = fields2[1].GetUInt32();
3479 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3480 if(!itemProto)
3482 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3483 continue;
3486 Item *pItem = NewItemOrBag(itemProto);
3487 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER)))
3489 pItem->FSetState(ITEM_REMOVED);
3490 pItem->SaveToDB(); // it also deletes item object !
3491 continue;
3494 mi.AddItem(item_guidlow, item_template, pItem);
3496 while (resultItems->NextRow());
3498 delete resultItems;
3502 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3504 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3506 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, 0, mailTemplateId);
3508 while (resultMail->NextRow());
3510 delete resultMail;
3513 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3514 // Get guids of character's pets, will deleted in transaction
3515 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3517 // NOW we can finally clear other DB data related to character
3518 CharacterDatabase.BeginTransaction();
3519 if (resultPets)
3523 Field *fields3 = resultPets->Fetch();
3524 uint32 petguidlow = fields3[0].GetUInt32();
3525 Pet::DeleteFromDB(petguidlow);
3526 } while (resultPets->NextRow());
3527 delete resultPets;
3530 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3531 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3532 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3533 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3534 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3535 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3536 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3537 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3538 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3539 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3540 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3541 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3542 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3543 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3544 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3545 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3546 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3547 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3548 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3549 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
3550 CharacterDatabase.CommitTransaction();
3552 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3553 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
3556 void Player::SetMovement(PlayerMovementType pType)
3558 WorldPacket data;
3559 switch(pType)
3561 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
3562 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
3563 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
3564 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
3565 default:
3566 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
3567 return;
3569 data.append(GetPackGUID());
3570 data << uint32(0);
3571 GetSession()->SendPacket( &data );
3574 /* Preconditions:
3575 - a resurrectable corpse must not be loaded for the player (only bones)
3576 - the player must be in world
3578 void Player::BuildPlayerRepop()
3580 if(getRace() == RACE_NIGHTELF)
3581 CastSpell(this, 20584, true); // auras SPELL_AURA_INCREASE_SPEED(+speed in wisp form), SPELL_AURA_INCREASE_SWIM_SPEED(+swim speed in wisp form), SPELL_AURA_TRANSFORM (to wisp form)
3582 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3584 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3585 // there must be SMSG.STOP_MIRROR_TIMER
3586 // there we must send 888 opcode
3588 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3589 if(GetCorpse())
3591 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3592 assert(false);
3595 // create a corpse and place it at the player's location
3596 CreateCorpse();
3597 Corpse *corpse = GetCorpse();
3598 if(!corpse)
3600 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3601 return;
3603 GetMap()->Add(corpse);
3605 // convert player body to ghost
3606 SetHealth( 1 );
3608 SetMovement(MOVE_WATER_WALK);
3609 if(!GetSession()->isLogingOut())
3610 SetMovement(MOVE_UNROOT);
3612 // BG - remove insignia related
3613 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
3615 SendCorpseReclaimDelay();
3617 // to prevent cheating
3618 corpse->ResetGhostTime();
3620 StopMirrorTimers(); //disable timers(bars)
3622 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
3624 SetByteValue(UNIT_FIELD_BYTES_1, 3, PLAYER_STATE_FLAG_ALWAYS_STAND);
3627 void Player::SendDelayResponse(const uint32 ml_seconds)
3629 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
3630 data << (uint32)time(NULL);
3631 data << (uint32)0;
3632 GetSession()->SendPacket( &data );
3635 void Player::ResurrectPlayer(float restore_percent, bool updateToWorld, bool applySickness)
3637 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
3638 data << uint32(-1);
3639 data << float(0);
3640 data << float(0);
3641 data << float(0);
3642 GetSession()->SendPacket(&data);
3644 // speed change, land walk
3646 // remove death flag + set aura
3647 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
3648 if(getRace() == RACE_NIGHTELF)
3649 RemoveAurasDueToSpell(20584); // speed bonuses
3650 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3652 setDeathState(ALIVE);
3654 SetMovement(MOVE_LAND_WALK);
3655 SetMovement(MOVE_UNROOT);
3657 m_deathTimer = 0;
3659 // set health/powers (0- will be set in caller)
3660 if(restore_percent>0.0f)
3662 SetHealth(uint32(GetMaxHealth()*restore_percent));
3663 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
3664 SetPower(POWER_RAGE, 0);
3665 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
3668 // update visbility
3669 ObjectAccessor::UpdateVisibilityForPlayer(this);
3671 // some items limited to specific map
3672 DestroyZoneLimitedItem( true, GetZoneId());
3674 if(!applySickness || getLevel() <= 10)
3675 return;
3677 //Characters from level 1-10 are not affected by resurrection sickness.
3678 //Characters from level 11-19 will suffer from one minute of sickness
3679 //for each level they are above 10.
3680 //Characters level 20 and up suffer from ten minutes of sickness.
3681 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
3683 if(int32(getLevel()) >= startLevel)
3685 // set resurrection sickness
3686 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
3688 // not full duration
3689 if(int32(getLevel()) < startLevel+9)
3691 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
3693 for(int i =0; i < 3; ++i)
3695 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
3697 Aur->SetAuraDuration(delta*1000);
3698 Aur->UpdateAuraDuration();
3705 void Player::KillPlayer()
3707 SetMovement(MOVE_ROOT);
3709 StopMirrorTimers(); //disable timers(bars)
3711 setDeathState(CORPSE);
3712 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
3714 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
3715 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
3717 // 6 minutes until repop at graveyard
3718 m_deathTimer = 6*MINUTE*1000;
3720 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
3722 // don't create corpse at this moment, player might be falling
3724 // update visibility
3725 ObjectAccessor::UpdateObjectVisibility(this);
3728 void Player::CreateCorpse()
3730 // prevent existence 2 corpse for player
3731 SpawnCorpseBones();
3733 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
3735 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
3736 SetPvPDeath(false);
3738 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this, GetMapId(), GetPositionX(),
3739 GetPositionY(), GetPositionZ(), GetOrientation()))
3741 delete corpse;
3742 return;
3745 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
3746 _pb = GetUInt32Value(PLAYER_BYTES);
3747 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
3749 uint8 race = (uint8)(_uf);
3750 uint8 skin = (uint8)(_pb);
3751 uint8 face = (uint8)(_pb >> 8);
3752 uint8 hairstyle = (uint8)(_pb >> 16);
3753 uint8 haircolor = (uint8)(_pb >> 24);
3754 uint8 facialhair = (uint8)(_pb2);
3756 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
3757 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
3759 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
3760 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
3762 uint32 flags = CORPSE_FLAG_UNK2;
3763 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
3764 flags |= CORPSE_FLAG_HIDE_HELM;
3765 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
3766 flags |= CORPSE_FLAG_HIDE_CLOAK;
3767 if(InBattleGround())
3768 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
3769 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
3771 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
3773 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
3775 uint32 iDisplayID;
3776 uint16 iIventoryType;
3777 uint32 _cfi;
3778 for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
3780 if(m_items[i])
3782 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
3783 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
3785 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
3786 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
3790 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
3791 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
3792 assert(entry);
3793 if(entry->map_type != MAP_BATTLEGROUND)
3794 corpse->SaveToDB();
3796 // register for player, but not show
3797 ObjectAccessor::Instance().AddCorpse(corpse);
3800 void Player::SpawnCorpseBones()
3802 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
3803 SaveToDB(); // prevent loading as ghost without corpse
3806 Corpse* Player::GetCorpse() const
3808 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
3811 void Player::DurabilityLossAll(double percent, bool inventory)
3813 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
3814 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3815 DurabilityLoss(pItem,percent);
3817 if(inventory)
3819 // bags not have durability
3820 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3822 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
3823 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3824 DurabilityLoss(pItem,percent);
3826 // keys not have durability
3827 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3829 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3830 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3831 if(ItemPrototype const *pBagProto = pBag->GetProto())
3832 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
3833 if(Item* pItem = GetItemByPos( i, j ))
3834 DurabilityLoss(pItem,percent);
3838 void Player::DurabilityLoss(Item* item, double percent)
3840 if(!item )
3841 return;
3843 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3845 if(!pMaxDurability)
3846 return;
3848 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
3850 if(pDurabilityLoss < 1 )
3851 pDurabilityLoss = 1;
3853 DurabilityPointsLoss(item,pDurabilityLoss);
3856 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
3858 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
3859 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3860 DurabilityPointsLoss(pItem,points);
3862 if(inventory)
3864 // bags not have durability
3865 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3867 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
3868 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3869 DurabilityPointsLoss(pItem,points);
3871 // keys not have durability
3872 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3874 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3875 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3876 if(ItemPrototype const *pBagProto = pBag->GetProto())
3877 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
3878 if(Item* pItem = GetItemByPos( i, j ))
3879 DurabilityPointsLoss(pItem,points);
3883 void Player::DurabilityPointsLoss(Item* item, int32 points)
3885 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3886 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
3887 int32 pNewDurability = pOldDurability - points;
3889 if (pNewDurability < 0)
3890 pNewDurability = 0;
3891 else if (pNewDurability > pMaxDurability)
3892 pNewDurability = pMaxDurability;
3894 if (pOldDurability != pNewDurability)
3896 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
3897 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
3898 _ApplyItemMods(item,item->GetSlot(), false);
3900 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
3902 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
3903 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
3904 _ApplyItemMods(item,item->GetSlot(), true);
3906 item->SetState(ITEM_CHANGED, this);
3910 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
3912 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
3913 DurabilityPointsLoss(pItem,1);
3916 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
3918 uint32 TotalCost = 0;
3919 // equipped, backpack, bags itself
3920 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
3921 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
3923 // bank, buyback and keys not repaired
3925 // items in inventory bags
3926 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; j++)
3927 for(int i = 0; i < MAX_BAG_SIZE; i++)
3928 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
3929 return TotalCost;
3932 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
3934 Item* item = GetItemByPos(pos);
3936 uint32 TotalCost = 0;
3937 if(!item)
3938 return TotalCost;
3940 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3941 if(!maxDurability)
3942 return TotalCost;
3944 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
3946 if(cost)
3948 uint32 LostDurability = maxDurability - curDurability;
3949 if(LostDurability>0)
3951 ItemPrototype const *ditemProto = sItemStorage.LookupEntry<ItemPrototype>(item->GetEntry());
3952 if(!ditemProto)
3954 sLog.outError("ERROR: RepairDurability: Unknown item id %u", ditemProto);
3955 return TotalCost;
3958 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
3959 if(!dcost)
3961 sLog.outError("ERROR: RepairDurability: Wrong item lvl %u", dcost);
3962 return TotalCost;
3965 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry((ditemProto->Quality+1)*2);
3966 if(!dQualitymodEntry)
3968 sLog.outError("ERROR: RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntry);
3969 return TotalCost;
3972 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
3973 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
3975 costs = uint32(costs * discountMod);
3977 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
3978 costs = 1;
3980 if (guildBank)
3982 if (GetGuildId()==0)
3984 DEBUG_LOG("You are not member of a guild");
3985 return TotalCost;
3988 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
3989 if (!pGuild)
3990 return TotalCost;
3992 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
3994 DEBUG_LOG("You do not have rights to withdraw for repairs");
3995 return TotalCost;
3998 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4000 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4001 return TotalCost;
4004 if (pGuild->GetGuildBankMoney() < costs)
4006 DEBUG_LOG("There is not enough money in bank");
4007 return TotalCost;
4010 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4011 TotalCost = costs;
4013 else if (GetMoney() < costs)
4015 DEBUG_LOG("You do not have enough money");
4016 return TotalCost;
4018 else
4019 ModifyMoney( -int32(costs) );
4023 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4024 item->SetState(ITEM_CHANGED, this);
4026 // reapply mods for total broken and repaired item if equipped
4027 if(IsEquipmentPos(pos) && !curDurability)
4028 _ApplyItemMods(item,pos & 255, true);
4029 return TotalCost;
4032 void Player::RepopAtGraveyard()
4034 // note: this can be called also when the player is alive
4035 // for example from WorldSession::HandleMovementOpcodes
4037 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4039 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4040 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4042 ResurrectPlayer(0.5f);
4043 SpawnCorpseBones();
4046 WorldSafeLocsEntry const *ClosestGrave = NULL;
4048 // Special handle for battleground maps
4049 BattleGround *bg = sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
4051 if(bg && (bg->GetTypeID() == BATTLEGROUND_AB || bg->GetTypeID() == BATTLEGROUND_EY))
4052 ClosestGrave = bg->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetTeam());
4053 else
4054 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4056 // stop countdown until repop
4057 m_deathTimer = 0;
4059 // if no grave found, stay at the current location
4060 // and don't show spirit healer location
4061 if(ClosestGrave)
4063 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4064 if(isDead()) // not send if alive, because it used in TeleportTo()
4066 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4067 data << ClosestGrave->map_id;
4068 data << ClosestGrave->x;
4069 data << ClosestGrave->y;
4070 data << ClosestGrave->z;
4071 GetSession()->SendPacket(&data);
4076 void Player::JoinedChannel(Channel *c)
4078 m_channels.push_back(c);
4081 void Player::LeftChannel(Channel *c)
4083 m_channels.remove(c);
4086 void Player::CleanupChannels()
4088 while(!m_channels.empty())
4090 Channel* ch = *m_channels.begin();
4091 m_channels.erase(m_channels.begin()); // remove from player's channel list
4092 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4093 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4094 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4097 sLog.outDebug("Player: channels cleaned up!");
4100 void Player::UpdateLocalChannels(uint32 newZone )
4102 if(m_channels.empty())
4103 return;
4105 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4106 if(!current_zone)
4107 return;
4109 ChannelMgr* cMgr = channelMgr(GetTeam());
4110 if(!cMgr)
4111 return;
4113 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4115 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4117 next = i; ++next;
4119 // skip non built-in channels
4120 if(!(*i)->IsConstant())
4121 continue;
4123 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4124 if(!ch)
4125 continue;
4127 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4128 continue;
4130 // new channel
4131 char new_channel_name_buf[100];
4132 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4133 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4135 if((*i)!=new_channel)
4137 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4139 // leave old channel
4140 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4141 std::string name = (*i)->GetName(); // stroe name, (*i)erase in LeftChannel
4142 LeftChannel(*i); // remove from player's channel list
4143 cMgr->LeftChannel(name); // delete if empty
4146 sLog.outDebug("Player: channels cleaned up!");
4149 void Player::LeaveLFGChannel()
4151 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4153 if((*i)->IsLFG())
4155 (*i)->Leave(GetGUID());
4156 break;
4161 void Player::UpdateDefense()
4163 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4165 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4167 // update dependent from defense skill part
4168 UpdateDefenseBonusesMod();
4172 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply, bool affectStats)
4174 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4176 sLog.outError("ERROR in HandleBaseModValue(): nonexisted BaseModGroup of wrong BaseModType!");
4177 return;
4180 float val = 1.0f;
4182 switch(modType)
4184 case FLAT_MOD:
4185 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4186 break;
4187 case PCT_MOD:
4188 if(amount <= -100.0f)
4189 amount = -200.0f;
4191 val = (100.0f + amount) / 100.0f;
4192 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4193 break;
4196 if(!CanModifyStats())
4197 return;
4199 switch(modGroup)
4201 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4202 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4203 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4204 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4205 default: break;
4209 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4211 if(modGroup >= BASEMOD_END || modType > MOD_END)
4213 sLog.outError("ERROR: trial to access nonexisted BaseModGroup or wrong BaseModType!");
4214 return 0.0f;
4217 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4218 return 0.0f;
4220 return m_auraBaseMod[modGroup][modType];
4223 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4225 if(modGroup >= BASEMOD_END)
4227 sLog.outError("ERROR: wrong BaseModGroup in GetTotalBaseModValue()!");
4228 return 0.0f;
4231 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4232 return 0.0f;
4234 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4237 uint32 Player::GetShieldBlockValue() const
4239 BaseModGroup modGroup = SHIELD_BLOCK_VALUE;
4241 float value = GetTotalBaseModValue(modGroup) + GetStat(STAT_STRENGTH)/20 - 1;
4243 value = (value < 0) ? 0 : value;
4245 return uint32(value);
4248 float Player::GetMeleeCritFromAgility()
4250 uint32 level = getLevel();
4251 uint32 pclass = getClass();
4253 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4255 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4256 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4257 if (critBase==NULL || critRatio==NULL)
4258 return 0.0f;
4260 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4261 return crit*100.0f;
4264 float Player::GetDodgeFromAgility()
4266 // Table for base dodge values
4267 float dodge_base[MAX_CLASSES] = {
4268 0.0075f, // Warrior
4269 0.00652f, // Paladin
4270 -0.0545f, // Hunter
4271 -0.0059f, // Rogue
4272 0.03183f, // Priest
4273 0.0114f, // DK
4274 0.0167f, // Shaman
4275 0.034575f, // Mage
4276 0.02011f, // Warlock
4277 0.0f, // ??
4278 -0.0187f // Druid
4280 // Crit/agility to dodge/agility coefficient multipliers
4281 float crit_to_dodge[MAX_CLASSES] = {
4282 1.1f, // Warrior
4283 1.0f, // Paladin
4284 1.6f, // Hunter
4285 2.0f, // Rogue
4286 1.0f, // Priest
4287 1.0f, // DK?
4288 1.0f, // Shaman
4289 1.0f, // Mage
4290 1.0f, // Warlock
4291 0.0f, // ??
4292 1.7f // Druid
4295 uint32 level = getLevel();
4296 uint32 pclass = getClass();
4298 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4300 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4301 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4302 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4303 return 0.0f;
4305 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4306 return dodge*100.0f;
4309 float Player::GetSpellCritFromIntellect()
4311 uint32 level = getLevel();
4312 uint32 pclass = getClass();
4314 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4316 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4317 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4318 if (critBase==NULL || critRatio==NULL)
4319 return 0.0f;
4321 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4322 return crit*100.0f;
4325 float Player::GetRatingCoefficient(CombatRating cr) const
4327 uint32 level = getLevel();
4329 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4331 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4332 if (Rating == NULL)
4333 return 1.0f; // By default use minimum coefficient (not must be called)
4335 return Rating->ratio;
4338 float Player::GetRatingBonusValue(CombatRating cr) const
4340 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4343 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4345 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.0f;
4346 if (melee>25.0f) melee = 25.0f;
4347 return uint32 (melee * damage /100.0f);
4350 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4352 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.0f;
4353 if (ranged>25.0f) ranged=25.0f;
4354 return uint32 (ranged * damage /100.0f);
4357 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4359 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.0f;
4360 // In wow script resilience limited to 25%
4361 if (spell>25.0f)
4362 spell = 25.0f;
4363 return uint32 (spell * damage / 100.0f);
4366 uint32 Player::GetDotDamageReduction(uint32 damage) const
4368 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4369 // Dot resilience not limited (limit it by 100%)
4370 if (spellDot > 100.0f)
4371 spellDot = 100.0f;
4372 return uint32 (spellDot * damage / 100.0f);
4375 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4377 switch (attType)
4379 case BASE_ATTACK:
4380 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4381 case OFF_ATTACK:
4382 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4383 default:
4384 break;
4386 return 0.0f;
4389 float Player::OCTRegenHPPerSpirit()
4391 uint32 level = getLevel();
4392 uint32 pclass = getClass();
4394 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4396 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4397 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4398 if (baseRatio==NULL || moreRatio==NULL)
4399 return 0.0f;
4401 // Formula from PaperDollFrame script
4402 float spirit = GetStat(STAT_SPIRIT);
4403 float baseSpirit = spirit;
4404 if (baseSpirit>50) baseSpirit = 50;
4405 float moreSpirit = spirit - baseSpirit;
4406 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4407 return regen;
4410 float Player::OCTRegenMPPerSpirit()
4412 uint32 level = getLevel();
4413 uint32 pclass = getClass();
4415 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4417 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4418 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4419 if (moreRatio==NULL)
4420 return 0.0f;
4422 // Formula get from PaperDollFrame script
4423 float spirit = GetStat(STAT_SPIRIT);
4424 float regen = spirit * moreRatio->ratio;
4425 return regen;
4428 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4430 ApplyModUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, value, apply);
4432 float RatingCoeffecient = GetRatingCoefficient(cr);
4433 float RatingChange = 0.0f;
4435 bool affectStats = CanModifyStats();
4437 switch (cr)
4439 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4440 case CR_DEFENSE_SKILL:
4441 UpdateDefenseBonusesMod();
4442 break;
4443 case CR_DODGE:
4444 UpdateDodgePercentage();
4445 break;
4446 case CR_PARRY:
4447 UpdateParryPercentage();
4448 break;
4449 case CR_BLOCK:
4450 UpdateBlockPercentage();
4451 break;
4452 case CR_HIT_MELEE:
4453 RatingChange = value / RatingCoeffecient;
4454 m_modMeleeHitChance += apply ? RatingChange : -RatingChange;
4455 break;
4456 case CR_HIT_RANGED:
4457 RatingChange = value / RatingCoeffecient;
4458 m_modRangedHitChance += apply ? RatingChange : -RatingChange;
4459 break;
4460 case CR_HIT_SPELL:
4461 RatingChange = value / RatingCoeffecient;
4462 m_modSpellHitChance += apply ? RatingChange : -RatingChange;
4463 break;
4464 case CR_CRIT_MELEE:
4465 if(affectStats)
4467 UpdateCritPercentage(BASE_ATTACK);
4468 UpdateCritPercentage(OFF_ATTACK);
4470 break;
4471 case CR_CRIT_RANGED:
4472 if(affectStats)
4473 UpdateCritPercentage(RANGED_ATTACK);
4474 break;
4475 case CR_CRIT_SPELL:
4476 if(affectStats)
4477 UpdateAllSpellCritChances();
4478 break;
4479 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4480 case CR_HIT_TAKEN_RANGED:
4481 break;
4482 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4483 break;
4484 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4485 case CR_CRIT_TAKEN_RANGED:
4486 break;
4487 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4488 break;
4489 case CR_HASTE_MELEE:
4490 RatingChange = value / RatingCoeffecient;
4491 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4492 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4493 break;
4494 case CR_HASTE_RANGED:
4495 RatingChange = value / RatingCoeffecient;
4496 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4497 break;
4498 case CR_HASTE_SPELL:
4499 RatingChange = value / RatingCoeffecient;
4500 ApplyCastTimePercentMod(RatingChange,apply);
4501 break;
4502 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4503 case CR_WEAPON_SKILL_OFFHAND:
4504 case CR_WEAPON_SKILL_RANGED:
4505 break;
4506 case CR_EXPERTISE:
4507 if(affectStats)
4509 UpdateExpertise(BASE_ATTACK);
4510 UpdateExpertise(OFF_ATTACK);
4512 break;
4516 void Player::SetRegularAttackTime()
4518 for(int i = 0; i < MAX_ATTACK; ++i)
4520 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4521 if(tmpitem && !tmpitem->IsBroken())
4523 ItemPrototype const *proto = tmpitem->GetProto();
4524 if(proto->Delay)
4525 SetAttackTime(WeaponAttackType(i), proto->Delay);
4526 else
4527 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4532 //skill+step, checking for max value
4533 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4535 if(!skill_id)
4536 return false;
4538 uint16 i=0;
4539 for (; i < PLAYER_MAX_SKILLS; i++)
4540 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
4541 break;
4543 if(i>=PLAYER_MAX_SKILLS)
4544 return false;
4546 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4547 uint32 value = SKILL_VALUE(data);
4548 uint32 max = SKILL_MAX(data);
4550 if ((!max) || (!value) || (value >= max))
4551 return false;
4553 if (value*512 < max*urand(0,512))
4555 uint32 new_value = value+step;
4556 if(new_value > max)
4557 new_value = max;
4559 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
4560 return true;
4563 return false;
4566 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
4568 if ( SkillValue >= GrayLevel )
4569 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
4570 if ( SkillValue >= GreenLevel )
4571 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
4572 if ( SkillValue >= YellowLevel )
4573 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
4574 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
4577 bool Player::UpdateCraftSkill(uint32 spellid)
4579 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
4581 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
4582 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
4584 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4586 if(_spell_idx->second->skillId)
4588 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
4590 // Alchemy Discoveries here
4591 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
4592 if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
4594 if(uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
4595 learnSpell(discoveredSpell);
4598 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
4600 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
4601 _spell_idx->second->max_value,
4602 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
4603 _spell_idx->second->min_value),
4604 craft_skill_gain);
4607 return false;
4610 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
4612 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
4614 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4616 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4617 switch (SkillId)
4619 case SKILL_HERBALISM:
4620 case SKILL_LOCKPICKING:
4621 case SKILL_JEWELCRAFTING:
4622 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4623 case SKILL_SKINNING:
4624 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
4625 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4626 else
4627 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
4628 case SKILL_MINING:
4629 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
4630 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4631 else
4632 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
4634 return false;
4637 bool Player::UpdateFishingSkill()
4639 sLog.outDebug("UpdateFishingSkill");
4641 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
4643 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
4645 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4647 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
4650 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
4652 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
4653 if ( !SkillId )
4654 return false;
4656 if(Chance <= 0) // speedup in 0 chance case
4658 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4659 return false;
4662 uint16 i=0;
4663 for (; i < PLAYER_MAX_SKILLS; i++)
4664 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
4665 if ( i >= PLAYER_MAX_SKILLS )
4666 return false;
4668 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4669 uint16 SkillValue = SKILL_VALUE(data);
4670 uint16 MaxValue = SKILL_MAX(data);
4672 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
4673 return false;
4675 int32 Roll = irand(1,1000);
4677 if ( Roll <= Chance )
4679 uint32 new_value = SkillValue+step;
4680 if(new_value > MaxValue)
4681 new_value = MaxValue;
4683 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
4684 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
4685 return true;
4688 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4689 return false;
4692 void Player::UpdateWeaponSkill (WeaponAttackType attType)
4694 // no skill gain in pvp
4695 Unit *pVictim = getVictim();
4696 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
4697 return;
4699 if(IsInFeralForm())
4700 return; // always maximized SKILL_FERAL_COMBAT in fact
4702 if(m_form == FORM_TREE)
4703 return; // use weapon but not skill up
4705 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
4707 switch(attType)
4709 case BASE_ATTACK:
4711 Item *tmpitem = GetWeaponForAttack(attType,true);
4713 if (!tmpitem)
4714 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
4715 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
4716 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4717 break;
4719 case OFF_ATTACK:
4720 case RANGED_ATTACK:
4722 Item *tmpitem = GetWeaponForAttack(attType,true);
4723 if (tmpitem)
4724 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4725 break;
4728 UpdateAllCritPercentages();
4731 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, MeleeHitOutcome outcome, bool defence)
4733 switch(outcome)
4735 case MELEE_HIT_CRIT:
4736 case MELEE_HIT_DODGE:
4737 case MELEE_HIT_PARRY:
4738 case MELEE_HIT_BLOCK:
4739 case MELEE_HIT_BLOCK_CRIT:
4740 return;
4742 default:
4743 break;
4746 uint32 plevel = getLevel(); // if defense than pVictim == attacker
4747 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
4748 uint32 moblevel = pVictim->getLevelForTarget(this);
4749 if(moblevel < greylevel)
4750 return;
4752 if (moblevel > plevel + 5)
4753 moblevel = plevel + 5;
4755 uint32 lvldif = moblevel - greylevel;
4756 if(lvldif < 3)
4757 lvldif = 3;
4759 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
4760 if(skilldif <= 0)
4761 return;
4763 float chance = float(3 * lvldif * skilldif) / plevel;
4764 if(!defence)
4766 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
4767 chance *= 0.1f * GetStat(STAT_INTELLECT);
4770 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
4772 if(roll_chance_f(chance))
4774 if(defence)
4775 UpdateDefense();
4776 else
4777 UpdateWeaponSkill(attType);
4779 else
4780 return;
4783 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
4785 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4786 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
4788 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
4789 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
4790 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
4792 if(talent) // permanent bonus stored in high part
4793 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
4794 else // temporary/item bonus stored in low part
4795 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
4796 return;
4800 void Player::UpdateMaxSkills()
4802 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
4804 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4805 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4807 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
4809 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
4810 if(!pSkill)
4811 continue;
4813 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
4814 continue;
4816 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4817 uint32 max = SKILL_MAX(data);
4818 uint32 val = SKILL_VALUE(data);
4820 // update only level dependent max skill values
4821 if(max!=1 && max != maxconfskill)
4823 uint32 max_Skill = GetMaxSkillValueForLevel();
4824 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,max_Skill));
4829 void Player::UpdateSkillsToMaxSkillsForLevel()
4831 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4832 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4834 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
4835 if( IsProfessionSkill(pskill) || pskill == SKILL_RIDING )
4836 continue;
4837 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4839 uint32 max = SKILL_MAX(data);
4841 if(max > 1)
4842 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
4844 if(pskill == SKILL_DEFENSE)
4845 UpdateDefenseBonusesMod();
4849 // This functions sets a skill line value (and adds if doesn't exist yet)
4850 // To "remove" a skill line, set it's values to zero
4851 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
4853 if(!id)
4854 return;
4856 uint16 i=0;
4857 for (; i < PLAYER_MAX_SKILLS; i++)
4858 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
4860 if(i<PLAYER_MAX_SKILLS) //has skill
4862 if(currVal)
4863 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
4864 else //remove
4866 // clear skill fields
4867 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
4868 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
4869 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
4871 // remove spells that depend on this skill when removing the skill
4872 for (PlayerSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
4874 ++next;
4875 if(itr->second->state == PLAYERSPELL_REMOVED)
4876 continue;
4878 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(itr->first);
4879 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(itr->first);
4881 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4883 if (_spell_idx->second->skillId == id)
4885 // this may remove more than one spell (dependants)
4886 removeSpell(itr->first);
4887 next = m_spells.begin();
4888 break;
4894 else if(currVal) //add
4896 for (i=0; i < PLAYER_MAX_SKILLS; i++)
4897 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4899 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
4900 if(!pSkill)
4902 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
4903 return;
4905 // enable unlearn button for primary professions only
4906 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
4907 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
4908 else
4909 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
4910 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
4912 // apply skill bonuses
4913 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
4915 // temporary bonuses
4916 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
4917 for(AuraList::const_iterator i = mModSkill.begin(); i != mModSkill.end(); ++i)
4918 if ((*i)->GetModifier()->m_miscvalue == int32(id))
4919 (*i)->ApplyModifier(true);
4921 // permanent bonuses
4922 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
4923 for(AuraList::const_iterator i = mModSkillTalent.begin(); i != mModSkillTalent.end(); ++i)
4924 if ((*i)->GetModifier()->m_miscvalue == int32(id))
4925 (*i)->ApplyModifier(true);
4927 // Learn all spells for skill
4928 learnSkillRewardedSpells(id);
4929 return;
4934 bool Player::HasSkill(uint32 skill) const
4936 if(!skill)return false;
4937 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4939 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
4941 return true;
4944 return false;
4947 uint16 Player::GetSkillValue(uint32 skill) const
4949 if(!skill)
4950 return 0;
4952 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4954 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
4956 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
4958 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
4959 result += SKILL_TEMP_BONUS(bonus);
4960 result += SKILL_PERM_BONUS(bonus);
4961 return result < 0 ? 0 : result;
4964 return 0;
4967 uint16 Player::GetMaxSkillValue(uint32 skill) const
4969 if(!skill)return 0;
4970 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4972 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
4974 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
4976 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
4977 result += SKILL_TEMP_BONUS(bonus);
4978 result += SKILL_PERM_BONUS(bonus);
4979 return result < 0 ? 0 : result;
4982 return 0;
4985 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
4987 if(!skill)return 0;
4988 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4990 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
4992 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
4995 return 0;
4998 uint16 Player::GetBaseSkillValue(uint32 skill) const
5000 if(!skill)return 0;
5001 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5003 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5005 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5006 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5007 return result < 0 ? 0 : result;
5010 return 0;
5013 uint16 Player::GetPureSkillValue(uint32 skill) const
5015 if(!skill)return 0;
5016 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5018 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5020 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5023 return 0;
5026 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5028 if(!skill)
5029 return 0;
5031 for (int i = 0; i < PLAYER_MAX_SKILLS; i++)
5033 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5035 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5039 return 0;
5042 void Player::SendInitialActionButtons()
5044 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5046 WorldPacket data(SMSG_ACTION_BUTTONS, (MAX_ACTION_BUTTONS*4));
5047 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5049 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5050 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5052 data << uint16(itr->second.action);
5053 data << uint8(itr->second.misc);
5054 data << uint8(itr->second.type);
5056 else
5058 data << uint32(0);
5062 GetSession()->SendPacket( &data );
5063 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5066 void Player::addActionButton(const uint8 button, const uint16 action, const uint8 type, const uint8 misc)
5068 if(button >= MAX_ACTION_BUTTONS)
5070 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5071 return;
5074 // check cheating with adding non-known spells to action bar
5075 if(type==ACTION_BUTTON_SPELL)
5077 if(!sSpellStore.LookupEntry(action))
5079 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5080 return;
5083 if(!HasSpell(action))
5085 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5086 return;
5090 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5092 if (buttonItr==m_actionButtons.end())
5093 { // just add new button
5094 m_actionButtons[button] = ActionButton(action,type,misc);
5096 else
5097 { // change state of current button
5098 ActionButtonUpdateState uState = buttonItr->second.uState;
5099 buttonItr->second = ActionButton(action,type,misc);
5100 if (uState != ACTIONBUTTON_NEW) buttonItr->second.uState = ACTIONBUTTON_CHANGED;
5103 sLog.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action, button );
5106 void Player::removeActionButton(uint8 button)
5108 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5109 if (buttonItr==m_actionButtons.end())
5110 return;
5112 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5113 m_actionButtons.erase(buttonItr); // new and not saved
5114 else
5115 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5117 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5120 void Player::SetDontMove(bool dontMove)
5122 m_dontMove = dontMove;
5125 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5127 // prevent crash when a bad coord is sent by the client
5128 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5130 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5131 return false;
5134 Map *m = MapManager::Instance().GetMap(GetMapId(), this);
5136 const float old_x = GetPositionX();
5137 const float old_y = GetPositionY();
5138 const float old_z = GetPositionZ();
5139 const float old_r = GetOrientation();
5141 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5143 if (teleport || old_x != x || old_y != y || old_z != z)
5144 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5145 else
5146 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5148 // move and update visible state if need
5149 m->PlayerRelocation(this, x, y, z, orientation);
5151 // reread after Map::Relocation
5152 m = MapManager::Instance().GetMap(GetMapId(), this);
5153 x = GetPositionX();
5154 y = GetPositionY();
5155 z = GetPositionZ();
5158 // code block for underwater state update
5159 UpdateUnderwaterState(m, x, y, z);
5161 CheckExploreSystem();
5163 // group update
5164 if(GetGroup())
5165 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5167 return true;
5170 void Player::SaveRecallPosition()
5172 m_recallMap = GetMapId();
5173 m_recallX = GetPositionX();
5174 m_recallY = GetPositionY();
5175 m_recallZ = GetPositionZ();
5176 m_recallO = GetOrientation();
5179 void Player::SendMessageToSet(WorldPacket *data, bool self)
5181 MapManager::Instance().GetMap(GetMapId(), this)->MessageBroadcast(this, data, self);
5184 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5186 MapManager::Instance().GetMap(GetMapId(), this)->MessageDistBroadcast(this, data, dist, self);
5189 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5191 MapManager::Instance().GetMap(GetMapId(), this)->MessageDistBroadcast(this, data, dist, self,own_team_only);
5194 void Player::SendDirectMessage(WorldPacket *data)
5196 GetSession()->SendPacket(data);
5199 void Player::CheckExploreSystem()
5201 if (!isAlive())
5202 return;
5204 if (isInFlight())
5205 return;
5207 uint16 areaFlag=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY());
5208 if(areaFlag==0xffff)
5209 return;
5210 int offset = areaFlag / 32;
5212 if(offset >= 128)
5214 sLog.outError("ERROR: Wrong area flag %u in map data for (X: %f Y: %f) point to field PLAYER_EXPLORED_ZONES_1 + %u ( %u must be < 64 ).",areaFlag,GetPositionX(),GetPositionY(),offset,offset);
5215 return;
5218 uint32 val = (uint32)(1 << (areaFlag % 32));
5219 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5221 if( !(currFields & val) )
5223 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5225 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5226 if(!p)
5228 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5230 else if(p->area_level > 0)
5232 uint32 area = p->ID;
5233 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5235 SendExplorationExperience(area,0);
5237 else
5239 int32 diff = int32(getLevel()) - p->area_level;
5240 uint32 XP = 0;
5241 if (diff < -5)
5243 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5245 else if (diff > 5)
5247 int32 exploration_percent = (100-((diff-5)*5));
5248 if (exploration_percent > 100)
5249 exploration_percent = 100;
5250 else if (exploration_percent < 0)
5251 exploration_percent = 0;
5253 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5255 else
5257 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5260 GiveXP( XP, NULL );
5261 SendExplorationExperience(area,XP);
5263 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5268 uint32 Player::TeamForRace(uint8 race)
5270 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5271 if(!rEntry)
5273 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5274 return ALLIANCE;
5277 switch(rEntry->TeamID)
5279 case 7: return ALLIANCE;
5280 case 1: return HORDE;
5283 sLog.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5284 return ALLIANCE;
5287 uint32 Player::getFactionForRace(uint8 race)
5289 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5290 if(!rEntry)
5292 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5293 return 0;
5296 return rEntry->FactionID;
5299 void Player::setFactionForRace(uint8 race)
5301 m_team = TeamForRace(race);
5302 setFaction( getFactionForRace(race) );
5305 void Player::UpdateReputation() const
5307 sLog.outDetail( "WORLD: Player::UpdateReputation" );
5309 for(FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
5311 SendFactionState(&(itr->second));
5315 void Player::SendFactionState(FactionState const* faction) const
5317 if(faction->Flags & FACTION_FLAG_VISIBLE) //If faction is visible then update it
5319 WorldPacket data(SMSG_SET_FACTION_STANDING, (16)); // last check 2.4.0
5320 data << (float) 0; // unk 2.4.0
5321 data << (uint32) 1; // count
5322 // for
5323 data << (uint32) faction->ReputationListID;
5324 data << (uint32) faction->Standing;
5325 // end for
5326 GetSession()->SendPacket(&data);
5330 void Player::SendInitialReputations()
5332 WorldPacket data(SMSG_INITIALIZE_FACTIONS, (4+128*5));
5333 data << uint32 (0x00000080);
5335 RepListID a = 0;
5337 for (FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); itr++)
5339 // fill in absent fields
5340 for (; a != itr->first; a++)
5342 data << uint8 (0x00);
5343 data << uint32 (0x00000000);
5346 // fill in encountered data
5347 data << uint8 (itr->second.Flags);
5348 data << uint32 (itr->second.Standing);
5350 ++a;
5353 // fill in absent fields
5354 for (; a != 128; a++)
5356 data << uint8 (0x00);
5357 data << uint32 (0x00000000);
5360 GetSession()->SendPacket(&data);
5363 FactionState const* Player::GetFactionState( FactionEntry const* factionEntry) const
5365 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5366 if (itr != m_factions.end())
5367 return &itr->second;
5369 return NULL;
5372 void Player::SetFactionAtWar(FactionState* faction, bool atWar)
5374 // not allow declare war to own faction
5375 if(atWar && (faction->Flags & FACTION_FLAG_PEACE_FORCED) )
5376 return;
5378 // already set
5379 if(((faction->Flags & FACTION_FLAG_AT_WAR) != 0) == atWar)
5380 return;
5382 if( atWar )
5383 faction->Flags |= FACTION_FLAG_AT_WAR;
5384 else
5385 faction->Flags &= ~FACTION_FLAG_AT_WAR;
5387 faction->Changed = true;
5390 void Player::SetFactionInactive(FactionState* faction, bool inactive)
5392 // always invisible or hidden faction can't be inactive
5393 if(inactive && ((faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN)) || !(faction->Flags & FACTION_FLAG_VISIBLE) ) )
5394 return;
5396 // already set
5397 if(((faction->Flags & FACTION_FLAG_INACTIVE) != 0) == inactive)
5398 return;
5400 if(inactive)
5401 faction->Flags |= FACTION_FLAG_INACTIVE;
5402 else
5403 faction->Flags &= ~FACTION_FLAG_INACTIVE;
5405 faction->Changed = true;
5408 void Player::SetFactionVisibleForFactionTemplateId(uint32 FactionTemplateId)
5410 FactionTemplateEntry const*factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5412 if(!factionTemplateEntry)
5413 return;
5415 SetFactionVisibleForFactionId(factionTemplateEntry->faction);
5418 void Player::SetFactionVisibleForFactionId(uint32 FactionId)
5420 FactionEntry const *factionEntry = sFactionStore.LookupEntry(FactionId);
5421 if(!factionEntry)
5422 return;
5424 if(factionEntry->reputationListID < 0)
5425 return;
5427 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5428 if (itr == m_factions.end())
5429 return;
5431 SetFactionVisible(&itr->second);
5434 void Player::SetFactionVisible(FactionState* faction)
5436 // always invisible or hidden faction can't be make visible
5437 if(faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN))
5438 return;
5440 // already set
5441 if(faction->Flags & FACTION_FLAG_VISIBLE)
5442 return;
5444 faction->Flags |= FACTION_FLAG_VISIBLE;
5445 faction->Changed = true;
5447 if(!m_session->PlayerLoading())
5449 // make faction visible in reputation list at client
5450 WorldPacket data(SMSG_SET_FACTION_VISIBLE, 4);
5451 data << faction->ReputationListID;
5452 GetSession()->SendPacket(&data);
5456 void Player::SetInitialFactions()
5458 for(unsigned int i = 1; i < sFactionStore.GetNumRows(); i++)
5460 FactionEntry const *factionEntry = sFactionStore.LookupEntry(i);
5462 if( factionEntry && (factionEntry->reputationListID >= 0))
5464 FactionState newFaction;
5465 newFaction.ID = factionEntry->ID;
5466 newFaction.ReputationListID = factionEntry->reputationListID;
5467 newFaction.Standing = 0;
5468 newFaction.Flags = GetDefaultReputationFlags(factionEntry);
5469 newFaction.Changed = true;
5471 m_factions[newFaction.ReputationListID] = newFaction;
5476 uint32 Player::GetDefaultReputationFlags(const FactionEntry *factionEntry) const
5478 if (!factionEntry)
5479 return 0;
5481 uint32 raceMask = getRaceMask();
5482 uint32 classMask = getClassMask();
5483 for (int i=0; i < 4; i++)
5485 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5486 (factionEntry->BaseRepClassMask[i]==0 ||
5487 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5488 return factionEntry->ReputationFlags[i];
5490 return 0;
5493 int32 Player::GetBaseReputation(const FactionEntry *factionEntry) const
5495 if (!factionEntry)
5496 return 0;
5498 uint32 raceMask = getRaceMask();
5499 uint32 classMask = getClassMask();
5500 for (int i=0; i < 4; i++)
5502 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5503 (factionEntry->BaseRepClassMask[i]==0 ||
5504 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5505 return factionEntry->BaseRepValue[i];
5508 // in faction.dbc exist factions with (RepListId >=0, listed in character reputation list) with all BaseRepRaceMask[i]==0
5509 return 0;
5512 int32 Player::GetReputation(uint32 faction_id) const
5514 FactionEntry const *factionEntry = sFactionStore.LookupEntry(faction_id);
5516 if (!factionEntry)
5518 sLog.outError("Player::GetReputation: Can't get reputation of %s for unknown faction (faction template id) #%u.",GetName(), faction_id);
5519 return 0;
5522 return GetReputation(factionEntry);
5525 int32 Player::GetReputation(const FactionEntry *factionEntry) const
5527 // Faction without recorded reputation. Just ignore.
5528 if(!factionEntry)
5529 return 0;
5531 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5532 if (itr != m_factions.end())
5533 return GetBaseReputation(factionEntry) + itr->second.Standing;
5535 return 0;
5538 ReputationRank Player::GetReputationRank(uint32 faction) const
5540 FactionEntry const*factionEntry = sFactionStore.LookupEntry(faction);
5541 if(!factionEntry)
5542 return MIN_REPUTATION_RANK;
5544 return GetReputationRank(factionEntry);
5547 ReputationRank Player::ReputationToRank(int32 standing) const
5549 int32 Limit = Reputation_Cap + 1;
5550 for (int i = MAX_REPUTATION_RANK-1; i >= MIN_REPUTATION_RANK; --i)
5552 Limit -= ReputationRank_Length[i];
5553 if (standing >= Limit )
5554 return ReputationRank(i);
5556 return MIN_REPUTATION_RANK;
5559 ReputationRank Player::GetReputationRank(const FactionEntry *factionEntry) const
5561 int32 Reputation = GetReputation(factionEntry);
5562 return ReputationToRank(Reputation);
5565 ReputationRank Player::GetBaseReputationRank(const FactionEntry *factionEntry) const
5567 int32 Reputation = GetBaseReputation(factionEntry);
5568 return ReputationToRank(Reputation);
5571 bool Player::ModifyFactionReputation(uint32 FactionTemplateId, int32 DeltaReputation)
5573 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5575 if(!factionTemplateEntry)
5577 sLog.outError("Player::ModifyFactionReputation: Can't update reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5578 return false;
5581 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5583 // Faction without recorded reputation. Just ignore.
5584 if(!factionEntry)
5585 return false;
5587 return ModifyFactionReputation(factionEntry, DeltaReputation);
5590 bool Player::ModifyFactionReputation(FactionEntry const* factionEntry, int32 standing)
5592 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5593 if (flist)
5595 bool res = false;
5596 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5598 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5599 if(factionEntryCalc)
5600 res = ModifyOneFactionReputation(factionEntryCalc, standing);
5602 return res;
5604 else
5605 return ModifyOneFactionReputation(factionEntry, standing);
5608 bool Player::ModifyOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5610 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5611 if (itr != m_factions.end())
5613 int32 BaseRep = GetBaseReputation(factionEntry);
5614 int32 new_rep = BaseRep + itr->second.Standing + standing;
5616 if (new_rep > Reputation_Cap)
5617 new_rep = Reputation_Cap;
5618 else
5619 if (new_rep < Reputation_Bottom)
5620 new_rep = Reputation_Bottom;
5622 if(ReputationToRank(new_rep) <= REP_HOSTILE)
5623 SetFactionAtWar(&itr->second,true);
5625 itr->second.Standing = new_rep - BaseRep;
5626 itr->second.Changed = true;
5628 SetFactionVisible(&itr->second);
5630 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
5632 if(uint32 questid = GetQuestSlotQuestId(i))
5634 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
5635 if( qInfo && qInfo->GetRepObjectiveFaction() == factionEntry->ID )
5637 QuestStatusData& q_status = mQuestStatus[questid];
5638 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
5640 if(GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
5641 if ( CanCompleteQuest( questid ) )
5642 CompleteQuest( questid );
5644 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
5646 if(GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
5647 IncompleteQuest( questid );
5653 SendFactionState(&(itr->second));
5655 return true;
5657 return false;
5660 bool Player::SetFactionReputation(uint32 FactionTemplateId, int32 standing)
5662 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5664 if(!factionTemplateEntry)
5666 sLog.outError("Player::SetFactionReputation: Can't set reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5667 return false;
5670 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5672 // Faction without recorded reputation. Just ignore.
5673 if(!factionEntry)
5674 return false;
5676 return SetFactionReputation(factionEntry, standing);
5679 bool Player::SetFactionReputation(FactionEntry const* factionEntry, int32 standing)
5681 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5682 if (flist)
5684 bool res = false;
5685 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5687 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5688 if(factionEntryCalc)
5689 res = SetOneFactionReputation(factionEntryCalc, standing);
5691 return res;
5693 else
5694 return SetOneFactionReputation(factionEntry, standing);
5697 bool Player::SetOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5699 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5700 if (itr != m_factions.end())
5702 if (standing > Reputation_Cap)
5703 standing = Reputation_Cap;
5704 else
5705 if (standing < Reputation_Bottom)
5706 standing = Reputation_Bottom;
5708 int32 BaseRep = GetBaseReputation(factionEntry);
5709 itr->second.Standing = standing - BaseRep;
5710 itr->second.Changed = true;
5712 SetFactionVisible(&itr->second);
5714 if(ReputationToRank(standing) <= REP_HOSTILE)
5715 SetFactionAtWar(&itr->second,true);
5717 SendFactionState(&(itr->second));
5718 return true;
5720 return false;
5723 //Calculate total reputation percent player gain with quest/creature level
5724 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, bool for_quest)
5726 // for grey creature kill received 20%, in other case 100.
5727 int32 percent = (!for_quest && (creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))) ? 20 : 100;
5729 int32 repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5731 percent += rep > 0 ? repMod : -repMod;
5733 if(percent <=0)
5734 return 0;
5736 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100);
5739 //Calculates how many reputation points player gains in victim's enemy factions
5740 void Player::RewardReputation(Unit *pVictim, float rate)
5742 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5743 return;
5745 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5747 if(!Rep)
5748 return;
5750 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5752 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue1,false);
5753 donerep1 = int32(donerep1*rate);
5754 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5755 uint32 current_reputation_rank1 = GetReputationRank(factionEntry1);
5756 if(factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5757 ModifyFactionReputation(factionEntry1, donerep1);
5759 // Wiki: Team factions value divided by 2
5760 if(Rep->is_teamaward1)
5762 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5763 if(team1_factionEntry)
5764 ModifyFactionReputation(team1_factionEntry, donerep1 / 2);
5768 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5770 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue2,false);
5771 donerep2 = int32(donerep2*rate);
5772 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5773 uint32 current_reputation_rank2 = GetReputationRank(factionEntry2);
5774 if(factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5775 ModifyFactionReputation(factionEntry2, donerep2);
5777 // Wiki: Team factions value divided by 2
5778 if(Rep->is_teamaward2)
5780 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5781 if(team2_factionEntry)
5782 ModifyFactionReputation(team2_factionEntry, donerep2 / 2);
5787 //Calculate how many reputation points player gain with the quest
5788 void Player::RewardReputation(Quest const *pQuest)
5790 // quest reputation reward/loss
5791 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5793 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5795 int32 rep = CalculateReputationGain(pQuest->GetQuestLevel(),pQuest->RewRepValue[i],true);
5796 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
5797 if(factionEntry)
5798 ModifyFactionReputation(factionEntry, rep);
5802 // TODO: implement reputation spillover
5805 void Player::UpdateArenaFields(void)
5807 /* arena calcs go here */
5810 void Player::UpdateHonorFields()
5812 /// called when rewarding honor and at each save
5813 uint64 now = time(NULL);
5814 uint64 today = uint64(time(NULL) / DAY) * DAY;
5816 if(m_lastHonorUpdateTime < today)
5818 uint64 yesterday = today - DAY;
5820 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
5822 // update yesterday's contribution
5823 if(m_lastHonorUpdateTime >= yesterday )
5825 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
5827 // this is the first update today, reset today's contribution
5828 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
5829 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
5831 else
5833 // no honor/kills yesterday or today, reset
5834 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
5835 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
5839 m_lastHonorUpdateTime = now;
5842 ///Calculate the amount of honor gained based on the victim
5843 ///and the size of the group for which the honor is divided
5844 ///An exact honor value can also be given (overriding the calcs)
5845 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
5847 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5848 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
5849 return false;
5851 uint64 victim_guid = 0;
5852 uint32 victim_rank = 0;
5853 time_t now = time(NULL);
5855 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5856 UpdateHonorFields();
5858 if(honor <= 0)
5860 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
5861 return false;
5863 victim_guid = uVictim->GetGUID();
5865 if( uVictim->GetTypeId() == TYPEID_PLAYER )
5867 Player *pVictim = (Player *)uVictim;
5869 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
5870 return false;
5872 float f = 1; //need for total kills (?? need more info)
5873 uint32 k_grey = 0;
5874 uint32 k_level = getLevel();
5875 uint32 v_level = pVictim->getLevel();
5878 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
5879 // [0] Just name
5880 // [1..14] Alliance honor titles and player name
5881 // [15..28] Horde honor titles and player name
5882 // [29..38] Other title and player name
5883 // [39+] Nothing
5884 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
5885 // Get Killer titles, CharTitlesEntry::bit_index
5886 // Ranks:
5887 // title[1..14] -> rank[5..18]
5888 // title[15..28] -> rank[5..18]
5889 // title[other] -> 0
5890 if (victim_title == 0)
5891 victim_guid = 0; // Don't show HK: <rank> message, only log.
5892 else if (victim_title < 15)
5893 victim_rank = victim_title + 4;
5894 else if (victim_title < 29)
5895 victim_rank = victim_title - 14 + 4;
5896 else
5897 victim_guid = 0; // Don't show HK: <rank> message, only log.
5900 if(k_level <= 5)
5901 k_grey = 0;
5902 else if( k_level <= 39 )
5903 k_grey = k_level - 5 - k_level/10;
5904 else
5905 k_grey = k_level - 1 - k_level/5;
5907 if(v_level<=k_grey)
5908 return false;
5910 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
5912 int32 v_rank =1; //need more info
5914 honor = ((f * diff_level * (190 + v_rank*10))/6);
5915 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
5917 // count the number of playerkills in one day
5918 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
5919 // and those in a lifetime
5920 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
5922 else
5924 Creature *cVictim = (Creature *)uVictim;
5926 if (!cVictim->isRacialLeader())
5927 return false;
5929 honor = 100; // ??? need more info
5930 victim_rank = 19; // HK: Leader
5934 if (uVictim != NULL)
5936 honor *= sWorld.getRate(RATE_HONOR);
5938 if(groupsize > 1)
5939 honor /= groupsize;
5941 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
5944 // honor - for show honor points in log
5945 // victim_guid - for show victim name in log
5946 // victim_rank [1..4] HK: <dishonored rank>
5947 // victim_rank [5..19] HK: <alliance\horde rank>
5948 // victim_rank [0,20+] HK: <>
5949 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
5950 data << (uint32) honor;
5951 data << (uint64) victim_guid;
5952 data << (uint32) victim_rank;
5954 GetSession()->SendPacket(&data);
5956 // add honor points
5957 ModifyHonorPoints(int32(honor));
5959 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
5960 return true;
5963 void Player::ModifyHonorPoints( int32 value )
5965 if(value < 0)
5967 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
5968 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
5969 else
5970 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
5972 else
5973 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
5976 void Player::ModifyArenaPoints( int32 value )
5978 if(value < 0)
5980 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
5981 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
5982 else
5983 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
5985 else
5986 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
5989 uint32 Player::GetGuildIdFromDB(uint64 guid)
5991 std::ostringstream ss;
5992 ss<<"SELECT guildid FROM guild_member WHERE guid='"<<guid<<"'";
5993 QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
5994 if( result )
5996 uint32 v = result->Fetch()[0].GetUInt32();
5997 delete result;
5998 return v;
6000 else
6001 return 0;
6004 uint32 Player::GetRankFromDB(uint64 guid)
6006 std::ostringstream ss;
6007 ss<<"SELECT rank FROM guild_member WHERE guid='"<<guid<<"'";
6008 QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
6009 if( result )
6011 uint32 v = result->Fetch()[0].GetUInt32();
6012 delete result;
6013 return v;
6015 else
6016 return 0;
6019 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6021 // need fix it!
6022 QueryResult *result = CharacterDatabase.PQuery("SELECT arenateamid FROM arena_team_member WHERE guid='%u'", GUID_LOPART(guid));
6023 if(result)
6025 // init id to 0, check the arena type before assigning a value to id
6026 uint32 id = 0;
6029 QueryResult *result2 = CharacterDatabase.PQuery("SELECT type FROM arena_team WHERE arenateamid='%u'", id);
6030 if(result2)
6032 uint8 dbtype = (*result2)[0].GetUInt32();
6033 delete result2;
6034 if(dbtype == type)
6036 // if the type matches, we've found the id
6037 id = (*result)[0].GetUInt32();
6038 break;
6041 } while(result->NextRow());
6042 delete result;
6043 return id;
6045 // no arenateam for the specified guid, return 0
6046 return 0;
6049 uint32 Player::GetZoneIdFromDB(uint64 guid)
6051 std::ostringstream ss;
6053 ss<<"SELECT zone FROM characters WHERE guid='"<<GUID_LOPART(guid)<<"'";
6054 QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
6055 if (!result)
6056 return 0;
6057 Field* fields = result->Fetch();
6058 uint32 zone = fields[0].GetUInt32();
6059 delete result;
6061 if (!zone)
6063 // stored zone is zero, use generic and slow zone detection
6064 ss.str("");
6065 ss<<"SELECT map,position_x,position_y FROM characters WHERE guid='"<<GUID_LOPART(guid)<<"'";
6066 result = CharacterDatabase.Query(ss.str().c_str());
6067 if( !result )
6068 return 0;
6069 fields = result->Fetch();
6070 uint32 map = fields[0].GetUInt32();
6071 float posx = fields[1].GetFloat();
6072 float posy = fields[2].GetFloat();
6073 delete result;
6075 zone = MapManager::Instance().GetZoneId(map,posx,posy);
6077 ss.str("");
6078 ss << "UPDATE characters SET zone='"<<zone<<"' WHERE guid='"<<GUID_LOPART(guid)<<"'";
6079 CharacterDatabase.Execute(ss.str().c_str());
6082 return zone;
6085 void Player::UpdateArea(uint32 newArea)
6087 // FFA_PVP flags are area and not zone id dependent
6088 // so apply them accordingly
6089 m_areaUpdateId = newArea;
6091 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6093 if(area && (area->flags & AREA_FLAG_ARENA))
6095 if(!isGameMaster())
6096 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
6098 else
6100 // remove ffa flag only if not ffapvp realm
6101 // removal in sanctuaries and capitals is handled in zone update
6102 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6103 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
6106 UpdateAreaDependentAuras(newArea);
6109 void Player::UpdateZone(uint32 newZone)
6111 m_zoneUpdateId = newZone;
6112 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6114 // zone changed, so area changed as well, update it
6115 UpdateArea(GetAreaId());
6117 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6118 if(!zone)
6119 return;
6121 if (sWorld.getConfig(CONFIG_WEATHER))
6123 Weather *wth = sWorld.FindWeather(zone->ID);
6124 if(wth)
6126 wth->SendWeatherUpdateToPlayer(this);
6128 else
6130 if(!sWorld.AddWeather(zone->ID))
6132 // send fine weather packet to remove old zone's weather
6133 Weather::SendFineWeatherUpdateToPlayer(this);
6138 pvpInfo.inHostileArea =
6139 GetTeam() == ALLIANCE && zone->team == AREATEAM_HORDE ||
6140 GetTeam() == HORDE && zone->team == AREATEAM_ALLY ||
6141 sWorld.IsPvPRealm() && zone->team == AREATEAM_NONE ||
6142 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6144 if(pvpInfo.inHostileArea) // in hostile area
6146 if(!IsPvP() || pvpInfo.endTimer != 0)
6147 UpdatePvP(true, true);
6149 else // in friendly area
6151 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6152 pvpInfo.endTimer = time(0); // start toggle-off
6155 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6157 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_SANCTUARY);
6158 if(sWorld.IsFFAPvPRealm())
6159 RemoveFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6161 else
6163 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_SANCTUARY);
6166 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6168 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6169 SetRestType(REST_TYPE_IN_CITY);
6170 InnEnter(time(0),GetMapId(),0,0,0);
6172 if(sWorld.IsFFAPvPRealm())
6173 RemoveFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6175 else // anywhere else
6177 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6179 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6181 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6183 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6184 SetRestType(REST_TYPE_NO);
6186 if(sWorld.IsFFAPvPRealm())
6187 SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6190 else // not in tavern (leave city then)
6192 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6193 SetRestType(REST_TYPE_NO);
6195 // Set player to FFA PVP when not in rested enviroment.
6196 if(sWorld.IsFFAPvPRealm())
6197 SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6202 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6203 // if player resurrected at teleport this will be applied in resurrect code
6204 if(isAlive())
6205 DestroyZoneLimitedItem( true, newZone );
6207 // recent client version not send leave/join channel packets for built-in local channels
6208 UpdateLocalChannels( newZone );
6210 // group update
6211 if(GetGroup())
6212 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6214 UpdateZoneDependentAuras(newZone);
6217 //If players are too far way of duel flag... then player loose the duel
6218 void Player::CheckDuelDistance(time_t currTime)
6220 if(!duel)
6221 return;
6223 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6224 GameObject* obj = ObjectAccessor::GetGameObject(*this, duelFlagGUID);
6225 if(!obj)
6226 return;
6228 if(duel->outOfBound == 0)
6230 if(!IsWithinDistInMap(obj, 50))
6232 duel->outOfBound = currTime;
6234 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6235 GetSession()->SendPacket(&data);
6238 else
6240 if(IsWithinDistInMap(obj, 40))
6242 duel->outOfBound = 0;
6244 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6245 GetSession()->SendPacket(&data);
6247 else if(currTime >= (duel->outOfBound+10))
6249 DuelComplete(DUEL_FLED);
6254 void Player::DuelComplete(DuelCompleteType type)
6256 // duel not requested
6257 if(!duel)
6258 return;
6260 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6261 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6262 GetSession()->SendPacket(&data);
6263 duel->opponent->GetSession()->SendPacket(&data);
6265 if(type != DUEL_INTERUPTED)
6267 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6268 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6269 data << duel->opponent->GetName();
6270 data << GetName();
6271 SendMessageToSet(&data,true);
6274 // cool-down duel spell
6275 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6277 data<<GetGUID();
6278 data<<uint8(0x0);
6280 data<<(uint32)7266;
6281 data<<uint32(0x0);
6282 GetSession()->SendPacket(&data);
6283 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6284 data<<duel->opponent->GetGUID();
6285 data<<uint8(0x0);
6286 data<<(uint32)7266;
6287 data<<uint32(0x0);
6288 duel->opponent->GetSession()->SendPacket(&data);*/
6290 //Remove Duel Flag object
6291 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
6292 if(obj)
6293 duel->initiator->RemoveGameObject(obj,true);
6295 /* remove auras */
6296 std::vector<uint32> auras2remove;
6297 AuraMap const& vAuras = duel->opponent->GetAuras();
6298 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); i++)
6300 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6301 auras2remove.push_back(i->second->GetId());
6304 for(size_t i=0; i<auras2remove.size(); i++)
6305 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6307 auras2remove.clear();
6308 AuraMap const& auras = GetAuras();
6309 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); i++)
6311 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6312 auras2remove.push_back(i->second->GetId());
6314 for(size_t i=0; i<auras2remove.size(); i++)
6315 RemoveAurasDueToSpell(auras2remove[i]);
6317 // cleanup combo points
6318 if(GetComboTarget()==duel->opponent->GetGUID())
6319 ClearComboPoints();
6320 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6321 ClearComboPoints();
6323 if(duel->opponent->GetComboTarget()==GetGUID())
6324 duel->opponent->ClearComboPoints();
6325 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6326 duel->opponent->ClearComboPoints();
6328 //cleanups
6329 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6330 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6331 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6332 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6334 delete duel->opponent->duel;
6335 duel->opponent->duel = NULL;
6336 delete duel;
6337 duel = NULL;
6340 //---------------------------------------------------------//
6342 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6344 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6345 return;
6347 // not apply/remove mods for broken item
6348 if(item->IsBroken())
6349 return;
6351 ItemPrototype const *proto = item->GetProto();
6353 if(!proto)
6354 return;
6356 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6358 uint32 attacktype = Player::GetAttackBySlot(slot);
6359 if(attacktype < MAX_ATTACK)
6360 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6362 _ApplyItemBonuses(proto,slot,apply);
6364 if( slot==EQUIPMENT_SLOT_RANGED )
6365 _ApplyAmmoBonuses();
6367 ApplyItemEquipSpell(item,apply);
6368 ApplyEnchantment(item, apply);
6370 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6371 CorrectMetaGemEnchants(slot, apply);
6373 sLog.outDebug("_ApplyItemMods complete.");
6376 void Player::_ApplyItemBonuses(ItemPrototype const *proto,uint8 slot,bool apply)
6378 if(slot >= INVENTORY_SLOT_BAG_END || !proto)
6379 return;
6381 for (int i = 0; i < 10; i++)
6383 float val = float (proto->ItemStat[i].ItemStatValue);
6385 if(val==0)
6386 continue;
6388 switch (proto->ItemStat[i].ItemStatType)
6390 case ITEM_MOD_MANA:
6391 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6392 break;
6393 case ITEM_MOD_HEALTH: // modify HP
6394 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6395 break;
6396 case ITEM_MOD_AGILITY: // modify agility
6397 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6398 ApplyStatBuffMod(STAT_AGILITY, val, apply);
6399 break;
6400 case ITEM_MOD_STRENGTH: //modify strength
6401 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6402 ApplyStatBuffMod(STAT_STRENGTH, val, apply);
6403 break;
6404 case ITEM_MOD_INTELLECT: //modify intellect
6405 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6406 ApplyStatBuffMod(STAT_INTELLECT, val, apply);
6407 break;
6408 case ITEM_MOD_SPIRIT: //modify spirit
6409 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6410 ApplyStatBuffMod(STAT_SPIRIT, val, apply);
6411 break;
6412 case ITEM_MOD_STAMINA: //modify stamina
6413 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6414 ApplyStatBuffMod(STAT_STAMINA, val, apply);
6415 break;
6416 case ITEM_MOD_DEFENSE_SKILL_RATING:
6417 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6418 break;
6419 case ITEM_MOD_DODGE_RATING:
6420 ApplyRatingMod(CR_DODGE, int32(val), apply);
6421 break;
6422 case ITEM_MOD_PARRY_RATING:
6423 ApplyRatingMod(CR_PARRY, int32(val), apply);
6424 break;
6425 case ITEM_MOD_BLOCK_RATING:
6426 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6427 break;
6428 case ITEM_MOD_HIT_MELEE_RATING:
6429 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6430 break;
6431 case ITEM_MOD_HIT_RANGED_RATING:
6432 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6433 break;
6434 case ITEM_MOD_HIT_SPELL_RATING:
6435 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6436 break;
6437 case ITEM_MOD_CRIT_MELEE_RATING:
6438 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6439 break;
6440 case ITEM_MOD_CRIT_RANGED_RATING:
6441 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6442 break;
6443 case ITEM_MOD_CRIT_SPELL_RATING:
6444 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6445 break;
6446 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6447 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6448 break;
6449 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6450 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6451 break;
6452 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6453 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6454 break;
6455 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6456 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6457 break;
6458 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6459 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6460 break;
6461 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6462 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6463 break;
6464 case ITEM_MOD_HASTE_MELEE_RATING:
6465 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6466 break;
6467 case ITEM_MOD_HASTE_RANGED_RATING:
6468 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6469 break;
6470 case ITEM_MOD_HASTE_SPELL_RATING:
6471 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6472 break;
6473 case ITEM_MOD_HIT_RATING:
6474 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6475 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6476 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6477 break;
6478 case ITEM_MOD_CRIT_RATING:
6479 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6480 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6481 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6482 break;
6483 case ITEM_MOD_HIT_TAKEN_RATING:
6484 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6485 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6486 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6487 break;
6488 case ITEM_MOD_CRIT_TAKEN_RATING:
6489 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6490 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6491 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6492 break;
6493 case ITEM_MOD_RESILIENCE_RATING:
6494 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6495 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6496 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6497 break;
6498 case ITEM_MOD_HASTE_RATING:
6499 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6500 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6501 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6502 break;
6503 case ITEM_MOD_EXPERTISE_RATING:
6504 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6505 break;
6509 if (proto->Armor)
6510 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(proto->Armor), apply);
6512 if (proto->Block)
6513 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6515 if (proto->HolyRes)
6516 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6518 if (proto->FireRes)
6519 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6521 if (proto->NatureRes)
6522 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6524 if (proto->FrostRes)
6525 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6527 if (proto->ShadowRes)
6528 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6530 if (proto->ArcaneRes)
6531 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6533 WeaponAttackType attType = BASE_ATTACK;
6534 float damage = 0.0f;
6536 if( slot == EQUIPMENT_SLOT_RANGED && (
6537 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6538 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6540 attType = RANGED_ATTACK;
6542 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6544 attType = OFF_ATTACK;
6547 if (proto->Damage[0].DamageMin > 0 )
6549 damage = apply ? proto->Damage[0].DamageMin : BASE_MINDAMAGE;
6550 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6551 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6554 if (proto->Damage[0].DamageMax > 0 )
6556 damage = apply ? proto->Damage[0].DamageMax : BASE_MAXDAMAGE;
6557 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6560 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6561 return;
6563 if (proto->Delay)
6565 if(slot == EQUIPMENT_SLOT_RANGED)
6566 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6567 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6568 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6569 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6570 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6573 if(CanModifyStats() && (damage || proto->Delay))
6574 UpdateDamagePhysical(attType);
6577 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6579 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6580 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6581 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6583 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6584 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6585 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6587 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6588 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6589 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6592 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6594 // generic not weapon specific case processes in aura code
6595 if(aura->GetSpellProto()->EquippedItemClass == -1)
6596 return;
6598 BaseModGroup mod = BASEMOD_END;
6599 switch(attackType)
6601 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6602 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6603 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6604 default: return;
6607 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6609 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6613 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6615 // ignore spell mods for not wands
6616 Modifier const* modifier = aura->GetModifier();
6617 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6618 return;
6620 // generic not weapon specific case processes in aura code
6621 if(aura->GetSpellProto()->EquippedItemClass == -1)
6622 return;
6624 UnitMods unitMod = UNIT_MOD_END;
6625 switch(attackType)
6627 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6628 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6629 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6630 default: return;
6633 UnitModifierType unitModType = TOTAL_VALUE;
6634 switch(modifier->m_auraname)
6636 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6637 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6638 default: return;
6641 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6643 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6647 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6649 if(!item)
6650 return;
6652 ItemPrototype const *proto = item->GetProto();
6653 if(!proto)
6654 return;
6656 for (int i = 0; i < 5; i++)
6658 _Spell const& spellData = proto->Spells[i];
6660 // no spell
6661 if(!spellData.SpellId )
6662 continue;
6664 // wrong triggering type
6665 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6666 continue;
6668 // check if it is valid spell
6669 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6670 if(!spellproto)
6671 continue;
6673 ApplyEquipSpell(spellproto,item,apply,form_change);
6677 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6679 if(apply)
6681 // Cannot be used in this stance/form
6682 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)!=0)
6683 return;
6685 if(form_change) // check aura active state from other form
6687 bool found = false;
6688 for (int k=0; k < 3; ++k)
6690 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6691 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6693 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6695 found = true;
6696 break;
6699 if(found)
6700 break;
6703 if(found) // and skip re-cast already active aura at form change
6704 return;
6707 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6709 CastSpell(this,spellInfo,true,item);
6711 else
6713 if(form_change) // check aura compatibility
6715 // Cannot be used in this stance/form
6716 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==0)
6717 return; // and remove only not compatible at form change
6720 if(item)
6721 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6722 else
6723 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6727 void Player::UpdateEquipSpellsAtFormChange()
6729 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6731 if(m_items[i] && !m_items[i]->IsBroken())
6733 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6734 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6738 // item set bonuses not dependent from item broken state
6739 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6741 ItemSetEffect* eff = ItemSetEff[setindex];
6742 if(!eff)
6743 continue;
6745 for(uint32 y=0;y<8; ++y)
6747 SpellEntry const* spellInfo = eff->spells[y];
6748 if(!spellInfo)
6749 continue;
6751 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
6752 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
6757 void Player::CastItemCombatSpell(Item *item,Unit* Target, WeaponAttackType attType)
6759 if(!item || item->IsBroken())
6760 return;
6762 ItemPrototype const *proto = item->GetProto();
6763 if(!proto)
6764 return;
6766 if (!Target || Target == this )
6767 return;
6769 for (int i = 0; i < 5; i++)
6771 _Spell const& spellData = proto->Spells[i];
6773 // no spell
6774 if(!spellData.SpellId )
6775 continue;
6777 // wrong triggering type
6778 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
6779 continue;
6781 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6782 if(!spellInfo)
6784 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
6785 continue;
6788 // not allow proc extra attack spell at extra attack
6789 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6790 return;
6792 float chance = spellInfo->procChance;
6794 if(spellData.SpellPPMRate)
6796 uint32 WeaponSpeed = GetAttackTime(attType);
6797 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
6799 else if(chance > 100.0f)
6801 chance = GetWeaponProcChance();
6804 if (roll_chance_f(chance))
6805 this->CastSpell(Target, spellInfo->Id, true, item);
6808 // item combat enchantments
6809 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6811 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6812 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6813 if(!pEnchant) continue;
6814 for (int s=0;s<3;s++)
6816 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
6817 continue;
6819 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6820 if (!spellInfo)
6822 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6823 continue;
6826 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
6827 if (roll_chance_f(chance))
6829 if(IsPositiveSpell(pEnchant->spellid[s]))
6830 CastSpell(this, pEnchant->spellid[s], true, item);
6831 else
6832 CastSpell(Target, pEnchant->spellid[s], true, item);
6838 void Player::_RemoveAllItemMods()
6840 sLog.outDebug("_RemoveAllItemMods start.");
6842 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6844 if(m_items[i])
6846 ItemPrototype const *proto = m_items[i]->GetProto();
6847 if(!proto)
6848 continue;
6850 // item set bonuses not dependent from item broken state
6851 if(proto->ItemSet)
6852 RemoveItemsSetItem(this,proto);
6854 if(m_items[i]->IsBroken())
6855 continue;
6857 ApplyItemEquipSpell(m_items[i],false);
6858 ApplyEnchantment(m_items[i], false);
6862 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6864 if(m_items[i])
6866 if(m_items[i]->IsBroken())
6867 continue;
6868 ItemPrototype const *proto = m_items[i]->GetProto();
6869 if(!proto)
6870 continue;
6872 uint32 attacktype = Player::GetAttackBySlot(i);
6873 if(attacktype < MAX_ATTACK)
6874 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
6876 _ApplyItemBonuses(proto,i, false);
6878 if( i == EQUIPMENT_SLOT_RANGED )
6879 _ApplyAmmoBonuses();
6883 sLog.outDebug("_RemoveAllItemMods complete.");
6886 void Player::_ApplyAllItemMods()
6888 sLog.outDebug("_ApplyAllItemMods start.");
6890 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6892 if(m_items[i])
6894 if(m_items[i]->IsBroken())
6895 continue;
6897 ItemPrototype const *proto = m_items[i]->GetProto();
6898 if(!proto)
6899 continue;
6901 uint32 attacktype = Player::GetAttackBySlot(i);
6902 if(attacktype < MAX_ATTACK)
6903 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
6905 _ApplyItemBonuses(proto,i, true);
6907 if( i == EQUIPMENT_SLOT_RANGED )
6908 _ApplyAmmoBonuses();
6912 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6914 if(m_items[i])
6916 ItemPrototype const *proto = m_items[i]->GetProto();
6917 if(!proto)
6918 continue;
6920 // item set bonuses not dependent from item broken state
6921 if(proto->ItemSet)
6922 AddItemsSetItem(this,m_items[i]);
6924 if(m_items[i]->IsBroken())
6925 continue;
6927 ApplyItemEquipSpell(m_items[i],true);
6928 ApplyEnchantment(m_items[i], true);
6932 sLog.outDebug("_ApplyAllItemMods complete.");
6935 void Player::_ApplyAmmoBonuses()
6937 // check ammo
6938 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
6939 if(!ammo_id)
6940 return;
6942 float currentAmmoDPS;
6944 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
6945 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
6946 currentAmmoDPS = 0.0f;
6947 else
6948 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
6950 if(currentAmmoDPS == GetAmmoDPS())
6951 return;
6953 m_ammoDPS = currentAmmoDPS;
6955 if(CanModifyStats())
6956 UpdateDamagePhysical(RANGED_ATTACK);
6959 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
6961 if(!ammo_proto)
6962 return false;
6964 // check ranged weapon
6965 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
6966 if(!weapon || weapon->IsBroken() )
6967 return false;
6969 ItemPrototype const* weapon_proto = weapon->GetProto();
6970 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
6971 return false;
6973 // check ammo ws. weapon compatibility
6974 switch(weapon_proto->SubClass)
6976 case ITEM_SUBCLASS_WEAPON_BOW:
6977 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
6978 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
6979 return false;
6980 break;
6981 case ITEM_SUBCLASS_WEAPON_GUN:
6982 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
6983 return false;
6984 break;
6985 default:
6986 return false;
6989 return true;
6992 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
6993 Called by remove insignia spell effect */
6994 void Player::RemovedInsignia(Player* looterPlr)
6996 if (!GetBattleGroundId())
6997 return;
6999 // If not released spirit, do it !
7000 if(m_deathTimer > 0)
7002 m_deathTimer = 0;
7003 BuildPlayerRepop();
7004 RepopAtGraveyard();
7007 Corpse *corpse = GetCorpse();
7008 if (!corpse)
7009 return;
7011 // We have to convert player corpse to bones, not to be able to resurrect there
7012 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7013 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
7014 if (!bones)
7015 return;
7017 // Now we must make bones lootable, and send player loot
7018 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7020 // We store the level of our player in the gold field
7021 // We retrieve this information at Player::SendLoot()
7022 bones->loot.gold = getLevel();
7023 bones->lootRecipient = looterPlr;
7024 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7027 /*Loot type MUST be
7028 1-corpse, go
7029 2-skinning
7030 3-Fishing
7033 void Player::SendLootRelease( uint64 guid )
7035 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7036 data << uint64(guid) << uint8(1);
7037 SendDirectMessage( &data );
7040 void Player::SendLoot(uint64 guid, LootType loot_type)
7042 Loot *loot = 0;
7043 PermissionTypes permission = ALL_PERMISSION;
7045 sLog.outDebug("Player::SendLoot");
7046 if (IS_GAMEOBJECT_GUID(guid))
7048 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7049 GameObject *go =
7050 ObjectAccessor::GetGameObject(*this, guid);
7052 // not check distance for GO in case owned GO (fishing bobber case, for example)
7053 // And permit out of range GO with no owner in case fishing hole
7054 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7056 SendLootRelease(guid);
7057 return;
7060 loot = &go->loot;
7062 if(go->getLootState() == GO_READY)
7064 uint32 lootid = go->GetLootId();
7066 if(lootid)
7068 sLog.outDebug(" if(lootid)");
7069 loot->clear();
7070 loot->FillLoot(lootid, LootTemplates_Gameobject, this);
7073 if(loot_type == LOOT_FISHING)
7074 go->getFishLoot(loot);
7076 go->SetLootState(GO_ACTIVATED);
7079 else if (IS_ITEM_GUID(guid))
7081 Item *item = GetItemByGuid( guid );
7083 if (!item)
7085 SendLootRelease(guid);
7086 return;
7089 if(loot_type == LOOT_DISENCHANTING)
7091 loot = &item->loot;
7093 if(!item->m_lootGenerated)
7095 item->m_lootGenerated = true;
7096 loot->clear();
7097 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this);
7100 else if(loot_type == LOOT_PROSPECTING)
7102 loot = &item->loot;
7104 if(!item->m_lootGenerated)
7106 item->m_lootGenerated = true;
7107 loot->clear();
7108 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this);
7111 else
7113 loot = &item->loot;
7115 if(!item->m_lootGenerated)
7117 item->m_lootGenerated = true;
7118 loot->clear();
7119 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this);
7121 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7125 else if (IS_CORPSE_GUID(guid)) // remove insignia
7127 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7129 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7131 SendLootRelease(guid);
7132 return;
7135 loot = &bones->loot;
7137 if (!bones->lootForBody)
7139 bones->lootForBody = true;
7140 uint32 pLevel = bones->loot.gold;
7141 bones->loot.clear();
7142 // It may need a better formula
7143 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7144 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7147 if (bones->lootRecipient != this)
7148 permission = NONE_PERMISSION;
7150 else
7152 Creature *creature = ObjectAccessor::GetCreature(*this, guid);
7154 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7155 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7157 SendLootRelease(guid);
7158 return;
7161 if(loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7163 SendLootRelease(guid);
7164 return;
7167 loot = &creature->loot;
7169 if(loot_type == LOOT_PICKPOCKETING)
7171 if ( !creature->lootForPickPocketed )
7173 creature->lootForPickPocketed = true;
7174 loot->clear();
7176 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7177 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this);
7179 // Generate extra money for pick pocket loot
7180 const uint32 a = urand(0, creature->getLevel()/2);
7181 const uint32 b = urand(0, getLevel()/2);
7182 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7185 else
7187 // the player whose group may loot the corpse
7188 Player *recipient = creature->GetLootRecipient();
7189 if (!recipient)
7191 creature->SetLootRecipient(this);
7192 recipient = this;
7195 if (creature->lootForPickPocketed)
7197 creature->lootForPickPocketed = false;
7198 loot->clear();
7201 if(!creature->lootForBody)
7203 creature->lootForBody = true;
7204 loot->clear();
7206 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7207 loot->FillLoot(lootid, LootTemplates_Creature, recipient);
7209 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7211 if(Group* group = recipient->GetGroup())
7213 group->UpdateLooterGuid(creature,true);
7215 switch (group->GetLootMethod())
7217 case GROUP_LOOT:
7218 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7219 group->GroupLoot(recipient->GetGUID(), loot, creature);
7220 break;
7221 case NEED_BEFORE_GREED:
7222 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7223 break;
7224 case MASTER_LOOT:
7225 group->MasterLoot(recipient->GetGUID(), loot, creature);
7226 break;
7227 default:
7228 break;
7233 // possible only if creature->lootForBody && loot->empty() at spell cast check
7234 if (loot_type == LOOT_SKINNING)
7236 loot->clear();
7237 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this);
7239 // set group rights only for loot_type != LOOT_SKINNING
7240 else
7242 if(Group* group = GetGroup())
7244 if( group == recipient->GetGroup() )
7246 if(group->GetLootMethod() == FREE_FOR_ALL)
7247 permission = ALL_PERMISSION;
7248 else if(group->GetLooterGuid() == GetGUID())
7250 if(group->GetLootMethod() == MASTER_LOOT)
7251 permission = MASTER_PERMISSION;
7252 else
7253 permission = ALL_PERMISSION;
7255 else
7256 permission = GROUP_PERMISSION;
7258 else
7259 permission = NONE_PERMISSION;
7261 else if(recipient == this)
7262 permission = ALL_PERMISSION;
7263 else
7264 permission = NONE_PERMISSION;
7269 SetLootGUID(guid);
7271 QuestItemList *q_list = 0;
7272 if (permission != NONE_PERMISSION)
7274 QuestItemMap const& lootPlayerQuestItems = loot->GetPlayerQuestItems();
7275 QuestItemMap::const_iterator itr = lootPlayerQuestItems.find(GetGUIDLow());
7276 if (itr == lootPlayerQuestItems.end())
7277 q_list = loot->FillQuestLoot(this);
7278 else
7279 q_list = itr->second;
7282 QuestItemList *ffa_list = 0;
7283 if (permission != NONE_PERMISSION)
7285 QuestItemMap const& lootPlayerFFAItems = loot->GetPlayerFFAItems();
7286 QuestItemMap::const_iterator itr = lootPlayerFFAItems.find(GetGUIDLow());
7287 if (itr == lootPlayerFFAItems.end())
7288 ffa_list = loot->FillFFALoot(this);
7289 else
7290 ffa_list = itr->second;
7293 QuestItemList *conditional_list = 0;
7294 if (permission != NONE_PERMISSION)
7296 QuestItemMap const& lootPlayerNonQuestNonFFAConditionalItems = loot->GetPlayerNonQuestNonFFAConditionalItems();
7297 QuestItemMap::const_iterator itr = lootPlayerNonQuestNonFFAConditionalItems.find(GetGUIDLow());
7298 if (itr == lootPlayerNonQuestNonFFAConditionalItems.end())
7299 conditional_list = loot->FillNonQuestNonFFAConditionalLoot(this);
7300 else
7301 conditional_list = itr->second;
7304 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING and LOOT_INSIGNIA unsupported by client, sending LOOT_SKINNING instead
7305 if(loot_type == LOOT_PICKPOCKETING || loot_type == LOOT_DISENCHANTING || loot_type == LOOT_PROSPECTING || loot_type == LOOT_INSIGNIA)
7306 loot_type = LOOT_SKINNING;
7308 if(loot_type == LOOT_FISHINGHOLE)
7309 loot_type = LOOT_FISHING;
7311 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7313 data << uint64(guid);
7314 data << uint8(loot_type);
7315 data << LootView(*loot, q_list, ffa_list, conditional_list, this, permission);
7317 SendDirectMessage(&data);
7319 // add 'this' player as one of the players that are looting 'loot'
7320 if (permission != NONE_PERMISSION)
7321 loot->AddLooter(GetGUID());
7323 if ( loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid) )
7324 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7327 void Player::SendNotifyLootMoneyRemoved()
7329 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7330 GetSession()->SendPacket( &data );
7333 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7335 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7336 data << uint8(lootSlot);
7337 GetSession()->SendPacket( &data );
7340 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7342 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7343 data << Field;
7344 data << Value;
7345 GetSession()->SendPacket(&data);
7348 void Player::SendInitWorldStates()
7350 // data depends on zoneid/mapid...
7351 BattleGround* bg = GetBattleGround();
7352 uint16 NumberOfFields = 0;
7353 uint32 mapid = GetMapId();
7354 uint32 zoneid = GetZoneId();
7355 uint32 areaid = GetAreaId();
7356 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7357 // may be exist better way to do this...
7358 switch(zoneid)
7360 case 0:
7361 case 1:
7362 case 4:
7363 case 8:
7364 case 10:
7365 case 11:
7366 case 12:
7367 case 36:
7368 case 38:
7369 case 40:
7370 case 41:
7371 case 51:
7372 case 267:
7373 case 1519:
7374 case 1537:
7375 case 2257:
7376 case 2918:
7377 NumberOfFields = 6;
7378 break;
7379 case 2597:
7380 NumberOfFields = 81;
7381 break;
7382 case 3277:
7383 NumberOfFields = 14;
7384 break;
7385 case 3358:
7386 case 3820:
7387 NumberOfFields = 38;
7388 break;
7389 case 3483:
7390 NumberOfFields = 22;
7391 break;
7392 case 3519:
7393 NumberOfFields = 36;
7394 break;
7395 case 3521:
7396 NumberOfFields = 35;
7397 break;
7398 case 3698:
7399 case 3702:
7400 case 3968:
7401 NumberOfFields = 9;
7402 break;
7403 case 3703:
7404 NumberOfFields = 9;
7405 break;
7406 default:
7407 NumberOfFields = 10;
7408 break;
7411 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7412 data << uint32(mapid); // mapid
7413 data << uint32(zoneid); // zone id
7414 data << uint32(areaid); // area id, new 2.1.0
7415 data << uint16(NumberOfFields); // count of uint64 blocks
7416 data << uint32(0x8d8) << uint32(0x0); // 1
7417 data << uint32(0x8d7) << uint32(0x0); // 2
7418 data << uint32(0x8d6) << uint32(0x0); // 3
7419 data << uint32(0x8d5) << uint32(0x0); // 4
7420 data << uint32(0x8d4) << uint32(0x0); // 5
7421 data << uint32(0x8d3) << uint32(0x0); // 6
7422 if(mapid == 530) // Outland
7424 data << uint32(0x9bf) << uint32(0x0); // 7
7425 data << uint32(0x9bd) << uint32(0xF); // 8
7426 data << uint32(0x9bb) << uint32(0xF); // 9
7428 switch(zoneid)
7430 case 1:
7431 case 11:
7432 case 12:
7433 case 38:
7434 case 40:
7435 case 51:
7436 case 1519:
7437 case 1537:
7438 case 2257:
7439 break;
7440 case 2597: // AV
7441 data << uint32(0x7ae) << uint32(0x1); // 7
7442 data << uint32(0x532) << uint32(0x1); // 8
7443 data << uint32(0x531) << uint32(0x0); // 9
7444 data << uint32(0x52e) << uint32(0x0); // 10
7445 data << uint32(0x571) << uint32(0x0); // 11
7446 data << uint32(0x570) << uint32(0x0); // 12
7447 data << uint32(0x567) << uint32(0x1); // 13
7448 data << uint32(0x566) << uint32(0x1); // 14
7449 data << uint32(0x550) << uint32(0x1); // 15
7450 data << uint32(0x544) << uint32(0x0); // 16
7451 data << uint32(0x536) << uint32(0x0); // 17
7452 data << uint32(0x535) << uint32(0x1); // 18
7453 data << uint32(0x518) << uint32(0x0); // 19
7454 data << uint32(0x517) << uint32(0x0); // 20
7455 data << uint32(0x574) << uint32(0x0); // 21
7456 data << uint32(0x573) << uint32(0x0); // 22
7457 data << uint32(0x572) << uint32(0x0); // 23
7458 data << uint32(0x56f) << uint32(0x0); // 24
7459 data << uint32(0x56e) << uint32(0x0); // 25
7460 data << uint32(0x56d) << uint32(0x0); // 26
7461 data << uint32(0x56c) << uint32(0x0); // 27
7462 data << uint32(0x56b) << uint32(0x0); // 28
7463 data << uint32(0x56a) << uint32(0x1); // 29
7464 data << uint32(0x569) << uint32(0x1); // 30
7465 data << uint32(0x568) << uint32(0x1); // 13
7466 data << uint32(0x565) << uint32(0x0); // 32
7467 data << uint32(0x564) << uint32(0x0); // 33
7468 data << uint32(0x563) << uint32(0x0); // 34
7469 data << uint32(0x562) << uint32(0x0); // 35
7470 data << uint32(0x561) << uint32(0x0); // 36
7471 data << uint32(0x560) << uint32(0x0); // 37
7472 data << uint32(0x55f) << uint32(0x0); // 38
7473 data << uint32(0x55e) << uint32(0x0); // 39
7474 data << uint32(0x55d) << uint32(0x0); // 40
7475 data << uint32(0x3c6) << uint32(0x4); // 41
7476 data << uint32(0x3c4) << uint32(0x6); // 42
7477 data << uint32(0x3c2) << uint32(0x4); // 43
7478 data << uint32(0x516) << uint32(0x1); // 44
7479 data << uint32(0x515) << uint32(0x0); // 45
7480 data << uint32(0x3b6) << uint32(0x6); // 46
7481 data << uint32(0x55c) << uint32(0x0); // 47
7482 data << uint32(0x55b) << uint32(0x0); // 48
7483 data << uint32(0x55a) << uint32(0x0); // 49
7484 data << uint32(0x559) << uint32(0x0); // 50
7485 data << uint32(0x558) << uint32(0x0); // 51
7486 data << uint32(0x557) << uint32(0x0); // 52
7487 data << uint32(0x556) << uint32(0x0); // 53
7488 data << uint32(0x555) << uint32(0x0); // 54
7489 data << uint32(0x554) << uint32(0x1); // 55
7490 data << uint32(0x553) << uint32(0x1); // 56
7491 data << uint32(0x552) << uint32(0x1); // 57
7492 data << uint32(0x551) << uint32(0x1); // 58
7493 data << uint32(0x54f) << uint32(0x0); // 59
7494 data << uint32(0x54e) << uint32(0x0); // 60
7495 data << uint32(0x54d) << uint32(0x1); // 61
7496 data << uint32(0x54c) << uint32(0x0); // 62
7497 data << uint32(0x54b) << uint32(0x0); // 63
7498 data << uint32(0x545) << uint32(0x0); // 64
7499 data << uint32(0x543) << uint32(0x1); // 65
7500 data << uint32(0x542) << uint32(0x0); // 66
7501 data << uint32(0x540) << uint32(0x0); // 67
7502 data << uint32(0x53f) << uint32(0x0); // 68
7503 data << uint32(0x53e) << uint32(0x0); // 69
7504 data << uint32(0x53d) << uint32(0x0); // 70
7505 data << uint32(0x53c) << uint32(0x0); // 71
7506 data << uint32(0x53b) << uint32(0x0); // 72
7507 data << uint32(0x53a) << uint32(0x1); // 73
7508 data << uint32(0x539) << uint32(0x0); // 74
7509 data << uint32(0x538) << uint32(0x0); // 75
7510 data << uint32(0x537) << uint32(0x0); // 76
7511 data << uint32(0x534) << uint32(0x0); // 77
7512 data << uint32(0x533) << uint32(0x0); // 78
7513 data << uint32(0x530) << uint32(0x0); // 79
7514 data << uint32(0x52f) << uint32(0x0); // 80
7515 data << uint32(0x52d) << uint32(0x1); // 81
7516 break;
7517 case 3277: // WS
7518 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7519 bg->FillInitialWorldStates(data);
7520 else
7522 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7523 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7524 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7525 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7526 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7527 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7528 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7529 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7531 break;
7532 case 3358: // AB
7533 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7534 bg->FillInitialWorldStates(data);
7535 else
7537 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7538 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7539 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7540 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7541 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7542 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7543 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7544 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7545 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7546 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7547 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7548 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7549 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7550 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7551 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7552 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7553 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7554 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7555 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7556 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7557 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7558 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7559 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7560 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7561 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7562 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7563 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7564 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7565 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7566 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7567 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7568 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7570 break;
7571 case 3820: // EY
7572 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7573 bg->FillInitialWorldStates(data);
7574 else
7576 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7577 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7578 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7579 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7580 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7581 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7582 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7583 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7584 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7585 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7586 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7587 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7588 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7589 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7590 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7591 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7592 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7593 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7594 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontroled (1 - yes, 0 - no)
7595 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7596 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7597 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7598 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7599 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7600 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7601 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7602 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7603 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7604 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7605 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7606 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7607 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7608 // and some more ... unknown
7610 break;
7611 case 3483: // Hellfire Peninsula
7612 data << uint32(0x9ba) << uint32(0x1); // 10
7613 data << uint32(0x9b9) << uint32(0x1); // 11
7614 data << uint32(0x9b5) << uint32(0x0); // 12
7615 data << uint32(0x9b4) << uint32(0x1); // 13
7616 data << uint32(0x9b3) << uint32(0x0); // 14
7617 data << uint32(0x9b2) << uint32(0x0); // 15
7618 data << uint32(0x9b1) << uint32(0x1); // 16
7619 data << uint32(0x9b0) << uint32(0x0); // 17
7620 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7621 data << uint32(0x9ac) << uint32(0x0); // 19
7622 data << uint32(0x9a8) << uint32(0x0); // 20
7623 data << uint32(0x9a7) << uint32(0x0); // 21
7624 data << uint32(0x9a6) << uint32(0x1); // 22
7625 break;
7626 case 3519: // Terokkar Forest
7627 data << uint32(0xa41) << uint32(0x0); // 10
7628 data << uint32(0xa40) << uint32(0x14); // 11
7629 data << uint32(0xa3f) << uint32(0x0); // 12
7630 data << uint32(0xa3e) << uint32(0x0); // 13
7631 data << uint32(0xa3d) << uint32(0x5); // 14
7632 data << uint32(0xa3c) << uint32(0x0); // 15
7633 data << uint32(0xa87) << uint32(0x0); // 16
7634 data << uint32(0xa86) << uint32(0x0); // 17
7635 data << uint32(0xa85) << uint32(0x0); // 18
7636 data << uint32(0xa84) << uint32(0x0); // 19
7637 data << uint32(0xa83) << uint32(0x0); // 20
7638 data << uint32(0xa82) << uint32(0x0); // 21
7639 data << uint32(0xa81) << uint32(0x0); // 22
7640 data << uint32(0xa80) << uint32(0x0); // 23
7641 data << uint32(0xa7e) << uint32(0x0); // 24
7642 data << uint32(0xa7d) << uint32(0x0); // 25
7643 data << uint32(0xa7c) << uint32(0x0); // 26
7644 data << uint32(0xa7b) << uint32(0x0); // 27
7645 data << uint32(0xa7a) << uint32(0x0); // 28
7646 data << uint32(0xa79) << uint32(0x0); // 29
7647 data << uint32(0x9d0) << uint32(0x5); // 30
7648 data << uint32(0x9ce) << uint32(0x0); // 31
7649 data << uint32(0x9cd) << uint32(0x0); // 32
7650 data << uint32(0x9cc) << uint32(0x0); // 33
7651 data << uint32(0xa88) << uint32(0x0); // 34
7652 data << uint32(0xad0) << uint32(0x0); // 35
7653 data << uint32(0xacf) << uint32(0x1); // 36
7654 break;
7655 case 3521: // Zangarmarsh
7656 data << uint32(0x9e1) << uint32(0x0); // 10
7657 data << uint32(0x9e0) << uint32(0x0); // 11
7658 data << uint32(0x9df) << uint32(0x0); // 12
7659 data << uint32(0xa5d) << uint32(0x1); // 13
7660 data << uint32(0xa5c) << uint32(0x0); // 14
7661 data << uint32(0xa5b) << uint32(0x1); // 15
7662 data << uint32(0xa5a) << uint32(0x0); // 16
7663 data << uint32(0xa59) << uint32(0x1); // 17
7664 data << uint32(0xa58) << uint32(0x0); // 18
7665 data << uint32(0xa57) << uint32(0x0); // 19
7666 data << uint32(0xa56) << uint32(0x0); // 20
7667 data << uint32(0xa55) << uint32(0x1); // 21
7668 data << uint32(0xa54) << uint32(0x0); // 22
7669 data << uint32(0x9e7) << uint32(0x0); // 23
7670 data << uint32(0x9e6) << uint32(0x0); // 24
7671 data << uint32(0x9e5) << uint32(0x0); // 25
7672 data << uint32(0xa00) << uint32(0x0); // 26
7673 data << uint32(0x9ff) << uint32(0x1); // 27
7674 data << uint32(0x9fe) << uint32(0x0); // 28
7675 data << uint32(0x9fd) << uint32(0x0); // 29
7676 data << uint32(0x9fc) << uint32(0x1); // 30
7677 data << uint32(0x9fb) << uint32(0x0); // 31
7678 data << uint32(0xa62) << uint32(0x0); // 32
7679 data << uint32(0xa61) << uint32(0x1); // 33
7680 data << uint32(0xa60) << uint32(0x1); // 34
7681 data << uint32(0xa5f) << uint32(0x0); // 35
7682 break;
7683 case 3698: // Nagrand Arena
7684 data << uint32(0xa0f) << uint32(0x0); // 7
7685 data << uint32(0xa10) << uint32(0x0); // 8
7686 data << uint32(0xa11) << uint32(0x0); // 9
7687 break;
7688 case 3702: // Blade's Edge Arena
7689 data << uint32(0x9f0) << uint32(0x0); // 7
7690 data << uint32(0x9f1) << uint32(0x0); // 8
7691 data << uint32(0x9f3) << uint32(0x0); // 9
7692 break;
7693 case 3968: // Ruins of Lordaeron
7694 data << uint32(0xbb8) << uint32(0x0); // 7
7695 data << uint32(0xbb9) << uint32(0x0); // 8
7696 data << uint32(0xbba) << uint32(0x0); // 9
7697 break;
7698 case 3703: // Shattrath City
7699 break;
7700 default:
7701 data << uint32(0x914) << uint32(0x0); // 7
7702 data << uint32(0x913) << uint32(0x0); // 8
7703 data << uint32(0x912) << uint32(0x0); // 9
7704 data << uint32(0x915) << uint32(0x0); // 10
7705 break;
7707 GetSession()->SendPacket(&data);
7710 uint32 Player::GetXPRestBonus(uint32 xp)
7712 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
7714 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
7715 rested_bonus = xp;
7717 SetRestBonus( GetRestBonus() - rested_bonus);
7719 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
7720 return rested_bonus;
7723 void Player::SetBindPoint(uint64 guid)
7725 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
7726 data << uint64(guid);
7727 GetSession()->SendPacket( &data );
7730 void Player::SendTalentWipeConfirm(uint64 guid)
7732 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
7733 data << uint64(guid);
7734 data << uint32(resetTalentsCost());
7735 GetSession()->SendPacket( &data );
7738 void Player::SendPetSkillWipeConfirm()
7740 Pet* pet = GetPet();
7741 if(!pet)
7742 return;
7743 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
7744 data << pet->GetGUID();
7745 data << uint32(pet->resetTalentsCost());
7746 GetSession()->SendPacket( &data );
7749 /*********************************************************/
7750 /*** STORAGE SYSTEM ***/
7751 /*********************************************************/
7753 void Player::SetVirtualItemSlot( uint8 i, Item* item)
7755 assert(i < 3);
7756 if(i < 2 && item)
7758 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
7759 return;
7760 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
7761 if(charges == 0)
7762 return;
7763 if(charges > 1)
7764 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
7765 else if(charges <= 1)
7767 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
7768 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
7773 void Player::SetSheath( uint32 sheathed )
7775 switch (sheathed)
7777 case SHEATH_STATE_UNARMED: // no prepared weapon
7778 SetVirtualItemSlot(0,NULL);
7779 SetVirtualItemSlot(1,NULL);
7780 SetVirtualItemSlot(2,NULL);
7781 break;
7782 case SHEATH_STATE_MELEE: // prepared melee weapon
7784 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
7785 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
7786 SetVirtualItemSlot(2,NULL);
7787 }; break;
7788 case SHEATH_STATE_RANGED: // prepared ranged weapon
7789 SetVirtualItemSlot(0,NULL);
7790 SetVirtualItemSlot(1,NULL);
7791 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
7792 break;
7793 default:
7794 SetVirtualItemSlot(0,NULL);
7795 SetVirtualItemSlot(1,NULL);
7796 SetVirtualItemSlot(2,NULL);
7797 break;
7799 SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); // this must visualize Sheath changing for other players...
7802 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
7804 uint8 pClass = getClass();
7806 uint8 slots[4];
7807 slots[0] = NULL_SLOT;
7808 slots[1] = NULL_SLOT;
7809 slots[2] = NULL_SLOT;
7810 slots[3] = NULL_SLOT;
7811 switch( proto->InventoryType )
7813 case INVTYPE_HEAD:
7814 slots[0] = EQUIPMENT_SLOT_HEAD;
7815 break;
7816 case INVTYPE_NECK:
7817 slots[0] = EQUIPMENT_SLOT_NECK;
7818 break;
7819 case INVTYPE_SHOULDERS:
7820 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
7821 break;
7822 case INVTYPE_BODY:
7823 slots[0] = EQUIPMENT_SLOT_BODY;
7824 break;
7825 case INVTYPE_CHEST:
7826 slots[0] = EQUIPMENT_SLOT_CHEST;
7827 break;
7828 case INVTYPE_ROBE:
7829 slots[0] = EQUIPMENT_SLOT_CHEST;
7830 break;
7831 case INVTYPE_WAIST:
7832 slots[0] = EQUIPMENT_SLOT_WAIST;
7833 break;
7834 case INVTYPE_LEGS:
7835 slots[0] = EQUIPMENT_SLOT_LEGS;
7836 break;
7837 case INVTYPE_FEET:
7838 slots[0] = EQUIPMENT_SLOT_FEET;
7839 break;
7840 case INVTYPE_WRISTS:
7841 slots[0] = EQUIPMENT_SLOT_WRISTS;
7842 break;
7843 case INVTYPE_HANDS:
7844 slots[0] = EQUIPMENT_SLOT_HANDS;
7845 break;
7846 case INVTYPE_FINGER:
7847 slots[0] = EQUIPMENT_SLOT_FINGER1;
7848 slots[1] = EQUIPMENT_SLOT_FINGER2;
7849 break;
7850 case INVTYPE_TRINKET:
7851 slots[0] = EQUIPMENT_SLOT_TRINKET1;
7852 slots[1] = EQUIPMENT_SLOT_TRINKET2;
7853 break;
7854 case INVTYPE_CLOAK:
7855 slots[0] = EQUIPMENT_SLOT_BACK;
7856 break;
7857 case INVTYPE_WEAPON:
7859 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7861 // suggest offhand slot only if know dual wielding
7862 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
7863 if(CanDualWield())
7864 slots[1] = EQUIPMENT_SLOT_OFFHAND;
7865 };break;
7866 case INVTYPE_SHIELD:
7867 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7868 break;
7869 case INVTYPE_RANGED:
7870 slots[0] = EQUIPMENT_SLOT_RANGED;
7871 break;
7872 case INVTYPE_2HWEAPON:
7873 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7874 break;
7875 case INVTYPE_TABARD:
7876 slots[0] = EQUIPMENT_SLOT_TABARD;
7877 break;
7878 case INVTYPE_WEAPONMAINHAND:
7879 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7880 break;
7881 case INVTYPE_WEAPONOFFHAND:
7882 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7883 break;
7884 case INVTYPE_HOLDABLE:
7885 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7886 break;
7887 case INVTYPE_THROWN:
7888 slots[0] = EQUIPMENT_SLOT_RANGED;
7889 break;
7890 case INVTYPE_RANGEDRIGHT:
7891 slots[0] = EQUIPMENT_SLOT_RANGED;
7892 break;
7893 case INVTYPE_BAG:
7894 slots[0] = INVENTORY_SLOT_BAG_1;
7895 slots[1] = INVENTORY_SLOT_BAG_2;
7896 slots[2] = INVENTORY_SLOT_BAG_3;
7897 slots[3] = INVENTORY_SLOT_BAG_4;
7898 break;
7899 case INVTYPE_RELIC:
7901 switch(proto->SubClass)
7903 case ITEM_SUBCLASS_ARMOR_LIBRAM:
7904 if (pClass == CLASS_PALADIN)
7905 slots[0] = EQUIPMENT_SLOT_RANGED;
7906 break;
7907 case ITEM_SUBCLASS_ARMOR_IDOL:
7908 if (pClass == CLASS_DRUID)
7909 slots[0] = EQUIPMENT_SLOT_RANGED;
7910 break;
7911 case ITEM_SUBCLASS_ARMOR_TOTEM:
7912 if (pClass == CLASS_SHAMAN)
7913 slots[0] = EQUIPMENT_SLOT_RANGED;
7914 break;
7915 case ITEM_SUBCLASS_ARMOR_MISC:
7916 if (pClass == CLASS_WARLOCK)
7917 slots[0] = EQUIPMENT_SLOT_RANGED;
7918 break;
7920 break;
7922 default :
7923 return NULL_SLOT;
7926 if( slot != NULL_SLOT )
7928 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
7930 for (int i = 0; i < 4; i++)
7932 if ( slots[i] == slot )
7933 return slot;
7937 else
7939 // search free slot at first
7940 for (int i = 0; i < 4; i++)
7942 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
7944 // in case 2hand equipped weapon offhand slot empty but not free
7945 if(slots[i]==EQUIPMENT_SLOT_OFFHAND)
7947 Item* mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );
7948 if(!mainItem || mainItem->GetProto()->InventoryType != INVTYPE_2HWEAPON)
7949 return slots[i];
7951 else
7952 return slots[i];
7956 // if not found free and can swap return first appropriate from used
7957 for (int i = 0; i < 4; i++)
7959 if ( slots[i] != NULL_SLOT && swap )
7960 return slots[i];
7964 // no free position
7965 return NULL_SLOT;
7968 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
7970 Item *pItem;
7971 uint32 tempcount = 0;
7973 uint8 res = EQUIP_ERR_OK;
7975 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
7977 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
7978 if( pItem && pItem->GetEntry() == item )
7980 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
7981 if(ires==EQUIP_ERR_OK)
7983 tempcount += pItem->GetCount();
7984 if( tempcount >= count )
7985 return EQUIP_ERR_OK;
7987 else
7988 res = ires;
7991 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
7993 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
7994 if( pItem && pItem->GetEntry() == item )
7996 tempcount += pItem->GetCount();
7997 if( tempcount >= count )
7998 return EQUIP_ERR_OK;
8001 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
8003 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8004 if( pItem && pItem->GetEntry() == item )
8006 tempcount += pItem->GetCount();
8007 if( tempcount >= count )
8008 return EQUIP_ERR_OK;
8011 Bag *pBag;
8012 ItemPrototype const *pBagProto;
8013 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8015 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8016 if( pBag )
8018 pBagProto = pBag->GetProto();
8019 if( pBagProto )
8021 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
8023 pItem = GetItemByPos( i, j );
8024 if( pItem && pItem->GetEntry() == item )
8026 tempcount += pItem->GetCount();
8027 if( tempcount >= count )
8028 return EQUIP_ERR_OK;
8035 // not found req. item count and have unequippable items
8036 return res;
8039 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8041 uint32 count = 0;
8042 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8044 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8045 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8046 count += pItem->GetCount();
8048 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
8050 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8051 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8052 count += pItem->GetCount();
8054 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8056 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8057 if( pBag )
8058 count += pBag->GetItemCount(item,skipItem);
8061 if(skipItem && skipItem->GetProto()->GemProperties)
8063 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8065 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8066 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8067 count += pItem->GetGemCountWithID(item);
8071 if(inBankAlso)
8073 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8075 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8076 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8077 count += pItem->GetCount();
8079 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8081 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8082 if( pBag )
8083 count += pBag->GetItemCount(item,skipItem);
8086 if(skipItem && skipItem->GetProto()->GemProperties)
8088 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8090 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8091 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8092 count += pItem->GetGemCountWithID(item);
8097 return count;
8100 Item* Player::GetItemByGuid( uint64 guid ) const
8102 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8104 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8105 if( pItem && pItem->GetGUID() == guid )
8106 return pItem;
8108 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
8110 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8111 if( pItem && pItem->GetGUID() == guid )
8112 return pItem;
8115 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8117 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8118 if( pBag )
8120 ItemPrototype const *pBagProto = pBag->GetProto();
8121 if( pBagProto )
8123 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
8125 Item* pItem = pBag->GetItemByPos( j );
8126 if( pItem && pItem->GetGUID() == guid )
8127 return pItem;
8132 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8134 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8135 if( pBag )
8137 ItemPrototype const *pBagProto = pBag->GetProto();
8138 if( pBagProto )
8140 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
8142 Item* pItem = pBag->GetItemByPos( j );
8143 if( pItem && pItem->GetGUID() == guid )
8144 return pItem;
8150 return NULL;
8153 Item* Player::GetItemByPos( uint16 pos ) const
8155 uint8 bag = pos >> 8;
8156 uint8 slot = pos & 255;
8157 return GetItemByPos( bag, slot );
8160 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8162 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END ) )
8163 return m_items[slot];
8164 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8165 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8167 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8168 if ( pBag )
8169 return pBag->GetItemByPos(slot);
8171 return NULL;
8174 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8176 uint16 slot;
8177 switch (attackType)
8179 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8180 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8181 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8182 default: return NULL;
8185 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8186 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8187 return NULL;
8189 if(!useable)
8190 return item;
8192 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8193 return NULL;
8195 return item;
8198 Item* Player::GetShield(bool useable) const
8200 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8201 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8202 return NULL;
8204 if(!useable)
8205 return item;
8207 if( item->IsBroken())
8208 return NULL;
8210 return item;
8213 uint32 Player::GetAttackBySlot( uint8 slot )
8215 switch(slot)
8217 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8218 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8219 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8220 default: return MAX_ATTACK;
8224 bool Player::HasBankBagSlot( uint8 slot ) const
8226 uint32 maxslot = GetByteValue(PLAYER_BYTES_2, 2) + BANK_SLOT_BAG_START;
8227 if( slot < maxslot )
8228 return true;
8229 return false;
8232 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8234 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8235 return true;
8236 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8237 return true;
8238 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8239 return true;
8240 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END ) )
8241 return true;
8242 return false;
8245 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8247 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8248 return true;
8249 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8250 return true;
8251 return false;
8254 bool Player::IsBankPos( uint8 bag, uint8 slot )
8256 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8257 return true;
8258 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8259 return true;
8260 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8261 return true;
8262 return false;
8265 bool Player::IsBagPos( uint16 pos )
8267 uint8 bag = pos >> 8;
8268 uint8 slot = pos & 255;
8269 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8270 return true;
8271 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8272 return true;
8273 return false;
8276 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8278 uint32 tempcount = 0;
8279 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8281 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8282 if( pItem && pItem->GetEntry() == item )
8284 tempcount += pItem->GetCount();
8285 if( tempcount >= count )
8286 return true;
8289 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
8291 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8292 if( pItem && pItem->GetEntry() == item )
8294 tempcount += pItem->GetCount();
8295 if( tempcount >= count )
8296 return true;
8299 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8301 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8303 if(ItemPrototype const *pBagProto = pBag->GetProto())
8305 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
8307 Item* pItem = GetItemByPos( i, j );
8308 if( pItem && pItem->GetEntry() == item )
8310 tempcount += pItem->GetCount();
8311 if( tempcount >= count )
8312 return true;
8319 if(inBankAlso)
8321 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8323 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8324 if( pItem && pItem->GetEntry() == item )
8326 tempcount += pItem->GetCount();
8327 if( tempcount >= count )
8328 return true;
8331 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8333 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8335 if(ItemPrototype const *pBagProto = pBag->GetProto())
8337 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
8339 Item* pItem = GetItemByPos( i, j );
8340 if( pItem && pItem->GetEntry() == item )
8342 tempcount += pItem->GetCount();
8343 if( tempcount >= count )
8344 return true;
8352 return false;
8355 Item* Player::GetItemOrItemWithGemEquipped( uint32 item ) const
8357 Item *pItem;
8358 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
8360 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8361 if( pItem && pItem->GetEntry() == item )
8362 return pItem;
8365 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8366 if (pProto && pProto->GemProperties)
8368 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
8370 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8371 if( pItem && pItem->GetProto()->Socket[0].Color )
8373 if (pItem->GetGemCountWithID(item) > 0 )
8374 return pItem;
8379 return NULL;
8382 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8384 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8385 if( !pProto )
8387 if(no_space_count)
8388 *no_space_count = count;
8389 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8392 // no maximum
8393 if(pProto->MaxCount == 0)
8394 return EQUIP_ERR_OK;
8396 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8398 if( curcount + count > pProto->MaxCount )
8400 if(no_space_count)
8401 *no_space_count = count +curcount - pProto->MaxCount;
8402 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8405 return EQUIP_ERR_OK;
8408 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8410 Item *pItem;
8411 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8413 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8414 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8415 return true;
8417 for(uint8 i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
8419 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8420 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8421 return true;
8423 Bag *pBag;
8424 ItemPrototype const *pBagProto;
8425 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8427 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8428 if( pBag )
8430 pBagProto = pBag->GetProto();
8431 if( pBagProto )
8433 for(uint32 j = 0; j < pBagProto->ContainerSlots; ++j)
8435 pItem = GetItemByPos( i, j );
8436 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8437 return true;
8442 return false;
8445 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8447 Item* pItem2 = GetItemByPos( bag, slot );
8449 // ignore move item (this slot will be empty at move)
8450 if(pItem2==pSrcItem)
8451 pItem2 = NULL;
8453 uint32 need_space;
8455 // empty specific slot - check item fit to slot
8456 if( !pItem2 || swap )
8458 if( bag == INVENTORY_SLOT_BAG_0 )
8460 // keyring case
8461 if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8462 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8464 // prevent cheating
8465 if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8466 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8468 else
8470 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8471 if( !pBag )
8472 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8474 ItemPrototype const* pBagProto = pBag->GetProto();
8475 if( !pBagProto )
8476 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8478 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8479 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8482 // non empty stack with space
8483 need_space = pProto->Stackable;
8485 // non empty slot, check item type
8486 else
8488 // check item type
8489 if(pItem2->GetEntry() != pProto->ItemId)
8490 return EQUIP_ERR_ITEM_CANT_STACK;
8492 // check free space
8493 if(pItem2->GetCount() >= pProto->Stackable)
8494 return EQUIP_ERR_ITEM_CANT_STACK;
8496 need_space = pProto->Stackable - pItem2->GetCount();
8499 if(need_space > count)
8500 need_space = count;
8502 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8503 if(!newPosition.isContainedIn(dest))
8505 dest.push_back(newPosition);
8506 count -= need_space;
8508 return EQUIP_ERR_OK;
8511 uint8 Player::_CanStoreItem_InBag( uint8 bag, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool merge, bool non_specialized, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot ) const
8513 // skip specific bag already processed in first called _CanStoreItem_InBag
8514 if(bag==skip_bag)
8515 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8517 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8518 if( !pBag )
8519 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8521 ItemPrototype const* pBagProto = pBag->GetProto();
8522 if( !pBagProto )
8523 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8525 // specialized bag mode or non-specilized
8526 if( non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) )
8527 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8529 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8530 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8532 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
8534 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8535 if(j==skip_slot)
8536 continue;
8538 Item* pItem2 = GetItemByPos( bag, j );
8540 // ignore move item (this slot will be empty at move)
8541 if(pItem2==pSrcItem)
8542 pItem2 = NULL;
8544 // if merge skip empty, if !merge skip non-empty
8545 if((pItem2!=NULL)!=merge)
8546 continue;
8548 if( pItem2 )
8550 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->Stackable )
8552 uint32 need_space = pProto->Stackable - pItem2->GetCount();
8553 if(need_space > count)
8554 need_space = count;
8556 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8557 if(!newPosition.isContainedIn(dest))
8559 dest.push_back(newPosition);
8560 count -= need_space;
8562 if(count==0)
8563 return EQUIP_ERR_OK;
8567 else
8569 uint32 need_space = pProto->Stackable;
8570 if(need_space > count)
8571 need_space = count;
8573 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8574 if(!newPosition.isContainedIn(dest))
8576 dest.push_back(newPosition);
8577 count -= need_space;
8579 if(count==0)
8580 return EQUIP_ERR_OK;
8584 return EQUIP_ERR_OK;
8587 uint8 Player::_CanStoreItem_InInventorySlots( uint8 slot_begin, uint8 slot_end, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool merge, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot ) const
8589 for(uint32 j = slot_begin; j < slot_end; j++)
8591 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8592 if(INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
8593 continue;
8595 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
8597 // ignore move item (this slot will be empty at move)
8598 if(pItem2==pSrcItem)
8599 pItem2 = NULL;
8601 // if merge skip empty, if !merge skip non-empty
8602 if((pItem2!=NULL)!=merge)
8603 continue;
8605 if( pItem2 )
8607 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->Stackable )
8609 uint32 need_space = pProto->Stackable - pItem2->GetCount();
8610 if(need_space > count)
8611 need_space = count;
8612 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8613 if(!newPosition.isContainedIn(dest))
8615 dest.push_back(newPosition);
8616 count -= need_space;
8618 if(count==0)
8619 return EQUIP_ERR_OK;
8623 else
8625 uint32 need_space = pProto->Stackable;
8626 if(need_space > count)
8627 need_space = count;
8629 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8630 if(!newPosition.isContainedIn(dest))
8632 dest.push_back(newPosition);
8633 count -= need_space;
8635 if(count==0)
8636 return EQUIP_ERR_OK;
8640 return EQUIP_ERR_OK;
8643 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
8645 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
8647 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8648 if( !pProto )
8650 if(no_space_count)
8651 *no_space_count = count;
8652 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
8655 if(pItem && pItem->IsBindedNotWith(GetGUID()))
8657 if(no_space_count)
8658 *no_space_count = count;
8659 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
8662 // check count of items (skip for auto move for same player from bank)
8663 uint32 no_similar_count = 0; // can't store this amount similar items
8664 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
8665 if(res!=EQUIP_ERR_OK)
8667 if(count==no_similar_count)
8669 if(no_space_count)
8670 *no_space_count = no_similar_count;
8671 return res;
8673 count -= no_similar_count;
8676 // in specific slot
8677 if( bag != NULL_BAG && slot != NULL_SLOT )
8679 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
8680 if(res!=EQUIP_ERR_OK)
8682 if(no_space_count)
8683 *no_space_count = count + no_similar_count;
8684 return res;
8687 if(count==0)
8689 if(no_similar_count==0)
8690 return EQUIP_ERR_OK;
8692 if(no_space_count)
8693 *no_space_count = count + no_similar_count;
8694 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8698 // not specific slot or have spece for partly store only in specific slot
8700 // in specific bag
8701 if( bag != NULL_BAG )
8703 // search stack in bag for merge to
8704 if( pProto->Stackable > 1 )
8706 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8708 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
8709 if(res!=EQUIP_ERR_OK)
8711 if(no_space_count)
8712 *no_space_count = count + no_similar_count;
8713 return res;
8716 if(count==0)
8718 if(no_similar_count==0)
8719 return EQUIP_ERR_OK;
8721 if(no_space_count)
8722 *no_space_count = count + no_similar_count;
8723 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8726 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
8727 if(res!=EQUIP_ERR_OK)
8729 if(no_space_count)
8730 *no_space_count = count + no_similar_count;
8731 return res;
8734 if(count==0)
8736 if(no_similar_count==0)
8737 return EQUIP_ERR_OK;
8739 if(no_space_count)
8740 *no_space_count = count + no_similar_count;
8741 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8744 else // equipped bag
8746 // we need check 2 time (specilized/non_specialized), use NULL_BAG to prevent skipping bag
8747 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
8748 if(res!=EQUIP_ERR_OK)
8749 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
8751 if(res!=EQUIP_ERR_OK)
8753 if(no_space_count)
8754 *no_space_count = count + no_similar_count;
8755 return res;
8758 if(count==0)
8760 if(no_similar_count==0)
8761 return EQUIP_ERR_OK;
8763 if(no_space_count)
8764 *no_space_count = count + no_similar_count;
8765 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8770 // search free slot in bag for place to
8771 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8773 // search free slot - keyring case
8774 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
8776 uint32 keyringSize = GetMaxKeyringSize();
8777 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
8778 if(res!=EQUIP_ERR_OK)
8780 if(no_space_count)
8781 *no_space_count = count + no_similar_count;
8782 return res;
8785 if(count==0)
8787 if(no_similar_count==0)
8788 return EQUIP_ERR_OK;
8790 if(no_space_count)
8791 *no_space_count = count + no_similar_count;
8792 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8796 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
8797 if(res!=EQUIP_ERR_OK)
8799 if(no_space_count)
8800 *no_space_count = count + no_similar_count;
8801 return res;
8804 if(count==0)
8806 if(no_similar_count==0)
8807 return EQUIP_ERR_OK;
8809 if(no_space_count)
8810 *no_space_count = count + no_similar_count;
8811 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8814 else // equipped bag
8816 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
8817 if(res!=EQUIP_ERR_OK)
8818 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
8820 if(res!=EQUIP_ERR_OK)
8822 if(no_space_count)
8823 *no_space_count = count + no_similar_count;
8824 return res;
8827 if(count==0)
8829 if(no_similar_count==0)
8830 return EQUIP_ERR_OK;
8832 if(no_space_count)
8833 *no_space_count = count + no_similar_count;
8834 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8839 // not specific bag or have space for partly store only in specific bag
8841 // search stack for merge to
8842 if( pProto->Stackable > 1 )
8844 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
8845 if(res!=EQUIP_ERR_OK)
8847 if(no_space_count)
8848 *no_space_count = count + no_similar_count;
8849 return res;
8852 if(count==0)
8854 if(no_similar_count==0)
8855 return EQUIP_ERR_OK;
8857 if(no_space_count)
8858 *no_space_count = count + no_similar_count;
8859 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8862 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
8863 if(res!=EQUIP_ERR_OK)
8865 if(no_space_count)
8866 *no_space_count = count + no_similar_count;
8867 return res;
8870 if(count==0)
8872 if(no_similar_count==0)
8873 return EQUIP_ERR_OK;
8875 if(no_space_count)
8876 *no_space_count = count + no_similar_count;
8877 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8880 if( pProto->BagFamily )
8882 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8884 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
8885 if(res!=EQUIP_ERR_OK)
8886 continue;
8888 if(count==0)
8890 if(no_similar_count==0)
8891 return EQUIP_ERR_OK;
8893 if(no_space_count)
8894 *no_space_count = count + no_similar_count;
8895 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8900 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8902 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
8903 if(res!=EQUIP_ERR_OK)
8904 continue;
8906 if(count==0)
8908 if(no_similar_count==0)
8909 return EQUIP_ERR_OK;
8911 if(no_space_count)
8912 *no_space_count = count + no_similar_count;
8913 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8918 // search free slot - special bag case
8919 if( pProto->BagFamily )
8921 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
8923 uint32 keyringSize = GetMaxKeyringSize();
8924 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
8925 if(res!=EQUIP_ERR_OK)
8927 if(no_space_count)
8928 *no_space_count = count + no_similar_count;
8929 return res;
8932 if(count==0)
8934 if(no_similar_count==0)
8935 return EQUIP_ERR_OK;
8937 if(no_space_count)
8938 *no_space_count = count + no_similar_count;
8939 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8943 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8945 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
8946 if(res!=EQUIP_ERR_OK)
8947 continue;
8949 if(count==0)
8951 if(no_similar_count==0)
8952 return EQUIP_ERR_OK;
8954 if(no_space_count)
8955 *no_space_count = count + no_similar_count;
8956 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8961 // search free slot
8962 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
8963 if(res!=EQUIP_ERR_OK)
8965 if(no_space_count)
8966 *no_space_count = count + no_similar_count;
8967 return res;
8970 if(count==0)
8972 if(no_similar_count==0)
8973 return EQUIP_ERR_OK;
8975 if(no_space_count)
8976 *no_space_count = count + no_similar_count;
8977 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8980 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8982 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
8983 if(res!=EQUIP_ERR_OK)
8984 continue;
8986 if(count==0)
8988 if(no_similar_count==0)
8989 return EQUIP_ERR_OK;
8991 if(no_space_count)
8992 *no_space_count = count + no_similar_count;
8993 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8997 if(no_space_count)
8998 *no_space_count = count + no_similar_count;
9000 return EQUIP_ERR_INVENTORY_FULL;
9003 //////////////////////////////////////////////////////////////////////////
9004 uint8 Player::CanStoreItems( Item **pItems,int count) const
9006 Item *pItem2;
9008 // fill space table
9009 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9010 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9011 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9013 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9014 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9015 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9017 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
9019 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9021 if (pItem2 && !pItem2->IsInTrade())
9023 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9027 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
9029 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9031 if (pItem2 && !pItem2->IsInTrade())
9033 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9037 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9039 Bag *pBag;
9040 ItemPrototype const *pBagProto;
9042 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9043 if( pBag )
9045 pBagProto = pBag->GetProto();
9047 if( pBagProto )
9049 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
9051 pItem2 = GetItemByPos( i, j );
9052 if (pItem2 && !pItem2->IsInTrade())
9054 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9061 // check free space for all items
9062 for (int k=0;k<count;k++)
9064 Item *pItem = pItems[k];
9066 // no item
9067 if (!pItem) continue;
9069 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9070 ItemPrototype const *pProto = pItem->GetProto();
9072 // strange item
9073 if( !pProto )
9074 return EQUIP_ERR_ITEM_NOT_FOUND;
9076 // item it 'bind'
9077 if(pItem->IsBindedNotWith(GetGUID()))
9078 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9080 Bag *pBag;
9081 ItemPrototype const *pBagProto;
9083 // item is 'one item only'
9084 uint8 res = CanTakeMoreSimilarItems(pItem);
9085 if(res != EQUIP_ERR_OK)
9086 return res;
9088 // search stack for merge to
9089 if( pProto->Stackable > 1 )
9091 bool b_found = false;
9093 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; t++)
9095 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9096 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->Stackable )
9098 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9099 b_found = true;
9100 break;
9103 if (b_found) continue;
9105 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9107 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9108 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->Stackable )
9110 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9111 b_found = true;
9112 break;
9115 if (b_found) continue;
9117 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9119 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9120 if( pBag )
9122 pBagProto = pBag->GetProto();
9123 if( pBagProto )
9125 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
9127 pItem2 = GetItemByPos( t, j );
9128 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->Stackable )
9130 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9131 b_found = true;
9132 break;
9138 if (b_found) continue;
9141 // special bag case
9142 if( pProto->BagFamily )
9144 bool b_found = false;
9145 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9147 uint32 keyringSize = GetMaxKeyringSize();
9148 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9150 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9152 inv_keys[t-KEYRING_SLOT_START] = 1;
9153 b_found = true;
9154 break;
9159 if (b_found) continue;
9161 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9163 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9164 if( pBag )
9166 pBagProto = pBag->GetProto();
9168 // not plain container check
9169 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9170 ItemCanGoIntoBag(pProto,pBagProto) )
9172 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
9174 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9176 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9177 b_found = true;
9178 break;
9184 if (b_found) continue;
9187 // search free slot
9188 bool b_found = false;
9189 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9191 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9193 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9194 b_found = true;
9195 break;
9198 if (b_found) continue;
9200 // search free slot in bags
9201 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9203 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9204 if( pBag )
9206 pBagProto = pBag->GetProto();
9207 if( pBagProto && ItemCanGoIntoBag(pProto,pBagProto))
9209 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
9211 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9213 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9214 b_found = true;
9215 break;
9222 // no free slot found?
9223 if (!b_found)
9224 return EQUIP_ERR_INVENTORY_FULL;
9227 return EQUIP_ERR_OK;
9230 //////////////////////////////////////////////////////////////////////////
9231 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, uint32 count, bool swap ) const
9233 dest = 0;
9234 Item *pItem = Item::CreateItem( item, count, this );
9235 if( pItem )
9237 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9238 delete pItem;
9239 return result;
9242 return EQUIP_ERR_ITEM_NOT_FOUND;
9245 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9247 dest = 0;
9248 if( pItem )
9250 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9251 ItemPrototype const *pProto = pItem->GetProto();
9252 if( pProto )
9254 // May be here should be more stronger checks; STUNNED checked
9255 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9256 if (not_loading && hasUnitState(UNIT_STAT_STUNNED))
9257 return EQUIP_ERR_YOU_ARE_STUNNED;
9259 if(pItem->IsBindedNotWith(GetGUID()))
9260 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9262 // check count of items (skip for auto move for same player from bank)
9263 uint8 res = CanTakeMoreSimilarItems(pItem);
9264 if(res != EQUIP_ERR_OK)
9265 return res;
9267 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9268 // - combat
9269 // - in-progress arenas
9270 if( !pProto->CanChangeEquipStateInCombat() )
9272 if( isInCombat() )
9273 return EQUIP_ERR_NOT_IN_COMBAT;
9275 if(BattleGround* bg = GetBattleGround())
9276 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9277 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9280 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9281 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9283 if(IsNonMeleeSpellCasted(false))
9284 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9286 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9287 if( eslot == NULL_SLOT )
9288 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9290 uint8 msg = CanUseItem( pItem , not_loading );
9291 if( msg != EQUIP_ERR_OK )
9292 return msg;
9293 if( !swap && GetItemByPos( INVENTORY_SLOT_BAG_0, eslot ) )
9294 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9296 // check unique-equipped on item
9297 if (pProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
9299 // there is an equip limit on this item
9300 Item* tItem = GetItemOrItemWithGemEquipped(pProto->ItemId);
9301 if (tItem && (!swap || tItem->GetSlot() != eslot ) )
9302 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
9305 // check unique-equipped on gems
9306 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
9308 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
9309 if(!enchant_id)
9310 continue;
9311 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
9312 if(!enchantEntry)
9313 continue;
9315 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
9316 if(pGem && (pGem->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED))
9318 Item* tItem = GetItemOrItemWithGemEquipped(enchantEntry->GemID);
9319 if(tItem && (!swap || tItem->GetSlot() != eslot ))
9320 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
9324 // check unique-equipped special item classes
9325 if (pProto->Class == ITEM_CLASS_QUIVER)
9327 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9329 if( Item* pBag = GetItemByPos( INVENTORY_SLOT_BAG_0, i ) )
9331 if( ItemPrototype const* pBagProto = pBag->GetProto() )
9333 if( pBagProto->Class==pProto->Class && pBagProto->SubClass==pProto->SubClass &&
9334 (!swap || pBag->GetSlot() != eslot ) )
9336 if(pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9337 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH;
9338 else
9339 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9346 uint32 type = pProto->InventoryType;
9348 if(eslot == EQUIPMENT_SLOT_OFFHAND)
9350 if( type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND )
9352 if(!CanDualWield())
9353 return EQUIP_ERR_CANT_DUAL_WIELD;
9356 Item *mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );
9357 if(mainItem)
9359 if(mainItem->GetProto()->InventoryType == INVTYPE_2HWEAPON)
9360 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9364 // equip two-hand weapon case (with possible unequip 2 items)
9365 if( type == INVTYPE_2HWEAPON )
9367 if(eslot != EQUIPMENT_SLOT_MAINHAND)
9368 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9370 // offhand item must can be stored in inventitory for offhand item and it also must be unequipped
9371 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9372 ItemPosCountVec off_dest;
9373 if( offItem && (!not_loading ||
9374 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9375 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ) )
9376 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9378 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9379 return EQUIP_ERR_OK;
9382 if( !swap )
9383 return EQUIP_ERR_ITEM_NOT_FOUND;
9384 else
9385 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9388 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9390 // Applied only to equipped items and bank bags
9391 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9392 return EQUIP_ERR_OK;
9394 Item* pItem = GetItemByPos(pos);
9396 // Applied only to existed equipped item
9397 if( !pItem )
9398 return EQUIP_ERR_OK;
9400 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9402 ItemPrototype const *pProto = pItem->GetProto();
9403 if( !pProto )
9404 return EQUIP_ERR_ITEM_NOT_FOUND;
9406 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9407 // - combat
9408 // - in-progress arenas
9409 if( !pProto->CanChangeEquipStateInCombat() )
9411 if( isInCombat() )
9412 return EQUIP_ERR_NOT_IN_COMBAT;
9414 if(BattleGround* bg = GetBattleGround())
9415 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9416 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9419 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9420 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9422 return EQUIP_ERR_OK;
9425 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
9427 if( !pItem )
9428 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9430 uint32 count = pItem->GetCount();
9432 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
9433 ItemPrototype const *pProto = pItem->GetProto();
9434 if( !pProto )
9435 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9437 if( pItem->IsBindedNotWith(GetGUID()) )
9438 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9440 // check count of items (skip for auto move for same player from bank)
9441 uint8 res = CanTakeMoreSimilarItems(pItem);
9442 if(res != EQUIP_ERR_OK)
9443 return res;
9445 // in specific slot
9446 if( bag != NULL_BAG && slot != NULL_SLOT )
9448 if( pProto->InventoryType == INVTYPE_BAG )
9450 Bag *pBag = (Bag*)pItem;
9451 if( pBag )
9453 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9455 if( !HasBankBagSlot( slot ) )
9456 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
9457 if( uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK )
9458 return cantuse;
9460 else
9462 if( !pBag->IsEmpty() )
9463 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9467 else
9469 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9470 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
9473 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9474 if(res!=EQUIP_ERR_OK)
9475 return res;
9477 if(count==0)
9478 return EQUIP_ERR_OK;
9481 // not specific slot or have spece for partly store only in specific slot
9483 // in specific bag
9484 if( bag != NULL_BAG )
9486 if( pProto->InventoryType == INVTYPE_BAG )
9488 Bag *pBag = (Bag*)pItem;
9489 if( pBag && !pBag->IsEmpty() )
9490 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9493 // search stack in bag for merge to
9494 if( pProto->Stackable > 1 )
9496 if( bag == INVENTORY_SLOT_BAG_0 )
9498 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9499 if(res!=EQUIP_ERR_OK)
9500 return res;
9502 if(count==0)
9503 return EQUIP_ERR_OK;
9505 else
9507 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9508 if(res!=EQUIP_ERR_OK)
9509 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9511 if(res!=EQUIP_ERR_OK)
9512 return res;
9514 if(count==0)
9515 return EQUIP_ERR_OK;
9519 // search free slot in bag
9520 if( bag == INVENTORY_SLOT_BAG_0 )
9522 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9523 if(res!=EQUIP_ERR_OK)
9524 return res;
9526 if(count==0)
9527 return EQUIP_ERR_OK;
9529 else
9531 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9532 if(res!=EQUIP_ERR_OK)
9533 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9535 if(res!=EQUIP_ERR_OK)
9536 return res;
9538 if(count==0)
9539 return EQUIP_ERR_OK;
9543 // not specific bag or have spece for partly store only in specific bag
9545 // search stack for merge to
9546 if( pProto->Stackable > 1 )
9548 // in slots
9549 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9550 if(res!=EQUIP_ERR_OK)
9551 return res;
9553 if(count==0)
9554 return EQUIP_ERR_OK;
9556 // in special bags
9557 if( pProto->BagFamily )
9559 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9561 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9562 if(res!=EQUIP_ERR_OK)
9563 continue;
9565 if(count==0)
9566 return EQUIP_ERR_OK;
9570 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9572 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9573 if(res!=EQUIP_ERR_OK)
9574 continue;
9576 if(count==0)
9577 return EQUIP_ERR_OK;
9581 // search free place in special bag
9582 if( pProto->BagFamily )
9584 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9586 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9587 if(res!=EQUIP_ERR_OK)
9588 continue;
9590 if(count==0)
9591 return EQUIP_ERR_OK;
9595 // search free space
9596 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9597 if(res!=EQUIP_ERR_OK)
9598 return res;
9600 if(count==0)
9601 return EQUIP_ERR_OK;
9603 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9605 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9606 if(res!=EQUIP_ERR_OK)
9607 continue;
9609 if(count==0)
9610 return EQUIP_ERR_OK;
9612 return EQUIP_ERR_BANK_FULL;
9615 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
9617 if( pItem )
9619 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
9620 if( !isAlive() && not_loading )
9621 return EQUIP_ERR_YOU_ARE_DEAD;
9622 //if( isStunned() )
9623 // return EQUIP_ERR_YOU_ARE_STUNNED;
9624 ItemPrototype const *pProto = pItem->GetProto();
9625 if( pProto )
9627 if( pItem->IsBindedNotWith(GetGUID()) )
9628 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9629 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9630 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9631 if( pItem->GetSkill() != 0 )
9633 if( GetSkillValue( pItem->GetSkill() ) == 0 )
9634 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9636 if( pProto->RequiredSkill != 0 )
9638 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9639 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9640 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9641 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9643 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9644 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9645 if( pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank )
9646 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9647 if( getLevel() < pProto->RequiredLevel )
9648 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9649 return EQUIP_ERR_OK;
9652 return EQUIP_ERR_ITEM_NOT_FOUND;
9655 bool Player::CanUseItem( ItemPrototype const *pProto )
9657 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
9659 if( pProto )
9661 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9662 return false;
9663 if( pProto->RequiredSkill != 0 )
9665 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9666 return false;
9667 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9668 return false;
9670 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9671 return false;
9672 if( getLevel() < pProto->RequiredLevel )
9673 return false;
9674 return true;
9676 return false;
9679 uint8 Player::CanUseAmmo( uint32 item ) const
9681 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
9682 if( !isAlive() )
9683 return EQUIP_ERR_YOU_ARE_DEAD;
9684 //if( isStunned() )
9685 // return EQUIP_ERR_YOU_ARE_STUNNED;
9686 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
9687 if( pProto )
9689 if( pProto->InventoryType!= INVTYPE_AMMO )
9690 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
9691 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9692 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9693 if( pProto->RequiredSkill != 0 )
9695 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9696 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9697 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9698 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9700 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9701 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9702 /*if( GetReputation() < pProto->RequiredReputation )
9703 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9705 if( getLevel() < pProto->RequiredLevel )
9706 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9708 // Requires No Ammo
9709 if(GetDummyAura(46699))
9710 return EQUIP_ERR_BAG_FULL6;
9712 return EQUIP_ERR_OK;
9714 return EQUIP_ERR_ITEM_NOT_FOUND;
9717 void Player::SetAmmo( uint32 item )
9719 if(!item)
9720 return;
9722 // already set
9723 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
9724 return;
9726 // check ammo
9727 if(item)
9729 uint8 msg = CanUseAmmo( item );
9730 if( msg != EQUIP_ERR_OK )
9732 SendEquipError( msg, NULL, NULL );
9733 return;
9737 SetUInt32Value(PLAYER_AMMO_ID, item);
9739 _ApplyAmmoBonuses();
9742 void Player::RemoveAmmo()
9744 SetUInt32Value(PLAYER_AMMO_ID, 0);
9746 m_ammoDPS = 0.0f;
9748 if(CanModifyStats())
9749 UpdateDamagePhysical(RANGED_ATTACK);
9752 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
9753 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
9755 uint32 count = 0;
9756 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
9757 count += itr->count;
9759 Item *pItem = Item::CreateItem( item, count, this );
9760 if( pItem )
9762 ItemAddedQuestCheck( item, count );
9763 if(randomPropertyId)
9764 pItem->SetItemRandomProperties(randomPropertyId);
9765 pItem = StoreItem( dest, pItem, update );
9767 return pItem;
9770 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
9772 if( !pItem )
9773 return NULL;
9775 Item* lastItem = pItem;
9777 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
9779 uint16 pos = itr->pos;
9780 uint32 count = itr->count;
9782 ++itr;
9784 if(itr == dest.end())
9786 lastItem = _StoreItem(pos,pItem,count,false,update);
9787 break;
9790 lastItem = _StoreItem(pos,pItem,count,true,update);
9793 return lastItem;
9796 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
9797 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
9799 if( !pItem )
9800 return NULL;
9802 uint8 bag = pos >> 8;
9803 uint8 slot = pos & 255;
9805 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
9807 Item *pItem2 = GetItemByPos( bag, slot );
9809 if( !pItem2 )
9811 if(clone)
9812 pItem = pItem->CloneItem(count,this);
9813 else
9814 pItem->SetCount(count);
9816 if(!pItem)
9817 return NULL;
9819 if( pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
9820 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
9821 pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
9822 pItem->SetBinding( true );
9824 if( bag == INVENTORY_SLOT_BAG_0 )
9826 m_items[slot] = pItem;
9827 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
9828 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
9829 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
9831 pItem->SetSlot( slot );
9832 pItem->SetContainer( NULL );
9834 if( IsInWorld() && update )
9836 pItem->AddToWorld();
9837 pItem->SendUpdateToPlayer( this );
9840 pItem->SetState(ITEM_CHANGED, this);
9842 else
9844 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
9845 if( pBag )
9847 pBag->StoreItem( slot, pItem, update );
9848 if( IsInWorld() && update )
9850 pItem->AddToWorld();
9851 pItem->SendUpdateToPlayer( this );
9853 pItem->SetState(ITEM_CHANGED, this);
9854 pBag->SetState(ITEM_CHANGED, this);
9858 AddEnchantmentDurations(pItem);
9859 AddItemDurations(pItem);
9861 return pItem;
9863 else
9865 if( pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
9866 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
9867 pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
9868 pItem2->SetBinding( true );
9870 pItem2->SetCount( pItem2->GetCount() + count );
9871 if( IsInWorld() && update )
9872 pItem2->SendUpdateToPlayer( this );
9874 if(!clone)
9876 // delete item (it not in any slot currently)
9877 if( IsInWorld() && update )
9879 pItem->RemoveFromWorld();
9880 pItem->DestroyForPlayer( this );
9883 RemoveEnchantmentDurations(pItem);
9884 RemoveItemDurations(pItem);
9886 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
9887 pItem->SetState(ITEM_REMOVED, this);
9889 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
9890 AddEnchantmentDurations(pItem2);
9892 pItem2->SetState(ITEM_CHANGED, this);
9894 return pItem2;
9898 Item* Player::EquipNewItem( uint16 pos, uint32 item, uint32 count, bool update )
9900 Item *pItem = Item::CreateItem( item, count, this );
9901 if( pItem )
9903 ItemAddedQuestCheck( item, count );
9904 Item * retItem = EquipItem( pos, pItem, update );
9906 return retItem;
9908 return NULL;
9911 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
9913 if( pItem )
9915 AddEnchantmentDurations(pItem);
9916 AddItemDurations(pItem);
9918 uint8 bag = pos >> 8;
9919 uint8 slot = pos & 255;
9921 Item *pItem2 = GetItemByPos( bag, slot );
9923 if( !pItem2 )
9925 VisualizeItem( slot, pItem);
9927 if(isAlive())
9929 ItemPrototype const *pProto = pItem->GetProto();
9931 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
9932 if(pProto && pProto->ItemSet)
9933 AddItemsSetItem(this,pItem);
9935 _ApplyItemMods(pItem, slot, true);
9937 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
9939 m_weaponChangeTimer = DEFAULT_SWITCH_WEAPON;
9940 if (getClass() == CLASS_ROGUE)
9941 m_weaponChangeTimer = ROGUE_SWITCH_WEAPON;
9945 if( IsInWorld() && update )
9947 pItem->AddToWorld();
9948 pItem->SendUpdateToPlayer( this );
9951 ApplyEquipCooldown(pItem);
9953 if( slot == EQUIPMENT_SLOT_MAINHAND )
9954 UpdateExpertise(BASE_ATTACK);
9955 else if( slot == EQUIPMENT_SLOT_OFFHAND )
9956 UpdateExpertise(OFF_ATTACK);
9958 else
9960 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
9961 if( IsInWorld() && update )
9962 pItem2->SendUpdateToPlayer( this );
9964 // delete item (it not in any slot currently)
9965 //pItem->DeleteFromDB();
9966 if( IsInWorld() && update )
9968 pItem->RemoveFromWorld();
9969 pItem->DestroyForPlayer( this );
9972 RemoveEnchantmentDurations(pItem);
9973 RemoveItemDurations(pItem);
9975 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
9976 pItem->SetState(ITEM_REMOVED, this);
9977 pItem2->SetState(ITEM_CHANGED, this);
9979 ApplyEquipCooldown(pItem2);
9981 return pItem2;
9985 return pItem;
9988 void Player::QuickEquipItem( uint16 pos, Item *pItem)
9990 if( pItem )
9992 AddEnchantmentDurations(pItem);
9993 AddItemDurations(pItem);
9995 uint8 slot = pos & 255;
9996 VisualizeItem( slot, pItem);
9998 if( IsInWorld() )
10000 pItem->AddToWorld();
10001 pItem->SendUpdateToPlayer( this );
10006 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10008 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10009 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10010 // entry // Size: 1
10011 // inspected enchantments // Size: 6
10012 // ? // Size: 5
10013 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10014 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10015 // // = 16
10017 if(pItem)
10019 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetUInt64Value(ITEM_FIELD_CREATOR));
10021 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10022 SetUInt32Value(VisibleBase + 0, pItem->GetEntry());
10024 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10025 SetUInt32Value(VisibleBase + 1 + i, pItem->GetEnchantmentId(EnchantmentSlot(i)));
10027 // Use SetInt16Value to prevent set high part to FFFF for negative value
10028 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES + (slot * MAX_VISIBLE_ITEM_OFFSET), 0, pItem->GetItemRandomPropertyId());
10029 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetItemSuffixFactor());
10031 else
10033 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10035 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10036 SetUInt32Value(VisibleBase + 0, 0);
10038 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10039 SetUInt32Value(VisibleBase + 1 + i, 0);
10041 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 0 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10042 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10046 void Player::VisualizeItem( uint8 slot, Item *pItem)
10048 if(!pItem)
10049 return;
10051 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10052 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10053 pItem->SetBinding( true );
10055 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10057 m_items[slot] = pItem;
10058 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10059 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10060 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10061 pItem->SetSlot( slot );
10062 pItem->SetContainer( NULL );
10064 if( slot < EQUIPMENT_SLOT_END )
10065 SetVisibleItemSlot(slot,pItem);
10067 pItem->SetState(ITEM_CHANGED, this);
10070 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10072 // note: removeitem does not actually change the item
10073 // it only takes the item out of storage temporarily
10074 // note2: if removeitem is to be used for delinking
10075 // the item must be removed from the player's updatequeue
10077 Item *pItem = GetItemByPos( bag, slot );
10078 if( pItem )
10080 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10082 RemoveEnchantmentDurations(pItem);
10083 RemoveItemDurations(pItem);
10085 if( bag == INVENTORY_SLOT_BAG_0 )
10087 if ( slot < INVENTORY_SLOT_BAG_END )
10089 ItemPrototype const *pProto = pItem->GetProto();
10090 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10092 if(pProto && pProto->ItemSet)
10093 RemoveItemsSetItem(this,pProto);
10095 _ApplyItemMods(pItem, slot, false);
10097 // remove item dependent auras and casts (only weapon and armor slots)
10098 if(slot < EQUIPMENT_SLOT_END)
10099 RemoveItemDependentAurasAndCasts(pItem);
10101 // remove held enchantments
10102 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10104 if (pItem->GetItemSuffixFactor())
10106 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10107 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10109 else
10111 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10112 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10117 m_items[slot] = NULL;
10118 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10120 if ( slot < EQUIPMENT_SLOT_END )
10121 SetVisibleItemSlot(slot,NULL);
10123 else
10125 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10126 if( pBag )
10127 pBag->RemoveItem(slot, update);
10129 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10130 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10131 pItem->SetSlot( NULL_SLOT );
10132 if( IsInWorld() && update )
10133 pItem->SendUpdateToPlayer( this );
10135 if( slot == EQUIPMENT_SLOT_MAINHAND )
10136 UpdateExpertise(BASE_ATTACK);
10137 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10138 UpdateExpertise(OFF_ATTACK);
10142 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10143 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10145 if(Item* it = GetItemByPos(bag,slot))
10147 ItemRemovedQuestCheck(it->GetEntry(),it->GetCount());
10148 RemoveItem( bag,slot,update);
10149 it->RemoveFromUpdateQueueOf(this);
10150 if(it->IsInWorld())
10152 it->RemoveFromWorld();
10153 it->DestroyForPlayer( this );
10158 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10159 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10161 // update quest counters
10162 ItemAddedQuestCheck(pItem->GetEntry(),pItem->GetCount());
10164 // store item
10165 Item* pLastItem = StoreItem( dest, pItem, update);
10167 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10168 if(pLastItem==pItem)
10170 // update owner for last item (this can be original item with wrong owner
10171 if(pLastItem->GetOwnerGUID() != GetGUID())
10172 pLastItem->SetOwnerGUID(GetGUID());
10174 // if this original item then it need create record in inventory
10175 // in case trade we laready have item in other player inventory
10176 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10180 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10182 Item *pItem = GetItemByPos( bag, slot );
10183 if( pItem )
10185 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10187 // start from destroy contained items (only equipped bag can have its)
10188 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10190 for (int i = 0; i < MAX_BAG_SIZE; i++)
10191 DestroyItem(slot,i,update);
10194 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10195 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10197 ItemPrototype const *pProto = pItem->GetProto();
10199 RemoveEnchantmentDurations(pItem);
10200 RemoveItemDurations(pItem);
10202 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10204 if( bag == INVENTORY_SLOT_BAG_0 )
10207 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10209 // equipment and equipped bags can have applied bonuses
10210 if ( slot < INVENTORY_SLOT_BAG_END )
10212 ItemPrototype const *pProto = pItem->GetProto();
10214 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10215 if(pProto && pProto->ItemSet)
10216 RemoveItemsSetItem(this,pProto);
10218 _ApplyItemMods(pItem, slot, false);
10221 if ( slot < EQUIPMENT_SLOT_END )
10223 // remove item dependent auras and casts (only weapon and armor slots)
10224 RemoveItemDependentAurasAndCasts(pItem);
10226 // equipment visual show
10227 SetVisibleItemSlot(slot,NULL);
10230 m_items[slot] = NULL;
10232 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10233 pBag->RemoveItem(slot, update);
10235 if( IsInWorld() && update )
10237 pItem->RemoveFromWorld();
10238 pItem->DestroyForPlayer(this);
10241 //pItem->SetOwnerGUID(0);
10242 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10243 pItem->SetSlot( NULL_SLOT );
10244 pItem->SetState(ITEM_REMOVED, this);
10248 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10250 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10251 Item *pItem;
10252 ItemPrototype const *pProto;
10253 uint32 remcount = 0;
10255 // in inventory
10256 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10258 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10259 if( pItem && pItem->GetEntry() == item )
10261 if( pItem->GetCount() + remcount <= count )
10263 // all items in inventory can unequipped
10264 remcount += pItem->GetCount();
10265 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10267 if(remcount >=count)
10268 return;
10270 else
10272 pProto = pItem->GetProto();
10273 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10274 pItem->SetCount( pItem->GetCount() - count + remcount );
10275 if( IsInWorld() & update )
10276 pItem->SendUpdateToPlayer( this );
10277 pItem->SetState(ITEM_CHANGED, this);
10278 return;
10282 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
10284 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10285 if( pItem && pItem->GetEntry() == item )
10287 if( pItem->GetCount() + remcount <= count )
10289 // all keys can be unequipped
10290 remcount += pItem->GetCount();
10291 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10293 if(remcount >=count)
10294 return;
10296 else
10298 pProto = pItem->GetProto();
10299 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10300 pItem->SetCount( pItem->GetCount() - count + remcount );
10301 if( IsInWorld() & update )
10302 pItem->SendUpdateToPlayer( this );
10303 pItem->SetState(ITEM_CHANGED, this);
10304 return;
10309 // in inventory bags
10310 Bag *pBag;
10311 ItemPrototype const *pBagProto;
10312 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10314 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10315 if( pBag )
10317 pBagProto = pBag->GetProto();
10318 if( pBagProto )
10320 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
10322 pItem = pBag->GetItemByPos(j);
10323 if( pItem && pItem->GetEntry() == item )
10325 // all items in bags can be unequipped
10326 if( pItem->GetCount() + remcount <= count )
10328 remcount += pItem->GetCount();
10329 DestroyItem( i, j, update );
10331 if(remcount >=count)
10332 return;
10334 else
10336 pProto = pItem->GetProto();
10337 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10338 pItem->SetCount( pItem->GetCount() - count + remcount );
10339 if( IsInWorld() && update )
10340 pItem->SendUpdateToPlayer( this );
10341 pItem->SetState(ITEM_CHANGED, this);
10342 return;
10350 // in equipment and bag list
10351 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10353 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10354 if( pItem && pItem->GetEntry() == item )
10356 if( pItem->GetCount() + remcount <= count )
10358 if(!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i,false) == EQUIP_ERR_OK )
10360 remcount += pItem->GetCount();
10361 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10363 if(remcount >=count)
10364 return;
10367 else
10369 pProto = pItem->GetProto();
10370 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10371 pItem->SetCount( pItem->GetCount() - count + remcount );
10372 if( IsInWorld() & update )
10373 pItem->SendUpdateToPlayer( this );
10374 pItem->SetState(ITEM_CHANGED, this);
10375 return;
10381 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10383 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10385 // in inventory
10386 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10388 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10389 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10390 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10392 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
10394 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10395 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10396 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10399 // in inventory bags
10400 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10402 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10403 if( pBag )
10405 ItemPrototype const *pBagProto = pBag->GetProto();
10406 if( pBagProto )
10408 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
10410 Item* pItem = pBag->GetItemByPos(j);
10411 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10412 DestroyItem( i, j, update);
10418 // in equipment and bag list
10419 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10421 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10422 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10423 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10427 void Player::DestroyConjuredItems( bool update )
10429 // used when entering arena
10430 // distroys all conjured items
10431 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
10433 // in inventory
10434 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10436 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10437 if( pItem && pItem->GetProto() &&
10438 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10439 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10440 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10443 // in inventory bags
10444 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10446 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10447 if( pBag )
10449 ItemPrototype const *pBagProto = pBag->GetProto();
10450 if( pBagProto )
10452 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
10454 Item* pItem = pBag->GetItemByPos(j);
10455 if( pItem && pItem->GetProto() &&
10456 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10457 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10458 DestroyItem( i, j, update);
10464 // in equipment and bag list
10465 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10467 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10468 if( pItem && pItem->GetProto() &&
10469 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10470 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10471 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10475 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
10477 if(!pItem)
10478 return;
10480 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
10482 if( pItem->GetCount() <= count )
10484 count-= pItem->GetCount();
10486 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
10488 else
10490 ItemRemovedQuestCheck( pItem->GetEntry(), count);
10491 pItem->SetCount( pItem->GetCount() - count );
10492 count = 0;
10493 if( IsInWorld() & update )
10494 pItem->SendUpdateToPlayer( this );
10495 pItem->SetState(ITEM_CHANGED, this);
10499 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
10501 uint8 srcbag = src >> 8;
10502 uint8 srcslot = src & 255;
10504 uint8 dstbag = dst >> 8;
10505 uint8 dstslot = dst & 255;
10507 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10508 if( !pSrcItem )
10510 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10511 return;
10514 // not let split all items (can be only at cheating)
10515 if(pSrcItem->GetCount() == count)
10517 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10518 return;
10521 // not let split more existed items (can be only at cheating)
10522 if(pSrcItem->GetCount() < count)
10524 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
10525 return;
10528 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
10530 //best error message found for attempting to split while looting
10531 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10532 return;
10535 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
10536 Item *pNewItem = pSrcItem->CloneItem( count, this );
10537 if( !pNewItem )
10539 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10540 return;
10543 if( IsInventoryPos( dst ) )
10545 // change item amount before check (for unique max count check)
10546 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10548 ItemPosCountVec dest;
10549 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
10550 if( msg != EQUIP_ERR_OK )
10552 delete pNewItem;
10553 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10554 SendEquipError( msg, pSrcItem, NULL );
10555 return;
10558 if( IsInWorld() )
10559 pSrcItem->SendUpdateToPlayer( this );
10560 pSrcItem->SetState(ITEM_CHANGED, this);
10561 StoreItem( dest, pNewItem, true);
10563 else if( IsBankPos ( dst ) )
10565 // change item amount before check (for unique max count check)
10566 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10568 ItemPosCountVec dest;
10569 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
10570 if( msg != EQUIP_ERR_OK )
10572 delete pNewItem;
10573 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10574 SendEquipError( msg, pSrcItem, NULL );
10575 return;
10578 if( IsInWorld() )
10579 pSrcItem->SendUpdateToPlayer( this );
10580 pSrcItem->SetState(ITEM_CHANGED, this);
10581 BankItem( dest, pNewItem, true);
10583 else if( IsEquipmentPos ( dst ) )
10585 // change item amount before check (for unique max count check), provide space for splitted items
10586 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10588 uint16 dest;
10589 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
10590 if( msg != EQUIP_ERR_OK )
10592 delete pNewItem;
10593 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10594 SendEquipError( msg, pSrcItem, NULL );
10595 return;
10598 if( IsInWorld() )
10599 pSrcItem->SendUpdateToPlayer( this );
10600 pSrcItem->SetState(ITEM_CHANGED, this);
10601 EquipItem( dest, pNewItem, true);
10602 AutoUnequipOffhandIfNeed();
10606 void Player::SwapItem( uint16 src, uint16 dst )
10608 uint8 srcbag = src >> 8;
10609 uint8 srcslot = src & 255;
10611 uint8 dstbag = dst >> 8;
10612 uint8 dstslot = dst & 255;
10614 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10615 Item *pDstItem = GetItemByPos( dstbag, dstslot );
10617 if( !pSrcItem )
10618 return;
10620 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
10622 if(!isAlive() )
10624 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
10625 return;
10628 if(pSrcItem->m_lootGenerated) // prevent swap looting item
10630 //best error message found for attempting to swap while looting
10631 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
10632 return;
10635 // check unequip potability for equipped items and bank bags
10636 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
10638 // bags can be swapped with empty bag slots
10639 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ));
10640 if(msg != EQUIP_ERR_OK)
10642 SendEquipError( msg, pSrcItem, pDstItem );
10643 return;
10647 // prevent put equipped/bank bag in self
10648 if( IsBagPos ( src ) && srcslot == dstbag)
10650 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
10651 return;
10654 if( !pDstItem )
10656 if( IsInventoryPos( dst ) )
10658 ItemPosCountVec dest;
10659 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
10660 if( msg != EQUIP_ERR_OK )
10662 SendEquipError( msg, pSrcItem, NULL );
10663 return;
10666 RemoveItem(srcbag, srcslot, true);
10667 StoreItem( dest, pSrcItem, true);
10669 else if( IsBankPos ( dst ) )
10671 ItemPosCountVec dest;
10672 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
10673 if( msg != EQUIP_ERR_OK )
10675 SendEquipError( msg, pSrcItem, NULL );
10676 return;
10679 RemoveItem(srcbag, srcslot, true);
10680 BankItem( dest, pSrcItem, true);
10682 else if( IsEquipmentPos ( dst ) )
10684 uint16 dest;
10685 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
10686 if( msg != EQUIP_ERR_OK )
10688 SendEquipError( msg, pSrcItem, NULL );
10689 return;
10692 RemoveItem(srcbag, srcslot, true);
10693 EquipItem( dest, pSrcItem, true);
10694 AutoUnequipOffhandIfNeed();
10697 else // if (!pDstItem)
10699 if(pDstItem->m_lootGenerated) // prevent swap looting item
10701 //best error message found for attempting to swap while looting
10702 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
10703 return;
10706 // check unequip potability for equipped items and bank bags
10707 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
10709 // bags can be swapped with empty bag slots
10710 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) );
10711 if(msg != EQUIP_ERR_OK)
10713 SendEquipError( msg, pSrcItem, pDstItem );
10714 return;
10718 // attempt merge to / fill target item
10720 uint8 msg;
10721 ItemPosCountVec sDest;
10722 uint16 eDest;
10723 if( IsInventoryPos( dst ) )
10724 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
10725 else if( IsBankPos ( dst ) )
10726 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
10727 else if( IsEquipmentPos ( dst ) )
10728 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
10729 else
10730 return;
10732 // can be merge/fill
10733 if(msg == EQUIP_ERR_OK)
10735 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->Stackable )
10737 RemoveItem(srcbag, srcslot, true);
10739 if( IsInventoryPos( dst ) )
10740 StoreItem( sDest, pSrcItem, true);
10741 else if( IsBankPos ( dst ) )
10742 BankItem( sDest, pSrcItem, true);
10743 else if( IsEquipmentPos ( dst ) )
10745 EquipItem( eDest, pSrcItem, true);
10746 AutoUnequipOffhandIfNeed();
10749 else
10751 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->Stackable );
10752 pDstItem->SetCount( pSrcItem->GetProto()->Stackable );
10753 pSrcItem->SetState(ITEM_CHANGED, this);
10754 pDstItem->SetState(ITEM_CHANGED, this);
10755 if( IsInWorld() )
10757 pSrcItem->SendUpdateToPlayer( this );
10758 pDstItem->SendUpdateToPlayer( this );
10761 return;
10765 // impossible merge/fill, do real swap
10766 uint8 msg;
10768 // check src->dest move possibility
10769 ItemPosCountVec sDest;
10770 uint16 eDest;
10771 if( IsInventoryPos( dst ) )
10772 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
10773 else if( IsBankPos( dst ) )
10774 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
10775 else if( IsEquipmentPos( dst ) )
10777 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
10778 if( msg == EQUIP_ERR_OK )
10779 msg = CanUnequipItem( eDest, true );
10782 if( msg != EQUIP_ERR_OK )
10784 SendEquipError( msg, pSrcItem, pDstItem );
10785 return;
10788 // check dest->src move possibility
10789 ItemPosCountVec sDest2;
10790 uint16 eDest2;
10791 if( IsInventoryPos( src ) )
10792 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
10793 else if( IsBankPos( src ) )
10794 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
10795 else if( IsEquipmentPos( src ) )
10797 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
10798 if( msg == EQUIP_ERR_OK )
10799 msg = CanUnequipItem( eDest2, true);
10802 if( msg != EQUIP_ERR_OK )
10804 SendEquipError( msg, pDstItem, pSrcItem );
10805 return;
10808 // now do moves, remove...
10809 RemoveItem(dstbag, dstslot, false);
10810 RemoveItem(srcbag, srcslot, false);
10812 // add to dest
10813 if( IsInventoryPos( dst ) )
10814 StoreItem(sDest, pSrcItem, true);
10815 else if( IsBankPos( dst ) )
10816 BankItem(sDest, pSrcItem, true);
10817 else if( IsEquipmentPos( dst ) )
10818 EquipItem(eDest, pSrcItem, true);
10820 // add to src
10821 if( IsInventoryPos( src ) )
10822 StoreItem(sDest2, pDstItem, true);
10823 else if( IsBankPos( src ) )
10824 BankItem(sDest2, pDstItem, true);
10825 else if( IsEquipmentPos( src ) )
10826 EquipItem(eDest2, pDstItem, true);
10828 AutoUnequipOffhandIfNeed();
10832 void Player::AddItemToBuyBackSlot( Item *pItem )
10834 if( pItem )
10836 uint32 slot = m_currentBuybackSlot;
10837 // if current back slot non-empty search oldest or free
10838 if(m_items[slot])
10840 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
10841 uint32 oldest_slot = BUYBACK_SLOT_START;
10843 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
10845 // found empty
10846 if(!m_items[i])
10848 slot = i;
10849 break;
10852 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
10854 if(oldest_time > i_time)
10856 oldest_time = i_time;
10857 oldest_slot = i;
10861 // find oldest
10862 slot = oldest_slot;
10865 RemoveItemFromBuyBackSlot( slot, true );
10866 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
10868 m_items[slot] = pItem;
10869 time_t base = time(NULL);
10870 uint32 etime = uint32(base - m_logintime + (30 * 3600));
10871 uint32 eslot = slot - BUYBACK_SLOT_START;
10873 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, pItem->GetGUID() );
10874 ItemPrototype const *pProto = pItem->GetProto();
10875 if( pProto )
10876 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
10877 else
10878 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
10879 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
10881 // move to next (for non filled list is move most optimized choice)
10882 if(m_currentBuybackSlot < BUYBACK_SLOT_END-1)
10883 ++m_currentBuybackSlot;
10887 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
10889 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
10890 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
10891 return m_items[slot];
10892 return NULL;
10895 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
10897 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
10898 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
10900 Item *pItem = m_items[slot];
10901 if( pItem )
10903 pItem->RemoveFromWorld();
10904 if(del) pItem->SetState(ITEM_REMOVED, this);
10907 m_items[slot] = NULL;
10909 uint32 eslot = slot - BUYBACK_SLOT_START;
10910 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, 0 );
10911 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
10912 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
10914 // if current backslot is filled set to now free slot
10915 if(m_items[m_currentBuybackSlot])
10916 m_currentBuybackSlot = slot;
10920 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
10922 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg);
10923 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
10924 data << uint8(msg);
10926 if(msg)
10928 data << uint64(pItem ? pItem->GetGUID() : 0);
10929 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
10930 data << uint8(0); // not 0 there...
10932 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
10934 uint32 level = 0;
10936 if(pItem)
10937 if(ItemPrototype const* proto = pItem->GetProto())
10938 level = proto->RequiredLevel;
10940 data << uint32(level); // new 2.4.0
10943 GetSession()->SendPacket(&data);
10946 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
10948 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
10949 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
10950 data << uint64(pCreature ? pCreature->GetGUID() : 0);
10951 data << uint32(item);
10952 if( param > 0 )
10953 data << uint32(param);
10954 data << uint8(msg);
10955 GetSession()->SendPacket(&data);
10958 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
10960 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
10961 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
10962 data << uint64(pCreature ? pCreature->GetGUID() : 0);
10963 data << uint64(guid);
10964 if( param > 0 )
10965 data << uint32(param);
10966 data << uint8(msg);
10967 GetSession()->SendPacket(&data);
10970 void Player::ClearTrade()
10972 tradeGold = 0;
10973 acceptTrade = false;
10974 for(int i = 0; i < TRADE_SLOT_COUNT; i++)
10975 tradeItems[i] = NULL_SLOT;
10978 void Player::TradeCancel(bool sendback)
10980 if(pTrader)
10982 // send yellow "Trade cancelled" message to both traders
10983 WorldSession* ws;
10984 ws = GetSession();
10985 if(sendback)
10986 ws->SendCancelTrade();
10987 ws = pTrader->GetSession();
10988 if(!ws->PlayerLogout())
10989 ws->SendCancelTrade();
10991 // cleanup
10992 ClearTrade();
10993 pTrader->ClearTrade();
10994 // prevent loss of reference
10995 pTrader->pTrader = NULL;
10996 pTrader = NULL;
11000 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11002 if(m_itemDuration.empty())
11003 return;
11005 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time,realtimeonly);
11007 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); )
11009 Item* item = *itr;
11010 ++itr; // current element can be erased in UpdateDuration
11012 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11013 item->UpdateDuration(this,time);
11017 void Player::UpdateEnchantTime(uint32 time)
11019 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11021 assert(itr->item);
11022 next=itr;
11023 if(!itr->item->GetEnchantmentId(itr->slot))
11025 next = m_enchantDuration.erase(itr);
11027 else if(itr->leftduration <= time)
11029 ApplyEnchantment(itr->item,itr->slot,false,false);
11030 itr->item->ClearEnchantment(itr->slot);
11031 next = m_enchantDuration.erase(itr);
11033 else if(itr->leftduration > time)
11035 itr->leftduration -= time;
11036 ++next;
11041 void Player::AddEnchantmentDurations(Item *item)
11043 for(int x=0;x<MAX_ENCHANTMENT_SLOT;++x)
11045 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11046 continue;
11048 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11049 if( duration > 0 )
11050 AddEnchantmentDuration(item,EnchantmentSlot(x),duration);
11054 void Player::RemoveEnchantmentDurations(Item *item)
11056 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();)
11058 if(itr->item == item)
11060 // save duration in item
11061 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot),itr->leftduration);
11062 itr = m_enchantDuration.erase(itr);
11064 else
11065 ++itr;
11069 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11071 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11072 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11074 next = itr;
11075 if(itr->slot==slot)
11077 if(itr->item && itr->item->GetEnchantmentId(slot))
11079 // remove from stats
11080 ApplyEnchantment(itr->item,slot,false,false);
11081 // remove visual
11082 itr->item->ClearEnchantment(slot);
11084 // remove from update list
11085 next = m_enchantDuration.erase(itr);
11087 else
11088 ++next;
11091 // remove enchants from inventory items
11092 // NOTE: no need to remove these from stats, since these aren't equipped
11093 // in inventory
11094 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
11096 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11097 if( pItem && pItem->GetEnchantmentId(slot) )
11098 pItem->ClearEnchantment(slot);
11101 // in inventory bags
11102 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11104 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11105 if( pBag )
11107 ItemPrototype const *pBagProto = pBag->GetProto();
11108 if( pBagProto )
11110 for(uint32 j = 0; j < pBagProto->ContainerSlots; j++)
11112 Item* pItem = pBag->GetItemByPos(j);
11113 if( pItem && pItem->GetEnchantmentId(slot) )
11114 pItem->ClearEnchantment(slot);
11121 // duration == 0 will remove item enchant
11122 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11124 if(!item)
11125 return;
11127 if(slot >= MAX_ENCHANTMENT_SLOT)
11128 return;
11130 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11132 if(itr->item == item && itr->slot == slot)
11134 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
11135 m_enchantDuration.erase(itr);
11136 break;
11139 if(item && duration > 0 )
11141 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(),slot,uint32(duration/1000));
11142 m_enchantDuration.push_back(EnchantDuration(item,slot,duration));
11146 void Player::ApplyEnchantment(Item *item,bool apply)
11148 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11149 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11152 void Player::ApplyEnchantment(Item *item,EnchantmentSlot slot,bool apply, bool apply_dur, bool ignore_condition)
11154 if(!item)
11155 return;
11157 if(!item->IsEquipped())
11158 return;
11160 if(slot >= MAX_ENCHANTMENT_SLOT)
11161 return;
11163 uint32 enchant_id = item->GetEnchantmentId(slot);
11164 if(!enchant_id)
11165 return;
11167 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11168 if(!pEnchant)
11169 return;
11171 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11172 return;
11174 for (int s=0; s<3; s++)
11176 uint32 enchant_display_type = pEnchant->type[s];
11177 uint32 enchant_amount = pEnchant->amount[s];
11178 uint32 enchant_spell_id = pEnchant->spellid[s];
11180 switch(enchant_display_type)
11182 case ITEM_ENCHANTMENT_TYPE_NONE:
11183 break;
11184 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11185 // processed in Player::CastItemCombatSpell
11186 break;
11187 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11188 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11189 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11190 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11191 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11192 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11193 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11194 break;
11195 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11196 if(enchant_spell_id)
11198 if(apply)
11200 int32 basepoints = int32(enchant_amount);
11201 // Random Property Exist - try found basepoints for spell (basepoints depencs from item suffix factor)
11202 if (item->GetItemRandomPropertyId() !=0 && !enchant_amount)
11204 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11205 if (item_rand)
11207 // Search enchant_amount
11208 for (int k=0; k<3; k++)
11210 if(item_rand->enchant_id[k] == enchant_id)
11212 basepoints = int32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11213 break;
11218 // Cast custom spell vs all equal basepoints getted from enchant_amount
11219 if (basepoints)
11220 CastCustomSpell(this,enchant_spell_id,&basepoints,&basepoints,&basepoints,true,item);
11221 else
11222 CastSpell(this,enchant_spell_id,true,item);
11224 else
11225 RemoveAurasDueToItemSpell(item,enchant_spell_id);
11227 break;
11228 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11229 if (!enchant_amount)
11231 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11232 if(item_rand)
11234 for (int k=0; k<3; k++)
11236 if(item_rand->enchant_id[k] == enchant_id)
11238 enchant_amount = uint32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11239 break;
11245 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11246 break;
11247 case ITEM_ENCHANTMENT_TYPE_STAT:
11249 if (!enchant_amount)
11251 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11252 if(item_rand_suffix)
11254 for (int k=0; k<3; k++)
11256 if(item_rand_suffix->enchant_id[k] == enchant_id)
11258 enchant_amount = uint32((item_rand_suffix->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11259 break;
11265 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11266 switch (enchant_spell_id)
11268 case ITEM_MOD_AGILITY:
11269 sLog.outDebug("+ %u AGILITY",enchant_amount);
11270 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11271 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11272 break;
11273 case ITEM_MOD_STRENGTH:
11274 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11275 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11276 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11277 break;
11278 case ITEM_MOD_INTELLECT:
11279 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11280 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11281 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11282 break;
11283 case ITEM_MOD_SPIRIT:
11284 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11285 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11286 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11287 break;
11288 case ITEM_MOD_STAMINA:
11289 sLog.outDebug("+ %u STAMINA",enchant_amount);
11290 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11291 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11292 break;
11293 case ITEM_MOD_DEFENSE_SKILL_RATING:
11294 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11295 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11296 break;
11297 case ITEM_MOD_DODGE_RATING:
11298 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11299 sLog.outDebug("+ %u DODGE", enchant_amount);
11300 break;
11301 case ITEM_MOD_PARRY_RATING:
11302 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11303 sLog.outDebug("+ %u PARRY", enchant_amount);
11304 break;
11305 case ITEM_MOD_BLOCK_RATING:
11306 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11307 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11308 break;
11309 case ITEM_MOD_HIT_MELEE_RATING:
11310 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11311 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11312 break;
11313 case ITEM_MOD_HIT_RANGED_RATING:
11314 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11315 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11316 break;
11317 case ITEM_MOD_HIT_SPELL_RATING:
11318 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11319 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11320 break;
11321 case ITEM_MOD_CRIT_MELEE_RATING:
11322 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11323 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11324 break;
11325 case ITEM_MOD_CRIT_RANGED_RATING:
11326 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11327 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11328 break;
11329 case ITEM_MOD_CRIT_SPELL_RATING:
11330 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11331 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11332 break;
11333 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11334 // in Enchantments
11335 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11336 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11337 // break;
11338 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11339 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11340 // break;
11341 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11342 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11343 // break;
11344 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11345 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11346 // break;
11347 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11348 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11349 // break;
11350 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11351 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11352 // break;
11353 // case ITEM_MOD_HASTE_MELEE_RATING:
11354 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11355 // break;
11356 // case ITEM_MOD_HASTE_RANGED_RATING:
11357 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11358 // break;
11359 case ITEM_MOD_HASTE_SPELL_RATING:
11360 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11361 break;
11362 case ITEM_MOD_HIT_RATING:
11363 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11364 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11365 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11366 sLog.outDebug("+ %u HIT", enchant_amount);
11367 break;
11368 case ITEM_MOD_CRIT_RATING:
11369 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11370 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11371 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11372 sLog.outDebug("+ %u CRITICAL", enchant_amount);
11373 break;
11374 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11375 // case ITEM_MOD_HIT_TAKEN_RATING:
11376 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11377 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11378 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11379 // break;
11380 // case ITEM_MOD_CRIT_TAKEN_RATING:
11381 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11382 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11383 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11384 // break;
11385 case ITEM_MOD_RESILIENCE_RATING:
11386 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11387 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11388 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11389 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
11390 break;
11391 case ITEM_MOD_HASTE_RATING:
11392 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11393 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11394 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11395 sLog.outDebug("+ %u HASTE", enchant_amount);
11396 break;
11397 case ITEM_MOD_EXPERTISE_RATING:
11398 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
11399 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
11400 break;
11401 default:
11402 break;
11404 break;
11406 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
11408 if(getClass() == CLASS_SHAMAN)
11410 float addValue = 0.0f;
11411 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11413 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11414 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
11416 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
11418 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11419 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
11422 break;
11424 default:
11425 sLog.outError("Unknown item enchantment display type: %d",enchant_display_type);
11426 break;
11427 } /*switch(enchant_display_type)*/
11428 } /*for*/
11430 // visualize enchantment at player and equipped items
11431 if(slot < MAX_INSPECTED_ENCHANTMENT_SLOT)
11433 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (item->GetSlot() * MAX_VISIBLE_ITEM_OFFSET);
11434 SetUInt32Value(VisibleBase + 1 + slot, apply? item->GetEnchantmentId(slot) : 0);
11437 if(apply_dur)
11439 if(apply)
11441 // set duration
11442 uint32 duration = item->GetEnchantmentDuration(slot);
11443 if(duration > 0)
11444 AddEnchantmentDuration(item,slot,duration);
11446 else
11448 // duration == 0 will remove EnchantDuration
11449 AddEnchantmentDuration(item,slot,0);
11454 void Player::SendEnchantmentDurations()
11456 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11458 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(),itr->slot,uint32(itr->leftduration)/1000);
11462 void Player::SendItemDurations()
11464 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end();++itr)
11466 (*itr)->SendTimeUpdate(this);
11470 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
11472 if(!item) // prevent crash
11473 return;
11475 // last check 2.0.10
11476 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
11477 data << GetGUID(); // player GUID
11478 data << uint32(received); // 0=looted, 1=from npc
11479 data << uint32(created); // 0=received, 1=created
11480 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
11481 data << (uint8)item->GetBagSlot(); // bagslot
11482 // item slot, but when added to stack: 0xFFFFFFFF
11483 data << (uint32) ((item->GetCount()==count) ? item->GetSlot() : -1);
11484 data << uint32(item->GetEntry()); // item id
11485 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
11486 data << uint32(item->GetItemRandomPropertyId()); // random item property id
11487 data << uint32(count); // count of items
11488 data << GetItemCount(item->GetEntry()); // count of items in inventory
11490 if (broadcast && GetGroup())
11491 GetGroup()->BroadcastPacket(&data);
11492 else
11493 GetSession()->SendPacket(&data);
11496 /*********************************************************/
11497 /*** QUEST SYSTEM ***/
11498 /*********************************************************/
11500 void Player::PrepareQuestMenu( uint64 guid )
11502 Object *pObject;
11503 QuestRelations* pObjectQR;
11504 QuestRelations* pObjectQIR;
11505 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11506 if( pCreature )
11508 pObject = (Object*)pCreature;
11509 pObjectQR = &objmgr.mCreatureQuestRelations;
11510 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11512 else
11514 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
11515 if( pGameObject )
11517 pObject = (Object*)pGameObject;
11518 pObjectQR = &objmgr.mGOQuestRelations;
11519 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11521 else
11522 return;
11525 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
11526 qm.ClearMenu();
11528 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
11530 uint32 quest_id = i->second;
11531 QuestStatus status = GetQuestStatus( quest_id );
11532 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
11533 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11534 else if ( status == QUEST_STATUS_INCOMPLETE )
11535 qm.AddMenuItem(quest_id, DIALOG_STATUS_INCOMPLETE);
11536 else if (status == QUEST_STATUS_AVAILABLE )
11537 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
11540 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
11542 uint32 quest_id = i->second;
11543 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11544 if(!pQuest) continue;
11546 QuestStatus status = GetQuestStatus( quest_id );
11548 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
11549 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11550 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
11551 qm.AddMenuItem(quest_id, DIALOG_STATUS_AVAILABLE);
11555 void Player::SendPreparedQuest( uint64 guid )
11557 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
11558 if( questMenu.Empty() )
11559 return;
11561 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
11563 uint32 status = qmi0.m_qIcon;
11565 // single element case
11566 if ( questMenu.MenuItemCount() == 1 )
11568 // Auto open -- maybe also should verify there is no greeting
11569 uint32 quest_id = qmi0.m_qId;
11570 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11571 if ( pQuest )
11573 if( status == DIALOG_STATUS_REWARD_REP && !GetQuestRewardStatus( quest_id ) )
11574 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest,false), true );
11575 else if( status == DIALOG_STATUS_INCOMPLETE )
11576 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, false, true );
11577 // Send completable on repeatable quest if player don't have quest
11578 else if( pQuest->IsRepeatable() )
11579 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
11580 else
11581 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
11584 // multiply entries
11585 else
11587 QEmote qe;
11588 qe._Delay = 0;
11589 qe._Emote = 0;
11590 std::string title = "";
11591 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11592 if( pCreature )
11594 uint32 textid = pCreature->GetNpcTextId();
11595 GossipText * gossiptext = objmgr.GetGossipText(textid);
11596 if( !gossiptext )
11598 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
11599 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
11600 title = "";
11602 else
11604 qe = gossiptext->Options[0].Emotes[0];
11606 if(!gossiptext->Options[0].Text_0.empty())
11608 title = gossiptext->Options[0].Text_0;
11610 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
11611 if (loc_idx >= 0)
11613 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
11614 if (nl)
11616 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
11617 title = nl->Text_0[0][loc_idx];
11621 else
11623 title = gossiptext->Options[0].Text_1;
11625 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
11626 if (loc_idx >= 0)
11628 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
11629 if (nl)
11631 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
11632 title = nl->Text_1[0][loc_idx];
11638 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
11642 bool Player::IsActiveQuest( uint32 quest_id ) const
11644 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
11646 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
11649 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
11651 Object *pObject;
11652 QuestRelations* pObjectQR;
11653 QuestRelations* pObjectQIR;
11655 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11656 if( pCreature )
11658 pObject = (Object*)pCreature;
11659 pObjectQR = &objmgr.mCreatureQuestRelations;
11660 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11662 else
11664 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
11665 if( pGameObject )
11667 pObject = (Object*)pGameObject;
11668 pObjectQR = &objmgr.mGOQuestRelations;
11669 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11671 else
11672 return NULL;
11675 uint32 nextQuestID = pQuest->GetNextQuestInChain();
11676 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
11678 if (itr->second == nextQuestID)
11679 return objmgr.GetQuestTemplate(nextQuestID);
11682 return NULL;
11685 bool Player::CanSeeStartQuest( Quest const *pQuest )
11687 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
11688 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
11689 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
11690 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
11692 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
11695 return false;
11698 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
11700 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
11701 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
11702 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
11703 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
11704 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
11705 && SatisfyQuestDay( pQuest, msg );
11708 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
11710 if( !SatisfyQuestLog( msg ) )
11711 return false;
11713 uint32 srcitem = pQuest->GetSrcItemId();
11714 if( srcitem > 0 )
11716 uint32 count = pQuest->GetSrcItemCount();
11717 ItemPosCountVec dest;
11718 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
11720 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
11721 if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
11722 return true;
11723 else if( msg != EQUIP_ERR_OK )
11725 SendEquipError( msg, NULL, NULL );
11726 return false;
11729 return true;
11732 bool Player::CanCompleteQuest( uint32 quest_id )
11734 if( quest_id )
11736 QuestStatusData& q_status = mQuestStatus[quest_id];
11737 if( q_status.m_status == QUEST_STATUS_COMPLETE )
11738 return false; // not allow re-complete quest
11740 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
11742 if(!qInfo)
11743 return false;
11745 // auto complete quest
11746 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
11747 return true;
11749 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
11752 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
11754 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
11756 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
11757 return false;
11761 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
11763 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
11765 if( qInfo->ReqCreatureOrGOId[i] == 0 )
11766 continue;
11768 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
11769 return false;
11773 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
11774 return false;
11776 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
11777 return false;
11779 if ( qInfo->GetRewOrReqMoney() < 0 )
11781 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
11782 return false;
11785 uint32 repFacId = qInfo->GetRepObjectiveFaction();
11786 if ( repFacId && GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
11787 return false;
11789 return true;
11792 return false;
11795 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
11797 // Solve problem that player don't have the quest and try complete it.
11798 // if repeatable she must be able to complete event if player don't have it.
11799 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
11800 if( !CanTakeQuest(pQuest, false) )
11801 return false;
11803 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
11804 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
11805 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
11806 return false;
11808 if( !CanRewardQuest(pQuest, false) )
11809 return false;
11811 return true;
11814 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
11816 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
11817 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
11818 return false;
11820 // daily quest can't be rewarded (10 daily quest already completed)
11821 if(!SatisfyQuestDay(pQuest,true))
11822 return false;
11824 // rewarded and not repeatable quest (only cheating case, then ignore without message)
11825 if(GetQuestRewardStatus(pQuest->GetQuestId()))
11826 return false;
11828 // prevent receive reward with quest items in bank
11829 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
11831 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
11833 if( pQuest->ReqItemCount[i]!= 0 &&
11834 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
11836 if(msg)
11837 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
11838 return false;
11843 // prevent receive reward with low money and GetRewOrReqMoney() < 0
11844 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
11845 return false;
11847 return true;
11850 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
11852 // prevent receive reward with quest items in bank or for not completed quest
11853 if(!CanRewardQuest(pQuest,msg))
11854 return false;
11856 if ( pQuest->GetRewChoiceItemsCount() > 0 )
11858 if( pQuest->RewChoiceItemId[reward] )
11860 ItemPosCountVec dest;
11861 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
11862 if( res != EQUIP_ERR_OK )
11864 SendEquipError( res, NULL, NULL );
11865 return false;
11870 if ( pQuest->GetRewItemsCount() > 0 )
11872 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
11874 if( pQuest->RewItemId[i] )
11876 ItemPosCountVec dest;
11877 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
11878 if( res != EQUIP_ERR_OK )
11880 SendEquipError( res, NULL, NULL );
11881 return false;
11887 return true;
11890 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
11892 uint16 log_slot = FindQuestSlot( 0 );
11893 assert(log_slot < MAX_QUEST_LOG_SIZE);
11895 uint32 quest_id = pQuest->GetQuestId();
11897 // if not exist then created with set uState==NEW and rewarded=false
11898 QuestStatusData& questStatusData = mQuestStatus[quest_id];
11899 if (questStatusData.uState != QUEST_NEW)
11900 questStatusData.uState = QUEST_CHANGED;
11902 // check for repeatable quests status reset
11903 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
11904 questStatusData.m_explored = false;
11906 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
11908 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
11909 questStatusData.m_itemcount[i] = 0;
11912 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
11914 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
11915 questStatusData.m_creatureOrGOcount[i] = 0;
11918 GiveQuestSourceItem( pQuest );
11919 AdjustQuestReqItemCount( pQuest );
11921 if( pQuest->GetRepObjectiveFaction() )
11922 SetFactionVisibleForFactionId(pQuest->GetRepObjectiveFaction());
11924 uint32 qtime = 0;
11925 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
11927 uint32 limittime = pQuest->GetLimitTime();
11929 // shared timed quest
11930 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
11931 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / 1000;
11933 AddTimedQuest( quest_id );
11934 questStatusData.m_timer = limittime * 1000;
11935 qtime = static_cast<uint32>(time(NULL)) + limittime;
11937 else
11938 questStatusData.m_timer = 0;
11940 SetQuestSlot(log_slot, quest_id, qtime);
11942 //starting initial quest script
11943 if(questGiver && pQuest->GetQuestStartScript()!=0)
11944 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
11946 UpdateForQuestsGO();
11949 void Player::CompleteQuest( uint32 quest_id )
11951 if( quest_id )
11953 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
11955 uint16 log_slot = FindQuestSlot( quest_id );
11956 if( log_slot < MAX_QUEST_LOG_SIZE)
11957 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
11959 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
11961 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
11962 RewardQuest(qInfo,0,this,false);
11963 else
11964 SendQuestComplete( quest_id );
11969 void Player::IncompleteQuest( uint32 quest_id )
11971 if( quest_id )
11973 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
11975 uint16 log_slot = FindQuestSlot( quest_id );
11976 if( log_slot < MAX_QUEST_LOG_SIZE)
11977 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
11981 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
11983 uint32 quest_id = pQuest->GetQuestId();
11985 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; i++ )
11987 if ( pQuest->ReqItemId[i] )
11988 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
11991 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
11992 // SetTimedQuest( 0 );
11993 m_timedquests.erase(pQuest->GetQuestId());
11995 if ( pQuest->GetRewChoiceItemsCount() > 0 )
11997 if( pQuest->RewChoiceItemId[reward] )
11999 ItemPosCountVec dest;
12000 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK )
12002 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12003 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12008 if ( pQuest->GetRewItemsCount() > 0 )
12010 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12012 if( pQuest->RewItemId[i] )
12014 ItemPosCountVec dest;
12015 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK )
12017 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12018 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12024 RewardReputation( pQuest );
12026 if( pQuest->GetRewSpellCast() > 0 )
12027 CastSpell( this, pQuest->GetRewSpellCast(), true);
12028 else if( pQuest->GetRewSpell() > 0)
12029 CastSpell( this, pQuest->GetRewSpell(), true);
12031 uint16 log_slot = FindQuestSlot( quest_id );
12032 if( log_slot < MAX_QUEST_LOG_SIZE)
12033 SetQuestSlot(log_slot,0);
12035 QuestStatusData& q_status = mQuestStatus[quest_id];
12037 // Not give XP in case already completed once repeatable quest
12038 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12040 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
12041 GiveXP( XP , NULL );
12042 else
12043 ModifyMoney( int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)) );
12045 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12046 ModifyMoney( pQuest->GetRewOrReqMoney() );
12048 // honor reward
12049 if(pQuest->GetRewHonorableKills())
12050 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12052 // title reward
12053 if(pQuest->GetCharTitleId())
12055 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12056 SetFlag64(PLAYER__FIELD_KNOWN_TITLES, (uint64(1) << titleEntry->bit_index));
12059 // Send reward mail
12060 if(pQuest->GetRewMailTemplateId())
12062 MailMessageType mailType;
12063 uint32 senderGuidOrEntry;
12064 switch(questGiver->GetTypeId())
12066 case TYPEID_UNIT:
12067 mailType = MAIL_CREATURE;
12068 senderGuidOrEntry = questGiver->GetEntry();
12069 break;
12070 case TYPEID_GAMEOBJECT:
12071 mailType = MAIL_GAMEOBJECT;
12072 senderGuidOrEntry = questGiver->GetEntry();
12073 break;
12074 case TYPEID_ITEM:
12075 mailType = MAIL_ITEM;
12076 senderGuidOrEntry = questGiver->GetEntry();
12077 break;
12078 case TYPEID_PLAYER:
12079 mailType = MAIL_NORMAL;
12080 senderGuidOrEntry = questGiver->GetGUIDLow();
12081 break;
12082 default:
12083 mailType = MAIL_NORMAL;
12084 senderGuidOrEntry = GetGUIDLow();
12085 break;
12088 Loot questMailLoot;
12090 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this);
12092 // fill mail
12093 MailItemsInfo mi; // item list preparing
12095 for(size_t i = 0; mi.size() < MAX_MAIL_ITEMS && i < questMailLoot.items.size(); ++i)
12097 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12099 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12101 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12102 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12107 for(size_t i = 0; mi.size() < MAX_MAIL_ITEMS && i < questMailLoot.quest_items.size(); ++i)
12109 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i+questMailLoot.items.size(),this))
12111 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12113 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12114 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12119 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12122 if(pQuest->IsDaily())
12123 SetDailyQuestStatus(quest_id);
12125 if ( !pQuest->IsRepeatable() )
12126 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12127 else
12128 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12130 q_status.m_rewarded = true;
12132 if(announce)
12133 SendQuestReward( pQuest, XP, questGiver );
12135 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12138 void Player::FailQuest( uint32 quest_id )
12140 if( quest_id )
12142 IncompleteQuest( quest_id );
12144 uint16 log_slot = FindQuestSlot( quest_id );
12145 if( log_slot < MAX_QUEST_LOG_SIZE)
12147 SetQuestSlotTimer(log_slot, 1 );
12148 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12150 SendQuestFailed( quest_id );
12154 void Player::FailTimedQuest( uint32 quest_id )
12156 if( quest_id )
12158 QuestStatusData& q_status = mQuestStatus[quest_id];
12160 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12161 q_status.m_timer = 0;
12163 IncompleteQuest( quest_id );
12165 uint16 log_slot = FindQuestSlot( quest_id );
12166 if( log_slot < MAX_QUEST_LOG_SIZE)
12168 SetQuestSlotTimer(log_slot, 1 );
12169 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12171 SendQuestTimerFailed( quest_id );
12175 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12177 int32 zoneOrSort = qInfo->GetZoneOrSort();
12178 int32 skillOrClass = qInfo->GetSkillOrClass();
12180 // skip zone zoneOrSort and 0 case skillOrClass
12181 if( zoneOrSort >= 0 && skillOrClass == 0 )
12182 return true;
12184 int32 questSort = -zoneOrSort;
12185 uint8 reqSortClass = ClassByQuestSort(questSort);
12187 // check class sort cases in zoneOrSort
12188 if( reqSortClass != 0 && getClass() != reqSortClass)
12190 if( msg )
12191 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12192 return false;
12195 // check class
12196 if( skillOrClass < 0 )
12198 uint8 reqClass = -int32(skillOrClass);
12199 if(getClass() != reqClass)
12201 if( msg )
12202 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12203 return false;
12206 // check skill
12207 else if( skillOrClass > 0 )
12209 uint32 reqSkill = skillOrClass;
12210 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12212 if( msg )
12213 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12214 return false;
12218 return true;
12221 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12223 if( getLevel() < qInfo->GetMinLevel() )
12225 if( msg )
12226 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12227 return false;
12229 return true;
12232 bool Player::SatisfyQuestLog( bool msg )
12234 // exist free slot
12235 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12236 return true;
12238 if( msg )
12240 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12241 GetSession()->SendPacket( &data );
12242 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12244 return false;
12247 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12249 // No previous quest (might be first quest in a series)
12250 if( qInfo->prevQuests.empty())
12251 return true;
12253 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12255 uint32 prevId = abs(*iter);
12257 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12258 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12260 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12262 // If any of the positive previous quests completed, return true
12263 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12265 // skip one-from-all exclusive group
12266 if(qPrevInfo->GetExclusiveGroup() >= 0)
12267 return true;
12269 // each-from-all exclusive group ( < 0)
12270 // can be start if only all quests in prev quest exclusive group complited and rewarded
12271 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12272 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12274 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12276 for(; iter != end; ++iter)
12278 uint32 exclude_Id = iter->second;
12280 // skip checked quest id, only state of other quests in group is interesting
12281 if(exclude_Id == prevId)
12282 continue;
12284 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12286 // alternative quest from group also must be completed and rewarded(reported)
12287 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12289 if( msg )
12290 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12291 return false;
12294 return true;
12296 // If any of the negative previous quests active, return true
12297 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12298 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
12300 // skip one-from-all exclusive group
12301 if(qPrevInfo->GetExclusiveGroup() >= 0)
12302 return true;
12304 // each-from-all exclusive group ( < 0)
12305 // can be start if only all quests in prev quest exclusive group active
12306 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12307 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12309 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12311 for(; iter != end; ++iter)
12313 uint32 exclude_Id = iter->second;
12315 // skip checked quest id, only state of other quests in group is interesting
12316 if(exclude_Id == prevId)
12317 continue;
12319 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12321 // alternative quest from group also must be active
12322 if( i_exstatus == mQuestStatus.end() ||
12323 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
12324 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
12326 if( msg )
12327 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12328 return false;
12331 return true;
12336 // Has only positive prev. quests in non-rewarded state
12337 // and negative prev. quests in non-active state
12338 if( msg )
12339 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12341 return false;
12344 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
12346 uint32 reqraces = qInfo->GetRequiredRaces();
12347 if ( reqraces == 0 )
12348 return true;
12349 if( (reqraces & getRaceMask()) == 0 )
12351 if( msg )
12352 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
12353 return false;
12355 return true;
12358 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
12360 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
12361 if(fIdMin && GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
12363 if( msg )
12364 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12365 return false;
12368 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
12369 if(fIdMax && GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
12371 if( msg )
12372 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12373 return false;
12376 return true;
12379 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
12381 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
12382 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
12384 if( msg )
12385 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
12386 return false;
12388 return true;
12391 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
12393 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
12395 if( msg )
12396 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
12397 return false;
12399 return true;
12402 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
12404 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12405 if(qInfo->GetExclusiveGroup() <= 0)
12406 return true;
12408 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
12409 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
12411 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
12413 for(; iter != end; ++iter)
12415 uint32 exclude_Id = iter->second;
12417 // skip checked quest id, only state of other quests in group is interesting
12418 if(exclude_Id == qInfo->GetQuestId())
12419 continue;
12421 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12423 // alternative quest already started or completed
12424 if( i_exstatus != mQuestStatus.end()
12425 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
12427 if( msg )
12428 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12429 return false;
12432 return true;
12435 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
12437 if(!qInfo->GetNextQuestInChain())
12438 return true;
12440 // next quest in chain already started or completed
12441 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
12442 if( itr != mQuestStatus.end()
12443 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
12445 if( msg )
12446 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12447 return false;
12450 // check for all quests further up the chain
12451 // only necessary if there are quest chains with more than one quest that can be skipped
12452 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12453 return true;
12456 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
12458 // No previous quest in chain
12459 if( qInfo->prevChainQuests.empty())
12460 return true;
12462 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
12464 uint32 prevId = *iter;
12466 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12468 if( i_prevstatus != mQuestStatus.end() )
12470 // If any of the previous quests in chain active, return false
12471 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12472 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
12474 if( msg )
12475 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12476 return false;
12480 // check for all quests further down the chain
12481 // only necessary if there are quest chains with more than one quest that can be skipped
12482 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12483 // return false;
12486 // No previous quest in chain active
12487 return true;
12490 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
12492 if(!qInfo->IsDaily())
12493 return true;
12495 bool have_slot = false;
12496 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
12498 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
12499 if(qInfo->GetQuestId()==id)
12500 return false;
12502 if(!id)
12503 have_slot = true;
12506 if(!have_slot)
12508 if( msg )
12509 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
12510 return false;
12513 return true;
12516 bool Player::GiveQuestSourceItem( Quest const *pQuest )
12518 uint32 srcitem = pQuest->GetSrcItemId();
12519 if( srcitem > 0 )
12521 uint32 count = pQuest->GetSrcItemCount();
12522 if( count <= 0 )
12523 count = 1;
12525 ItemPosCountVec dest;
12526 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12527 if( msg == EQUIP_ERR_OK )
12529 Item * item = StoreNewItem(dest, srcitem, true);
12530 SendNewItem(item, count, true, false);
12531 return true;
12533 // player already have max amount required item, just report success
12534 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12535 return true;
12536 else
12537 SendEquipError( msg, NULL, NULL );
12538 return false;
12541 return true;
12544 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
12546 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12547 if( qInfo )
12549 uint32 srcitem = qInfo->GetSrcItemId();
12550 if( srcitem > 0 )
12552 uint32 count = qInfo->GetSrcItemCount();
12553 if( count <= 0 )
12554 count = 1;
12556 // exist one case when destroy source quest item not possible:
12557 // non un-equippable item (equipped non-empty bag, for example)
12558 uint8 res = CanUnequipItems(srcitem,count);
12559 if(res != EQUIP_ERR_OK)
12561 if(msg)
12562 SendEquipError( res, NULL, NULL );
12563 return false;
12566 DestroyItemCount(srcitem, count, true, true);
12569 return true;
12572 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
12574 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12575 if( qInfo )
12577 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
12578 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12579 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
12580 && !qInfo->IsRepeatable() )
12581 return itr->second.m_rewarded;
12583 return false;
12585 return false;
12588 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
12590 if( quest_id )
12592 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12593 if( itr != mQuestStatus.end() )
12594 return itr->second.m_status;
12596 return QUEST_STATUS_NONE;
12599 bool Player::CanShareQuest(uint32 quest_id) const
12601 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12602 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
12604 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12605 if( itr != mQuestStatus.end() )
12606 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
12608 return false;
12611 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
12613 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12614 if( qInfo )
12616 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
12618 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12619 m_timedquests.erase(qInfo->GetQuestId());
12622 QuestStatusData& q_status = mQuestStatus[quest_id];
12624 q_status.m_status = status;
12625 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12628 UpdateForQuestsGO();
12631 // not used in MaNGOS, but used in scripting code
12632 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
12634 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12635 if( !qInfo )
12636 return 0;
12638 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
12639 if ( qInfo->ReqCreatureOrGOId[j] == entry )
12640 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
12642 return 0;
12645 void Player::AdjustQuestReqItemCount( Quest const* pQuest )
12647 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12649 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12651 uint32 reqitemcount = pQuest->ReqItemCount[i];
12652 if( reqitemcount != 0 )
12654 uint32 quest_id = pQuest->GetQuestId();
12655 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
12657 QuestStatusData& q_status = mQuestStatus[quest_id];
12658 q_status.m_itemcount[i] = std::min(curitemcount, reqitemcount);
12659 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12665 uint16 Player::FindQuestSlot( uint32 quest_id ) const
12667 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12668 if ( GetQuestSlotQuestId(i) == quest_id )
12669 return i;
12671 return MAX_QUEST_LOG_SIZE;
12674 void Player::AreaExploredOrEventHappens( uint32 questId )
12676 if( questId )
12678 uint16 log_slot = FindQuestSlot( questId );
12679 if( log_slot < MAX_QUEST_LOG_SIZE)
12681 QuestStatusData& q_status = mQuestStatus[questId];
12683 if(!q_status.m_explored)
12685 q_status.m_explored = true;
12686 if (q_status.uState != QUEST_NEW)
12687 q_status.uState = QUEST_CHANGED;
12690 if( CanCompleteQuest( questId ) )
12691 CompleteQuest( questId );
12695 //not used in mangosd, function for external script library
12696 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
12698 if( Group *pGroup = GetGroup() )
12700 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
12702 Player *pGroupGuy = itr->getSource();
12704 // for any leave or dead (with not released body) group member at appropriate distance
12705 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
12706 pGroupGuy->AreaExploredOrEventHappens(questId);
12709 else
12710 AreaExploredOrEventHappens(questId);
12713 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
12715 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12717 uint32 questid = GetQuestSlotQuestId(i);
12718 if ( questid == 0 )
12719 continue;
12721 QuestStatusData& q_status = mQuestStatus[questid];
12723 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
12724 continue;
12726 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
12727 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12728 continue;
12730 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
12732 uint32 reqitem = qInfo->ReqItemId[j];
12733 if ( reqitem == entry )
12735 uint32 reqitemcount = qInfo->ReqItemCount[j];
12736 uint32 curitemcount = q_status.m_itemcount[j];
12737 if ( curitemcount < reqitemcount )
12739 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
12740 q_status.m_itemcount[j] += additemcount;
12741 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12743 SendQuestUpdateAddItem( qInfo, j, additemcount );
12745 if ( CanCompleteQuest( questid ) )
12746 CompleteQuest( questid );
12747 return;
12751 UpdateForQuestsGO();
12754 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
12756 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12758 uint32 questid = GetQuestSlotQuestId(i);
12759 if(!questid)
12760 continue;
12761 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
12762 if ( !qInfo )
12763 continue;
12764 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12765 continue;
12767 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
12769 uint32 reqitem = qInfo->ReqItemId[j];
12770 if ( reqitem == entry )
12772 QuestStatusData& q_status = mQuestStatus[questid];
12774 uint32 reqitemcount = qInfo->ReqItemCount[j];
12775 uint32 curitemcount;
12776 if( q_status.m_status != QUEST_STATUS_COMPLETE )
12777 curitemcount = q_status.m_itemcount[j];
12778 else
12779 curitemcount = GetItemCount(entry,true);
12780 if ( curitemcount < reqitemcount + count )
12782 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
12783 q_status.m_itemcount[j] = curitemcount - remitemcount;
12784 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12786 IncompleteQuest( questid );
12788 return;
12792 UpdateForQuestsGO();
12795 void Player::KilledMonster( uint32 entry, uint64 guid )
12797 uint32 addkillcount = 1;
12798 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12800 uint32 questid = GetQuestSlotQuestId(i);
12801 if(!questid)
12802 continue;
12804 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
12805 if( !qInfo )
12806 continue;
12807 // just if !ingroup || !noraidgroup || raidgroup
12808 QuestStatusData& q_status = mQuestStatus[questid];
12809 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
12811 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
12813 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
12815 // skip GO activate objective or none
12816 if(qInfo->ReqCreatureOrGOId[j] <=0)
12817 continue;
12819 // skip Cast at creature objective
12820 if(qInfo->ReqSpell[j] !=0 )
12821 continue;
12823 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
12825 if ( reqkill == entry )
12827 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
12828 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
12829 if ( curkillcount < reqkillcount )
12831 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
12832 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12834 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
12836 if ( CanCompleteQuest( questid ) )
12837 CompleteQuest( questid );
12839 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
12840 continue;
12848 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
12850 bool isCreature = IS_CREATURE_GUID(guid);
12852 uint32 addCastCount = 1;
12853 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12855 uint32 questid = GetQuestSlotQuestId(i);
12856 if(!questid)
12857 continue;
12859 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
12860 if ( !qInfo )
12861 continue;
12863 QuestStatusData& q_status = mQuestStatus[questid];
12865 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12867 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
12869 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
12871 // skip kill creature objective (0) or wrong spell casts
12872 if(qInfo->ReqSpell[j] != spell_id )
12873 continue;
12875 uint32 reqTarget = 0;
12877 if(isCreature)
12879 // creature activate objectives
12880 if(qInfo->ReqCreatureOrGOId[j] > 0)
12881 // checked at quest_template loading
12882 reqTarget = qInfo->ReqCreatureOrGOId[j];
12884 else
12886 // GO activate objective
12887 if(qInfo->ReqCreatureOrGOId[j] < 0)
12888 // checked at quest_template loading
12889 reqTarget = - qInfo->ReqCreatureOrGOId[j];
12892 // other not this creature/GO related objectives
12893 if( reqTarget != entry )
12894 continue;
12896 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
12897 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
12898 if ( curCastCount < reqCastCount )
12900 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
12901 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12903 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
12906 if ( CanCompleteQuest( questid ) )
12907 CompleteQuest( questid );
12909 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
12910 break;
12917 void Player::TalkedToCreature( uint32 entry, uint64 guid )
12919 uint32 addTalkCount = 1;
12920 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12922 uint32 questid = GetQuestSlotQuestId(i);
12923 if(!questid)
12924 continue;
12926 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
12927 if ( !qInfo )
12928 continue;
12930 QuestStatusData& q_status = mQuestStatus[questid];
12932 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12934 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
12936 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
12938 // skip spell casts and Gameobject objectives
12939 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
12940 continue;
12942 uint32 reqTarget = 0;
12944 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
12945 // checked at quest_template loading
12946 reqTarget = qInfo->ReqCreatureOrGOId[j];
12947 else
12948 continue;
12950 if ( reqTarget == entry )
12952 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
12953 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
12954 if ( curTalkCount < reqTalkCount )
12956 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
12957 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12959 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
12961 if ( CanCompleteQuest( questid ) )
12962 CompleteQuest( questid );
12964 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
12965 continue;
12973 void Player::MoneyChanged( uint32 count )
12975 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12977 uint32 questid = GetQuestSlotQuestId(i);
12978 if (!questid)
12979 continue;
12981 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
12982 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
12984 QuestStatusData& q_status = mQuestStatus[questid];
12986 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12988 if(int32(count) >= -qInfo->GetRewOrReqMoney())
12990 if ( CanCompleteQuest( questid ) )
12991 CompleteQuest( questid );
12994 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
12996 if(int32(count) < -qInfo->GetRewOrReqMoney())
12997 IncompleteQuest( questid );
13003 bool Player::HasQuestForItem( uint32 itemid ) const
13005 for( QuestStatusMap::const_iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
13007 QuestStatusData const& q_status = i->second;
13009 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13011 Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
13012 if(!qinfo)
13013 continue;
13015 // hide quest if player is in raid-group and quest is no raid quest
13016 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13017 continue;
13019 // There should be no mixed ReqItem/ReqSource drop
13020 // This part for ReqItem drop
13021 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13023 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13024 return true;
13026 // This part - for ReqSource
13027 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; j++)
13029 // examined item is a source item
13030 if (qinfo->ReqSourceId[j] == itemid && qinfo->ReqSourceRef[j] > 0 && qinfo->ReqSourceRef[j] <= QUEST_OBJECTIVES_COUNT)
13032 uint32 idx = qinfo->ReqSourceRef[j]-1;
13034 // total count of created ReqItems and SourceItems is less than ReqItemCount
13035 if(qinfo->ReqItemId[idx] != 0 &&
13036 q_status.m_itemcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid,true) < qinfo->ReqItemCount[idx] * qinfo->ReqSourceCount[j])
13037 return true;
13039 // total count of casted ReqCreatureOrGOs and SourceItems is less than ReqCreatureOrGOCount
13040 if (qinfo->ReqCreatureOrGOId[idx] != 0)
13042 if(q_status.m_creatureOrGOcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid,true) < qinfo->ReqCreatureOrGOCount[idx] * qinfo->ReqSourceCount[j])
13043 return true;
13045 // spell with SPELL_EFFECT_QUEST_COMPLETE or SPELL_EFFECT_SEND_EVENT (with script) case
13046 else if(qinfo->ReqSpell[idx] != 0)
13048 // not casted and need more reagents/item for use.
13049 if(!q_status.m_explored && GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13050 return true;
13056 return false;
13059 void Player::SendQuestComplete( uint32 quest_id )
13061 if( quest_id )
13063 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13064 data << quest_id;
13065 GetSession()->SendPacket( &data );
13066 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13070 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13072 uint32 questid = pQuest->GetQuestId();
13073 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13074 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4+4+pQuest->GetRewItemsCount()*8) );
13075 data << questid;
13076 data << uint32(0x03);
13078 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13080 data << XP;
13081 data << uint32(pQuest->GetRewOrReqMoney());
13083 else
13085 data << uint32(0);
13086 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13088 data << uint32(0); // new 2.3.0, HonorPoints?
13089 data << uint32( pQuest->GetRewItemsCount() ); // max is 5
13091 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
13093 if ( pQuest->RewItemId[i] > 0 )
13094 data << pQuest->RewItemId[i] << pQuest->RewItemCount[i];
13095 else
13096 data << uint32(0) << uint32(0);
13098 GetSession()->SendPacket( &data );
13100 if (pQuest->GetQuestCompleteScript() != 0)
13101 sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13104 void Player::SendQuestFailed( uint32 quest_id )
13106 if( quest_id )
13108 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4 );
13109 data << quest_id;
13110 GetSession()->SendPacket( &data );
13111 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13115 void Player::SendQuestTimerFailed( uint32 quest_id )
13117 if( quest_id )
13119 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13120 data << quest_id;
13121 GetSession()->SendPacket( &data );
13122 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13126 void Player::SendCanTakeQuestResponse( uint32 msg )
13128 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13129 data << uint32(msg);
13130 GetSession()->SendPacket( &data );
13131 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13134 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13136 if( pPlayer )
13138 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13139 data << uint64(pPlayer->GetGUID());
13140 data << uint8(msg); // valid values: 0-8
13141 GetSession()->SendPacket( &data );
13142 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13146 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13148 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, (4+4) );
13149 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13150 data << pQuest->ReqItemId[item_idx];
13151 data << count;
13152 GetSession()->SendPacket( &data );
13155 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13157 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13159 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13160 if (entry < 0)
13161 // client expected gameobject template id in form (id|0x80000000)
13162 entry = (-entry) | 0x80000000;
13164 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13165 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13166 data << uint32(pQuest->GetQuestId());
13167 data << uint32(entry);
13168 data << uint32(old_count + add_count);
13169 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13170 data << uint64(guid);
13171 GetSession()->SendPacket(&data);
13173 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13174 if( log_slot < MAX_QUEST_LOG_SIZE)
13175 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13178 /*********************************************************/
13179 /*** LOAD SYSTEM ***/
13180 /*********************************************************/
13182 bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
13184 bool delete_result = true;
13185 if(!result)
13187 // 0 1 2 3 4 5 6 7 8 9
13188 result = CharacterDatabase.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid);
13189 if(!result) return false;
13191 else delete_result = false;
13193 Field *fields = result->Fetch();
13195 if(!LoadValues( fields[1].GetString()))
13197 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
13198 if(delete_result) delete result;
13199 return false;
13202 // overwrite possible wrong/corrupted guid
13203 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13205 m_name = fields[2].GetCppString();
13207 Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
13208 SetMapId(fields[6].GetUInt32());
13209 // the instance id is not needed at character enum
13211 m_Played_time[0] = fields[7].GetUInt32();
13212 m_Played_time[1] = fields[8].GetUInt32();
13214 m_atLoginFlags = fields[9].GetUInt32();
13216 // I don't see these used anywhere ..
13217 /*_LoadGroup();
13219 _LoadBoundInstances();*/
13221 if (delete_result) delete result;
13223 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
13224 m_items[i] = NULL;
13226 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
13227 m_deathState = DEAD;
13229 return true;
13232 void Player::_LoadDeclinedNames(QueryResult* result)
13234 if(!result)
13235 return;
13237 if(m_declinedname)
13238 delete m_declinedname;
13240 m_declinedname = new DeclinedName;
13241 Field *fields = result->Fetch();
13242 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13243 m_declinedname->name[i] = fields[i].GetCppString();
13245 delete result;
13248 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
13250 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
13251 if(!result)
13252 return false;
13254 Field *fields = result->Fetch();
13256 x = fields[0].GetFloat();
13257 y = fields[1].GetFloat();
13258 z = fields[2].GetFloat();
13259 o = fields[3].GetFloat();
13260 mapid = fields[4].GetUInt32();
13261 in_flight = !fields[5].GetCppString().empty();
13263 delete result;
13264 return true;
13267 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
13269 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
13270 if( !result )
13271 return false;
13273 Field *fields = result->Fetch();
13275 data = StrSplit(fields[0].GetCppString(), " ");
13277 delete result;
13279 return true;
13282 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
13284 if(index >= data.size())
13285 return 0;
13287 return (uint32)atoi(data[index].c_str());
13290 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
13292 float result;
13293 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
13294 memcpy(&result, &temp, sizeof(result));
13296 return result;
13299 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
13301 Tokens data;
13302 if(!LoadValuesArrayFromDB(data,guid))
13303 return 0;
13305 return GetUInt32ValueFromArray(data,index);
13308 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
13310 float result;
13311 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
13312 memcpy(&result, &temp, sizeof(result));
13314 return result;
13317 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
13319 //// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 [28] [29] 30 31 32
13320 //QueryResult *result = CharacterDatabase.PQuery("SELECT guid, account, data, name, race, class, position_x, position_y, position_z, map, orientation, taximask, cinematic, totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, online, death_expire_time, taxi_path, dungeon_difficulty FROM characters WHERE guid = '%u'", guid);
13321 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
13323 if(!result)
13325 sLog.outError("ERROR: Player (GUID: %u) not found in table `characters`, can't load. ",guid);
13326 return false;
13329 Field *fields = result->Fetch();
13331 uint32 dbAccountId = fields[1].GetUInt32();
13333 // check if the character's account in the db and the logged in account match.
13334 // player should be able to load/delete character only with correct account!
13335 if( dbAccountId != GetSession()->GetAccountId() )
13337 sLog.outError("ERROR: Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
13338 delete result;
13339 return false;
13342 Object::_Create( guid, 0, HIGHGUID_PLAYER );
13344 m_name = fields[3].GetCppString();
13346 // check name limitations
13347 if(!ObjectMgr::IsValidName(m_name) || GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name))
13349 delete result;
13350 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
13351 return false;
13354 if(!LoadValues( fields[2].GetString()))
13356 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
13357 delete result;
13358 return false;
13361 // overwrite possible wrong/corrupted guid
13362 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13364 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13365 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
13367 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), 0 );
13368 SetVisibleItemSlot(slot,NULL);
13370 if (m_items[slot])
13372 delete m_items[slot];
13373 m_items[slot] = NULL;
13377 // update money limits
13378 if(GetMoney() > MAX_MONEY_AMOUNT)
13379 SetMoney(MAX_MONEY_AMOUNT);
13381 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
13382 outDebugValues();
13384 m_race = fields[4].GetUInt8();
13385 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13386 //Other way is to saves m_team into characters table.
13387 setFactionForRace(m_race);
13388 SetCharm(0);
13390 m_class = fields[5].GetUInt8();
13392 PlayerInfo const *info = objmgr.GetPlayerInfo(m_race, m_class);
13393 if(!info)
13395 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
13396 delete result;
13397 return false;
13400 InitPrimaryProffesions(); // to max set before any spell loaded
13402 uint32 transGUID = fields[24].GetUInt32();
13403 Relocate(fields[6].GetFloat(),fields[7].GetFloat(),fields[8].GetFloat(),fields[10].GetFloat());
13404 SetMapId(fields[9].GetUInt32());
13405 SetDifficulty(fields[32].GetUInt32()); // may be changed in _LoadGroup
13407 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
13409 // check arena teams integrity
13410 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
13412 uint32 arena_team_id = GetArenaTeamId(arena_slot);
13413 if(!arena_team_id)
13414 continue;
13416 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
13417 if(at->HaveMember(GetGUID()))
13418 continue;
13420 // arena team not exist or not member, cleanup fields
13421 for(int j =0; j < 6; ++j)
13422 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
13425 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
13427 if(!IsPositionValid())
13429 sLog.outError("ERROR: Player (guidlow %d) have invalid coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",guid,GetPositionX(),GetPositionY(),GetPositionZ(),GetOrientation());
13431 SetMapId(info->mapId);
13432 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
13434 transGUID = 0;
13436 m_movementInfo.t_x = 0.0f;
13437 m_movementInfo.t_y = 0.0f;
13438 m_movementInfo.t_z = 0.0f;
13439 m_movementInfo.t_o = 0.0f;
13442 // load the player's map here if it's not already loaded
13443 Map *map = GetMap();
13444 // since the player may not be bound to the map yet, make sure subsequent
13445 // getmap calls won't create new maps
13446 SetInstanceId(map->GetInstanceId());
13448 SaveRecallPosition();
13450 if (transGUID != 0)
13452 m_movementInfo.t_x = fields[20].GetFloat();
13453 m_movementInfo.t_y = fields[21].GetFloat();
13454 m_movementInfo.t_z = fields[22].GetFloat();
13455 m_movementInfo.t_o = fields[23].GetFloat();
13457 if( !MaNGOS::IsValidMapCoord(
13458 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13459 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
13460 // transport size limited
13461 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
13463 sLog.outError("ERROR: Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
13464 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13465 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
13467 SetMapId(info->mapId);
13468 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
13470 m_movementInfo.t_x = 0.0f;
13471 m_movementInfo.t_y = 0.0f;
13472 m_movementInfo.t_z = 0.0f;
13473 m_movementInfo.t_o = 0.0f;
13475 transGUID = 0;
13479 if (transGUID != 0)
13481 for (MapManager::TransportSet::iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
13483 if( (*iter)->GetGUIDLow() == transGUID)
13485 m_transport = *iter;
13486 m_transport->AddPassenger(this);
13487 SetMapId(m_transport->GetMapId());
13488 break;
13492 if(!m_transport)
13494 sLog.outError("ERROR: Player (guidlow %d) have invalid transport guid (%u). Teleport to default race/class locations.",
13495 guid,transGUID);
13497 SetMapId(info->mapId);
13498 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
13500 m_movementInfo.t_x = 0.0f;
13501 m_movementInfo.t_y = 0.0f;
13502 m_movementInfo.t_z = 0.0f;
13503 m_movementInfo.t_o = 0.0f;
13505 transGUID = 0;
13509 time_t now = time(NULL);
13510 time_t logoutTime = time_t(fields[16].GetUInt64());
13512 // since last logout (in seconds)
13513 uint64 time_diff = uint64(now - logoutTime);
13515 // set value, including drunk invisibility detection
13516 // calculate sobering. after 15 minutes logged out, the player will be sober again
13517 float soberFactor;
13518 if(time_diff > 15*MINUTE)
13519 soberFactor = 0;
13520 else
13521 soberFactor = 1-time_diff/(15.0f*MINUTE);
13522 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
13523 SetDrunkValue(newDrunkenValue);
13525 m_rest_bonus = fields[15].GetFloat();
13526 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
13527 float bubble0 = 0.031;
13528 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
13529 float bubble1 = 0.125;
13531 if((int32)fields[16].GetUInt32() > 0)
13533 float bubble = fields[17].GetUInt32() > 0
13534 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
13535 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
13537 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
13540 m_cinematic = fields[12].GetUInt32();
13541 m_Played_time[0]= fields[13].GetUInt32();
13542 m_Played_time[1]= fields[14].GetUInt32();
13544 m_resetTalentsCost = fields[18].GetUInt32();
13545 m_resetTalentsTime = time_t(fields[19].GetUInt64());
13547 // reserve some flags
13548 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
13550 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
13551 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
13553 m_taxi.LoadTaxiMask( fields[11].GetString() ); // must be before InitTaxiNodesForLevel
13555 uint32 extraflags = fields[25].GetUInt32();
13557 m_stableSlots = fields[26].GetUInt32();
13558 if(m_stableSlots > 2)
13560 sLog.outError("Player can have not more 2 stable slots, but have in DB %u",uint32(m_stableSlots));
13561 m_stableSlots = 2;
13564 m_atLoginFlags = fields[27].GetUInt32();
13566 // Honor system
13567 // Update Honor kills data
13568 m_lastHonorUpdateTime = logoutTime;
13569 UpdateHonorFields();
13571 m_deathExpireTime = (time_t)fields[30].GetUInt64();
13572 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
13573 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
13575 std::string taxi_nodes = fields[31].GetCppString();
13577 delete result;
13579 // clear channel spell data (if saved at channel spell casting)
13580 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
13581 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
13583 // clear charm/summon related fields
13584 SetUInt64Value(UNIT_FIELD_CHARM,0);
13585 SetUInt64Value(UNIT_FIELD_SUMMON,0);
13586 SetUInt64Value(UNIT_FIELD_CHARMEDBY,0);
13587 SetUInt64Value(UNIT_FIELD_SUMMONEDBY,0);
13588 SetUInt64Value(UNIT_FIELD_CREATEDBY,0);
13590 // reset some aura modifiers before aura apply
13591 SetUInt64Value(PLAYER_FARSIGHT, 0);
13592 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
13593 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
13595 // reset skill modifiers and set correct unlearn flags
13596 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; i++)
13598 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
13600 // set correct unlearn bit
13601 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
13602 if(!id) continue;
13604 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
13605 if(!pSkill) continue;
13607 // enable unlearn button for primary professions only
13608 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
13609 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
13610 else
13611 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
13614 // make sure the unit is considered out of combat for proper loading
13615 ClearInCombat();
13617 // make sure the unit is considered not in duel for proper loading
13618 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
13619 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
13621 // remember loaded power/health values to restore after stats initialization and modifier applying
13622 uint32 savedHealth = GetHealth();
13623 uint32 savedPower[MAX_POWERS];
13624 for(uint32 i = 0; i < MAX_POWERS; ++i)
13625 savedPower[i] = GetPower(Powers(i));
13627 // reset stats before loading any modifiers
13628 InitStatsForLevel();
13629 InitTaxiNodesForLevel();
13631 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
13633 //mails are loaded only when needed ;-) - when player in game click on mailbox.
13634 //_LoadMail();
13636 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
13638 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
13639 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
13640 m_deathState = DEAD;
13642 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
13644 // after spell load
13645 InitTalentForLevel();
13646 learnSkillRewardedSpells();
13648 // after spell load, learn rewarded spell if need also
13649 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
13650 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
13652 _LoadTutorials(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS));
13654 // must be before inventory (some items required reputation check)
13655 _LoadReputation(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
13657 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
13659 // update items with duration and realtime
13660 UpdateItemDuration(time_diff, true);
13662 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
13664 // unread mails and next delivery time, actual mails not loaded
13665 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
13667 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
13669 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
13670 return false;
13672 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
13673 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
13674 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
13676 if(!HasFlag64(PLAYER__FIELD_KNOWN_TITLES,uint64(1) << curTitle))
13677 SetUInt32Value(PLAYER_CHOSEN_TITLE,0);
13680 // Not finish taxi flight path
13681 if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes))
13683 // problems with taxi path loading
13684 TaxiNodesEntry const* nodeEntry = NULL;
13685 if(uint32 node_id = m_taxi.GetTaxiSource())
13686 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
13688 if(!nodeEntry) // don't know taxi start node, to homebind
13690 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
13691 SetMapId(m_homebindMapId);
13692 Relocate( m_homebindX, m_homebindY, m_homebindZ,0.0f);
13693 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
13695 else // have start node, to it
13697 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
13698 SetMapId(nodeEntry->map_id);
13699 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
13700 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
13702 m_taxi.ClearTaxiDestinations();
13704 else if(uint32 node_id = m_taxi.GetTaxiSource())
13706 // save source node as recall coord to prevent recall and fall from sky
13707 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
13708 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
13709 m_recallMap = nodeEntry->map_id;
13710 m_recallX = nodeEntry->x;
13711 m_recallY = nodeEntry->y;
13712 m_recallZ = nodeEntry->z;
13714 // flight will started later
13717 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
13719 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
13720 // Do now before stats re-calculation cleanup for ghost state unexpected auras
13721 if(!isAlive())
13722 RemoveAllAurasOnDeath();
13724 //apply all stat bonuses from items and auras
13725 SetCanModifyStats(true);
13726 UpdateAllStats();
13728 // restore remembered power/health values (but not more max values)
13729 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
13730 for(uint32 i = 0; i < MAX_POWERS; ++i)
13731 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
13733 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
13734 outDebugValues();
13736 // GM state
13737 if(GetSession()->GetSecurity() > SEC_PLAYER)
13739 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
13741 default:
13742 case 0: break; // disable
13743 case 1: SetGameMaster(true); break; // enable
13744 case 2: // save state
13745 if(extraflags & PLAYER_EXTRA_GM_ON)
13746 SetGameMaster(true);
13747 break;
13750 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
13752 default:
13753 case 0: break; // disable
13754 case 1: SetAcceptTicket(true); break; // enable
13755 case 2: // save state
13756 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
13757 SetAcceptTicket(true);
13758 break;
13761 switch(sWorld.getConfig(CONFIG_GM_CHAT))
13763 default:
13764 case 0: break; // disable
13765 case 1: SetGMChat(true); break; // enable
13766 case 2: // save state
13767 if(extraflags & PLAYER_EXTRA_GM_CHAT)
13768 SetGMChat(true);
13769 break;
13772 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
13774 default:
13775 case 0: break; // disable
13776 case 1: SetAcceptWhispers(true); break; // enable
13777 case 2: // save state
13778 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
13779 SetAcceptWhispers(true);
13780 break;
13784 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
13786 return true;
13789 bool Player::isAllowedToLoot(Creature* creature)
13791 if(Player* recipient = creature->GetLootRecipient())
13793 if (recipient == this)
13794 return true;
13795 if( Group* otherGroup = recipient->GetGroup())
13797 Group* thisGroup = GetGroup();
13798 if(!thisGroup)
13799 return false;
13800 return thisGroup == otherGroup;
13802 return false;
13804 else
13805 // prevent other players from looting if the recipient got disconnected
13806 return !creature->hasLootRecipient();
13809 void Player::_LoadActions(QueryResult *result)
13811 m_actionButtons.clear();
13813 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
13815 if(result)
13819 Field *fields = result->Fetch();
13821 uint8 button = fields[0].GetUInt8();
13823 addActionButton(button, fields[1].GetUInt16(), fields[2].GetUInt8(), fields[3].GetUInt8());
13825 m_actionButtons[button].uState = ACTIONBUTTON_UNCHANGED;
13827 while( result->NextRow() );
13829 delete result;
13833 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
13835 m_Auras.clear();
13836 for (int i = 0; i < TOTAL_AURAS; i++)
13837 m_modAuras[i].clear();
13839 // all aura related fields
13840 for(int i = UNIT_FIELD_AURA; i <= UNIT_FIELD_AURASTATE; ++i)
13841 SetUInt32Value(i, 0);
13843 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
13845 if(result)
13849 Field *fields = result->Fetch();
13850 uint64 caster_guid = fields[0].GetUInt64();
13851 uint32 spellid = fields[1].GetUInt32();
13852 uint32 effindex = fields[2].GetUInt32();
13853 int32 damage = (int32)fields[3].GetUInt32();
13854 int32 maxduration = (int32)fields[4].GetUInt32();
13855 int32 remaintime = (int32)fields[5].GetUInt32();
13856 int32 remaincharges = (int32)fields[6].GetUInt32();
13858 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
13859 if(!spellproto)
13861 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
13862 continue;
13865 if(effindex >= 3)
13867 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
13868 continue;
13871 // negative effects should continue counting down after logout
13872 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
13874 if(remaintime <= int32(timediff))
13875 continue;
13877 remaintime -= timediff;
13880 // prevent wrong values of remaincharges
13881 if(spellproto->procCharges)
13883 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
13884 remaincharges = spellproto->procCharges;
13886 else
13887 remaincharges = -1;
13889 //do not load single target auras (unless they were cast by the player)
13890 if (caster_guid != GetGUID() && IsSingleTargetSpell(spellproto))
13891 continue;
13893 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
13894 if(!damage)
13895 damage = aura->GetModifier()->m_amount;
13896 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
13897 AddAura(aura);
13899 while( result->NextRow() );
13901 delete result;
13904 if(m_class == CLASS_WARRIOR)
13905 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
13908 void Player::LoadCorpse()
13910 if( isAlive() )
13912 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
13914 else
13916 if(Corpse *corpse = GetCorpse())
13918 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
13920 else
13922 //Prevent Dead Player login without corpse
13923 ResurrectPlayer(0.5f);
13928 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
13930 //QueryResult *result = CharacterDatabase.PQuery("SELECT data,bag,slot,item,item_template FROM character_inventory JOIN item_instance ON character_inventory.item = item_instance.guid WHERE character_inventory.guid = '%u' ORDER BY bag,slot", GetGUIDLow());
13931 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
13932 //NOTE: the "order by `bag`" is important because it makes sure
13933 //the bagMap is filled before items in the bags are loaded
13934 //NOTE2: the "order by `slot`" is needed becaue mainhand weapons are (wrongly?)
13935 //expected to be equipped before offhand items (TODO: fixme)
13937 uint32 zone = GetZoneId();
13939 if (result)
13941 std::list<Item*> problematicItems;
13943 // prevent items from being added to the queue when stored
13944 m_itemUpdateQueueBlocked = true;
13947 Field *fields = result->Fetch();
13948 uint32 bag_guid = fields[1].GetUInt32();
13949 uint8 slot = fields[2].GetUInt8();
13950 uint32 item_guid = fields[3].GetUInt32();
13951 uint32 item_id = fields[4].GetUInt32();
13953 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
13955 if(!proto)
13957 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
13958 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
13959 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
13960 continue;
13963 Item *item = NewItemOrBag(proto);
13965 if(!item->LoadFromDB(item_guid, GetGUID(), result))
13967 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
13968 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
13969 item->FSetState(ITEM_REMOVED);
13970 item->SaveToDB(); // it also deletes item object !
13971 continue;
13974 // not allow have in alive state item limited to another map/zone
13975 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
13977 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
13978 item->FSetState(ITEM_REMOVED);
13979 item->SaveToDB(); // it also deletes item object !
13980 continue;
13983 // "Conjured items disappear if you are logged out for more than 15 minutes"
13984 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
13986 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
13987 item->FSetState(ITEM_REMOVED);
13988 item->SaveToDB(); // it also deletes item object !
13989 continue;
13992 bool success = true;
13994 if (!bag_guid)
13996 // the item is not in a bag
13997 item->SetContainer( NULL );
13998 item->SetSlot(slot);
14000 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14002 ItemPosCountVec dest;
14003 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14004 item = StoreItem(dest, item, true);
14005 else
14006 success = false;
14008 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14010 uint16 dest;
14011 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14012 QuickEquipItem(dest, item);
14013 else
14014 success = false;
14016 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14018 ItemPosCountVec dest;
14019 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14020 item = BankItem(dest, item, true);
14021 else
14022 success = false;
14025 if(success)
14027 // store bags that may contain items in them
14028 if(item->IsBag() && IsBagPos(item->GetPos()))
14029 bagMap[item_guid] = (Bag*)item;
14032 else
14034 item->SetSlot(NULL_SLOT);
14035 // the item is in a bag, find the bag
14036 std::map<uint64, Bag*>::iterator itr = bagMap.find(bag_guid);
14037 if(itr != bagMap.end())
14038 itr->second->StoreItem(slot, item, true );
14039 else
14040 success = false;
14043 // item's state may have changed after stored
14044 if (success)
14045 item->SetState(ITEM_UNCHANGED, this);
14046 else
14048 sLog.outError("Player::_LoadInventory: Player %s has item (GUID: %u Entry: %u) can't be loaded to inventory (Bag GUID: %u Slot: %u) by some reason, will send by mail.", GetName(),item_guid, item_id, bag_guid, slot);
14049 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14050 problematicItems.push_back(item);
14052 } while (result->NextRow());
14054 delete result;
14055 m_itemUpdateQueueBlocked = false;
14057 // send by mail problematic items
14058 while(!problematicItems.empty())
14060 // fill mail
14061 MailItemsInfo mi; // item list prepering
14063 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14065 Item* item = problematicItems.front();
14066 problematicItems.pop_front();
14068 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14071 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14073 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14076 //if(isAlive())
14077 _ApplyAllItemMods();
14080 // load mailed item which should receive current player
14081 void Player::_LoadMailedItems(Mail *mail)
14083 QueryResult* result = CharacterDatabase.PQuery("SELECT item_guid, item_template FROM mail_items WHERE mail_id='%u'", mail->messageID);
14084 if(!result)
14085 return;
14089 Field *fields = result->Fetch();
14090 uint32 item_guid_low = fields[0].GetUInt32();
14091 uint32 item_template = fields[1].GetUInt32();
14093 mail->AddItem(item_guid_low, item_template);
14095 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
14097 if(!proto)
14099 sLog.outError( "Player %u have unknown item_template (ProtoType) in mailed items(GUID: %u template: %u) in mail (%u), deleted.", GetGUIDLow(), item_guid_low, item_template,mail->messageID);
14100 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14101 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
14102 continue;
14105 Item *item = NewItemOrBag(proto);
14107 if(!item->LoadFromDB(item_guid_low, 0))
14109 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
14110 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14111 item->FSetState(ITEM_REMOVED);
14112 item->SaveToDB(); // it also deletes item object !
14113 continue;
14116 AddMItem(item);
14117 } while (result->NextRow());
14119 delete result;
14122 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
14124 //set a count of unread mails
14125 //QueryResult *resultMails = CharacterDatabase.PQuery("SELECT COUNT(id) FROM mail WHERE receiver = '%u' AND (checked & 1)=0 AND deliver_time <= '" I64FMTD "'", GUID_LOPART(playerGuid),(uint64)cTime);
14126 if (resultUnread)
14128 Field *fieldMail = resultUnread->Fetch();
14129 unReadMails = fieldMail[0].GetUInt8();
14130 delete resultUnread;
14133 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14134 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14135 if (resultDelivery)
14137 Field *fieldMail = resultDelivery->Fetch();
14138 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
14139 delete resultDelivery;
14143 void Player::_LoadMail()
14145 m_mail.clear();
14146 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14147 QueryResult *result = CharacterDatabase.PQuery("SELECT id,messageType,sender,receiver,subject,itemTextId,has_items,expire_time,deliver_time,money,cod,checked,stationery,mailTemplateId FROM mail WHERE receiver = '%u' ORDER BY id DESC",GetGUIDLow());
14148 if(result)
14152 Field *fields = result->Fetch();
14153 Mail *m = new Mail;
14154 m->messageID = fields[0].GetUInt32();
14155 m->messageType = fields[1].GetUInt8();
14156 m->sender = fields[2].GetUInt32();
14157 m->receiver = fields[3].GetUInt32();
14158 m->subject = fields[4].GetCppString();
14159 m->itemTextId = fields[5].GetUInt32();
14160 bool has_items = fields[6].GetBool();
14161 m->expire_time = (time_t)fields[7].GetUInt64();
14162 m->deliver_time = (time_t)fields[8].GetUInt64();
14163 m->money = fields[9].GetUInt32();
14164 m->COD = fields[10].GetUInt32();
14165 m->checked = fields[11].GetUInt32();
14166 m->stationery = fields[12].GetUInt8();
14167 m->mailTemplateId = fields[13].GetInt16();
14169 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
14171 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
14172 m->mailTemplateId = 0;
14175 m->state = MAIL_STATE_UNCHANGED;
14177 if (has_items)
14178 _LoadMailedItems(m);
14180 m_mail.push_back(m);
14181 } while( result->NextRow() );
14182 delete result;
14184 m_mailsLoaded = true;
14187 void Player::LoadPet()
14189 //fixme: the pet should still be loaded if the player is not in world
14190 // just not added to the map
14191 if(IsInWorld())
14193 Pet *pet = new Pet;
14194 if(!pet->LoadPetFromDB(this,0,0,true))
14195 delete pet;
14199 void Player::_LoadQuestStatus(QueryResult *result)
14201 mQuestStatus.clear();
14203 uint32 slot = 0;
14205 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14206 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest, status, rewarded, explored, timer, mobcount1, mobcount2, mobcount3, mobcount4, itemcount1, itemcount2, itemcount3, itemcount4 FROM character_queststatus WHERE guid = '%u'", GetGUIDLow());
14208 if(result)
14212 Field *fields = result->Fetch();
14214 uint32 quest_id = fields[0].GetUInt32();
14215 // used to be new, no delete?
14216 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14217 if( pQuest )
14219 // find or create
14220 QuestStatusData& questStatusData = mQuestStatus[quest_id];
14222 uint32 qstatus = fields[1].GetUInt32();
14223 if(qstatus < MAX_QUEST_STATUS)
14224 questStatusData.m_status = QuestStatus(qstatus);
14225 else
14227 questStatusData.m_status = QUEST_STATUS_NONE;
14228 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
14231 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
14232 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
14234 time_t quest_time = time_t(fields[4].GetUInt64());
14236 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
14238 AddTimedQuest( quest_id );
14240 if (quest_time <= sWorld.GetGameTime())
14241 questStatusData.m_timer = 1;
14242 else
14243 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * 1000;
14245 else
14246 quest_time = 0;
14248 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
14249 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
14250 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
14251 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
14252 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
14253 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
14254 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
14255 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
14257 questStatusData.uState = QUEST_UNCHANGED;
14259 // add to quest log
14260 if( slot < MAX_QUEST_LOG_SIZE &&
14261 ( questStatusData.m_status==QUEST_STATUS_INCOMPLETE ||
14262 questStatusData.m_status==QUEST_STATUS_COMPLETE && !questStatusData.m_rewarded ) )
14264 SetQuestSlot(slot,quest_id,quest_time);
14266 if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
14267 SetQuestSlotState(slot,QUEST_STATE_COMPLETE);
14269 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
14270 if(questStatusData.m_creatureOrGOcount[idx])
14271 SetQuestSlotCounter(slot,idx,questStatusData.m_creatureOrGOcount[idx]);
14273 ++slot;
14276 if(questStatusData.m_rewarded)
14278 // learn rewarded spell if unknown
14279 learnQuestRewardedSpells(pQuest);
14281 // set rewarded title if any
14282 if(pQuest->GetCharTitleId())
14284 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
14285 SetFlag64(PLAYER__FIELD_KNOWN_TITLES, (uint64(1) << titleEntry->bit_index));
14289 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
14292 while( result->NextRow() );
14294 delete result;
14297 // clear quest log tail
14298 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
14299 SetQuestSlot(i,0);
14302 void Player::_LoadDailyQuestStatus(QueryResult *result)
14304 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
14305 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
14307 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14309 if(result)
14311 uint32 quest_daily_idx = 0;
14315 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
14317 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
14318 break;
14321 Field *fields = result->Fetch();
14323 uint32 quest_id = fields[0].GetUInt32();
14325 // save _any_ from daily quest times (it must be after last reset anyway)
14326 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
14328 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14329 if( !pQuest )
14330 continue;
14332 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
14333 ++quest_daily_idx;
14335 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
14337 while( result->NextRow() );
14339 delete result;
14342 m_DailyQuestChanged = false;
14345 void Player::_LoadReputation(QueryResult *result)
14347 m_factions.clear();
14349 // Set initial reputations (so everything is nifty before DB data load)
14350 SetInitialFactions();
14352 //QueryResult *result = CharacterDatabase.PQuery("SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'",GetGUIDLow());
14354 if(result)
14358 Field *fields = result->Fetch();
14360 FactionEntry const *factionEntry = sFactionStore.LookupEntry(fields[0].GetUInt32());
14361 if( factionEntry && (factionEntry->reputationListID >= 0))
14363 FactionState* faction = &m_factions[factionEntry->reputationListID];
14365 // update standing to current
14366 faction->Standing = int32(fields[1].GetUInt32());
14368 uint32 dbFactionFlags = fields[2].GetUInt32();
14370 if( dbFactionFlags & FACTION_FLAG_VISIBLE )
14371 SetFactionVisible(faction); // have internal checks for forced invisibility
14373 if( dbFactionFlags & FACTION_FLAG_INACTIVE)
14374 SetFactionInactive(faction,true); // have internal checks for visibility requirement
14376 if( dbFactionFlags & FACTION_FLAG_AT_WAR ) // DB at war
14377 SetFactionAtWar(faction,true); // have internal checks for FACTION_FLAG_PEACE_FORCED
14378 else // DB not at war
14380 // allow remove if visible (and then not FACTION_FLAG_INVISIBLE_FORCED or FACTION_FLAG_HIDDEN)
14381 if( faction->Flags & FACTION_FLAG_VISIBLE )
14382 SetFactionAtWar(faction,false); // have internal checks for FACTION_FLAG_PEACE_FORCED
14385 // set atWar for hostile
14386 if(GetReputationRank(factionEntry) <= REP_HOSTILE)
14387 SetFactionAtWar(faction,true);
14389 // reset changed flag if values similar to saved in DB
14390 if(faction->Flags==dbFactionFlags)
14391 faction->Changed = false;
14394 while( result->NextRow() );
14396 delete result;
14400 void Player::_LoadSpells(QueryResult *result)
14402 for (PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
14403 delete itr->second;
14404 m_spells.clear();
14406 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,slot,active FROM character_spell WHERE guid = '%u'",GetGUIDLow());
14408 if(result)
14412 Field *fields = result->Fetch();
14414 addSpell(fields[0].GetUInt16(), fields[2].GetBool(), false, true, fields[1].GetUInt16(), fields[3].GetBool());
14416 while( result->NextRow() );
14418 delete result;
14422 void Player::_LoadTutorials(QueryResult *result)
14424 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
14426 if(result)
14430 Field *fields = result->Fetch();
14432 for (int iI=0; iI<8; iI++)
14433 m_Tutorials[iI] = fields[iI].GetUInt32();
14435 while( result->NextRow() );
14437 delete result;
14440 m_TutorialsChanged = false;
14443 void Player::_LoadGroup(QueryResult *result)
14445 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
14446 if(result)
14448 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
14449 delete result;
14450 Group* group = objmgr.GetGroupByLeader(leaderGuid);
14451 if(group)
14453 uint8 subgroup = group->GetMemberGroup(GetGUID());
14454 SetGroup(group, subgroup);
14455 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
14457 // the group leader may change the instance difficulty while the player is offline
14458 SetDifficulty(group->GetDifficulty());
14464 void Player::_LoadBoundInstances(QueryResult *result)
14466 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14467 m_boundInstances[i].clear();
14469 Group *group = GetGroup();
14471 //QueryResult *result = CharacterDatabase.PQuery("SELECT id, permanent, map, difficulty, resettime FROM character_instance LEFT JOIN instance ON instance = id WHERE guid = '%u'", GUID_LOPART(m_guid));
14472 if(result)
14476 Field *fields = result->Fetch();
14477 bool perm = fields[1].GetBool();
14478 uint32 mapId = fields[2].GetUInt32();
14479 uint32 instanceId = fields[0].GetUInt32();
14480 uint8 difficulty = fields[3].GetUInt8();
14481 time_t resetTime = (time_t)fields[4].GetUInt64();
14482 // the resettime for normal instances is only saved when the InstanceSave is unloaded
14483 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
14484 // and in that case it is not used
14486 if(!perm && group)
14488 sLog.outError("_LoadBoundInstances: player %s(%d) is in group %d but has a non-permanent character bind to map %d,%d,%d", GetName(), GetGUIDLow(), GUID_LOPART(group->GetLeaderGUID()), mapId, instanceId, difficulty);
14489 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
14490 continue;
14493 // since non permanent binds are always solo bind, they can always be reset
14494 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
14495 if(save) BindToInstance(save, perm, true);
14496 } while(result->NextRow());
14497 delete result;
14501 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
14503 // some instances only have one difficulty
14504 const MapEntry* entry = sMapStore.LookupEntry(mapid);
14505 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
14507 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
14508 if(itr != m_boundInstances[difficulty].end())
14509 return &itr->second;
14510 else
14511 return NULL;
14514 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
14516 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
14517 UnbindInstance(itr, difficulty, unload);
14520 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
14522 if(itr != m_boundInstances[difficulty].end())
14524 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
14525 itr->second.save->RemovePlayer(this); // save can become invalid
14526 m_boundInstances[difficulty].erase(itr++);
14530 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
14532 if(save)
14534 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
14535 if(bind.save)
14537 // update the save when the group kills a boss
14538 if(permanent != bind.perm || save != bind.save)
14539 if(!load) CharacterDatabase.PExecute("UPDATE character_instance SET instance = '%u', permanent = '%u' WHERE guid = '%u' AND instance = '%u'", save->GetInstanceId(), permanent, GetGUIDLow(), bind.save->GetInstanceId());
14541 else
14542 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
14544 if(bind.save != save)
14546 if(bind.save) bind.save->RemovePlayer(this);
14547 save->AddPlayer(this);
14550 if(permanent) save->SetCanReset(false);
14552 bind.save = save;
14553 bind.perm = permanent;
14554 if(!load) sLog.outDebug("Player::BindToInstance: %s(%d) is now bound to map %d, instance %d, difficulty %d", GetName(), GetGUIDLow(), save->GetMapId(), save->GetInstanceId(), save->GetDifficulty());
14555 return &bind;
14557 else
14558 return NULL;
14561 void Player::SendRaidInfo()
14563 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
14565 uint32 counter = 0, i;
14566 for(i = 0; i < TOTAL_DIFFICULTIES; i++)
14567 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); itr++)
14568 if(itr->second.perm) counter++;
14570 data << counter;
14571 for(i = 0; i < TOTAL_DIFFICULTIES; i++)
14573 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); itr++)
14575 if(itr->second.perm)
14577 InstanceSave *save = itr->second.save;
14578 data << (save->GetMapId());
14579 data << (uint32)(save->GetResetTime() - time(NULL));
14580 data << save->GetInstanceId();
14581 data << uint32(counter);
14582 counter--;
14586 GetSession()->SendPacket(&data);
14590 - called on every successful teleportation to a map
14592 void Player::SendSavedInstances()
14594 bool hasBeenSaved = false;
14595 WorldPacket data;
14597 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14599 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
14601 if(itr->second.perm) // only permanent binds are sent
14603 hasBeenSaved = true;
14604 break;
14609 //Send opcode 811. true or flase means, whether you have current raid/heroic instances
14610 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
14611 data << uint32(hasBeenSaved);
14612 GetSession()->SendPacket(&data);
14614 if(!hasBeenSaved)
14615 return;
14617 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14619 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
14621 if(itr->second.perm)
14623 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
14624 data << uint32(itr->second.save->GetMapId());
14625 GetSession()->SendPacket(&data);
14631 /// convert the player's binds to the group
14632 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
14634 bool has_binds = false;
14635 bool has_solo = false;
14637 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
14638 assert(player_guid);
14640 // copy all binds to the group, when changing leader it's assumed the character
14641 // will not have any solo binds
14643 if(player)
14645 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14647 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
14649 has_binds = true;
14650 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
14651 // permanent binds are not removed
14652 if(!itr->second.perm)
14654 player->UnbindInstance(itr, i, true); // increments itr
14655 has_solo = true;
14657 else
14658 ++itr;
14663 // if the player's not online we don't know what binds it has
14664 if(!player || !group || has_binds) CharacterDatabase.PExecute("INSERT INTO group_instance SELECT guid, instance, permanent FROM character_instance WHERE guid = '%u'", GUID_LOPART(player_guid));
14665 // the following should not get executed when changing leaders
14666 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
14669 bool Player::_LoadHomeBind(QueryResult *result)
14671 bool ok = false;
14672 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
14673 if (result)
14675 Field *fields = result->Fetch();
14676 m_homebindMapId = fields[0].GetUInt32();
14677 m_homebindZoneId = fields[1].GetUInt16();
14678 m_homebindX = fields[2].GetFloat();
14679 m_homebindY = fields[3].GetFloat();
14680 m_homebindZ = fields[4].GetFloat();
14681 delete result;
14683 // accept saved data only for valid position (and non instanceable)
14684 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
14685 !sMapStore.LookupEntry(m_homebindMapId)->Instanceable() )
14687 ok = true;
14689 else
14690 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
14693 if(!ok)
14695 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
14696 if(!info) return false;
14698 m_homebindMapId = info->mapId;
14699 m_homebindZoneId = info->zoneId;
14700 m_homebindX = info->positionX;
14701 m_homebindY = info->positionY;
14702 m_homebindZ = info->positionZ;
14704 CharacterDatabase.PExecute("INSERT INTO character_homebind (guid,map,zone,position_x,position_y,position_z) VALUES ('%u', '%u', '%u', '%f', '%f', '%f')", GetGUIDLow(), m_homebindMapId, (uint32)m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
14707 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",
14708 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
14710 return true;
14713 /*********************************************************/
14714 /*** SAVE SYSTEM ***/
14715 /*********************************************************/
14717 void Player::SaveToDB()
14719 // delay auto save at any saves (manual, in code, or autosave)
14720 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
14722 // first save/honor gain after midnight will also update the player's honor fields
14723 UpdateHonorFields();
14725 // Must saved before enter into BattleGround
14726 if(InBattleGround())
14727 return;
14729 int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
14730 //save, far from tavern/city
14731 //save, but in tavern/city
14732 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
14733 outDebugValues();
14735 // save state (after auras removing), if aura remove some flags then it must set it back by self)
14736 uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
14737 uint32 tmp_bytes2 = GetUInt32Value(UNIT_FIELD_BYTES_2);
14738 uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
14739 uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
14740 uint32 tmp_displayid = GetDisplayId();
14742 // Set player sit state to standing on save, also stealth and shifted form
14743 SetByteValue(UNIT_FIELD_BYTES_1, 0, 0); // stand state
14744 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0); // shapeshift
14745 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0); // stand flags?
14746 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_ROTATE);
14747 SetDisplayId(GetNativeDisplayId());
14749 bool inworld = IsInWorld();
14751 CharacterDatabase.BeginTransaction();
14753 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
14755 std::string sql_name = m_name;
14756 CharacterDatabase.escape_string(sql_name);
14758 std::ostringstream ss;
14759 ss << "INSERT INTO characters (guid,account,name,race,class,"
14760 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
14761 "taximask, online, cinematic, "
14762 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
14763 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
14764 "death_expire_time, taxi_path) VALUES ("
14765 << GetGUIDLow() << ", "
14766 << GetSession()->GetAccountId() << ", '"
14767 << sql_name << "', "
14768 << m_race << ", "
14769 << m_class << ", ";
14771 bool save_to_dest = false;
14772 if(IsBeingTeleported())
14774 // don't save to battlegrounds or arenas
14775 const MapEntry *entry = sMapStore.LookupEntry(GetTeleportDest().mapid);
14776 if(entry && entry->map_type != MAP_BATTLEGROUND && entry->map_type != MAP_ARENA)
14777 save_to_dest = true;
14780 if(!save_to_dest)
14782 ss << GetMapId() << ", "
14783 << (uint32)GetDifficulty() << ", "
14784 << finiteAlways(GetPositionX()) << ", "
14785 << finiteAlways(GetPositionY()) << ", "
14786 << finiteAlways(GetPositionZ()) << ", "
14787 << finiteAlways(GetOrientation()) << ", '";
14789 else
14791 ss << GetTeleportDest().mapid << ", "
14792 << (uint32)GetDifficulty() << ", "
14793 << finiteAlways(GetTeleportDest().x) << ", "
14794 << finiteAlways(GetTeleportDest().y) << ", "
14795 << finiteAlways(GetTeleportDest().z) << ", "
14796 << finiteAlways(GetTeleportDest().o) << ", '";
14799 uint16 i;
14800 for( i = 0; i < m_valuesCount; i++ )
14802 ss << GetUInt32Value(i) << " ";
14805 ss << "', '";
14807 for( i = 0; i < 8; i++ )
14808 ss << m_taxi.GetTaximask(i) << " ";
14810 ss << "', ";
14811 ss << (inworld ? 1 : 0);
14813 ss << ", ";
14814 ss << m_cinematic;
14816 ss << ", ";
14817 ss << m_Played_time[0];
14818 ss << ", ";
14819 ss << m_Played_time[1];
14821 ss << ", ";
14822 ss << finiteAlways(m_rest_bonus);
14823 ss << ", ";
14824 ss << (uint64)time(NULL);
14825 ss << ", ";
14826 ss << is_save_resting;
14827 ss << ", ";
14828 ss << m_resetTalentsCost;
14829 ss << ", ";
14830 ss << (uint64)m_resetTalentsTime;
14832 ss << ", ";
14833 ss << finiteAlways(m_movementInfo.t_x);
14834 ss << ", ";
14835 ss << finiteAlways(m_movementInfo.t_y);
14836 ss << ", ";
14837 ss << finiteAlways(m_movementInfo.t_z);
14838 ss << ", ";
14839 ss << finiteAlways(m_movementInfo.t_o);
14840 ss << ", ";
14841 if (m_transport)
14842 ss << m_transport->GetGUIDLow();
14843 else
14844 ss << "0";
14846 ss << ", ";
14847 ss << m_ExtraFlags;
14849 ss << ", ";
14850 ss << uint32(m_stableSlots); // to prevent save uint8 as char
14852 ss << ", ";
14853 ss << uint32(m_atLoginFlags);
14855 ss << ", ";
14856 ss << GetZoneId();
14858 ss << ", ";
14859 ss << (uint64)m_deathExpireTime;
14861 ss << ", '";
14862 ss << m_taxi.SaveTaxiDestinationsToString();
14863 ss << "' )";
14865 CharacterDatabase.Execute( ss.str().c_str() );
14867 if(m_mailsUpdated) //save mails only when needed
14868 _SaveMail();
14870 _SaveInventory();
14871 _SaveQuestStatus();
14872 _SaveDailyQuestStatus();
14873 _SaveTutorials();
14874 _SaveSpells();
14875 _SaveSpellCooldowns();
14876 _SaveActions();
14877 _SaveAuras();
14878 _SaveReputation();
14880 CharacterDatabase.CommitTransaction();
14882 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
14883 SetDisplayId(tmp_displayid);
14884 SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
14885 SetUInt32Value(UNIT_FIELD_BYTES_2, tmp_bytes2);
14886 SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
14887 SetUInt32Value(PLAYER_FLAGS, tmp_pflags);
14889 // save pet (hunter pet level and experience and all type pets health/mana).
14890 if(Pet* pet = GetPet())
14891 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
14894 // fast save function for item/money cheating preventing - save only inventory and money state
14895 void Player::SaveInventoryAndGoldToDB()
14897 _SaveInventory();
14898 SetUInt32ValueInDB(PLAYER_FIELD_COINAGE,GetMoney(),GetGUID());
14901 void Player::_SaveActions()
14903 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
14905 switch (itr->second.uState)
14907 case ACTIONBUTTON_NEW:
14908 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
14909 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc );
14910 itr->second.uState = ACTIONBUTTON_UNCHANGED;
14911 ++itr;
14912 break;
14913 case ACTIONBUTTON_CHANGED:
14914 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
14915 (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc, GetGUIDLow(), (uint32)itr->first );
14916 itr->second.uState = ACTIONBUTTON_UNCHANGED;
14917 ++itr;
14918 break;
14919 case ACTIONBUTTON_DELETED:
14920 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
14921 m_actionButtons.erase(itr++);
14922 break;
14923 default:
14924 ++itr;
14925 break;
14930 void Player::_SaveAuras()
14932 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14934 AuraMap const& auras = GetAuras();
14935 for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
14937 SpellEntry const *spellInfo = itr->second->GetSpellProto();
14939 //skip all auras from spells that are passive or need a shapeshift
14940 if (itr->second->IsPassive() || itr->second->IsRemovedOnShapeLost())
14941 continue;
14943 //do not save single target auras (unless they were cast by the player)
14944 if (itr->second->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo))
14945 continue;
14947 uint8 i;
14948 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
14949 for (i = 0; i < 3; i++)
14950 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
14951 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
14952 break;
14954 if (i == 3)
14956 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u' and spell = '%u' and effect_index= '%u'",GetGUIDLow(),(uint32)(*itr).second->GetId(), (uint32)(*itr).second->GetEffIndex());
14957 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges) "
14958 "VALUES ('%u', '" I64FMTD "' ,'%u', '%u', '%d', '%d', '%d', '%d')",
14959 GetGUIDLow(), itr->second->GetCasterGUID(), (uint32)(*itr).second->GetId(), (uint32)(*itr).second->GetEffIndex(), (*itr).second->GetModifier()->m_amount,int((*itr).second->GetAuraMaxDuration()),int((*itr).second->GetAuraDuration()),int((*itr).second->m_procCharges));
14964 void Player::_SaveInventory()
14966 // force items in buyback slots to new state
14967 // and remove those that aren't already
14968 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; i++)
14970 Item *item = m_items[i];
14971 if (!item || item->GetState() == ITEM_NEW) continue;
14972 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
14973 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
14974 m_items[i]->FSetState(ITEM_NEW);
14977 // update enchantment durations
14978 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
14980 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
14983 // if no changes
14984 if (m_itemUpdateQueue.empty()) return;
14986 // do not save if the update queue is corrupt
14987 bool error = false;
14988 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
14990 Item *item = m_itemUpdateQueue[i];
14991 if(!item || item->GetState() == ITEM_REMOVED) continue;
14992 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
14994 if (test == NULL)
14996 sLog.outError("Player(GUID: %u Name: %s)::_SaveInventory - the bag(%d) and slot(%d) values for the item with guid %d are incorrect, the player doesn't have an item at that position!", GetGUIDLow(), GetName(), item->GetBagSlot(), item->GetSlot(), item->GetGUIDLow());
14997 error = true;
14999 else if (test != item)
15001 sLog.outError("Player(GUID: %u Name: %s)::_SaveInventory - the bag(%d) and slot(%d) values for the item with guid %d are incorrect, the item with guid %d is there instead!", GetGUIDLow(), GetName(), item->GetBagSlot(), item->GetSlot(), item->GetGUIDLow(), test->GetGUIDLow());
15002 error = true;
15006 if (error)
15008 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15009 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15010 return;
15013 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15015 Item *item = m_itemUpdateQueue[i];
15016 if(!item) continue;
15018 Bag *container = item->GetContainer();
15019 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15021 switch(item->GetState())
15023 case ITEM_NEW:
15024 CharacterDatabase.PExecute("INSERT INTO character_inventory (guid,bag,slot,item,item_template) VALUES ('%u', '%u', '%u', '%u', '%u')", GetGUIDLow(), bag_guid, item->GetSlot(), item->GetGUIDLow(), item->GetEntry());
15025 break;
15026 case ITEM_CHANGED:
15027 CharacterDatabase.PExecute("UPDATE character_inventory SET guid='%u', bag='%u', slot='%u', item_template='%u' WHERE item='%u'", GetGUIDLow(), bag_guid, item->GetSlot(), item->GetEntry(), item->GetGUIDLow());
15028 break;
15029 case ITEM_REMOVED:
15030 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15031 break;
15032 case ITEM_UNCHANGED:
15033 break;
15036 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15038 m_itemUpdateQueue.clear();
15041 void Player::_SaveMail()
15043 if (!m_mailsLoaded)
15044 return;
15046 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); itr++)
15048 Mail *m = (*itr);
15049 if (m->state == MAIL_STATE_CHANGED)
15051 CharacterDatabase.PExecute("UPDATE mail SET itemTextId = '%u',has_items = '%u',expire_time = '" I64FMTD "', deliver_time = '" I64FMTD "',money = '%u',cod = '%u',checked = '%u' WHERE id = '%u'",
15052 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15053 if(m->removedItems.size())
15055 for(std::vector<uint32>::iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15056 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15057 m->removedItems.clear();
15059 m->state = MAIL_STATE_UNCHANGED;
15061 else if (m->state == MAIL_STATE_DELETED)
15063 if (m->HasItems())
15064 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15065 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15066 if (m->itemTextId)
15067 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15068 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15069 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15073 //deallocate deleted mails...
15074 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15076 if ((*itr)->state == MAIL_STATE_DELETED)
15078 Mail* m = *itr;
15079 m_mail.erase(itr);
15080 delete m;
15081 itr = m_mail.begin();
15083 else
15084 ++itr;
15087 m_mailsUpdated = false;
15090 void Player::_SaveQuestStatus()
15092 // we don't need transactions here.
15093 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15095 switch (i->second.uState)
15097 case QUEST_NEW :
15098 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15099 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15100 GetGUIDLow(), i->first, i->second.m_status, i->second.m_rewarded, i->second.m_explored, uint64(i->second.m_timer / 1000 + sWorld.GetGameTime()), i->second.m_creatureOrGOcount[0], i->second.m_creatureOrGOcount[1], i->second.m_creatureOrGOcount[2], i->second.m_creatureOrGOcount[3], i->second.m_itemcount[0], i->second.m_itemcount[1], i->second.m_itemcount[2], i->second.m_itemcount[3]);
15101 break;
15102 case QUEST_CHANGED :
15103 CharacterDatabase.PExecute("UPDATE character_queststatus SET status = '%u',rewarded = '%u',explored = '%u',timer = '" I64FMTD "',mobcount1 = '%u',mobcount2 = '%u',mobcount3 = '%u',mobcount4 = '%u',itemcount1 = '%u',itemcount2 = '%u',itemcount3 = '%u',itemcount4 = '%u' WHERE guid = '%u' AND quest = '%u' ",
15104 i->second.m_status, i->second.m_rewarded, i->second.m_explored, uint64(i->second.m_timer / 1000 + sWorld.GetGameTime()), i->second.m_creatureOrGOcount[0], i->second.m_creatureOrGOcount[1], i->second.m_creatureOrGOcount[2], i->second.m_creatureOrGOcount[3], i->second.m_itemcount[0], i->second.m_itemcount[1], i->second.m_itemcount[2], i->second.m_itemcount[3], GetGUIDLow(), i->first );
15105 break;
15106 case QUEST_UNCHANGED:
15107 break;
15109 i->second.uState = QUEST_UNCHANGED;
15113 void Player::_SaveDailyQuestStatus()
15115 if(!m_DailyQuestChanged)
15116 return;
15118 m_DailyQuestChanged = false;
15120 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15122 // we don't need transactions here.
15123 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15124 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15125 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
15126 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD "')",
15127 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
15130 void Player::_SaveReputation()
15132 for(FactionStateList::iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
15134 if (itr->second.Changed)
15136 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u' AND faction='%u'", GetGUIDLow(), itr->second.ID);
15137 CharacterDatabase.PExecute("INSERT INTO character_reputation (guid,faction,standing,flags) VALUES ('%u', '%u', '%i', '%u')", GetGUIDLow(), itr->second.ID, itr->second.Standing, itr->second.Flags);
15138 itr->second.Changed = false;
15143 void Player::_SaveSpells()
15145 for (PlayerSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
15147 ++next;
15148 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
15149 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
15150 if (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED)
15151 CharacterDatabase.PExecute("INSERT INTO character_spell (guid,spell,slot,active,disabled) VALUES ('%u', '%u', '%u','%u','%u')", GetGUIDLow(), itr->first, itr->second->slotId,itr->second->active ? 1 : 0,itr->second->disabled ? 1 : 0);
15153 if (itr->second->state == PLAYERSPELL_REMOVED)
15154 _removeSpell(itr->first);
15155 else
15156 itr->second->state = PLAYERSPELL_UNCHANGED;
15160 void Player::_SaveTutorials()
15162 if(!m_TutorialsChanged)
15163 return;
15165 uint32 Rows=0;
15166 // it's better than rebuilding indexes multiple times
15167 QueryResult *result = CharacterDatabase.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID );
15168 if(result)
15170 Rows = result->Fetch()[0].GetUInt32();
15171 delete result;
15174 if (Rows)
15176 CharacterDatabase.PExecute("UPDATE character_tutorial SET tut0='%u', tut1='%u', tut2='%u', tut3='%u', tut4='%u', tut5='%u', tut6='%u', tut7='%u' WHERE account = '%u' AND realmid = '%u'",
15177 m_Tutorials[0], m_Tutorials[1], m_Tutorials[2], m_Tutorials[3], m_Tutorials[4], m_Tutorials[5], m_Tutorials[6], m_Tutorials[7], GetSession()->GetAccountId(), realmID );
15179 else
15181 CharacterDatabase.PExecute("INSERT INTO character_tutorial (account,realmid,tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7) VALUES ('%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')", GetSession()->GetAccountId(), realmID, m_Tutorials[0], m_Tutorials[1], m_Tutorials[2], m_Tutorials[3], m_Tutorials[4], m_Tutorials[5], m_Tutorials[6], m_Tutorials[7]);
15184 m_TutorialsChanged = false;
15187 void Player::outDebugValues() const
15189 if(!sLog.IsOutDebug()) // optimize disabled debug output
15190 return;
15192 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
15193 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
15194 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
15195 sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
15196 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
15197 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
15198 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
15199 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
15200 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
15201 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
15202 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
15203 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
15206 /*********************************************************/
15207 /*** FLOOD FILTER SYSTEM ***/
15208 /*********************************************************/
15210 void Player::UpdateSpeakTime()
15212 // ignore chat spam protection for GMs in any mode
15213 if(GetSession()->GetSecurity() > SEC_PLAYER)
15214 return;
15216 time_t current = time (NULL);
15217 if(m_speakTime > current)
15219 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
15220 if(!max_count)
15221 return;
15223 ++m_speakCount;
15224 if(m_speakCount >= max_count)
15226 // prevent overwrite mute time, if message send just before mutes set, for example.
15227 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
15228 if(GetSession()->m_muteTime < new_mute)
15229 GetSession()->m_muteTime = new_mute;
15231 m_speakCount = 0;
15234 else
15235 m_speakCount = 0;
15237 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
15240 bool Player::CanSpeak() const
15242 return GetSession()->m_muteTime <= time (NULL);
15245 /*********************************************************/
15246 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15247 /*********************************************************/
15249 void Player::SendAttackSwingNotInRange()
15251 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
15252 GetSession()->SendPacket( &data );
15255 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
15257 std::ostringstream ss;
15258 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
15259 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
15260 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
15261 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15262 sLog.outDebug(ss.str().c_str());
15263 CharacterDatabase.Execute(ss.str().c_str());
15266 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
15268 std::ostringstream ss2;
15269 ss2<<"UPDATE characters SET data='";
15270 int i=0;
15271 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
15273 ss2<<tokens[i]<<" ";
15275 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15277 return CharacterDatabase.Execute(ss2.str().c_str());
15280 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
15282 char buf[11];
15283 snprintf(buf,11,"%u",value);
15285 if(index >= tokens.size())
15286 return;
15288 tokens[index] = buf;
15291 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
15293 Tokens tokens;
15294 if(!LoadValuesArrayFromDB(tokens,guid))
15295 return;
15297 if(index >= tokens.size())
15298 return;
15300 char buf[11];
15301 snprintf(buf,11,"%u",value);
15302 tokens[index] = buf;
15304 SaveValuesArrayInDB(tokens,guid);
15307 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
15309 uint32 temp;
15310 memcpy(&temp, &value, sizeof(value));
15311 Player::SetUInt32ValueInDB(index, temp, guid);
15314 void Player::SendAttackSwingNotStanding()
15316 WorldPacket data(SMSG_ATTACKSWING_NOTSTANDING, 0);
15317 GetSession()->SendPacket( &data );
15320 void Player::SendAttackSwingDeadTarget()
15322 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
15323 GetSession()->SendPacket( &data );
15326 void Player::SendAttackSwingCantAttack()
15328 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
15329 GetSession()->SendPacket( &data );
15332 void Player::SendAttackSwingCancelAttack()
15334 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
15335 GetSession()->SendPacket( &data );
15338 void Player::SendAttackSwingBadFacingAttack()
15340 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
15341 GetSession()->SendPacket( &data );
15344 void Player::SendAutoRepeatCancel()
15346 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, 0);
15347 GetSession()->SendPacket( &data );
15350 void Player::PlaySound(uint32 Sound, bool OnlySelf)
15352 WorldPacket data(SMSG_PLAY_SOUND, 4);
15353 data << Sound;
15354 if (OnlySelf)
15355 GetSession()->SendPacket( &data );
15356 else
15357 SendMessageToSet( &data, true );
15360 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
15362 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
15363 data << Area;
15364 data << Experience;
15365 GetSession()->SendPacket(&data);
15368 void Player::SendDungeonDifficulty(bool IsInGroup)
15370 uint8 val = 0x00000001;
15371 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
15372 data << (uint32)GetDifficulty();
15373 data << uint32(val);
15374 data << uint32(IsInGroup);
15375 GetSession()->SendPacket(&data);
15378 void Player::SendResetFailedNotify(uint32 mapid)
15380 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
15381 data << uint32(mapid);
15382 GetSession()->SendPacket(&data);
15385 /// Reset all solo instances and optionally send a message on success for each
15386 void Player::ResetInstances(uint8 method)
15388 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
15390 // we assume that when the difficulty changes, all instances that can be reset will be
15391 uint8 dif = GetDifficulty();
15393 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
15395 InstanceSave *p = itr->second.save;
15396 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
15397 if(!entry || !p->CanReset())
15399 ++itr;
15400 continue;
15403 if(method == INSTANCE_RESET_ALL)
15405 // the "reset all instances" method can only reset normal maps
15406 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
15408 ++itr;
15409 continue;
15413 // if the map is loaded, reset it
15414 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
15415 if(map && map->IsDungeon())
15416 ((InstanceMap*)map)->Reset(method);
15418 // since this is a solo instance there should not be any players inside
15419 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
15420 SendResetInstanceSuccess(p->GetMapId());
15422 p->DeleteFromDB();
15423 m_boundInstances[dif].erase(itr++);
15425 // the following should remove the instance save from the manager and delete it as well
15426 p->RemovePlayer(this);
15430 void Player::SendResetInstanceSuccess(uint32 MapId)
15432 WorldPacket data(SMSG_INSTANCE_RESET, 4);
15433 data << MapId;
15434 GetSession()->SendPacket(&data);
15437 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
15439 // TODO: find what other fail reasons there are besides players in the instance
15440 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
15441 data << reason;
15442 data << MapId;
15443 GetSession()->SendPacket(&data);
15446 /*********************************************************/
15447 /*** Update timers ***/
15448 /*********************************************************/
15450 ///checks the 15 afk reports per 5 minutes limit
15451 void Player::UpdateAfkReport(time_t currTime)
15453 if(m_bgAfkReportedTimer <= currTime)
15455 m_bgAfkReportedCount = 0;
15456 m_bgAfkReportedTimer = currTime+5*MINUTE;
15460 void Player::UpdateContestedPvP(uint32 diff)
15462 if(!m_contestedPvPTimer||isInCombat())
15463 return;
15464 if(m_contestedPvPTimer <= diff)
15466 ResetContestedPvP();
15468 else
15469 m_contestedPvPTimer -= diff;
15472 void Player::UpdatePvPFlag(time_t currTime)
15474 if(!IsPvP())
15475 return;
15476 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
15477 return;
15479 UpdatePvP(false);
15482 void Player::UpdateDuelFlag(time_t currTime)
15484 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
15485 return;
15487 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
15488 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
15490 duel->startTimer = 0;
15491 duel->startTime = currTime;
15492 duel->opponent->duel->startTimer = 0;
15493 duel->opponent->duel->startTime = currTime;
15496 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
15498 if(!pet)
15499 pet = GetPet();
15501 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
15503 //returning of reagents only for players, so best done here
15504 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
15505 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
15507 if(spellInfo)
15509 for(uint32 i = 0; i < 7; ++i)
15511 if(spellInfo->Reagent[i] > 0)
15513 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
15514 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
15515 if( msg == EQUIP_ERR_OK )
15517 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
15518 if(IsInWorld())
15519 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
15524 m_temporaryUnsummonedPetNumber = 0;
15527 if(!pet || pet->GetOwnerGUID()!=GetGUID())
15528 return;
15530 // only if current pet in slot
15531 switch(pet->getPetType())
15533 case MINI_PET:
15534 m_miniPet = 0;
15535 break;
15536 case GUARDIAN_PET:
15537 m_guardianPets.erase(pet->GetGUID());
15538 break;
15539 default:
15540 if(GetPetGUID()==pet->GetGUID())
15541 SetPet(0);
15542 break;
15545 pet->CombatStop();
15547 if(returnreagent)
15549 switch(pet->GetEntry())
15551 //warlock pets except imp are removed(?) when logging out
15552 case 1860:
15553 case 1863:
15554 case 417:
15555 case 17252:
15556 mode = PET_SAVE_NOT_IN_SLOT;
15557 break;
15561 pet->SavePetToDB(mode);
15563 pet->CleanupsBeforeDelete();
15564 pet->AddObjectToRemoveList();
15565 pet->m_removed = true;
15567 if(pet->isControlled())
15569 WorldPacket data(SMSG_PET_SPELLS, 8);
15570 data << uint64(0);
15571 GetSession()->SendPacket(&data);
15573 if(GetGroup())
15574 SetGroupUpdateFlag(GROUP_UPDATE_PET);
15578 void Player::RemoveMiniPet()
15580 if(Pet* pet = GetMiniPet())
15582 pet->Remove(PET_SAVE_AS_DELETED);
15583 m_miniPet = 0;
15587 Pet* Player::GetMiniPet()
15589 if(!m_miniPet)
15590 return NULL;
15591 return ObjectAccessor::GetPet(m_miniPet);
15594 void Player::RemoveGuardians()
15596 while(!m_guardianPets.empty())
15598 uint64 guid = *m_guardianPets.begin();
15599 if(Pet* pet = ObjectAccessor::GetPet(guid))
15600 pet->Remove(PET_SAVE_AS_DELETED);
15602 m_guardianPets.erase(guid);
15606 bool Player::HasGuardianWithEntry(uint32 entry)
15608 // pet guid middle part is entry (and creature also)
15609 // and in guardian list must be guardians with same entry _always_
15610 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
15611 if(GUID_ENPART(*itr)==entry)
15612 return true;
15614 return false;
15617 void Player::Uncharm()
15619 Unit* charm = GetCharm();
15620 if(!charm)
15621 return;
15623 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
15624 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
15627 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, std::string text, uint32 language) const
15629 *data << (uint8)msgtype;
15630 *data << (uint32)language;
15631 *data << (uint64)GetGUID();
15632 *data << (uint32)language; //language 2.1.0 ?
15633 *data << (uint64)GetGUID();
15634 *data << (uint32)(text.length()+1);
15635 *data << text;
15636 *data << (uint8)chatTag();
15639 void Player::Say(const std::string text, const uint32 language)
15641 WorldPacket data(SMSG_MESSAGECHAT, 200);
15642 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
15643 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
15646 void Player::Yell(const std::string text, const uint32 language)
15648 WorldPacket data(SMSG_MESSAGECHAT, 200);
15649 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
15650 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
15653 void Player::TextEmote(const std::string text)
15655 WorldPacket data(SMSG_MESSAGECHAT, 200);
15656 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
15657 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
15660 void Player::Whisper(std::string text, uint32 language,uint64 receiver)
15662 if (language != LANG_ADDON) // if not addon data
15663 language = LANG_UNIVERSAL; // whispers should always be readable
15665 Player *rPlayer = objmgr.GetPlayer(receiver);
15667 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
15668 if(!rPlayer->isDND() || isGameMaster())
15670 WorldPacket data(SMSG_MESSAGECHAT, 200);
15671 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
15672 rPlayer->GetSession()->SendPacket(&data);
15674 data.Initialize(SMSG_MESSAGECHAT, 200);
15675 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
15676 GetSession()->SendPacket(&data);
15678 else
15680 // announce to player that player he is whispering to is dnd and cannot receive his message
15681 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
15684 if(!isAcceptWhispers())
15686 SetAcceptWhispers(true);
15687 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
15690 // announce to player that player he is whispering to is afk
15691 if(rPlayer->isAFK())
15692 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
15694 // if player whisper someone, auto turn of dnd to be able to receive an answer
15695 if(isDND() && !rPlayer->isGameMaster())
15696 ToggleDND();
15699 void Player::PetSpellInitialize()
15701 Pet* pet = GetPet();
15703 if(pet)
15705 uint8 addlist = 0;
15707 sLog.outDebug("Pet Spells Groups");
15709 CreatureInfo const *cinfo = pet->GetCreatureInfo();
15711 if(pet->isControlled() && (pet->getPetType() == HUNTER_PET || cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK))
15713 for(PetSpellMap::iterator itr = pet->m_spells.begin();itr != pet->m_spells.end();itr++)
15715 if(itr->second->state == PETSPELL_REMOVED)
15716 continue;
15717 ++addlist;
15721 // first line + actionbar + spellcount + spells + last adds
15722 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);
15724 CharmInfo *charmInfo = pet->GetCharmInfo();
15726 //16
15727 data << (uint64)pet->GetGUID() << uint32(0x00000000) << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
15729 for(uint32 i = 0; i < 10; i++) //40
15731 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
15734 data << uint8(addlist); //1
15736 if(addlist && pet->isControlled())
15738 for (PetSpellMap::iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
15740 if(itr->second->state == PETSPELL_REMOVED)
15741 continue;
15743 data << uint16(itr->first);
15744 data << uint16(itr->second->active); // pet spell active state isn't boolean
15748 //data << uint8(0x01) << uint32(0x6010) << uint32(0x01) << uint32(0x05) << uint16(0x00); //15
15749 uint8 count = 3; //1+8+8+8=25
15751 // if count = 0, then end of packet...
15752 data << count;
15753 // uint32 value is spell id...
15754 // uint64 value is constant 0, unknown...
15755 data << uint32(0x6010) << uint64(0); // if count = 1, 2 or 3
15756 //data << uint32(0x5fd1) << uint64(0); // if count = 2
15757 data << uint32(0x8e8c) << uint64(0); // if count = 3
15758 data << uint32(0x8e8b) << uint64(0); // if count = 3
15760 GetSession()->SendPacket(&data);
15764 void Player::PossessSpellInitialize()
15766 Unit* charm = GetCharm();
15768 if(!charm)
15769 return;
15771 CharmInfo *charmInfo = charm->GetCharmInfo();
15773 if(!charmInfo)
15775 sLog.outError("Player::PossessSpellInitialize(): charm ("I64FMTD") has no charminfo!", charm->GetGUID());
15776 return;
15779 uint8 addlist = 0;
15780 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
15782 //16
15783 data << (uint64)charm->GetGUID() << uint32(0x00000000) << uint8(0) << uint8(0) << uint16(0);
15785 for(uint32 i = 0; i < 10; i++) //40
15787 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
15790 data << uint8(addlist); //1
15792 uint8 count = 3;
15793 data << count;
15794 data << uint32(0x6010) << uint64(0); // if count = 1, 2 or 3
15795 data << uint32(0x8e8c) << uint64(0); // if count = 3
15796 data << uint32(0x8e8b) << uint64(0); // if count = 3
15798 GetSession()->SendPacket(&data);
15801 void Player::CharmSpellInitialize()
15803 Unit* charm = GetCharm();
15805 if(!charm)
15806 return;
15808 CharmInfo *charmInfo = charm->GetCharmInfo();
15809 if(!charmInfo)
15811 sLog.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD") has no charminfo!", charm->GetGUID());
15812 return;
15815 uint8 addlist = 0;
15817 if(charm->GetTypeId() != TYPEID_PLAYER)
15819 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
15821 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
15823 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
15825 if(charmInfo->GetCharmSpell(i)->spellId)
15826 ++addlist;
15831 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
15833 data << (uint64)charm->GetGUID() << uint32(0x00000000);
15835 if(charm->GetTypeId() != TYPEID_PLAYER)
15836 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState());
15837 else
15838 data << uint8(0) << uint8(0);
15840 data << uint16(0);
15842 for(uint32 i = 0; i < 10; i++) //40
15844 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
15847 data << uint8(addlist); //1
15849 if(addlist)
15851 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
15853 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
15854 if(cspell->spellId)
15856 data << uint16(cspell->spellId);
15857 data << uint16(cspell->active);
15862 uint8 count = 3;
15863 data << count;
15864 data << uint32(0x6010) << uint64(0); // if count = 1, 2 or 3
15865 data << uint32(0x8e8c) << uint64(0); // if count = 3
15866 data << uint32(0x8e8b) << uint64(0); // if count = 3
15868 GetSession()->SendPacket(&data);
15871 int32 Player::GetTotalFlatMods(uint32 spellId, SpellModOp op)
15873 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
15874 if (!spellInfo) return 0;
15875 int32 total = 0;
15876 for (SpellModList::iterator itr = m_spellMods[op].begin(); itr != m_spellMods[op].end(); ++itr)
15878 SpellModifier *mod = *itr;
15880 if(!IsAffectedBySpellmod(spellInfo,mod))
15881 continue;
15883 if (mod->type == SPELLMOD_FLAT)
15884 total += mod->value;
15886 return total;
15889 int32 Player::GetTotalPctMods(uint32 spellId, SpellModOp op)
15891 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
15892 if (!spellInfo) return 0;
15893 int32 total = 0;
15894 for (SpellModList::iterator itr = m_spellMods[op].begin(); itr != m_spellMods[op].end(); ++itr)
15896 SpellModifier *mod = *itr;
15898 if(!IsAffectedBySpellmod(spellInfo,mod))
15899 continue;
15901 if (mod->type == SPELLMOD_PCT)
15902 total += mod->value;
15904 return total;
15907 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
15909 if (!mod || !spellInfo)
15910 return false;
15912 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
15914 // prevent apply to any spell except spell that trigger expire
15915 if(spell)
15917 if(mod->lastAffected != spell)
15918 return false;
15920 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
15921 return false;
15924 return spellmgr.IsAffectedBySpell(spellInfo,mod->spellId,mod->effectId,mod->mask);
15927 void Player::AddSpellMod(SpellModifier* mod, bool apply)
15929 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
15931 for(int eff=0;eff<64;++eff)
15933 uint64 _mask = uint64(1) << eff;
15934 if ( mod->mask & _mask)
15936 int32 val = 0;
15937 for (SpellModList::iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
15939 if ((*itr)->type == mod->type && (*itr)->mask & _mask)
15940 val += (*itr)->value;
15942 val += apply ? mod->value : -(mod->value);
15943 WorldPacket data(Opcode, (1+1+4));
15944 data << uint8(eff);
15945 data << uint8(mod->op);
15946 data << int32(val);
15947 SendDirectMessage(&data);
15951 if (apply)
15952 m_spellMods[mod->op].push_back(mod);
15953 else
15955 if (mod->charges == -1)
15956 --m_SpellModRemoveCount;
15957 m_spellMods[mod->op].remove(mod);
15958 delete mod;
15962 void Player::RemoveSpellMods(Spell const* spell)
15964 if(!spell || (m_SpellModRemoveCount == 0))
15965 return;
15967 for(int i=0;i<MAX_SPELLMOD;++i)
15969 for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
15971 SpellModifier *mod = *itr;
15972 ++itr;
15974 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
15976 RemoveAurasDueToSpell(mod->spellId);
15977 if (m_spellMods[i].empty())
15978 break;
15979 else
15980 itr = m_spellMods[i].begin();
15986 // send Proficiency
15987 void Player::SendProficiency(uint8 pr1, uint32 pr2)
15989 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
15990 data << pr1 << pr2;
15991 GetSession()->SendPacket (&data);
15994 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
15996 QueryResult *result = NULL;
15997 if(type==10)
15998 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
15999 else
16000 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16001 if(result)
16003 do // this part effectively does nothing, since the deletion / modification only takes place _after_ the PetitionQuery. Though I don't know if the result remains intact if I execute the delete query beforehand.
16004 { // and SendPetitionQueryOpcode reads data from the DB
16005 Field *fields = result->Fetch();
16006 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16007 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16009 // send update if charter owner in game
16010 Player* owner = objmgr.GetPlayer(ownerguid);
16011 if(owner)
16012 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16014 } while ( result->NextRow() );
16016 delete result;
16018 if(type==10)
16019 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16020 else
16021 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16024 CharacterDatabase.BeginTransaction();
16025 if(type == 10)
16027 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16028 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16030 else
16032 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16033 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16035 CharacterDatabase.CommitTransaction();
16038 void Player::SetRestBonus (float rest_bonus_new)
16040 // Prevent resting on max level
16041 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16042 rest_bonus_new = 0;
16044 if(rest_bonus_new < 0)
16045 rest_bonus_new = 0;
16047 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16049 if(rest_bonus_new > rest_bonus_max)
16050 m_rest_bonus = rest_bonus_max;
16051 else
16052 m_rest_bonus = rest_bonus_new;
16054 // update data for client
16055 if(m_rest_bonus>10)
16056 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16057 else if(m_rest_bonus<=1)
16058 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16060 //RestTickUpdate
16061 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16064 void Player::HandleStealthedUnitsDetection()
16066 std::list<Unit*> stealthedUnits;
16068 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16069 Cell cell(p);
16070 cell.data.Part.reserved = ALL_DISTRICT;
16071 cell.SetNoCreate();
16073 MaNGOS::AnyStealthedCheck u_check;
16074 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(stealthedUnits, u_check);
16076 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16077 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16079 CellLock<GridReadGuard> cell_lock(cell, p);
16080 cell_lock->Visit(cell_lock, world_unit_searcher, *MapManager::Instance().GetMap(GetMapId(), this));
16081 cell_lock->Visit(cell_lock, grid_unit_searcher, *MapManager::Instance().GetMap(GetMapId(), this));
16083 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
16085 if((*i)==this)
16087 i = stealthedUnits.erase(i);
16088 continue;
16091 if ((*i)->isVisibleForOrDetect(this,true))
16094 (*i)->SendUpdateToPlayer(this);
16095 m_clientGUIDs.insert((*i)->GetGUID());
16097 #ifdef MANGOS_DEBUG
16098 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16099 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
16100 #endif
16102 // target aura duration for caster show only if target exist at caster client
16103 // send data at target visibility change (adding to client)
16104 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
16105 SendAuraDurationsForTarget(*i);
16107 i = stealthedUnits.erase(i);
16108 continue;
16111 ++i;
16115 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, uint32 mount_id, Creature* npc)
16117 if(nodes.size() < 2)
16118 return false;
16120 // not let cheating with start flight mounted
16121 if(IsMounted())
16123 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16124 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
16125 GetSession()->SendPacket(&data);
16126 return false;
16129 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16131 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16132 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
16133 GetSession()->SendPacket(&data);
16134 return false;
16137 // not let cheating with start flight in time of logout process || if casting not finished || while in combat || if not use Spell's with EffectSendTaxi
16138 if(GetSession()->isLogingOut() ||
16139 (!m_currentSpells[CURRENT_GENERIC_SPELL] ||
16140 m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Effect[0] != SPELL_EFFECT_SEND_TAXI)&&
16141 IsNonMeleeSpellCasted(false) ||
16142 isInCombat())
16144 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16145 data << uint32(ERR_TAXIPLAYERBUSY);
16146 GetSession()->SendPacket(&data);
16147 return false;
16150 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
16151 return false;
16153 uint32 sourcenode = nodes[0];
16155 // starting node too far away (cheat?)
16156 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
16157 if( !node || node->map_id != GetMapId() ||
16158 (node->x - GetPositionX())*(node->x - GetPositionX())+
16159 (node->y - GetPositionY())*(node->y - GetPositionY())+
16160 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
16161 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE) )
16163 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16164 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16165 GetSession()->SendPacket(&data);
16166 return false;
16169 // Prepare to flight start now
16171 // stop combat at start taxi flight if any
16172 CombatStop();
16174 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16175 TradeCancel(true);
16177 // clean not finished taxi path if any
16178 m_taxi.ClearTaxiDestinations();
16180 // 0 element current node
16181 m_taxi.AddTaxiDestination(sourcenode);
16183 // fill destinations path tail
16184 uint32 sourcepath = 0;
16185 uint32 totalcost = 0;
16187 uint32 prevnode = sourcenode;
16188 uint32 lastnode = 0;
16190 for(uint32 i = 1; i < nodes.size(); ++i)
16192 uint32 path, cost;
16194 lastnode = nodes[i];
16195 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
16197 if(!path)
16199 m_taxi.ClearTaxiDestinations();
16200 return false;
16203 totalcost += cost;
16205 if(prevnode == sourcenode)
16206 sourcepath = path;
16208 m_taxi.AddTaxiDestination(lastnode);
16210 prevnode = lastnode;
16213 if(!mount_id) // if not provide then attempt use default.
16214 mount_id = objmgr.GetTaxiMount(sourcenode, GetTeam());
16216 if (mount_id == 0 || sourcepath == 0)
16218 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16219 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16220 GetSession()->SendPacket(&data);
16221 m_taxi.ClearTaxiDestinations();
16222 return false;
16225 uint32 money = GetMoney();
16227 if(npc)
16229 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
16232 if(money < totalcost)
16234 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16235 data << uint32(ERR_TAXINOTENOUGHMONEY);
16236 GetSession()->SendPacket(&data);
16237 m_taxi.ClearTaxiDestinations();
16238 return false;
16241 //Checks and preparations done, DO FLIGHT
16242 ModifyMoney(-(int32)totalcost);
16244 // prevent stealth flight
16245 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
16247 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16248 data << uint32(ERR_TAXIOK);
16249 GetSession()->SendPacket(&data);
16251 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16253 GetSession()->SendDoFlight(mount_id, sourcepath);
16255 return true;
16258 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
16260 // last check 2.0.10
16261 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
16262 data << GetGUID();
16263 data << uint8(0x0); // flags (0x1, 0x2)
16264 time_t curTime = time(NULL);
16265 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
16267 if (itr->second->state == PLAYERSPELL_REMOVED)
16268 continue;
16269 uint32 unSpellId = itr->first;
16270 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
16271 if (!spellInfo)
16273 ASSERT(spellInfo);
16274 continue;
16277 // Not send cooldown for this spells
16278 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
16279 continue;
16281 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
16283 data << unSpellId;
16284 data << unTimeMs; // in m.secs
16285 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/1000);
16288 GetSession()->SendPacket(&data);
16291 void Player::InitDataForForm(bool reapplyMods)
16293 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
16294 if(ssEntry && ssEntry->attackSpeed)
16296 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
16297 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
16298 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
16300 else
16301 SetRegularAttackTime();
16303 switch(m_form)
16305 case FORM_CAT:
16307 if(getPowerType()!=POWER_ENERGY)
16308 setPowerType(POWER_ENERGY);
16309 break;
16311 case FORM_BEAR:
16312 case FORM_DIREBEAR:
16314 if(getPowerType()!=POWER_RAGE)
16315 setPowerType(POWER_RAGE);
16316 break;
16318 default: // 0, for example
16320 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
16321 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
16322 setPowerType(Powers(cEntry->powerType));
16323 break;
16327 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
16328 if (!reapplyMods)
16329 UpdateEquipSpellsAtFormChange();
16331 UpdateAttackPowerAndDamage();
16332 UpdateAttackPowerAndDamage(true);
16335 // Return true is the bought item has a max count to force refresh of window by caller
16336 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
16338 // cheating attempt
16339 if(count < 1) count = 1;
16341 if(!isAlive())
16342 return false;
16344 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
16345 if( !pProto )
16347 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
16348 return false;
16351 Creature *pCreature = ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid,UNIT_NPC_FLAG_VENDOR);
16352 if (!pCreature)
16354 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
16355 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
16356 return false;
16359 VendorItemData const* vItems = pCreature->GetVendorItems();
16360 if(!vItems || vItems->Empty())
16362 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16363 return false;
16366 size_t vendor_slot = vItems->FindItemSlot(item);
16367 if(vendor_slot >= vItems->GetItemCount())
16369 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16370 return false;
16373 VendorItem const* crItem = vItems->m_items[vendor_slot];
16375 // check current item amount if it limited
16376 if( crItem->maxcount != 0 )
16378 if(pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
16380 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
16381 return false;
16385 if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
16387 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
16388 return false;
16391 if(crItem->ExtendedCost)
16393 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16394 if(!iece)
16396 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
16397 return false;
16400 // honor points price
16401 if(GetHonorPoints() < (iece->reqhonorpoints * count))
16403 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
16404 return false;
16407 // arena points price
16408 if(GetArenaPoints() < (iece->reqarenapoints * count))
16410 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
16411 return false;
16414 // item base price
16415 for (uint8 i = 0; i < 5; ++i)
16417 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
16419 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
16420 return false;
16424 // check for personal arena rating requirement
16425 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
16427 // probably not the proper equip err
16428 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
16429 return false;
16433 uint32 price = pProto->BuyPrice * count;
16435 // reputation discount
16436 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
16438 if( GetMoney() < price )
16440 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
16441 return false;
16444 uint8 bag = 0; // init for case invalid bagGUID
16446 if (bagguid != NULL_BAG && slot != NULL_SLOT)
16448 Bag *pBag;
16449 if( bagguid == GetGUID() )
16451 bag = INVENTORY_SLOT_BAG_0;
16453 else
16455 for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;i++)
16457 pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i);
16458 if( pBag )
16460 if( bagguid == pBag->GetGUID() )
16462 bag = i;
16463 break;
16470 if( IsInventoryPos( bag, slot ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
16472 ItemPosCountVec dest;
16473 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
16474 if( msg != EQUIP_ERR_OK )
16476 SendEquipError( msg, NULL, NULL );
16477 return false;
16480 ModifyMoney( -(int32)price );
16481 if(crItem->ExtendedCost) // case for new honor system
16483 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16484 if(iece->reqhonorpoints)
16485 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
16486 if(iece->reqarenapoints)
16487 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
16488 for (uint8 i = 0; i < 5; ++i)
16490 if(iece->reqitem[i])
16491 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
16495 if(Item *it = StoreNewItem( dest, item, true ))
16497 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
16499 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
16500 data << pCreature->GetGUID();
16501 data << (uint32)(vendor_slot+1); // numbered from 1 at client
16502 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
16503 data << (uint32)count;
16504 GetSession()->SendPacket(&data);
16506 SendNewItem(it, pProto->BuyCount*count, true, false, false);
16509 else if( IsEquipmentPos( bag, slot ) )
16511 uint16 dest;
16512 uint8 msg = CanEquipNewItem( slot, dest, item, pProto->BuyCount * count, false );
16513 if( msg != EQUIP_ERR_OK )
16515 SendEquipError( msg, NULL, NULL );
16516 return false;
16519 ModifyMoney( -(int32)price );
16520 if(crItem->ExtendedCost) // case for new honor system
16522 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16523 if(iece->reqhonorpoints)
16524 ModifyHonorPoints( - int32(iece->reqhonorpoints));
16525 if(iece->reqarenapoints)
16526 ModifyArenaPoints( - int32(iece->reqarenapoints));
16527 for (uint8 i = 0; i < 5; ++i)
16529 if(iece->reqitem[i])
16530 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
16534 if(Item *it = EquipNewItem( dest, item, pProto->BuyCount * count, true ))
16536 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
16538 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
16539 data << pCreature->GetGUID();
16540 data << (uint32)(vendor_slot+1); // numbered from 1 at client
16541 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
16542 data << (uint32)count;
16543 GetSession()->SendPacket(&data);
16545 SendNewItem(it, pProto->BuyCount*count, true, false, false);
16547 AutoUnequipOffhandIfNeed();
16550 else
16552 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
16553 return false;
16556 return crItem->maxcount!=0;
16559 uint32 Player::GetMaxPersonalArenaRatingRequirement()
16561 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
16562 // the personal rating of the arena team must match the required limit as well
16563 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
16564 uint32 max_personal_rating = 0;
16565 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
16567 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
16569 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
16570 uint32 t_rating = at->GetRating();
16571 p_rating = p_rating<t_rating? p_rating : t_rating;
16572 if(max_personal_rating < p_rating)
16573 max_personal_rating = p_rating;
16576 return max_personal_rating;
16579 void Player::UpdateHomebindTime(uint32 time)
16581 // GMs never get homebind timer online
16582 if (m_InstanceValid || isGameMaster())
16584 if(m_HomebindTimer) // instance valid, but timer not reset
16586 // hide reminder
16587 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
16588 data << uint32(0);
16589 data << uint32(0);
16590 GetSession()->SendPacket(&data);
16592 // instance is valid, reset homebind timer
16593 m_HomebindTimer = 0;
16595 else if (m_HomebindTimer > 0)
16597 if (time >= m_HomebindTimer)
16599 // teleport to homebind location
16600 TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
16602 else
16603 m_HomebindTimer -= time;
16605 else
16607 // instance is invalid, start homebind timer
16608 m_HomebindTimer = 60000;
16609 // send message to player
16610 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
16611 data << m_HomebindTimer;
16612 data << uint32(1);
16613 GetSession()->SendPacket(&data);
16614 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
16618 void Player::UpdatePvP(bool state, bool ovrride)
16620 if(!state || ovrride)
16622 SetPvP(state);
16623 if(Pet* pet = GetPet())
16624 pet->SetPvP(state);
16625 if(Unit* charmed = GetCharm())
16626 charmed->SetPvP(state);
16628 pvpInfo.endTimer = 0;
16630 else
16632 if(pvpInfo.endTimer != 0)
16633 pvpInfo.endTimer = time(NULL);
16634 else
16636 SetPvP(state);
16638 if(Pet* pet = GetPet())
16639 pet->SetPvP(state);
16640 if(Unit* charmed = GetCharm())
16641 charmed->SetPvP(state);
16646 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
16648 SpellCooldown sc;
16649 sc.end = end_time;
16650 sc.itemid = itemid;
16651 m_spellCooldowns[spellid] = sc;
16654 void Player::SendCooldownEvent(SpellEntry const *spellInfo)
16656 if ( !(spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE) )
16657 return;
16659 // Get spell cooldwn
16660 int32 cooldown = GetSpellRecoveryTime(spellInfo);
16661 // Apply spellmods
16662 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, cooldown);
16663 if (cooldown < 0)
16664 cooldown = 0;
16665 // Add cooldown
16666 AddSpellCooldown(spellInfo->Id, 0, time(NULL) + cooldown / 1000);
16667 // Send activate
16668 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
16669 data << spellInfo->Id;
16670 data << GetGUID();
16671 SendDirectMessage(&data);
16673 //slot to be excluded while counting
16674 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
16676 if(!enchantmentcondition)
16677 return true;
16679 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
16681 if(!Condition)
16682 return true;
16684 uint8 curcount[4] = {0, 0, 0, 0};
16686 //counting current equipped gem colors
16687 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
16689 if(i == slot)
16690 continue;
16691 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
16692 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
16694 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
16696 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
16697 if(!enchant_id)
16698 continue;
16700 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
16701 if(!enchantEntry)
16702 continue;
16704 uint32 gemid = enchantEntry->GemID;
16705 if(!gemid)
16706 continue;
16708 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
16709 if(!gemProto)
16710 continue;
16712 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
16713 if(!gemProperty)
16714 continue;
16716 uint8 GemColor = gemProperty->color;
16718 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
16720 if(tmpcolormask & GemColor)
16721 ++curcount[b];
16727 bool activate = true;
16729 for(int i = 0; i < 5; i++)
16731 if(!Condition->Color[i])
16732 continue;
16734 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
16736 // if have <CompareColor> use them as count, else use <value> from Condition
16737 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
16739 switch(Condition->Comparator[i])
16741 case 2: // requires less <color> than (<value> || <comparecolor>) gems
16742 activate &= (_cur_gem < _cmp_gem) ? true : false;
16743 break;
16744 case 3: // requires more <color> than (<value> || <comparecolor>) gems
16745 activate &= (_cur_gem > _cmp_gem) ? true : false;
16746 break;
16747 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
16748 activate &= (_cur_gem >= _cmp_gem) ? true : false;
16749 break;
16753 sLog.outDebug("Checking Condition %u, there are %u Meta Gems, %u Red Gems, %u Yellow Gems and %u Blue Gems, Activate:%s", enchantmentcondition, curcount[0], curcount[1], curcount[2], curcount[3], activate ? "yes" : "no");
16755 return activate;
16758 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
16760 //cycle all equipped items
16761 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
16763 //enchants for the slot being socketed are handled by Player::ApplyItemMods
16764 if(slot == exceptslot)
16765 continue;
16767 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
16769 if(!pItem || !pItem->GetProto()->Socket[0].Color)
16770 continue;
16772 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
16774 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
16775 if(!enchant_id)
16776 continue;
16778 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
16779 if(!enchantEntry)
16780 continue;
16782 uint32 condition = enchantEntry->EnchantmentCondition;
16783 if(condition)
16785 //was enchant active with/without item?
16786 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
16787 //should it now be?
16788 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
16790 // ignore item gem conditions
16791 //if state changed, (dis)apply enchant
16792 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
16799 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
16800 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
16802 //cycle all equipped items
16803 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
16805 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
16806 if(slot == exceptslot)
16807 continue;
16809 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
16811 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
16812 continue;
16814 //cycle all (gem)enchants
16815 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
16817 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
16818 if(!enchant_id) //if no enchant go to next enchant(slot)
16819 continue;
16821 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
16822 if(!enchantEntry)
16823 continue;
16825 //only metagems to be (de)activated, so only enchants with condition
16826 uint32 condition = enchantEntry->EnchantmentCondition;
16827 if(condition)
16828 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
16833 void Player::LeaveBattleground(bool teleportToEntryPoint)
16835 if(BattleGround *bg = GetBattleGround())
16837 bool need_debuf = bg->isBattleGround() && (bg->GetStatus() == STATUS_IN_PROGRESS) && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER);
16839 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
16841 // call after remove to be sure that player resurrected for correct cast
16842 if(need_debuf)
16843 CastSpell(this, 26013, true); // Deserter
16847 bool Player::CanJoinToBattleground() const
16849 // check Deserter debuff
16850 if(GetDummyAura(26013))
16851 return false;
16853 return true;
16856 bool Player::CanReportAfkDueToLimit()
16858 // a player can complain about 15 people per 5 minutes
16859 if(m_bgAfkReportedCount >= 15)
16860 return false;
16861 ++m_bgAfkReportedCount;
16862 return true;
16865 ///This player has been blamed to be inactive in a battleground
16866 void Player::ReportedAfkBy(Player* reporter)
16868 BattleGround *bg = GetBattleGround();
16869 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
16870 return;
16872 // check if player has 'Idle' or 'Inactive' debuff
16873 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
16875 m_bgAfkReporter.insert(reporter->GetGUIDLow());
16876 // 3 players have to complain to apply debuff
16877 if(m_bgAfkReporter.size() >= 3)
16879 // cast 'Idle' spell
16880 CastSpell(this, 43680, true);
16881 m_bgAfkReporter.clear();
16886 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
16888 // gamemaster in GM mode see all, including ghosts
16889 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
16890 return true;
16892 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
16893 if (InBattleGround())
16895 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
16896 return false;
16897 return true;
16900 // Live player see live player or dead player with not realized corpse
16901 if(pl->isAlive() || pl->m_deathTimer > 0)
16903 return isAlive() || m_deathTimer > 0;
16906 // Ghost see other friendly ghosts, that's for sure
16907 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
16908 return true;
16910 // Dead player see live players near own corpse
16911 if(isAlive())
16913 Corpse *corpse = pl->GetCorpse();
16914 if(corpse)
16916 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
16917 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
16918 return true;
16922 // and not see any other
16923 return false;
16926 bool Player::IsVisibleGloballyFor( Player* u ) const
16928 if(!u)
16929 return false;
16931 // Always can see self
16932 if (u==this)
16933 return true;
16935 // Visible units, always are visible for all players
16936 if (GetVisibility() == VISIBILITY_ON)
16937 return true;
16939 // GMs are visible for higher gms (or players are visible for gms)
16940 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
16941 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
16943 // non faction visibility non-breakable for non-GMs
16944 if (GetVisibility() == VISIBILITY_OFF)
16945 return false;
16947 // non-gm stealth/invisibility not hide from global player lists
16948 return true;
16951 void Player::UpdateVisibilityOf(WorldObject* target)
16953 if(HaveAtClient(target))
16955 if(!target->isVisibleForInState(this,true))
16957 target->DestroyForPlayer(this);
16958 m_clientGUIDs.erase(target->GetGUID());
16960 #ifdef MANGOS_DEBUG
16961 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16962 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
16963 #endif
16966 else
16968 if(target->isVisibleForInState(this,false))
16970 target->SendUpdateToPlayer(this);
16971 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
16972 m_clientGUIDs.insert(target->GetGUID());
16974 #ifdef MANGOS_DEBUG
16975 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16976 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
16977 #endif
16979 // target aura duration for caster show only if target exist at caster client
16980 // send data at target visibility change (adding to client)
16981 if(target!=this && target->isType(TYPEMASK_UNIT))
16982 SendAuraDurationsForTarget((Unit*)target);
16984 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
16985 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
16990 template<class T>
16991 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
16993 s64.insert(target->GetGUID());
16996 template<>
16997 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
16999 if(!target->IsTransport())
17000 s64.insert(target->GetGUID());
17003 template<class T>
17004 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
17006 if(HaveAtClient(target))
17008 if(!target->isVisibleForInState(this,true))
17010 target->BuildOutOfRangeUpdateBlock(&data);
17011 m_clientGUIDs.erase(target->GetGUID());
17013 #ifdef MANGOS_DEBUG
17014 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17015 sLog.outDebug("Object %u (Type: %u, Entry: %u) is out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),target->GetEntry(),GetGUIDLow(),GetDistance(target));
17016 #endif
17019 else
17021 if(target->isVisibleForInState(this,false))
17023 visibleNow.insert(target);
17024 target->BuildUpdate(data_updates);
17025 target->BuildCreateUpdateBlockForPlayer(&data, this);
17026 UpdateVisibilityOf_helper(m_clientGUIDs,target);
17028 #ifdef MANGOS_DEBUG
17029 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17030 sLog.outDebug("Object %u (Type: %u, Entry: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),target->GetEntry(),GetGUIDLow(),GetDistance(target));
17031 #endif
17036 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17037 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17038 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17039 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17040 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17042 void Player::InitPrimaryProffesions()
17044 SetFreePrimaryProffesions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
17047 void Player::SendComboPoints()
17049 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
17050 if (combotarget)
17052 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
17053 data.append(combotarget->GetPackGUID());
17054 data << uint8(m_comboPoints);
17055 GetSession()->SendPacket(&data);
17059 void Player::AddComboPoints(Unit* target, int8 count)
17061 if(!count)
17062 return;
17064 // without combo points lost (duration checked in aura)
17065 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17067 if(target->GetGUID() == m_comboTarget)
17069 m_comboPoints += count;
17071 else
17073 if(m_comboTarget)
17074 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17075 target->RemoveComboPointHolder(GetGUIDLow());
17077 m_comboTarget = target->GetGUID();
17078 m_comboPoints = count;
17080 target->AddComboPointHolder(GetGUIDLow());
17083 if (m_comboPoints > 5) m_comboPoints = 5;
17084 if (m_comboPoints < 0) m_comboPoints = 0;
17086 SendComboPoints();
17089 void Player::ClearComboPoints()
17091 if(!m_comboTarget)
17092 return;
17094 // without combopoints lost (duration checked in aura)
17095 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17097 m_comboPoints = 0;
17099 SendComboPoints();
17101 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17102 target->RemoveComboPointHolder(GetGUIDLow());
17104 m_comboTarget = 0;
17107 void Player::SetGroup(Group *group, int8 subgroup)
17109 if(group == NULL) m_group.unlink();
17110 else
17112 // never use SetGroup without a subgroup unless you specify NULL for group
17113 assert(subgroup >= 0);
17114 m_group.link(group, this);
17115 m_group.setSubGroup((uint8)subgroup);
17119 void Player::SendInitialPacketsBeforeAddToMap()
17121 WorldPacket data(SMSG_SET_REST_START, 4);
17122 data << uint32(0); // unknown, may be rest state time or expirience
17123 GetSession()->SendPacket(&data);
17125 // Homebind
17126 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
17127 data << m_homebindX << m_homebindY << m_homebindZ;
17128 data << (uint32) m_homebindMapId;
17129 data << (uint32) m_homebindZoneId;
17130 GetSession()->SendPacket(&data);
17132 // SMSG_SET_PROFICIENCY
17133 // SMSG_UPDATE_AURA_DURATION
17135 // tutorial stuff
17136 data.Initialize(SMSG_TUTORIAL_FLAGS, 8*4);
17137 for (int i = 0; i < 8; ++i)
17138 data << uint32( GetTutorialInt(i) );
17139 GetSession()->SendPacket(&data);
17141 SendInitialSpells();
17143 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
17144 data << uint32(0); // count, for(count) uint32;
17145 GetSession()->SendPacket(&data);
17147 SendInitialActionButtons();
17148 SendInitialReputations();
17149 UpdateZone(GetZoneId());
17150 SendInitWorldStates();
17152 // SMSG_SET_AURA_SINGLE
17154 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
17155 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
17156 data << (float)0.01666667f; // game speed
17157 GetSession()->SendPacket( &data );
17159 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17160 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
17161 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2);
17164 void Player::SendInitialPacketsAfterAddToMap()
17166 CastSpell(this, 836, true); // LOGINEFFECT
17168 // set some aura effects that send packet to player client after add player to map
17169 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17170 // same auras state lost at far teleport, send it one more time in this case also
17171 static const AuraType auratypes[] =
17173 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
17174 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
17175 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
17177 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
17179 Unit::AuraList const& auraList = GetAurasByType(*itr);
17180 if(!auraList.empty())
17181 auraList.front()->ApplyModifier(true,true);
17184 if(HasAuraType(SPELL_AURA_MOD_STUN))
17185 SetMovement(MOVE_ROOT);
17187 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17188 if(HasAuraType(SPELL_AURA_MOD_ROOT))
17190 WorldPacket data(SMSG_FORCE_MOVE_ROOT, 10);
17191 data.append(GetPackGUID());
17192 data << (uint32)2;
17193 SendMessageToSet(&data,true);
17196 SendEnchantmentDurations(); // must be after add to map
17197 SendItemDurations(); // must be after add to map
17200 void Player::SendUpdateToOutOfRangeGroupMembers()
17202 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
17203 return;
17204 if(Group* group = GetGroup())
17205 group->UpdatePlayerOutOfRange(this);
17207 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
17208 m_auraUpdateMask = 0;
17209 if(Pet *pet = GetPet())
17210 pet->ResetAuraUpdateMask();
17213 void Player::SendTransferAborted(uint32 mapid, uint16 reason)
17215 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
17216 data << uint32(mapid);
17217 data << uint16(reason); // transfer abort reason
17218 GetSession()->SendPacket(&data);
17221 void Player::SendInstanceResetWarning(uint32 mapid, uint32 time)
17223 // type of warning, based on the time remaining until reset
17224 uint32 type;
17225 if(time > 3600)
17226 type = RAID_INSTANCE_WELCOME;
17227 else if(time > 900 && time <= 3600)
17228 type = RAID_INSTANCE_WARNING_HOURS;
17229 else if(time > 300 && time <= 900)
17230 type = RAID_INSTANCE_WARNING_MIN;
17231 else
17232 type = RAID_INSTANCE_WARNING_MIN_SOON;
17233 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4);
17234 data << uint32(type);
17235 data << uint32(mapid);
17236 data << uint32(time);
17237 GetSession()->SendPacket(&data);
17240 void Player::ApplyEquipCooldown( Item * pItem )
17242 for(int i = 0; i <5; ++i)
17244 _Spell const& spellData = pItem->GetProto()->Spells[i];
17246 // no spell
17247 if( !spellData.SpellId )
17248 continue;
17250 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
17251 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
17252 continue;
17254 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
17256 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
17257 data << pItem->GetGUID();
17258 data << uint32(spellData.SpellId);
17259 GetSession()->SendPacket(&data);
17263 void Player::resetSpells()
17265 // not need after this call
17266 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
17268 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_SPELLS;
17269 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS), GetGUIDLow());
17272 // make full copy of map (spells removed and marked as deleted at another spell remove
17273 // and we can't use original map for safe iterative with visit each spell at loop end
17274 PlayerSpellMap smap = GetSpellMap();
17276 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
17277 removeSpell(iter->first); // only iter->first can be accessed, object by iter->second can be deleted already
17279 learnDefaultSpells();
17280 learnQuestRewardedSpells();
17283 void Player::learnDefaultSpells(bool loading)
17285 // learn default race/class spells
17286 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
17287 std::list<CreateSpellPair>::const_iterator spell_itr;
17288 for (spell_itr = info->spell.begin(); spell_itr!=info->spell.end(); ++spell_itr)
17290 uint16 tspell = spell_itr->first;
17291 if (tspell)
17293 sLog.outDebug("PLAYER: Adding initial spell, id = %u",tspell);
17294 if(loading || !spell_itr->second) // not care about passive spells or loading case
17295 addSpell(tspell,spell_itr->second);
17296 else // but send in normal spell in game learn case
17297 learnSpell(tspell);
17302 void Player::learnQuestRewardedSpells(Quest const* quest)
17304 uint32 spell_id = quest->GetRewSpellCast();
17306 // skip quests without rewarded spell
17307 if( !spell_id )
17308 return;
17310 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
17311 if(!spellInfo)
17312 return;
17314 // check learned spells state
17315 bool found = false;
17316 for(int i=0; i < 3; ++i)
17318 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
17320 found = true;
17321 break;
17325 // skip quests with not teaching spell or already known spell
17326 if(!found)
17327 return;
17329 // prevent learn non first rank unknown profession and second specialization for same profession)
17330 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
17331 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
17333 // not have first rank learned (unlearned prof?)
17334 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
17335 if( !HasSpell(first_spell) )
17336 return;
17338 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
17339 if(!learnedInfo)
17340 return;
17342 // specialization
17343 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
17345 // search other specialization for same prof
17346 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17348 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
17349 continue;
17351 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
17352 if(!itrInfo)
17353 return;
17355 // compare only specializations
17356 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
17357 continue;
17359 // compare same chain spells
17360 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
17361 continue;
17363 // now we have 2 specialization, learn possible only if found is lesser specialization rank
17364 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
17365 return;
17370 CastSpell( this, spell_id, true);
17373 void Player::learnQuestRewardedSpells()
17375 // learn spells received from quest completing
17376 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
17378 // skip no rewarded quests
17379 if(!itr->second.m_rewarded)
17380 continue;
17382 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
17383 if( !quest )
17384 continue;
17386 learnQuestRewardedSpells(quest);
17390 void Player::learnSkillRewardedSpells(uint32 skill_id )
17392 uint32 raceMask = getRaceMask();
17393 uint32 classMask = getClassMask();
17394 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
17396 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
17397 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
17398 continue;
17399 // Check race if set
17400 if (pAbility->racemask && !(pAbility->racemask & raceMask))
17401 continue;
17402 // Check class if set
17403 if (pAbility->classmask && !(pAbility->classmask & classMask))
17404 continue;
17406 if (SpellEntry const* spellentry = sSpellStore.LookupEntry(pAbility->spellId))
17408 // Ok need learn spell
17409 learnSpell(pAbility->spellId);
17414 void Player::learnSkillRewardedSpells()
17416 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
17418 if(!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
17419 continue;
17421 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
17423 learnSkillRewardedSpells(pskill);
17427 void Player::SendAuraDurationsForTarget(Unit* target)
17429 for(Unit::AuraMap::const_iterator itr = target->GetAuras().begin(); itr != target->GetAuras().end(); ++itr)
17431 Aura* aura = itr->second;
17432 if(aura->GetAuraSlot() >= MAX_AURAS || aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
17433 continue;
17435 aura->SendAuraDurationForCaster(this);
17439 void Player::SetDailyQuestStatus( uint32 quest_id )
17441 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
17443 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
17445 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
17446 m_lastDailyQuestTime = time(NULL); // last daily quest time
17447 m_DailyQuestChanged = true;
17448 break;
17453 void Player::ResetDailyQuestStatus()
17455 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
17456 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
17458 // DB data deleted in caller
17459 m_DailyQuestChanged = false;
17460 m_lastDailyQuestTime = 0;
17463 BattleGround* Player::GetBattleGround() const
17465 if(GetBattleGroundId()==0)
17466 return NULL;
17468 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
17471 bool Player::InArena() const
17473 BattleGround *bg = GetBattleGround();
17474 if(!bg || !bg->isArena())
17475 return false;
17477 return true;
17480 bool Player::GetBGAccessByLevel(uint32 bgTypeId) const
17482 BattleGround *bg = sBattleGroundMgr.GetBattleGround(bgTypeId);
17483 if(!bg)
17484 return false;
17486 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
17487 return false;
17489 return true;
17492 uint32 Player::GetMinLevelForBattleGroundQueueId(uint32 queue_id)
17494 if(queue_id < 1)
17495 return 0;
17497 if(queue_id >=6)
17498 queue_id = 6;
17500 return 10*(queue_id+1);
17503 uint32 Player::GetMaxLevelForBattleGroundQueueId(uint32 queue_id)
17505 if(queue_id >=6)
17506 return 255; // hardcoded max level
17508 return 10*(queue_id+2)-1;
17511 uint32 Player::GetBattleGroundQueueIdFromLevel() const
17513 uint32 level = getLevel();
17514 if(level <= 19)
17515 return 0;
17516 else if (level > 69)
17517 return 6;
17518 else
17519 return level/10 - 1; // 20..29 -> 1, 30-39 -> 2, ...
17522 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
17524 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
17525 if(!vendor_faction)
17526 return 1.0f;
17528 ReputationRank rank = GetReputationRank(vendor_faction->faction);
17529 if(rank <= REP_NEUTRAL)
17530 return 1.0f;
17532 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
17535 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
17537 uint32 racemask = getRaceMask();
17538 uint32 classmask = getClassMask();
17540 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
17541 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
17543 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
17545 // skip wrong race skills
17546 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
17547 return false;
17549 // skip wrong class skills
17550 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
17551 return false;
17553 return true;
17556 bool Player::HasQuestForGO(int32 GOId)
17558 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
17560 QuestStatusData qs=i->second;
17561 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
17563 Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
17564 if(!qinfo)
17565 continue;
17567 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
17568 continue;
17570 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
17572 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
17573 continue;
17575 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
17576 return true;
17580 return false;
17583 void Player::UpdateForQuestsGO()
17585 if(m_clientGUIDs.empty())
17586 return;
17588 UpdateData udata;
17589 WorldPacket packet;
17590 for(ClientGUIDs::iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
17592 if(IS_GAMEOBJECT_GUID(*itr))
17594 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
17595 if(obj)
17596 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
17599 udata.BuildPacket(&packet);
17600 GetSession()->SendPacket(&packet);
17603 void Player::SummonIfPossible(bool agree)
17605 if(!agree)
17607 m_summon_expire = 0;
17608 return;
17611 // expire and auto declined
17612 if(m_summon_expire < time(NULL))
17613 return;
17615 // stop taxi flight at summon
17616 if(isInFlight())
17618 GetMotionMaster()->MovementExpired();
17619 m_taxi.ClearTaxiDestinations();
17622 // drop flag at summon
17623 if(BattleGround *bg = GetBattleGround())
17624 bg->EventPlayerDroppedFlag(this);
17626 m_summon_expire = 0;
17628 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
17631 void Player::RemoveItemDurations( Item *item )
17633 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
17635 if(*itr==item)
17637 m_itemDuration.erase(itr);
17638 break;
17643 void Player::AddItemDurations( Item *item )
17645 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
17647 m_itemDuration.push_back(item);
17648 item->SendTimeUpdate(this);
17652 void Player::AutoUnequipOffhandIfNeed()
17654 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
17655 if(!offItem)
17656 return;
17658 Item *mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );
17660 if(!mainItem || mainItem->GetProto()->InventoryType != INVTYPE_2HWEAPON)
17661 return;
17663 ItemPosCountVec off_dest;
17664 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
17665 if( off_msg == EQUIP_ERR_OK )
17667 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
17668 StoreItem( off_dest, offItem, true );
17670 else
17672 sLog.outError("Player::EquipItem: Can's store offhand item at 2hand item equip for player (GUID: %u).",GetGUIDLow());
17676 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
17678 if(spellInfo->EquippedItemClass < 0)
17679 return true;
17681 // scan other equipped items for same requirements (mostly 2 daggers/etc)
17682 // for optimize check 2 used cases only
17683 switch(spellInfo->EquippedItemClass)
17685 case ITEM_CLASS_WEAPON:
17687 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
17688 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
17689 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
17690 return true;
17691 break;
17693 case ITEM_CLASS_ARMOR:
17695 // tabard not have dependent spells
17696 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
17697 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
17698 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
17699 return true;
17701 // shields can be equipped to offhand slot
17702 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
17703 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
17704 return true;
17706 // ranged slot can have some armor subclasses
17707 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
17708 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
17709 return true;
17711 break;
17713 default:
17714 sLog.outError("HasItemFitToSpellReqirements: Not handeled spell reqirement for item class %u",spellInfo->EquippedItemClass);
17715 break;
17718 return false;
17721 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
17723 AuraMap& auras = GetAuras();
17724 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
17726 Aura* aura = itr->second;
17728 // skip passive (passive item dependent spells work in another way) and not self applied auras
17729 SpellEntry const* spellInfo = aura->GetSpellProto();
17730 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
17732 ++itr;
17733 continue;
17736 // skip if not item dependent or have alternative item
17737 if(HasItemFitToSpellReqirements(spellInfo,pItem))
17739 ++itr;
17740 continue;
17743 // no alt item, remove aura, restart check
17744 RemoveAurasDueToSpell(aura->GetId());
17745 itr = auras.begin();
17748 // currently casted spells can be dependent from item
17749 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
17751 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
17752 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
17753 InterruptSpell(i);
17757 uint32 Player::GetResurrectionSpellId()
17759 // search priceless resurrection possabilities
17760 uint32 prio = 0;
17761 uint32 spell_id = 0;
17762 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
17763 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
17765 // Soulstone Resurrection // prio: 3 (max, non death persistent)
17766 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
17768 switch((*itr)->GetId())
17770 case 20707: spell_id = 3026; break; // rank 1
17771 case 20762: spell_id = 20758; break; // rank 2
17772 case 20763: spell_id = 20759; break; // rank 3
17773 case 20764: spell_id = 20760; break; // rank 4
17774 case 20765: spell_id = 20761; break; // rank 5
17775 case 27239: spell_id = 27240; break; // rank 6
17776 default:
17777 sLog.outError("Unhandled spell %%u: S.Resurrection",(*itr)->GetId());
17778 continue;
17781 prio = 3;
17783 // Twisting Nether // prio: 2 (max)
17784 else if((*itr)->GetId()==23701 && roll_chance_i(10))
17786 prio = 2;
17787 spell_id = 23700;
17791 // Reincarnation (passive spell) // prio: 1
17792 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
17793 spell_id = 21169;
17795 return spell_id;
17798 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
17800 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
17802 // prepare data for near group iteration (PvP and !PvP cases)
17803 uint32 xp = 0;
17804 bool honored_kill = false;
17806 if(Group *pGroup = GetGroup())
17808 uint32 count = 0;
17809 uint32 sum_level = 0;
17810 Player* member_with_max_level = NULL;
17811 Player* not_gray_member_with_max_level = NULL;
17813 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
17815 if(member_with_max_level)
17817 /// not get Xp in PvP or no not gray players in group
17818 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
17820 /// skip in check PvP case (for speed, not used)
17821 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
17822 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
17823 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
17825 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
17827 Player* pGroupGuy = itr->getSource();
17828 if(!pGroupGuy)
17829 continue;
17831 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
17832 continue; // member (alive or dead) or his corpse at req. distance
17834 // honor can be in PvP and !PvP (racial leader) cases (for alive)
17835 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
17836 honored_kill = true;
17838 // xp and reputation only in !PvP case
17839 if(!PvP)
17841 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
17843 // if is in dungeon then all receive full reputation at kill
17844 // rewarded any alive/dead/near_corpse group member
17845 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
17847 // XP updated only for alive group member
17848 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
17849 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
17851 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
17853 pGroupGuy->GiveXP(itr_xp, pVictim);
17854 if(Pet* pet = pGroupGuy->GetPet())
17855 pet->GivePetXP(itr_xp/2);
17858 // quest objectives updated only for alive group member or dead but with not released body
17859 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
17861 // normal creature (not pet/etc) can be only in !PvP case
17862 if(pVictim->GetTypeId()==TYPEID_UNIT)
17863 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
17869 else // if (!pGroup)
17871 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
17873 // honor can be in PvP and !PvP (racial leader) cases
17874 if(RewardHonor(pVictim,1))
17875 honored_kill = true;
17877 // xp and reputation only in !PvP case
17878 if(!PvP)
17880 RewardReputation(pVictim,1);
17881 GiveXP(xp, pVictim);
17883 if(Pet* pet = GetPet())
17884 pet->GivePetXP(xp);
17886 // normal creature (not pet/etc) can be only in !PvP case
17887 if(pVictim->GetTypeId()==TYPEID_UNIT)
17888 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
17891 return xp || honored_kill;
17894 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
17896 if(pRewardSource->GetDistance(this) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
17897 return true;
17899 if(isAlive())
17900 return false;
17902 Corpse* corpse = GetCorpse();
17903 if(!corpse)
17904 return false;
17906 return pRewardSource->GetDistance(corpse) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE);
17909 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
17911 Item* item = GetWeaponForAttack(attType,true);
17913 // unarmmed only with base attack
17914 if(attType != BASE_ATTACK && !item)
17915 return 0;
17917 // weapon skill or (unarmed for base attack)
17918 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
17919 return GetBaseSkillValue(skill);
17922 void Player::ResurectUsingRequestData()
17924 ResurrectPlayer(0.0f,false);
17926 if(GetMaxHealth() > m_resurrectHealth)
17927 SetHealth( m_resurrectHealth );
17928 else
17929 SetHealth( GetMaxHealth() );
17931 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
17932 SetPower(POWER_MANA, m_resurrectMana );
17933 else
17934 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
17936 SetPower(POWER_RAGE, 0 );
17938 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
17940 SpawnCorpseBones();
17942 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
17945 void Player::SetClientControl(Unit* target, uint8 allowMove)
17947 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
17948 data.append(target->GetPackGUID());
17949 data << uint8(allowMove);
17950 GetSession()->SendPacket(&data);
17953 void Player::UpdateZoneDependentAuras( uint32 newZone )
17955 // remove new continent flight forms
17956 if( !isGameMaster() &&
17957 GetVirtualMapForMapAndZone(GetMapId(),newZone) != 530)
17959 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
17960 RemoveSpellsCausingAura(SPELL_AURA_FLY);
17963 // Some spells applied at enter into zone (with subzones)
17964 // Human Illusion
17965 // NOTE: these are removed by RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
17966 if ( newZone == 2367 ) // Old Hillsbrad Foothills
17968 uint32 spellid = 0;
17969 // all horde races
17970 if( GetTeam() == HORDE )
17971 spellid = getGender() == GENDER_FEMALE ? 35481 : 35480;
17972 // and some alliance races
17973 else if( getRace() == RACE_NIGHTELF || getRace() == RACE_DRAENEI )
17974 spellid = getGender() == GENDER_FEMALE ? 35483 : 35482;
17976 if(spellid && !HasAura(spellid,0) )
17977 CastSpell(this,spellid,true);
17981 void Player::UpdateAreaDependentAuras( uint32 newArea )
17983 // remove auras from spells with area limitations
17984 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
17986 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
17987 if(!IsSpellAllowedInLocation(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea))
17988 RemoveAura(iter);
17989 else
17990 ++iter;
17993 // unmount if enter in this subzone
17994 if( newArea == 35)
17995 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
17996 // Dragonmaw Illusion
17997 else if( newArea == 3759 || newArea == 3966 || newArea == 3939 )
17999 if( GetDummyAura(40214) )
18001 if( !HasAura(40216,0) )
18002 CastSpell(this,40216,true);
18003 if( !HasAura(42016,0) )
18004 CastSpell(this,42016,true);
18009 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
18011 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18012 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18014 return copseReclaimDelay[0];
18017 time_t now = time(NULL);
18018 // 0..2 full period
18019 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
18020 return copseReclaimDelay[count];
18023 void Player::UpdateCorpseReclaimDelay()
18025 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
18027 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18028 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18029 return;
18031 time_t now = time(NULL);
18032 if(now < m_deathExpireTime)
18034 // full and partly periods 1..3
18035 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
18036 if(count < MAX_DEATH_COUNT)
18037 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
18038 else
18039 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
18041 else
18042 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
18045 void Player::SendCorpseReclaimDelay(bool load)
18047 Corpse* corpse = GetCorpse();
18048 if(!corpse)
18049 return;
18051 uint32 delay;
18052 if(load)
18054 if(corpse->GetGhostTime() > m_deathExpireTime)
18055 return;
18057 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
18059 uint32 count;
18060 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18061 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18063 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
18064 if(count>=MAX_DEATH_COUNT)
18065 count = MAX_DEATH_COUNT-1;
18067 else
18068 count=0;
18070 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
18072 time_t now = time(NULL);
18073 if(now >= expected_time)
18074 return;
18076 delay = expected_time-now;
18078 else
18079 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
18081 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
18082 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
18083 data << uint32(delay*1000);
18084 GetSession()->SendPacket( &data );
18087 Player* Player::GetNextRandomRaidMember(float radius)
18089 Group *pGroup = GetGroup();
18090 if(!pGroup)
18091 return NULL;
18093 std::vector<Player*> nearMembers;
18094 nearMembers.reserve(pGroup->GetMembersCount());
18096 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18098 Player* Target = itr->getSource();
18100 // IsHostileTo check duel and controlled by enemy
18101 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
18102 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
18103 nearMembers.push_back(Target);
18106 if (nearMembers.empty())
18107 return NULL;
18109 uint32 randTarget = urand(0,nearMembers.size()-1);
18110 return nearMembers[randTarget];
18113 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
18115 float water_z = m->GetWaterLevel(x,y);
18116 float height_z = m->GetHeight(x,y,z, false); // use .map base surface height
18117 uint8 flag1 = m->GetTerrainType(x,y);
18119 //!Underwater check, not in water if underground or above water level
18120 if (height_z <= INVALID_HEIGHT || z < (height_z-2) || z > (water_z - 2) )
18121 m_isunderwater &= 0x7A;
18122 else if ((z < (water_z - 2)) && (flag1 & 0x01))
18123 m_isunderwater |= 0x01;
18125 //!in lava check, anywhere under lava level
18126 if ((height_z <= INVALID_HEIGHT || z < (height_z - 0)) && (flag1 == 0x00) && IsInWater())
18127 m_isunderwater |= 0x80;
18130 void Player::SetCanParry( bool value )
18132 if(m_canParry==value)
18133 return;
18135 m_canParry = value;
18136 UpdateParryPercentage();
18139 void Player::SetCanBlock( bool value )
18141 if(m_canBlock==value)
18142 return;
18144 m_canBlock = value;
18145 UpdateBlockPercentage();
18148 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
18150 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
18151 if(itr->pos == this->pos)
18152 return true;
18154 return false;
18157 bool Player::isAllowUseBattleGroundObject()
18159 return ( //InBattleGround() && // in battleground - not need, check in other cases
18160 !IsMounted() && // not mounted
18161 !HasStealthAura() && // not stealthed
18162 !HasInvisibilityAura() && // not invisible
18163 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
18164 isAlive() // live player