More fixes for wrong format arg/value pairs.
[auctionmangos.git] / src / game / Player.cpp
blobdf3d925d0fd8da1a8d8a919656a65a18d015df30
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 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
3832 if(Item* pItem = GetItemByPos( i, j ))
3833 DurabilityLoss(pItem,percent);
3837 void Player::DurabilityLoss(Item* item, double percent)
3839 if(!item )
3840 return;
3842 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3844 if(!pMaxDurability)
3845 return;
3847 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
3849 if(pDurabilityLoss < 1 )
3850 pDurabilityLoss = 1;
3852 DurabilityPointsLoss(item,pDurabilityLoss);
3855 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
3857 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
3858 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3859 DurabilityPointsLoss(pItem,points);
3861 if(inventory)
3863 // bags not have durability
3864 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3866 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
3867 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3868 DurabilityPointsLoss(pItem,points);
3870 // keys not have durability
3871 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3873 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3874 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3875 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
3876 if(Item* pItem = GetItemByPos( i, j ))
3877 DurabilityPointsLoss(pItem,points);
3881 void Player::DurabilityPointsLoss(Item* item, int32 points)
3883 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3884 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
3885 int32 pNewDurability = pOldDurability - points;
3887 if (pNewDurability < 0)
3888 pNewDurability = 0;
3889 else if (pNewDurability > pMaxDurability)
3890 pNewDurability = pMaxDurability;
3892 if (pOldDurability != pNewDurability)
3894 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
3895 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
3896 _ApplyItemMods(item,item->GetSlot(), false);
3898 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
3900 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
3901 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
3902 _ApplyItemMods(item,item->GetSlot(), true);
3904 item->SetState(ITEM_CHANGED, this);
3908 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
3910 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
3911 DurabilityPointsLoss(pItem,1);
3914 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
3916 uint32 TotalCost = 0;
3917 // equipped, backpack, bags itself
3918 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
3919 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
3921 // bank, buyback and keys not repaired
3923 // items in inventory bags
3924 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; j++)
3925 for(int i = 0; i < MAX_BAG_SIZE; i++)
3926 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
3927 return TotalCost;
3930 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
3932 Item* item = GetItemByPos(pos);
3934 uint32 TotalCost = 0;
3935 if(!item)
3936 return TotalCost;
3938 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3939 if(!maxDurability)
3940 return TotalCost;
3942 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
3944 if(cost)
3946 uint32 LostDurability = maxDurability - curDurability;
3947 if(LostDurability>0)
3949 ItemPrototype const *ditemProto = item->GetProto();
3951 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
3952 if(!dcost)
3954 sLog.outError("ERROR: RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
3955 return TotalCost;
3958 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
3959 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
3960 if(!dQualitymodEntry)
3962 sLog.outError("ERROR: RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
3963 return TotalCost;
3966 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
3967 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
3969 costs = uint32(costs * discountMod);
3971 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
3972 costs = 1;
3974 if (guildBank)
3976 if (GetGuildId()==0)
3978 DEBUG_LOG("You are not member of a guild");
3979 return TotalCost;
3982 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
3983 if (!pGuild)
3984 return TotalCost;
3986 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
3988 DEBUG_LOG("You do not have rights to withdraw for repairs");
3989 return TotalCost;
3992 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
3994 DEBUG_LOG("You do not have enough money withdraw amount remaining");
3995 return TotalCost;
3998 if (pGuild->GetGuildBankMoney() < costs)
4000 DEBUG_LOG("There is not enough money in bank");
4001 return TotalCost;
4004 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4005 TotalCost = costs;
4007 else if (GetMoney() < costs)
4009 DEBUG_LOG("You do not have enough money");
4010 return TotalCost;
4012 else
4013 ModifyMoney( -int32(costs) );
4017 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4018 item->SetState(ITEM_CHANGED, this);
4020 // reapply mods for total broken and repaired item if equipped
4021 if(IsEquipmentPos(pos) && !curDurability)
4022 _ApplyItemMods(item,pos & 255, true);
4023 return TotalCost;
4026 void Player::RepopAtGraveyard()
4028 // note: this can be called also when the player is alive
4029 // for example from WorldSession::HandleMovementOpcodes
4031 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4033 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4034 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4036 ResurrectPlayer(0.5f);
4037 SpawnCorpseBones();
4040 WorldSafeLocsEntry const *ClosestGrave = NULL;
4042 // Special handle for battleground maps
4043 BattleGround *bg = sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
4045 if(bg && (bg->GetTypeID() == BATTLEGROUND_AB || bg->GetTypeID() == BATTLEGROUND_EY))
4046 ClosestGrave = bg->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetTeam());
4047 else
4048 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4050 // stop countdown until repop
4051 m_deathTimer = 0;
4053 // if no grave found, stay at the current location
4054 // and don't show spirit healer location
4055 if(ClosestGrave)
4057 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4058 if(isDead()) // not send if alive, because it used in TeleportTo()
4060 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4061 data << ClosestGrave->map_id;
4062 data << ClosestGrave->x;
4063 data << ClosestGrave->y;
4064 data << ClosestGrave->z;
4065 GetSession()->SendPacket(&data);
4070 void Player::JoinedChannel(Channel *c)
4072 m_channels.push_back(c);
4075 void Player::LeftChannel(Channel *c)
4077 m_channels.remove(c);
4080 void Player::CleanupChannels()
4082 while(!m_channels.empty())
4084 Channel* ch = *m_channels.begin();
4085 m_channels.erase(m_channels.begin()); // remove from player's channel list
4086 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4087 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4088 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4091 sLog.outDebug("Player: channels cleaned up!");
4094 void Player::UpdateLocalChannels(uint32 newZone )
4096 if(m_channels.empty())
4097 return;
4099 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4100 if(!current_zone)
4101 return;
4103 ChannelMgr* cMgr = channelMgr(GetTeam());
4104 if(!cMgr)
4105 return;
4107 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4109 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4111 next = i; ++next;
4113 // skip non built-in channels
4114 if(!(*i)->IsConstant())
4115 continue;
4117 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4118 if(!ch)
4119 continue;
4121 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4122 continue;
4124 // new channel
4125 char new_channel_name_buf[100];
4126 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4127 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4129 if((*i)!=new_channel)
4131 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4133 // leave old channel
4134 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4135 std::string name = (*i)->GetName(); // stroe name, (*i)erase in LeftChannel
4136 LeftChannel(*i); // remove from player's channel list
4137 cMgr->LeftChannel(name); // delete if empty
4140 sLog.outDebug("Player: channels cleaned up!");
4143 void Player::LeaveLFGChannel()
4145 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4147 if((*i)->IsLFG())
4149 (*i)->Leave(GetGUID());
4150 break;
4155 void Player::UpdateDefense()
4157 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4159 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4161 // update dependent from defense skill part
4162 UpdateDefenseBonusesMod();
4166 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply, bool affectStats)
4168 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4170 sLog.outError("ERROR in HandleBaseModValue(): nonexisted BaseModGroup of wrong BaseModType!");
4171 return;
4174 float val = 1.0f;
4176 switch(modType)
4178 case FLAT_MOD:
4179 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4180 break;
4181 case PCT_MOD:
4182 if(amount <= -100.0f)
4183 amount = -200.0f;
4185 val = (100.0f + amount) / 100.0f;
4186 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4187 break;
4190 if(!CanModifyStats())
4191 return;
4193 switch(modGroup)
4195 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4196 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4197 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4198 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4199 default: break;
4203 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4205 if(modGroup >= BASEMOD_END || modType > MOD_END)
4207 sLog.outError("ERROR: trial to access nonexisted BaseModGroup or wrong BaseModType!");
4208 return 0.0f;
4211 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4212 return 0.0f;
4214 return m_auraBaseMod[modGroup][modType];
4217 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4219 if(modGroup >= BASEMOD_END)
4221 sLog.outError("ERROR: wrong BaseModGroup in GetTotalBaseModValue()!");
4222 return 0.0f;
4225 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4226 return 0.0f;
4228 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4231 uint32 Player::GetShieldBlockValue() const
4233 BaseModGroup modGroup = SHIELD_BLOCK_VALUE;
4235 float value = GetTotalBaseModValue(modGroup) + GetStat(STAT_STRENGTH)/20 - 1;
4237 value = (value < 0) ? 0 : value;
4239 return uint32(value);
4242 float Player::GetMeleeCritFromAgility()
4244 uint32 level = getLevel();
4245 uint32 pclass = getClass();
4247 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4249 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4250 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4251 if (critBase==NULL || critRatio==NULL)
4252 return 0.0f;
4254 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4255 return crit*100.0f;
4258 float Player::GetDodgeFromAgility()
4260 // Table for base dodge values
4261 float dodge_base[MAX_CLASSES] = {
4262 0.0075f, // Warrior
4263 0.00652f, // Paladin
4264 -0.0545f, // Hunter
4265 -0.0059f, // Rogue
4266 0.03183f, // Priest
4267 0.0114f, // DK
4268 0.0167f, // Shaman
4269 0.034575f, // Mage
4270 0.02011f, // Warlock
4271 0.0f, // ??
4272 -0.0187f // Druid
4274 // Crit/agility to dodge/agility coefficient multipliers
4275 float crit_to_dodge[MAX_CLASSES] = {
4276 1.1f, // Warrior
4277 1.0f, // Paladin
4278 1.6f, // Hunter
4279 2.0f, // Rogue
4280 1.0f, // Priest
4281 1.0f, // DK?
4282 1.0f, // Shaman
4283 1.0f, // Mage
4284 1.0f, // Warlock
4285 0.0f, // ??
4286 1.7f // Druid
4289 uint32 level = getLevel();
4290 uint32 pclass = getClass();
4292 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4294 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4295 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4296 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4297 return 0.0f;
4299 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4300 return dodge*100.0f;
4303 float Player::GetSpellCritFromIntellect()
4305 uint32 level = getLevel();
4306 uint32 pclass = getClass();
4308 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4310 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4311 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4312 if (critBase==NULL || critRatio==NULL)
4313 return 0.0f;
4315 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4316 return crit*100.0f;
4319 float Player::GetRatingCoefficient(CombatRating cr) const
4321 uint32 level = getLevel();
4323 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4325 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4326 if (Rating == NULL)
4327 return 1.0f; // By default use minimum coefficient (not must be called)
4329 return Rating->ratio;
4332 float Player::GetRatingBonusValue(CombatRating cr) const
4334 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4337 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4339 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.0f;
4340 if (melee>25.0f) melee = 25.0f;
4341 return uint32 (melee * damage /100.0f);
4344 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4346 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.0f;
4347 if (ranged>25.0f) ranged=25.0f;
4348 return uint32 (ranged * damage /100.0f);
4351 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4353 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.0f;
4354 // In wow script resilience limited to 25%
4355 if (spell>25.0f)
4356 spell = 25.0f;
4357 return uint32 (spell * damage / 100.0f);
4360 uint32 Player::GetDotDamageReduction(uint32 damage) const
4362 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4363 // Dot resilience not limited (limit it by 100%)
4364 if (spellDot > 100.0f)
4365 spellDot = 100.0f;
4366 return uint32 (spellDot * damage / 100.0f);
4369 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4371 switch (attType)
4373 case BASE_ATTACK:
4374 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4375 case OFF_ATTACK:
4376 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4377 default:
4378 break;
4380 return 0.0f;
4383 float Player::OCTRegenHPPerSpirit()
4385 uint32 level = getLevel();
4386 uint32 pclass = getClass();
4388 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4390 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4391 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4392 if (baseRatio==NULL || moreRatio==NULL)
4393 return 0.0f;
4395 // Formula from PaperDollFrame script
4396 float spirit = GetStat(STAT_SPIRIT);
4397 float baseSpirit = spirit;
4398 if (baseSpirit>50) baseSpirit = 50;
4399 float moreSpirit = spirit - baseSpirit;
4400 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4401 return regen;
4404 float Player::OCTRegenMPPerSpirit()
4406 uint32 level = getLevel();
4407 uint32 pclass = getClass();
4409 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4411 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4412 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4413 if (moreRatio==NULL)
4414 return 0.0f;
4416 // Formula get from PaperDollFrame script
4417 float spirit = GetStat(STAT_SPIRIT);
4418 float regen = spirit * moreRatio->ratio;
4419 return regen;
4422 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4424 ApplyModUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, value, apply);
4426 float RatingCoeffecient = GetRatingCoefficient(cr);
4427 float RatingChange = 0.0f;
4429 bool affectStats = CanModifyStats();
4431 switch (cr)
4433 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4434 case CR_DEFENSE_SKILL:
4435 UpdateDefenseBonusesMod();
4436 break;
4437 case CR_DODGE:
4438 UpdateDodgePercentage();
4439 break;
4440 case CR_PARRY:
4441 UpdateParryPercentage();
4442 break;
4443 case CR_BLOCK:
4444 UpdateBlockPercentage();
4445 break;
4446 case CR_HIT_MELEE:
4447 RatingChange = value / RatingCoeffecient;
4448 m_modMeleeHitChance += apply ? RatingChange : -RatingChange;
4449 break;
4450 case CR_HIT_RANGED:
4451 RatingChange = value / RatingCoeffecient;
4452 m_modRangedHitChance += apply ? RatingChange : -RatingChange;
4453 break;
4454 case CR_HIT_SPELL:
4455 RatingChange = value / RatingCoeffecient;
4456 m_modSpellHitChance += apply ? RatingChange : -RatingChange;
4457 break;
4458 case CR_CRIT_MELEE:
4459 if(affectStats)
4461 UpdateCritPercentage(BASE_ATTACK);
4462 UpdateCritPercentage(OFF_ATTACK);
4464 break;
4465 case CR_CRIT_RANGED:
4466 if(affectStats)
4467 UpdateCritPercentage(RANGED_ATTACK);
4468 break;
4469 case CR_CRIT_SPELL:
4470 if(affectStats)
4471 UpdateAllSpellCritChances();
4472 break;
4473 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4474 case CR_HIT_TAKEN_RANGED:
4475 break;
4476 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4477 break;
4478 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4479 case CR_CRIT_TAKEN_RANGED:
4480 break;
4481 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4482 break;
4483 case CR_HASTE_MELEE:
4484 RatingChange = value / RatingCoeffecient;
4485 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4486 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4487 break;
4488 case CR_HASTE_RANGED:
4489 RatingChange = value / RatingCoeffecient;
4490 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4491 break;
4492 case CR_HASTE_SPELL:
4493 RatingChange = value / RatingCoeffecient;
4494 ApplyCastTimePercentMod(RatingChange,apply);
4495 break;
4496 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4497 case CR_WEAPON_SKILL_OFFHAND:
4498 case CR_WEAPON_SKILL_RANGED:
4499 break;
4500 case CR_EXPERTISE:
4501 if(affectStats)
4503 UpdateExpertise(BASE_ATTACK);
4504 UpdateExpertise(OFF_ATTACK);
4506 break;
4510 void Player::SetRegularAttackTime()
4512 for(int i = 0; i < MAX_ATTACK; ++i)
4514 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4515 if(tmpitem && !tmpitem->IsBroken())
4517 ItemPrototype const *proto = tmpitem->GetProto();
4518 if(proto->Delay)
4519 SetAttackTime(WeaponAttackType(i), proto->Delay);
4520 else
4521 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4526 //skill+step, checking for max value
4527 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4529 if(!skill_id)
4530 return false;
4532 uint16 i=0;
4533 for (; i < PLAYER_MAX_SKILLS; i++)
4534 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
4535 break;
4537 if(i>=PLAYER_MAX_SKILLS)
4538 return false;
4540 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4541 uint32 value = SKILL_VALUE(data);
4542 uint32 max = SKILL_MAX(data);
4544 if ((!max) || (!value) || (value >= max))
4545 return false;
4547 if (value*512 < max*urand(0,512))
4549 uint32 new_value = value+step;
4550 if(new_value > max)
4551 new_value = max;
4553 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
4554 return true;
4557 return false;
4560 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
4562 if ( SkillValue >= GrayLevel )
4563 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
4564 if ( SkillValue >= GreenLevel )
4565 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
4566 if ( SkillValue >= YellowLevel )
4567 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
4568 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
4571 bool Player::UpdateCraftSkill(uint32 spellid)
4573 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
4575 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
4576 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
4578 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4580 if(_spell_idx->second->skillId)
4582 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
4584 // Alchemy Discoveries here
4585 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
4586 if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
4588 if(uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
4589 learnSpell(discoveredSpell);
4592 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
4594 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
4595 _spell_idx->second->max_value,
4596 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
4597 _spell_idx->second->min_value),
4598 craft_skill_gain);
4601 return false;
4604 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
4606 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
4608 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4610 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4611 switch (SkillId)
4613 case SKILL_HERBALISM:
4614 case SKILL_LOCKPICKING:
4615 case SKILL_JEWELCRAFTING:
4616 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4617 case SKILL_SKINNING:
4618 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
4619 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4620 else
4621 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
4622 case SKILL_MINING:
4623 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
4624 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4625 else
4626 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
4628 return false;
4631 bool Player::UpdateFishingSkill()
4633 sLog.outDebug("UpdateFishingSkill");
4635 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
4637 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
4639 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4641 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
4644 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
4646 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
4647 if ( !SkillId )
4648 return false;
4650 if(Chance <= 0) // speedup in 0 chance case
4652 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4653 return false;
4656 uint16 i=0;
4657 for (; i < PLAYER_MAX_SKILLS; i++)
4658 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
4659 if ( i >= PLAYER_MAX_SKILLS )
4660 return false;
4662 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4663 uint16 SkillValue = SKILL_VALUE(data);
4664 uint16 MaxValue = SKILL_MAX(data);
4666 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
4667 return false;
4669 int32 Roll = irand(1,1000);
4671 if ( Roll <= Chance )
4673 uint32 new_value = SkillValue+step;
4674 if(new_value > MaxValue)
4675 new_value = MaxValue;
4677 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
4678 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
4679 return true;
4682 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4683 return false;
4686 void Player::UpdateWeaponSkill (WeaponAttackType attType)
4688 // no skill gain in pvp
4689 Unit *pVictim = getVictim();
4690 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
4691 return;
4693 if(IsInFeralForm())
4694 return; // always maximized SKILL_FERAL_COMBAT in fact
4696 if(m_form == FORM_TREE)
4697 return; // use weapon but not skill up
4699 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
4701 switch(attType)
4703 case BASE_ATTACK:
4705 Item *tmpitem = GetWeaponForAttack(attType,true);
4707 if (!tmpitem)
4708 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
4709 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
4710 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4711 break;
4713 case OFF_ATTACK:
4714 case RANGED_ATTACK:
4716 Item *tmpitem = GetWeaponForAttack(attType,true);
4717 if (tmpitem)
4718 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4719 break;
4722 UpdateAllCritPercentages();
4725 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, MeleeHitOutcome outcome, bool defence)
4727 switch(outcome)
4729 case MELEE_HIT_CRIT:
4730 case MELEE_HIT_DODGE:
4731 case MELEE_HIT_PARRY:
4732 case MELEE_HIT_BLOCK:
4733 case MELEE_HIT_BLOCK_CRIT:
4734 return;
4736 default:
4737 break;
4740 uint32 plevel = getLevel(); // if defense than pVictim == attacker
4741 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
4742 uint32 moblevel = pVictim->getLevelForTarget(this);
4743 if(moblevel < greylevel)
4744 return;
4746 if (moblevel > plevel + 5)
4747 moblevel = plevel + 5;
4749 uint32 lvldif = moblevel - greylevel;
4750 if(lvldif < 3)
4751 lvldif = 3;
4753 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
4754 if(skilldif <= 0)
4755 return;
4757 float chance = float(3 * lvldif * skilldif) / plevel;
4758 if(!defence)
4760 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
4761 chance *= 0.1f * GetStat(STAT_INTELLECT);
4764 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
4766 if(roll_chance_f(chance))
4768 if(defence)
4769 UpdateDefense();
4770 else
4771 UpdateWeaponSkill(attType);
4773 else
4774 return;
4777 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
4779 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4780 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
4782 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
4783 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
4784 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
4786 if(talent) // permanent bonus stored in high part
4787 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
4788 else // temporary/item bonus stored in low part
4789 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
4790 return;
4794 void Player::UpdateMaxSkills()
4796 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
4798 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4799 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4801 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
4803 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
4804 if(!pSkill)
4805 continue;
4807 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
4808 continue;
4810 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4811 uint32 max = SKILL_MAX(data);
4812 uint32 val = SKILL_VALUE(data);
4814 // update only level dependent max skill values
4815 if(max!=1 && max != maxconfskill)
4817 uint32 max_Skill = GetMaxSkillValueForLevel();
4818 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,max_Skill));
4823 void Player::UpdateSkillsToMaxSkillsForLevel()
4825 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4826 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4828 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
4829 if( IsProfessionSkill(pskill) || pskill == SKILL_RIDING )
4830 continue;
4831 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4833 uint32 max = SKILL_MAX(data);
4835 if(max > 1)
4836 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
4838 if(pskill == SKILL_DEFENSE)
4839 UpdateDefenseBonusesMod();
4843 // This functions sets a skill line value (and adds if doesn't exist yet)
4844 // To "remove" a skill line, set it's values to zero
4845 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
4847 if(!id)
4848 return;
4850 uint16 i=0;
4851 for (; i < PLAYER_MAX_SKILLS; i++)
4852 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
4854 if(i<PLAYER_MAX_SKILLS) //has skill
4856 if(currVal)
4857 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
4858 else //remove
4860 // clear skill fields
4861 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
4862 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
4863 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
4865 // remove spells that depend on this skill when removing the skill
4866 for (PlayerSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
4868 ++next;
4869 if(itr->second->state == PLAYERSPELL_REMOVED)
4870 continue;
4872 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(itr->first);
4873 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(itr->first);
4875 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4877 if (_spell_idx->second->skillId == id)
4879 // this may remove more than one spell (dependants)
4880 removeSpell(itr->first);
4881 next = m_spells.begin();
4882 break;
4888 else if(currVal) //add
4890 for (i=0; i < PLAYER_MAX_SKILLS; i++)
4891 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4893 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
4894 if(!pSkill)
4896 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
4897 return;
4899 // enable unlearn button for primary professions only
4900 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
4901 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
4902 else
4903 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
4904 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
4906 // apply skill bonuses
4907 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
4909 // temporary bonuses
4910 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
4911 for(AuraList::const_iterator i = mModSkill.begin(); i != mModSkill.end(); ++i)
4912 if ((*i)->GetModifier()->m_miscvalue == int32(id))
4913 (*i)->ApplyModifier(true);
4915 // permanent bonuses
4916 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
4917 for(AuraList::const_iterator i = mModSkillTalent.begin(); i != mModSkillTalent.end(); ++i)
4918 if ((*i)->GetModifier()->m_miscvalue == int32(id))
4919 (*i)->ApplyModifier(true);
4921 // Learn all spells for skill
4922 learnSkillRewardedSpells(id);
4923 return;
4928 bool Player::HasSkill(uint32 skill) const
4930 if(!skill)return false;
4931 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4933 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
4935 return true;
4938 return false;
4941 uint16 Player::GetSkillValue(uint32 skill) const
4943 if(!skill)
4944 return 0;
4946 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4948 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
4950 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
4952 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
4953 result += SKILL_TEMP_BONUS(bonus);
4954 result += SKILL_PERM_BONUS(bonus);
4955 return result < 0 ? 0 : result;
4958 return 0;
4961 uint16 Player::GetMaxSkillValue(uint32 skill) const
4963 if(!skill)return 0;
4964 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4966 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
4968 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
4970 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
4971 result += SKILL_TEMP_BONUS(bonus);
4972 result += SKILL_PERM_BONUS(bonus);
4973 return result < 0 ? 0 : result;
4976 return 0;
4979 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
4981 if(!skill)return 0;
4982 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4984 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
4986 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
4989 return 0;
4992 uint16 Player::GetBaseSkillValue(uint32 skill) const
4994 if(!skill)return 0;
4995 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4997 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
4999 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5000 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5001 return result < 0 ? 0 : result;
5004 return 0;
5007 uint16 Player::GetPureSkillValue(uint32 skill) const
5009 if(!skill)return 0;
5010 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5012 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5014 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5017 return 0;
5020 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5022 if(!skill)
5023 return 0;
5025 for (int i = 0; i < PLAYER_MAX_SKILLS; i++)
5027 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5029 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5033 return 0;
5036 void Player::SendInitialActionButtons()
5038 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5040 WorldPacket data(SMSG_ACTION_BUTTONS, (MAX_ACTION_BUTTONS*4));
5041 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5043 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5044 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5046 data << uint16(itr->second.action);
5047 data << uint8(itr->second.misc);
5048 data << uint8(itr->second.type);
5050 else
5052 data << uint32(0);
5056 GetSession()->SendPacket( &data );
5057 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5060 void Player::addActionButton(const uint8 button, const uint16 action, const uint8 type, const uint8 misc)
5062 if(button >= MAX_ACTION_BUTTONS)
5064 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5065 return;
5068 // check cheating with adding non-known spells to action bar
5069 if(type==ACTION_BUTTON_SPELL)
5071 if(!sSpellStore.LookupEntry(action))
5073 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5074 return;
5077 if(!HasSpell(action))
5079 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5080 return;
5084 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5086 if (buttonItr==m_actionButtons.end())
5087 { // just add new button
5088 m_actionButtons[button] = ActionButton(action,type,misc);
5090 else
5091 { // change state of current button
5092 ActionButtonUpdateState uState = buttonItr->second.uState;
5093 buttonItr->second = ActionButton(action,type,misc);
5094 if (uState != ACTIONBUTTON_NEW) buttonItr->second.uState = ACTIONBUTTON_CHANGED;
5097 sLog.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action, button );
5100 void Player::removeActionButton(uint8 button)
5102 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5103 if (buttonItr==m_actionButtons.end())
5104 return;
5106 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5107 m_actionButtons.erase(buttonItr); // new and not saved
5108 else
5109 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5111 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5114 void Player::SetDontMove(bool dontMove)
5116 m_dontMove = dontMove;
5119 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5121 // prevent crash when a bad coord is sent by the client
5122 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5124 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5125 return false;
5128 Map *m = MapManager::Instance().GetMap(GetMapId(), this);
5130 const float old_x = GetPositionX();
5131 const float old_y = GetPositionY();
5132 const float old_z = GetPositionZ();
5133 const float old_r = GetOrientation();
5135 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5137 if (teleport || old_x != x || old_y != y || old_z != z)
5138 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5139 else
5140 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5142 // move and update visible state if need
5143 m->PlayerRelocation(this, x, y, z, orientation);
5145 // reread after Map::Relocation
5146 m = MapManager::Instance().GetMap(GetMapId(), this);
5147 x = GetPositionX();
5148 y = GetPositionY();
5149 z = GetPositionZ();
5152 // code block for underwater state update
5153 UpdateUnderwaterState(m, x, y, z);
5155 CheckExploreSystem();
5157 // group update
5158 if(GetGroup())
5159 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5161 return true;
5164 void Player::SaveRecallPosition()
5166 m_recallMap = GetMapId();
5167 m_recallX = GetPositionX();
5168 m_recallY = GetPositionY();
5169 m_recallZ = GetPositionZ();
5170 m_recallO = GetOrientation();
5173 void Player::SendMessageToSet(WorldPacket *data, bool self)
5175 MapManager::Instance().GetMap(GetMapId(), this)->MessageBroadcast(this, data, self);
5178 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5180 MapManager::Instance().GetMap(GetMapId(), this)->MessageDistBroadcast(this, data, dist, self);
5183 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5185 MapManager::Instance().GetMap(GetMapId(), this)->MessageDistBroadcast(this, data, dist, self,own_team_only);
5188 void Player::SendDirectMessage(WorldPacket *data)
5190 GetSession()->SendPacket(data);
5193 void Player::CheckExploreSystem()
5195 if (!isAlive())
5196 return;
5198 if (isInFlight())
5199 return;
5201 uint16 areaFlag=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY());
5202 if(areaFlag==0xffff)
5203 return;
5204 int offset = areaFlag / 32;
5206 if(offset >= 128)
5208 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);
5209 return;
5212 uint32 val = (uint32)(1 << (areaFlag % 32));
5213 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5215 if( !(currFields & val) )
5217 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5219 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5220 if(!p)
5222 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5224 else if(p->area_level > 0)
5226 uint32 area = p->ID;
5227 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5229 SendExplorationExperience(area,0);
5231 else
5233 int32 diff = int32(getLevel()) - p->area_level;
5234 uint32 XP = 0;
5235 if (diff < -5)
5237 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5239 else if (diff > 5)
5241 int32 exploration_percent = (100-((diff-5)*5));
5242 if (exploration_percent > 100)
5243 exploration_percent = 100;
5244 else if (exploration_percent < 0)
5245 exploration_percent = 0;
5247 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5249 else
5251 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5254 GiveXP( XP, NULL );
5255 SendExplorationExperience(area,XP);
5257 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5262 uint32 Player::TeamForRace(uint8 race)
5264 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5265 if(!rEntry)
5267 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5268 return ALLIANCE;
5271 switch(rEntry->TeamID)
5273 case 7: return ALLIANCE;
5274 case 1: return HORDE;
5277 sLog.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5278 return ALLIANCE;
5281 uint32 Player::getFactionForRace(uint8 race)
5283 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5284 if(!rEntry)
5286 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5287 return 0;
5290 return rEntry->FactionID;
5293 void Player::setFactionForRace(uint8 race)
5295 m_team = TeamForRace(race);
5296 setFaction( getFactionForRace(race) );
5299 void Player::UpdateReputation() const
5301 sLog.outDetail( "WORLD: Player::UpdateReputation" );
5303 for(FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
5305 SendFactionState(&(itr->second));
5309 void Player::SendFactionState(FactionState const* faction) const
5311 if(faction->Flags & FACTION_FLAG_VISIBLE) //If faction is visible then update it
5313 WorldPacket data(SMSG_SET_FACTION_STANDING, (16)); // last check 2.4.0
5314 data << (float) 0; // unk 2.4.0
5315 data << (uint32) 1; // count
5316 // for
5317 data << (uint32) faction->ReputationListID;
5318 data << (uint32) faction->Standing;
5319 // end for
5320 GetSession()->SendPacket(&data);
5324 void Player::SendInitialReputations()
5326 WorldPacket data(SMSG_INITIALIZE_FACTIONS, (4+128*5));
5327 data << uint32 (0x00000080);
5329 RepListID a = 0;
5331 for (FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); itr++)
5333 // fill in absent fields
5334 for (; a != itr->first; a++)
5336 data << uint8 (0x00);
5337 data << uint32 (0x00000000);
5340 // fill in encountered data
5341 data << uint8 (itr->second.Flags);
5342 data << uint32 (itr->second.Standing);
5344 ++a;
5347 // fill in absent fields
5348 for (; a != 128; a++)
5350 data << uint8 (0x00);
5351 data << uint32 (0x00000000);
5354 GetSession()->SendPacket(&data);
5357 FactionState const* Player::GetFactionState( FactionEntry const* factionEntry) const
5359 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5360 if (itr != m_factions.end())
5361 return &itr->second;
5363 return NULL;
5366 void Player::SetFactionAtWar(FactionState* faction, bool atWar)
5368 // not allow declare war to own faction
5369 if(atWar && (faction->Flags & FACTION_FLAG_PEACE_FORCED) )
5370 return;
5372 // already set
5373 if(((faction->Flags & FACTION_FLAG_AT_WAR) != 0) == atWar)
5374 return;
5376 if( atWar )
5377 faction->Flags |= FACTION_FLAG_AT_WAR;
5378 else
5379 faction->Flags &= ~FACTION_FLAG_AT_WAR;
5381 faction->Changed = true;
5384 void Player::SetFactionInactive(FactionState* faction, bool inactive)
5386 // always invisible or hidden faction can't be inactive
5387 if(inactive && ((faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN)) || !(faction->Flags & FACTION_FLAG_VISIBLE) ) )
5388 return;
5390 // already set
5391 if(((faction->Flags & FACTION_FLAG_INACTIVE) != 0) == inactive)
5392 return;
5394 if(inactive)
5395 faction->Flags |= FACTION_FLAG_INACTIVE;
5396 else
5397 faction->Flags &= ~FACTION_FLAG_INACTIVE;
5399 faction->Changed = true;
5402 void Player::SetFactionVisibleForFactionTemplateId(uint32 FactionTemplateId)
5404 FactionTemplateEntry const*factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5406 if(!factionTemplateEntry)
5407 return;
5409 SetFactionVisibleForFactionId(factionTemplateEntry->faction);
5412 void Player::SetFactionVisibleForFactionId(uint32 FactionId)
5414 FactionEntry const *factionEntry = sFactionStore.LookupEntry(FactionId);
5415 if(!factionEntry)
5416 return;
5418 if(factionEntry->reputationListID < 0)
5419 return;
5421 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5422 if (itr == m_factions.end())
5423 return;
5425 SetFactionVisible(&itr->second);
5428 void Player::SetFactionVisible(FactionState* faction)
5430 // always invisible or hidden faction can't be make visible
5431 if(faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN))
5432 return;
5434 // already set
5435 if(faction->Flags & FACTION_FLAG_VISIBLE)
5436 return;
5438 faction->Flags |= FACTION_FLAG_VISIBLE;
5439 faction->Changed = true;
5441 if(!m_session->PlayerLoading())
5443 // make faction visible in reputation list at client
5444 WorldPacket data(SMSG_SET_FACTION_VISIBLE, 4);
5445 data << faction->ReputationListID;
5446 GetSession()->SendPacket(&data);
5450 void Player::SetInitialFactions()
5452 for(unsigned int i = 1; i < sFactionStore.GetNumRows(); i++)
5454 FactionEntry const *factionEntry = sFactionStore.LookupEntry(i);
5456 if( factionEntry && (factionEntry->reputationListID >= 0))
5458 FactionState newFaction;
5459 newFaction.ID = factionEntry->ID;
5460 newFaction.ReputationListID = factionEntry->reputationListID;
5461 newFaction.Standing = 0;
5462 newFaction.Flags = GetDefaultReputationFlags(factionEntry);
5463 newFaction.Changed = true;
5465 m_factions[newFaction.ReputationListID] = newFaction;
5470 uint32 Player::GetDefaultReputationFlags(const FactionEntry *factionEntry) const
5472 if (!factionEntry)
5473 return 0;
5475 uint32 raceMask = getRaceMask();
5476 uint32 classMask = getClassMask();
5477 for (int i=0; i < 4; i++)
5479 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5480 (factionEntry->BaseRepClassMask[i]==0 ||
5481 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5482 return factionEntry->ReputationFlags[i];
5484 return 0;
5487 int32 Player::GetBaseReputation(const FactionEntry *factionEntry) const
5489 if (!factionEntry)
5490 return 0;
5492 uint32 raceMask = getRaceMask();
5493 uint32 classMask = getClassMask();
5494 for (int i=0; i < 4; i++)
5496 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5497 (factionEntry->BaseRepClassMask[i]==0 ||
5498 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5499 return factionEntry->BaseRepValue[i];
5502 // in faction.dbc exist factions with (RepListId >=0, listed in character reputation list) with all BaseRepRaceMask[i]==0
5503 return 0;
5506 int32 Player::GetReputation(uint32 faction_id) const
5508 FactionEntry const *factionEntry = sFactionStore.LookupEntry(faction_id);
5510 if (!factionEntry)
5512 sLog.outError("Player::GetReputation: Can't get reputation of %s for unknown faction (faction template id) #%u.",GetName(), faction_id);
5513 return 0;
5516 return GetReputation(factionEntry);
5519 int32 Player::GetReputation(const FactionEntry *factionEntry) const
5521 // Faction without recorded reputation. Just ignore.
5522 if(!factionEntry)
5523 return 0;
5525 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5526 if (itr != m_factions.end())
5527 return GetBaseReputation(factionEntry) + itr->second.Standing;
5529 return 0;
5532 ReputationRank Player::GetReputationRank(uint32 faction) const
5534 FactionEntry const*factionEntry = sFactionStore.LookupEntry(faction);
5535 if(!factionEntry)
5536 return MIN_REPUTATION_RANK;
5538 return GetReputationRank(factionEntry);
5541 ReputationRank Player::ReputationToRank(int32 standing) const
5543 int32 Limit = Reputation_Cap + 1;
5544 for (int i = MAX_REPUTATION_RANK-1; i >= MIN_REPUTATION_RANK; --i)
5546 Limit -= ReputationRank_Length[i];
5547 if (standing >= Limit )
5548 return ReputationRank(i);
5550 return MIN_REPUTATION_RANK;
5553 ReputationRank Player::GetReputationRank(const FactionEntry *factionEntry) const
5555 int32 Reputation = GetReputation(factionEntry);
5556 return ReputationToRank(Reputation);
5559 ReputationRank Player::GetBaseReputationRank(const FactionEntry *factionEntry) const
5561 int32 Reputation = GetBaseReputation(factionEntry);
5562 return ReputationToRank(Reputation);
5565 bool Player::ModifyFactionReputation(uint32 FactionTemplateId, int32 DeltaReputation)
5567 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5569 if(!factionTemplateEntry)
5571 sLog.outError("Player::ModifyFactionReputation: Can't update reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5572 return false;
5575 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5577 // Faction without recorded reputation. Just ignore.
5578 if(!factionEntry)
5579 return false;
5581 return ModifyFactionReputation(factionEntry, DeltaReputation);
5584 bool Player::ModifyFactionReputation(FactionEntry const* factionEntry, int32 standing)
5586 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5587 if (flist)
5589 bool res = false;
5590 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5592 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5593 if(factionEntryCalc)
5594 res = ModifyOneFactionReputation(factionEntryCalc, standing);
5596 return res;
5598 else
5599 return ModifyOneFactionReputation(factionEntry, standing);
5602 bool Player::ModifyOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5604 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5605 if (itr != m_factions.end())
5607 int32 BaseRep = GetBaseReputation(factionEntry);
5608 int32 new_rep = BaseRep + itr->second.Standing + standing;
5610 if (new_rep > Reputation_Cap)
5611 new_rep = Reputation_Cap;
5612 else
5613 if (new_rep < Reputation_Bottom)
5614 new_rep = Reputation_Bottom;
5616 if(ReputationToRank(new_rep) <= REP_HOSTILE)
5617 SetFactionAtWar(&itr->second,true);
5619 itr->second.Standing = new_rep - BaseRep;
5620 itr->second.Changed = true;
5622 SetFactionVisible(&itr->second);
5624 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
5626 if(uint32 questid = GetQuestSlotQuestId(i))
5628 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
5629 if( qInfo && qInfo->GetRepObjectiveFaction() == factionEntry->ID )
5631 QuestStatusData& q_status = mQuestStatus[questid];
5632 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
5634 if(GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
5635 if ( CanCompleteQuest( questid ) )
5636 CompleteQuest( questid );
5638 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
5640 if(GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
5641 IncompleteQuest( questid );
5647 SendFactionState(&(itr->second));
5649 return true;
5651 return false;
5654 bool Player::SetFactionReputation(uint32 FactionTemplateId, int32 standing)
5656 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5658 if(!factionTemplateEntry)
5660 sLog.outError("Player::SetFactionReputation: Can't set reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5661 return false;
5664 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5666 // Faction without recorded reputation. Just ignore.
5667 if(!factionEntry)
5668 return false;
5670 return SetFactionReputation(factionEntry, standing);
5673 bool Player::SetFactionReputation(FactionEntry const* factionEntry, int32 standing)
5675 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5676 if (flist)
5678 bool res = false;
5679 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5681 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5682 if(factionEntryCalc)
5683 res = SetOneFactionReputation(factionEntryCalc, standing);
5685 return res;
5687 else
5688 return SetOneFactionReputation(factionEntry, standing);
5691 bool Player::SetOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5693 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5694 if (itr != m_factions.end())
5696 if (standing > Reputation_Cap)
5697 standing = Reputation_Cap;
5698 else
5699 if (standing < Reputation_Bottom)
5700 standing = Reputation_Bottom;
5702 int32 BaseRep = GetBaseReputation(factionEntry);
5703 itr->second.Standing = standing - BaseRep;
5704 itr->second.Changed = true;
5706 SetFactionVisible(&itr->second);
5708 if(ReputationToRank(standing) <= REP_HOSTILE)
5709 SetFactionAtWar(&itr->second,true);
5711 SendFactionState(&(itr->second));
5712 return true;
5714 return false;
5717 //Calculate total reputation percent player gain with quest/creature level
5718 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, bool for_quest)
5720 // for grey creature kill received 20%, in other case 100.
5721 int32 percent = (!for_quest && (creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))) ? 20 : 100;
5723 int32 repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5725 percent += rep > 0 ? repMod : -repMod;
5727 if(percent <=0)
5728 return 0;
5730 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100);
5733 //Calculates how many reputation points player gains in victim's enemy factions
5734 void Player::RewardReputation(Unit *pVictim, float rate)
5736 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5737 return;
5739 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5741 if(!Rep)
5742 return;
5744 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5746 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue1,false);
5747 donerep1 = int32(donerep1*rate);
5748 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5749 uint32 current_reputation_rank1 = GetReputationRank(factionEntry1);
5750 if(factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5751 ModifyFactionReputation(factionEntry1, donerep1);
5753 // Wiki: Team factions value divided by 2
5754 if(Rep->is_teamaward1)
5756 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5757 if(team1_factionEntry)
5758 ModifyFactionReputation(team1_factionEntry, donerep1 / 2);
5762 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5764 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue2,false);
5765 donerep2 = int32(donerep2*rate);
5766 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5767 uint32 current_reputation_rank2 = GetReputationRank(factionEntry2);
5768 if(factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5769 ModifyFactionReputation(factionEntry2, donerep2);
5771 // Wiki: Team factions value divided by 2
5772 if(Rep->is_teamaward2)
5774 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5775 if(team2_factionEntry)
5776 ModifyFactionReputation(team2_factionEntry, donerep2 / 2);
5781 //Calculate how many reputation points player gain with the quest
5782 void Player::RewardReputation(Quest const *pQuest)
5784 // quest reputation reward/loss
5785 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5787 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5789 int32 rep = CalculateReputationGain(pQuest->GetQuestLevel(),pQuest->RewRepValue[i],true);
5790 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
5791 if(factionEntry)
5792 ModifyFactionReputation(factionEntry, rep);
5796 // TODO: implement reputation spillover
5799 void Player::UpdateArenaFields(void)
5801 /* arena calcs go here */
5804 void Player::UpdateHonorFields()
5806 /// called when rewarding honor and at each save
5807 uint64 now = time(NULL);
5808 uint64 today = uint64(time(NULL) / DAY) * DAY;
5810 if(m_lastHonorUpdateTime < today)
5812 uint64 yesterday = today - DAY;
5814 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
5816 // update yesterday's contribution
5817 if(m_lastHonorUpdateTime >= yesterday )
5819 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
5821 // this is the first update today, reset today's contribution
5822 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
5823 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
5825 else
5827 // no honor/kills yesterday or today, reset
5828 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
5829 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
5833 m_lastHonorUpdateTime = now;
5836 ///Calculate the amount of honor gained based on the victim
5837 ///and the size of the group for which the honor is divided
5838 ///An exact honor value can also be given (overriding the calcs)
5839 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
5841 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5842 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
5843 return false;
5845 uint64 victim_guid = 0;
5846 uint32 victim_rank = 0;
5847 time_t now = time(NULL);
5849 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5850 UpdateHonorFields();
5852 if(honor <= 0)
5854 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
5855 return false;
5857 victim_guid = uVictim->GetGUID();
5859 if( uVictim->GetTypeId() == TYPEID_PLAYER )
5861 Player *pVictim = (Player *)uVictim;
5863 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
5864 return false;
5866 float f = 1; //need for total kills (?? need more info)
5867 uint32 k_grey = 0;
5868 uint32 k_level = getLevel();
5869 uint32 v_level = pVictim->getLevel();
5872 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
5873 // [0] Just name
5874 // [1..14] Alliance honor titles and player name
5875 // [15..28] Horde honor titles and player name
5876 // [29..38] Other title and player name
5877 // [39+] Nothing
5878 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
5879 // Get Killer titles, CharTitlesEntry::bit_index
5880 // Ranks:
5881 // title[1..14] -> rank[5..18]
5882 // title[15..28] -> rank[5..18]
5883 // title[other] -> 0
5884 if (victim_title == 0)
5885 victim_guid = 0; // Don't show HK: <rank> message, only log.
5886 else if (victim_title < 15)
5887 victim_rank = victim_title + 4;
5888 else if (victim_title < 29)
5889 victim_rank = victim_title - 14 + 4;
5890 else
5891 victim_guid = 0; // Don't show HK: <rank> message, only log.
5894 if(k_level <= 5)
5895 k_grey = 0;
5896 else if( k_level <= 39 )
5897 k_grey = k_level - 5 - k_level/10;
5898 else
5899 k_grey = k_level - 1 - k_level/5;
5901 if(v_level<=k_grey)
5902 return false;
5904 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
5906 int32 v_rank =1; //need more info
5908 honor = ((f * diff_level * (190 + v_rank*10))/6);
5909 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
5911 // count the number of playerkills in one day
5912 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
5913 // and those in a lifetime
5914 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
5916 else
5918 Creature *cVictim = (Creature *)uVictim;
5920 if (!cVictim->isRacialLeader())
5921 return false;
5923 honor = 100; // ??? need more info
5924 victim_rank = 19; // HK: Leader
5928 if (uVictim != NULL)
5930 honor *= sWorld.getRate(RATE_HONOR);
5932 if(groupsize > 1)
5933 honor /= groupsize;
5935 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
5938 // honor - for show honor points in log
5939 // victim_guid - for show victim name in log
5940 // victim_rank [1..4] HK: <dishonored rank>
5941 // victim_rank [5..19] HK: <alliance\horde rank>
5942 // victim_rank [0,20+] HK: <>
5943 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
5944 data << (uint32) honor;
5945 data << (uint64) victim_guid;
5946 data << (uint32) victim_rank;
5948 GetSession()->SendPacket(&data);
5950 // add honor points
5951 ModifyHonorPoints(int32(honor));
5953 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
5954 return true;
5957 void Player::ModifyHonorPoints( int32 value )
5959 if(value < 0)
5961 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
5962 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
5963 else
5964 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
5966 else
5967 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
5970 void Player::ModifyArenaPoints( int32 value )
5972 if(value < 0)
5974 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
5975 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
5976 else
5977 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
5979 else
5980 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
5983 uint32 Player::GetGuildIdFromDB(uint64 guid)
5985 std::ostringstream ss;
5986 ss<<"SELECT guildid FROM guild_member WHERE guid='"<<guid<<"'";
5987 QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
5988 if( result )
5990 uint32 v = result->Fetch()[0].GetUInt32();
5991 delete result;
5992 return v;
5994 else
5995 return 0;
5998 uint32 Player::GetRankFromDB(uint64 guid)
6000 std::ostringstream ss;
6001 ss<<"SELECT rank FROM guild_member WHERE guid='"<<guid<<"'";
6002 QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
6003 if( result )
6005 uint32 v = result->Fetch()[0].GetUInt32();
6006 delete result;
6007 return v;
6009 else
6010 return 0;
6013 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6015 // need fix it!
6016 QueryResult *result = CharacterDatabase.PQuery("SELECT arenateamid FROM arena_team_member WHERE guid='%u'", GUID_LOPART(guid));
6017 if(result)
6019 // init id to 0, check the arena type before assigning a value to id
6020 uint32 id = 0;
6023 QueryResult *result2 = CharacterDatabase.PQuery("SELECT type FROM arena_team WHERE arenateamid='%u'", id);
6024 if(result2)
6026 uint8 dbtype = (*result2)[0].GetUInt32();
6027 delete result2;
6028 if(dbtype == type)
6030 // if the type matches, we've found the id
6031 id = (*result)[0].GetUInt32();
6032 break;
6035 } while(result->NextRow());
6036 delete result;
6037 return id;
6039 // no arenateam for the specified guid, return 0
6040 return 0;
6043 uint32 Player::GetZoneIdFromDB(uint64 guid)
6045 std::ostringstream ss;
6047 ss<<"SELECT zone FROM characters WHERE guid='"<<GUID_LOPART(guid)<<"'";
6048 QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
6049 if (!result)
6050 return 0;
6051 Field* fields = result->Fetch();
6052 uint32 zone = fields[0].GetUInt32();
6053 delete result;
6055 if (!zone)
6057 // stored zone is zero, use generic and slow zone detection
6058 ss.str("");
6059 ss<<"SELECT map,position_x,position_y FROM characters WHERE guid='"<<GUID_LOPART(guid)<<"'";
6060 result = CharacterDatabase.Query(ss.str().c_str());
6061 if( !result )
6062 return 0;
6063 fields = result->Fetch();
6064 uint32 map = fields[0].GetUInt32();
6065 float posx = fields[1].GetFloat();
6066 float posy = fields[2].GetFloat();
6067 delete result;
6069 zone = MapManager::Instance().GetZoneId(map,posx,posy);
6071 ss.str("");
6072 ss << "UPDATE characters SET zone='"<<zone<<"' WHERE guid='"<<GUID_LOPART(guid)<<"'";
6073 CharacterDatabase.Execute(ss.str().c_str());
6076 return zone;
6079 void Player::UpdateArea(uint32 newArea)
6081 // FFA_PVP flags are area and not zone id dependent
6082 // so apply them accordingly
6083 m_areaUpdateId = newArea;
6085 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6087 if(area && (area->flags & AREA_FLAG_ARENA))
6089 if(!isGameMaster())
6090 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
6092 else
6094 // remove ffa flag only if not ffapvp realm
6095 // removal in sanctuaries and capitals is handled in zone update
6096 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6097 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
6100 UpdateAreaDependentAuras(newArea);
6103 void Player::UpdateZone(uint32 newZone)
6105 m_zoneUpdateId = newZone;
6106 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6108 // zone changed, so area changed as well, update it
6109 UpdateArea(GetAreaId());
6111 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6112 if(!zone)
6113 return;
6115 if (sWorld.getConfig(CONFIG_WEATHER))
6117 Weather *wth = sWorld.FindWeather(zone->ID);
6118 if(wth)
6120 wth->SendWeatherUpdateToPlayer(this);
6122 else
6124 if(!sWorld.AddWeather(zone->ID))
6126 // send fine weather packet to remove old zone's weather
6127 Weather::SendFineWeatherUpdateToPlayer(this);
6132 pvpInfo.inHostileArea =
6133 GetTeam() == ALLIANCE && zone->team == AREATEAM_HORDE ||
6134 GetTeam() == HORDE && zone->team == AREATEAM_ALLY ||
6135 sWorld.IsPvPRealm() && zone->team == AREATEAM_NONE ||
6136 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6138 if(pvpInfo.inHostileArea) // in hostile area
6140 if(!IsPvP() || pvpInfo.endTimer != 0)
6141 UpdatePvP(true, true);
6143 else // in friendly area
6145 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6146 pvpInfo.endTimer = time(0); // start toggle-off
6149 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6151 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_SANCTUARY);
6152 if(sWorld.IsFFAPvPRealm())
6153 RemoveFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6155 else
6157 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_SANCTUARY);
6160 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6162 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6163 SetRestType(REST_TYPE_IN_CITY);
6164 InnEnter(time(0),GetMapId(),0,0,0);
6166 if(sWorld.IsFFAPvPRealm())
6167 RemoveFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6169 else // anywhere else
6171 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6173 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6175 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6177 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6178 SetRestType(REST_TYPE_NO);
6180 if(sWorld.IsFFAPvPRealm())
6181 SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6184 else // not in tavern (leave city then)
6186 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6187 SetRestType(REST_TYPE_NO);
6189 // Set player to FFA PVP when not in rested enviroment.
6190 if(sWorld.IsFFAPvPRealm())
6191 SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6196 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6197 // if player resurrected at teleport this will be applied in resurrect code
6198 if(isAlive())
6199 DestroyZoneLimitedItem( true, newZone );
6201 // recent client version not send leave/join channel packets for built-in local channels
6202 UpdateLocalChannels( newZone );
6204 // group update
6205 if(GetGroup())
6206 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6208 UpdateZoneDependentAuras(newZone);
6211 //If players are too far way of duel flag... then player loose the duel
6212 void Player::CheckDuelDistance(time_t currTime)
6214 if(!duel)
6215 return;
6217 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6218 GameObject* obj = ObjectAccessor::GetGameObject(*this, duelFlagGUID);
6219 if(!obj)
6220 return;
6222 if(duel->outOfBound == 0)
6224 if(!IsWithinDistInMap(obj, 50))
6226 duel->outOfBound = currTime;
6228 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6229 GetSession()->SendPacket(&data);
6232 else
6234 if(IsWithinDistInMap(obj, 40))
6236 duel->outOfBound = 0;
6238 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6239 GetSession()->SendPacket(&data);
6241 else if(currTime >= (duel->outOfBound+10))
6243 DuelComplete(DUEL_FLED);
6248 void Player::DuelComplete(DuelCompleteType type)
6250 // duel not requested
6251 if(!duel)
6252 return;
6254 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6255 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6256 GetSession()->SendPacket(&data);
6257 duel->opponent->GetSession()->SendPacket(&data);
6259 if(type != DUEL_INTERUPTED)
6261 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6262 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6263 data << duel->opponent->GetName();
6264 data << GetName();
6265 SendMessageToSet(&data,true);
6268 // cool-down duel spell
6269 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6271 data<<GetGUID();
6272 data<<uint8(0x0);
6274 data<<(uint32)7266;
6275 data<<uint32(0x0);
6276 GetSession()->SendPacket(&data);
6277 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6278 data<<duel->opponent->GetGUID();
6279 data<<uint8(0x0);
6280 data<<(uint32)7266;
6281 data<<uint32(0x0);
6282 duel->opponent->GetSession()->SendPacket(&data);*/
6284 //Remove Duel Flag object
6285 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
6286 if(obj)
6287 duel->initiator->RemoveGameObject(obj,true);
6289 /* remove auras */
6290 std::vector<uint32> auras2remove;
6291 AuraMap const& vAuras = duel->opponent->GetAuras();
6292 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); i++)
6294 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6295 auras2remove.push_back(i->second->GetId());
6298 for(size_t i=0; i<auras2remove.size(); i++)
6299 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6301 auras2remove.clear();
6302 AuraMap const& auras = GetAuras();
6303 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); i++)
6305 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6306 auras2remove.push_back(i->second->GetId());
6308 for(size_t i=0; i<auras2remove.size(); i++)
6309 RemoveAurasDueToSpell(auras2remove[i]);
6311 // cleanup combo points
6312 if(GetComboTarget()==duel->opponent->GetGUID())
6313 ClearComboPoints();
6314 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6315 ClearComboPoints();
6317 if(duel->opponent->GetComboTarget()==GetGUID())
6318 duel->opponent->ClearComboPoints();
6319 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6320 duel->opponent->ClearComboPoints();
6322 //cleanups
6323 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6324 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6325 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6326 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6328 delete duel->opponent->duel;
6329 duel->opponent->duel = NULL;
6330 delete duel;
6331 duel = NULL;
6334 //---------------------------------------------------------//
6336 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6338 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6339 return;
6341 // not apply/remove mods for broken item
6342 if(item->IsBroken())
6343 return;
6345 ItemPrototype const *proto = item->GetProto();
6347 if(!proto)
6348 return;
6350 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6352 uint32 attacktype = Player::GetAttackBySlot(slot);
6353 if(attacktype < MAX_ATTACK)
6354 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6356 _ApplyItemBonuses(proto,slot,apply);
6358 if( slot==EQUIPMENT_SLOT_RANGED )
6359 _ApplyAmmoBonuses();
6361 ApplyItemEquipSpell(item,apply);
6362 ApplyEnchantment(item, apply);
6364 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6365 CorrectMetaGemEnchants(slot, apply);
6367 sLog.outDebug("_ApplyItemMods complete.");
6370 void Player::_ApplyItemBonuses(ItemPrototype const *proto,uint8 slot,bool apply)
6372 if(slot >= INVENTORY_SLOT_BAG_END || !proto)
6373 return;
6375 for (int i = 0; i < 10; i++)
6377 float val = float (proto->ItemStat[i].ItemStatValue);
6379 if(val==0)
6380 continue;
6382 switch (proto->ItemStat[i].ItemStatType)
6384 case ITEM_MOD_MANA:
6385 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6386 break;
6387 case ITEM_MOD_HEALTH: // modify HP
6388 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6389 break;
6390 case ITEM_MOD_AGILITY: // modify agility
6391 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6392 ApplyStatBuffMod(STAT_AGILITY, val, apply);
6393 break;
6394 case ITEM_MOD_STRENGTH: //modify strength
6395 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6396 ApplyStatBuffMod(STAT_STRENGTH, val, apply);
6397 break;
6398 case ITEM_MOD_INTELLECT: //modify intellect
6399 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6400 ApplyStatBuffMod(STAT_INTELLECT, val, apply);
6401 break;
6402 case ITEM_MOD_SPIRIT: //modify spirit
6403 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6404 ApplyStatBuffMod(STAT_SPIRIT, val, apply);
6405 break;
6406 case ITEM_MOD_STAMINA: //modify stamina
6407 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6408 ApplyStatBuffMod(STAT_STAMINA, val, apply);
6409 break;
6410 case ITEM_MOD_DEFENSE_SKILL_RATING:
6411 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6412 break;
6413 case ITEM_MOD_DODGE_RATING:
6414 ApplyRatingMod(CR_DODGE, int32(val), apply);
6415 break;
6416 case ITEM_MOD_PARRY_RATING:
6417 ApplyRatingMod(CR_PARRY, int32(val), apply);
6418 break;
6419 case ITEM_MOD_BLOCK_RATING:
6420 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6421 break;
6422 case ITEM_MOD_HIT_MELEE_RATING:
6423 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6424 break;
6425 case ITEM_MOD_HIT_RANGED_RATING:
6426 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6427 break;
6428 case ITEM_MOD_HIT_SPELL_RATING:
6429 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6430 break;
6431 case ITEM_MOD_CRIT_MELEE_RATING:
6432 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6433 break;
6434 case ITEM_MOD_CRIT_RANGED_RATING:
6435 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6436 break;
6437 case ITEM_MOD_CRIT_SPELL_RATING:
6438 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6439 break;
6440 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6441 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6442 break;
6443 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6444 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6445 break;
6446 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6447 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6448 break;
6449 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6450 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6451 break;
6452 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6453 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6454 break;
6455 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6456 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6457 break;
6458 case ITEM_MOD_HASTE_MELEE_RATING:
6459 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6460 break;
6461 case ITEM_MOD_HASTE_RANGED_RATING:
6462 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6463 break;
6464 case ITEM_MOD_HASTE_SPELL_RATING:
6465 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6466 break;
6467 case ITEM_MOD_HIT_RATING:
6468 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6469 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6470 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6471 break;
6472 case ITEM_MOD_CRIT_RATING:
6473 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6474 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6475 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6476 break;
6477 case ITEM_MOD_HIT_TAKEN_RATING:
6478 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6479 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6480 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6481 break;
6482 case ITEM_MOD_CRIT_TAKEN_RATING:
6483 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6484 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6485 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6486 break;
6487 case ITEM_MOD_RESILIENCE_RATING:
6488 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6489 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6490 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6491 break;
6492 case ITEM_MOD_HASTE_RATING:
6493 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6494 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6495 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6496 break;
6497 case ITEM_MOD_EXPERTISE_RATING:
6498 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6499 break;
6503 if (proto->Armor)
6504 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(proto->Armor), apply);
6506 if (proto->Block)
6507 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6509 if (proto->HolyRes)
6510 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6512 if (proto->FireRes)
6513 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6515 if (proto->NatureRes)
6516 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6518 if (proto->FrostRes)
6519 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6521 if (proto->ShadowRes)
6522 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6524 if (proto->ArcaneRes)
6525 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6527 WeaponAttackType attType = BASE_ATTACK;
6528 float damage = 0.0f;
6530 if( slot == EQUIPMENT_SLOT_RANGED && (
6531 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6532 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6534 attType = RANGED_ATTACK;
6536 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6538 attType = OFF_ATTACK;
6541 if (proto->Damage[0].DamageMin > 0 )
6543 damage = apply ? proto->Damage[0].DamageMin : BASE_MINDAMAGE;
6544 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6545 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6548 if (proto->Damage[0].DamageMax > 0 )
6550 damage = apply ? proto->Damage[0].DamageMax : BASE_MAXDAMAGE;
6551 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6554 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6555 return;
6557 if (proto->Delay)
6559 if(slot == EQUIPMENT_SLOT_RANGED)
6560 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6561 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6562 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6563 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6564 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6567 if(CanModifyStats() && (damage || proto->Delay))
6568 UpdateDamagePhysical(attType);
6571 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6573 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6574 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6575 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6577 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6578 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6579 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6581 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6582 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6583 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6586 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6588 // generic not weapon specific case processes in aura code
6589 if(aura->GetSpellProto()->EquippedItemClass == -1)
6590 return;
6592 BaseModGroup mod = BASEMOD_END;
6593 switch(attackType)
6595 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6596 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6597 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6598 default: return;
6601 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6603 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6607 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6609 // ignore spell mods for not wands
6610 Modifier const* modifier = aura->GetModifier();
6611 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6612 return;
6614 // generic not weapon specific case processes in aura code
6615 if(aura->GetSpellProto()->EquippedItemClass == -1)
6616 return;
6618 UnitMods unitMod = UNIT_MOD_END;
6619 switch(attackType)
6621 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6622 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6623 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6624 default: return;
6627 UnitModifierType unitModType = TOTAL_VALUE;
6628 switch(modifier->m_auraname)
6630 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6631 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6632 default: return;
6635 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6637 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6641 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6643 if(!item)
6644 return;
6646 ItemPrototype const *proto = item->GetProto();
6647 if(!proto)
6648 return;
6650 for (int i = 0; i < 5; i++)
6652 _Spell const& spellData = proto->Spells[i];
6654 // no spell
6655 if(!spellData.SpellId )
6656 continue;
6658 // wrong triggering type
6659 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6660 continue;
6662 // check if it is valid spell
6663 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6664 if(!spellproto)
6665 continue;
6667 ApplyEquipSpell(spellproto,item,apply,form_change);
6671 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6673 if(apply)
6675 // Cannot be used in this stance/form
6676 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)!=0)
6677 return;
6679 if(form_change) // check aura active state from other form
6681 bool found = false;
6682 for (int k=0; k < 3; ++k)
6684 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6685 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6687 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6689 found = true;
6690 break;
6693 if(found)
6694 break;
6697 if(found) // and skip re-cast already active aura at form change
6698 return;
6701 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6703 CastSpell(this,spellInfo,true,item);
6705 else
6707 if(form_change) // check aura compatibility
6709 // Cannot be used in this stance/form
6710 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==0)
6711 return; // and remove only not compatible at form change
6714 if(item)
6715 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6716 else
6717 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6721 void Player::UpdateEquipSpellsAtFormChange()
6723 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6725 if(m_items[i] && !m_items[i]->IsBroken())
6727 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6728 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6732 // item set bonuses not dependent from item broken state
6733 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6735 ItemSetEffect* eff = ItemSetEff[setindex];
6736 if(!eff)
6737 continue;
6739 for(uint32 y=0;y<8; ++y)
6741 SpellEntry const* spellInfo = eff->spells[y];
6742 if(!spellInfo)
6743 continue;
6745 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
6746 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
6751 void Player::CastItemCombatSpell(Item *item,Unit* Target, WeaponAttackType attType)
6753 if(!item || item->IsBroken())
6754 return;
6756 ItemPrototype const *proto = item->GetProto();
6757 if(!proto)
6758 return;
6760 if (!Target || Target == this )
6761 return;
6763 for (int i = 0; i < 5; i++)
6765 _Spell const& spellData = proto->Spells[i];
6767 // no spell
6768 if(!spellData.SpellId )
6769 continue;
6771 // wrong triggering type
6772 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
6773 continue;
6775 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6776 if(!spellInfo)
6778 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
6779 continue;
6782 // not allow proc extra attack spell at extra attack
6783 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6784 return;
6786 float chance = spellInfo->procChance;
6788 if(spellData.SpellPPMRate)
6790 uint32 WeaponSpeed = GetAttackTime(attType);
6791 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
6793 else if(chance > 100.0f)
6795 chance = GetWeaponProcChance();
6798 if (roll_chance_f(chance))
6799 this->CastSpell(Target, spellInfo->Id, true, item);
6802 // item combat enchantments
6803 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6805 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6806 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6807 if(!pEnchant) continue;
6808 for (int s=0;s<3;s++)
6810 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
6811 continue;
6813 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6814 if (!spellInfo)
6816 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6817 continue;
6820 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
6821 if (roll_chance_f(chance))
6823 if(IsPositiveSpell(pEnchant->spellid[s]))
6824 CastSpell(this, pEnchant->spellid[s], true, item);
6825 else
6826 CastSpell(Target, pEnchant->spellid[s], true, item);
6832 void Player::_RemoveAllItemMods()
6834 sLog.outDebug("_RemoveAllItemMods start.");
6836 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6838 if(m_items[i])
6840 ItemPrototype const *proto = m_items[i]->GetProto();
6841 if(!proto)
6842 continue;
6844 // item set bonuses not dependent from item broken state
6845 if(proto->ItemSet)
6846 RemoveItemsSetItem(this,proto);
6848 if(m_items[i]->IsBroken())
6849 continue;
6851 ApplyItemEquipSpell(m_items[i],false);
6852 ApplyEnchantment(m_items[i], false);
6856 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6858 if(m_items[i])
6860 if(m_items[i]->IsBroken())
6861 continue;
6862 ItemPrototype const *proto = m_items[i]->GetProto();
6863 if(!proto)
6864 continue;
6866 uint32 attacktype = Player::GetAttackBySlot(i);
6867 if(attacktype < MAX_ATTACK)
6868 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
6870 _ApplyItemBonuses(proto,i, false);
6872 if( i == EQUIPMENT_SLOT_RANGED )
6873 _ApplyAmmoBonuses();
6877 sLog.outDebug("_RemoveAllItemMods complete.");
6880 void Player::_ApplyAllItemMods()
6882 sLog.outDebug("_ApplyAllItemMods start.");
6884 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6886 if(m_items[i])
6888 if(m_items[i]->IsBroken())
6889 continue;
6891 ItemPrototype const *proto = m_items[i]->GetProto();
6892 if(!proto)
6893 continue;
6895 uint32 attacktype = Player::GetAttackBySlot(i);
6896 if(attacktype < MAX_ATTACK)
6897 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
6899 _ApplyItemBonuses(proto,i, true);
6901 if( i == EQUIPMENT_SLOT_RANGED )
6902 _ApplyAmmoBonuses();
6906 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6908 if(m_items[i])
6910 ItemPrototype const *proto = m_items[i]->GetProto();
6911 if(!proto)
6912 continue;
6914 // item set bonuses not dependent from item broken state
6915 if(proto->ItemSet)
6916 AddItemsSetItem(this,m_items[i]);
6918 if(m_items[i]->IsBroken())
6919 continue;
6921 ApplyItemEquipSpell(m_items[i],true);
6922 ApplyEnchantment(m_items[i], true);
6926 sLog.outDebug("_ApplyAllItemMods complete.");
6929 void Player::_ApplyAmmoBonuses()
6931 // check ammo
6932 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
6933 if(!ammo_id)
6934 return;
6936 float currentAmmoDPS;
6938 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
6939 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
6940 currentAmmoDPS = 0.0f;
6941 else
6942 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
6944 if(currentAmmoDPS == GetAmmoDPS())
6945 return;
6947 m_ammoDPS = currentAmmoDPS;
6949 if(CanModifyStats())
6950 UpdateDamagePhysical(RANGED_ATTACK);
6953 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
6955 if(!ammo_proto)
6956 return false;
6958 // check ranged weapon
6959 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
6960 if(!weapon || weapon->IsBroken() )
6961 return false;
6963 ItemPrototype const* weapon_proto = weapon->GetProto();
6964 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
6965 return false;
6967 // check ammo ws. weapon compatibility
6968 switch(weapon_proto->SubClass)
6970 case ITEM_SUBCLASS_WEAPON_BOW:
6971 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
6972 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
6973 return false;
6974 break;
6975 case ITEM_SUBCLASS_WEAPON_GUN:
6976 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
6977 return false;
6978 break;
6979 default:
6980 return false;
6983 return true;
6986 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
6987 Called by remove insignia spell effect */
6988 void Player::RemovedInsignia(Player* looterPlr)
6990 if (!GetBattleGroundId())
6991 return;
6993 // If not released spirit, do it !
6994 if(m_deathTimer > 0)
6996 m_deathTimer = 0;
6997 BuildPlayerRepop();
6998 RepopAtGraveyard();
7001 Corpse *corpse = GetCorpse();
7002 if (!corpse)
7003 return;
7005 // We have to convert player corpse to bones, not to be able to resurrect there
7006 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7007 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
7008 if (!bones)
7009 return;
7011 // Now we must make bones lootable, and send player loot
7012 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7014 // We store the level of our player in the gold field
7015 // We retrieve this information at Player::SendLoot()
7016 bones->loot.gold = getLevel();
7017 bones->lootRecipient = looterPlr;
7018 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7021 /*Loot type MUST be
7022 1-corpse, go
7023 2-skinning
7024 3-Fishing
7027 void Player::SendLootRelease( uint64 guid )
7029 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7030 data << uint64(guid) << uint8(1);
7031 SendDirectMessage( &data );
7034 void Player::SendLoot(uint64 guid, LootType loot_type)
7036 Loot *loot = 0;
7037 PermissionTypes permission = ALL_PERMISSION;
7039 sLog.outDebug("Player::SendLoot");
7040 if (IS_GAMEOBJECT_GUID(guid))
7042 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7043 GameObject *go =
7044 ObjectAccessor::GetGameObject(*this, guid);
7046 // not check distance for GO in case owned GO (fishing bobber case, for example)
7047 // And permit out of range GO with no owner in case fishing hole
7048 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7050 SendLootRelease(guid);
7051 return;
7054 loot = &go->loot;
7056 if(go->getLootState() == GO_READY)
7058 uint32 lootid = go->GetLootId();
7060 if(lootid)
7062 sLog.outDebug(" if(lootid)");
7063 loot->clear();
7064 loot->FillLoot(lootid, LootTemplates_Gameobject, this);
7067 if(loot_type == LOOT_FISHING)
7068 go->getFishLoot(loot);
7070 go->SetLootState(GO_ACTIVATED);
7073 else if (IS_ITEM_GUID(guid))
7075 Item *item = GetItemByGuid( guid );
7077 if (!item)
7079 SendLootRelease(guid);
7080 return;
7083 if(loot_type == LOOT_DISENCHANTING)
7085 loot = &item->loot;
7087 if(!item->m_lootGenerated)
7089 item->m_lootGenerated = true;
7090 loot->clear();
7091 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this);
7094 else if(loot_type == LOOT_PROSPECTING)
7096 loot = &item->loot;
7098 if(!item->m_lootGenerated)
7100 item->m_lootGenerated = true;
7101 loot->clear();
7102 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this);
7105 else
7107 loot = &item->loot;
7109 if(!item->m_lootGenerated)
7111 item->m_lootGenerated = true;
7112 loot->clear();
7113 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this);
7115 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7119 else if (IS_CORPSE_GUID(guid)) // remove insignia
7121 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7123 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7125 SendLootRelease(guid);
7126 return;
7129 loot = &bones->loot;
7131 if (!bones->lootForBody)
7133 bones->lootForBody = true;
7134 uint32 pLevel = bones->loot.gold;
7135 bones->loot.clear();
7136 // It may need a better formula
7137 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7138 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7141 if (bones->lootRecipient != this)
7142 permission = NONE_PERMISSION;
7144 else
7146 Creature *creature = ObjectAccessor::GetCreature(*this, guid);
7148 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7149 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7151 SendLootRelease(guid);
7152 return;
7155 if(loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7157 SendLootRelease(guid);
7158 return;
7161 loot = &creature->loot;
7163 if(loot_type == LOOT_PICKPOCKETING)
7165 if ( !creature->lootForPickPocketed )
7167 creature->lootForPickPocketed = true;
7168 loot->clear();
7170 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7171 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this);
7173 // Generate extra money for pick pocket loot
7174 const uint32 a = urand(0, creature->getLevel()/2);
7175 const uint32 b = urand(0, getLevel()/2);
7176 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7179 else
7181 // the player whose group may loot the corpse
7182 Player *recipient = creature->GetLootRecipient();
7183 if (!recipient)
7185 creature->SetLootRecipient(this);
7186 recipient = this;
7189 if (creature->lootForPickPocketed)
7191 creature->lootForPickPocketed = false;
7192 loot->clear();
7195 if(!creature->lootForBody)
7197 creature->lootForBody = true;
7198 loot->clear();
7200 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7201 loot->FillLoot(lootid, LootTemplates_Creature, recipient);
7203 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7205 if(Group* group = recipient->GetGroup())
7207 group->UpdateLooterGuid(creature,true);
7209 switch (group->GetLootMethod())
7211 case GROUP_LOOT:
7212 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7213 group->GroupLoot(recipient->GetGUID(), loot, creature);
7214 break;
7215 case NEED_BEFORE_GREED:
7216 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7217 break;
7218 case MASTER_LOOT:
7219 group->MasterLoot(recipient->GetGUID(), loot, creature);
7220 break;
7221 default:
7222 break;
7227 // possible only if creature->lootForBody && loot->empty() at spell cast check
7228 if (loot_type == LOOT_SKINNING)
7230 loot->clear();
7231 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this);
7233 // set group rights only for loot_type != LOOT_SKINNING
7234 else
7236 if(Group* group = GetGroup())
7238 if( group == recipient->GetGroup() )
7240 if(group->GetLootMethod() == FREE_FOR_ALL)
7241 permission = ALL_PERMISSION;
7242 else if(group->GetLooterGuid() == GetGUID())
7244 if(group->GetLootMethod() == MASTER_LOOT)
7245 permission = MASTER_PERMISSION;
7246 else
7247 permission = ALL_PERMISSION;
7249 else
7250 permission = GROUP_PERMISSION;
7252 else
7253 permission = NONE_PERMISSION;
7255 else if(recipient == this)
7256 permission = ALL_PERMISSION;
7257 else
7258 permission = NONE_PERMISSION;
7263 SetLootGUID(guid);
7265 QuestItemList *q_list = 0;
7266 if (permission != NONE_PERMISSION)
7268 QuestItemMap const& lootPlayerQuestItems = loot->GetPlayerQuestItems();
7269 QuestItemMap::const_iterator itr = lootPlayerQuestItems.find(GetGUIDLow());
7270 if (itr == lootPlayerQuestItems.end())
7271 q_list = loot->FillQuestLoot(this);
7272 else
7273 q_list = itr->second;
7276 QuestItemList *ffa_list = 0;
7277 if (permission != NONE_PERMISSION)
7279 QuestItemMap const& lootPlayerFFAItems = loot->GetPlayerFFAItems();
7280 QuestItemMap::const_iterator itr = lootPlayerFFAItems.find(GetGUIDLow());
7281 if (itr == lootPlayerFFAItems.end())
7282 ffa_list = loot->FillFFALoot(this);
7283 else
7284 ffa_list = itr->second;
7287 QuestItemList *conditional_list = 0;
7288 if (permission != NONE_PERMISSION)
7290 QuestItemMap const& lootPlayerNonQuestNonFFAConditionalItems = loot->GetPlayerNonQuestNonFFAConditionalItems();
7291 QuestItemMap::const_iterator itr = lootPlayerNonQuestNonFFAConditionalItems.find(GetGUIDLow());
7292 if (itr == lootPlayerNonQuestNonFFAConditionalItems.end())
7293 conditional_list = loot->FillNonQuestNonFFAConditionalLoot(this);
7294 else
7295 conditional_list = itr->second;
7298 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING and LOOT_INSIGNIA unsupported by client, sending LOOT_SKINNING instead
7299 if(loot_type == LOOT_PICKPOCKETING || loot_type == LOOT_DISENCHANTING || loot_type == LOOT_PROSPECTING || loot_type == LOOT_INSIGNIA)
7300 loot_type = LOOT_SKINNING;
7302 if(loot_type == LOOT_FISHINGHOLE)
7303 loot_type = LOOT_FISHING;
7305 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7307 data << uint64(guid);
7308 data << uint8(loot_type);
7309 data << LootView(*loot, q_list, ffa_list, conditional_list, this, permission);
7311 SendDirectMessage(&data);
7313 // add 'this' player as one of the players that are looting 'loot'
7314 if (permission != NONE_PERMISSION)
7315 loot->AddLooter(GetGUID());
7317 if ( loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid) )
7318 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7321 void Player::SendNotifyLootMoneyRemoved()
7323 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7324 GetSession()->SendPacket( &data );
7327 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7329 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7330 data << uint8(lootSlot);
7331 GetSession()->SendPacket( &data );
7334 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7336 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7337 data << Field;
7338 data << Value;
7339 GetSession()->SendPacket(&data);
7342 void Player::SendInitWorldStates()
7344 // data depends on zoneid/mapid...
7345 BattleGround* bg = GetBattleGround();
7346 uint16 NumberOfFields = 0;
7347 uint32 mapid = GetMapId();
7348 uint32 zoneid = GetZoneId();
7349 uint32 areaid = GetAreaId();
7350 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7351 // may be exist better way to do this...
7352 switch(zoneid)
7354 case 0:
7355 case 1:
7356 case 4:
7357 case 8:
7358 case 10:
7359 case 11:
7360 case 12:
7361 case 36:
7362 case 38:
7363 case 40:
7364 case 41:
7365 case 51:
7366 case 267:
7367 case 1519:
7368 case 1537:
7369 case 2257:
7370 case 2918:
7371 NumberOfFields = 6;
7372 break;
7373 case 2597:
7374 NumberOfFields = 81;
7375 break;
7376 case 3277:
7377 NumberOfFields = 14;
7378 break;
7379 case 3358:
7380 case 3820:
7381 NumberOfFields = 38;
7382 break;
7383 case 3483:
7384 NumberOfFields = 22;
7385 break;
7386 case 3519:
7387 NumberOfFields = 36;
7388 break;
7389 case 3521:
7390 NumberOfFields = 35;
7391 break;
7392 case 3698:
7393 case 3702:
7394 case 3968:
7395 NumberOfFields = 9;
7396 break;
7397 case 3703:
7398 NumberOfFields = 9;
7399 break;
7400 default:
7401 NumberOfFields = 10;
7402 break;
7405 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7406 data << uint32(mapid); // mapid
7407 data << uint32(zoneid); // zone id
7408 data << uint32(areaid); // area id, new 2.1.0
7409 data << uint16(NumberOfFields); // count of uint64 blocks
7410 data << uint32(0x8d8) << uint32(0x0); // 1
7411 data << uint32(0x8d7) << uint32(0x0); // 2
7412 data << uint32(0x8d6) << uint32(0x0); // 3
7413 data << uint32(0x8d5) << uint32(0x0); // 4
7414 data << uint32(0x8d4) << uint32(0x0); // 5
7415 data << uint32(0x8d3) << uint32(0x0); // 6
7416 if(mapid == 530) // Outland
7418 data << uint32(0x9bf) << uint32(0x0); // 7
7419 data << uint32(0x9bd) << uint32(0xF); // 8
7420 data << uint32(0x9bb) << uint32(0xF); // 9
7422 switch(zoneid)
7424 case 1:
7425 case 11:
7426 case 12:
7427 case 38:
7428 case 40:
7429 case 51:
7430 case 1519:
7431 case 1537:
7432 case 2257:
7433 break;
7434 case 2597: // AV
7435 data << uint32(0x7ae) << uint32(0x1); // 7
7436 data << uint32(0x532) << uint32(0x1); // 8
7437 data << uint32(0x531) << uint32(0x0); // 9
7438 data << uint32(0x52e) << uint32(0x0); // 10
7439 data << uint32(0x571) << uint32(0x0); // 11
7440 data << uint32(0x570) << uint32(0x0); // 12
7441 data << uint32(0x567) << uint32(0x1); // 13
7442 data << uint32(0x566) << uint32(0x1); // 14
7443 data << uint32(0x550) << uint32(0x1); // 15
7444 data << uint32(0x544) << uint32(0x0); // 16
7445 data << uint32(0x536) << uint32(0x0); // 17
7446 data << uint32(0x535) << uint32(0x1); // 18
7447 data << uint32(0x518) << uint32(0x0); // 19
7448 data << uint32(0x517) << uint32(0x0); // 20
7449 data << uint32(0x574) << uint32(0x0); // 21
7450 data << uint32(0x573) << uint32(0x0); // 22
7451 data << uint32(0x572) << uint32(0x0); // 23
7452 data << uint32(0x56f) << uint32(0x0); // 24
7453 data << uint32(0x56e) << uint32(0x0); // 25
7454 data << uint32(0x56d) << uint32(0x0); // 26
7455 data << uint32(0x56c) << uint32(0x0); // 27
7456 data << uint32(0x56b) << uint32(0x0); // 28
7457 data << uint32(0x56a) << uint32(0x1); // 29
7458 data << uint32(0x569) << uint32(0x1); // 30
7459 data << uint32(0x568) << uint32(0x1); // 13
7460 data << uint32(0x565) << uint32(0x0); // 32
7461 data << uint32(0x564) << uint32(0x0); // 33
7462 data << uint32(0x563) << uint32(0x0); // 34
7463 data << uint32(0x562) << uint32(0x0); // 35
7464 data << uint32(0x561) << uint32(0x0); // 36
7465 data << uint32(0x560) << uint32(0x0); // 37
7466 data << uint32(0x55f) << uint32(0x0); // 38
7467 data << uint32(0x55e) << uint32(0x0); // 39
7468 data << uint32(0x55d) << uint32(0x0); // 40
7469 data << uint32(0x3c6) << uint32(0x4); // 41
7470 data << uint32(0x3c4) << uint32(0x6); // 42
7471 data << uint32(0x3c2) << uint32(0x4); // 43
7472 data << uint32(0x516) << uint32(0x1); // 44
7473 data << uint32(0x515) << uint32(0x0); // 45
7474 data << uint32(0x3b6) << uint32(0x6); // 46
7475 data << uint32(0x55c) << uint32(0x0); // 47
7476 data << uint32(0x55b) << uint32(0x0); // 48
7477 data << uint32(0x55a) << uint32(0x0); // 49
7478 data << uint32(0x559) << uint32(0x0); // 50
7479 data << uint32(0x558) << uint32(0x0); // 51
7480 data << uint32(0x557) << uint32(0x0); // 52
7481 data << uint32(0x556) << uint32(0x0); // 53
7482 data << uint32(0x555) << uint32(0x0); // 54
7483 data << uint32(0x554) << uint32(0x1); // 55
7484 data << uint32(0x553) << uint32(0x1); // 56
7485 data << uint32(0x552) << uint32(0x1); // 57
7486 data << uint32(0x551) << uint32(0x1); // 58
7487 data << uint32(0x54f) << uint32(0x0); // 59
7488 data << uint32(0x54e) << uint32(0x0); // 60
7489 data << uint32(0x54d) << uint32(0x1); // 61
7490 data << uint32(0x54c) << uint32(0x0); // 62
7491 data << uint32(0x54b) << uint32(0x0); // 63
7492 data << uint32(0x545) << uint32(0x0); // 64
7493 data << uint32(0x543) << uint32(0x1); // 65
7494 data << uint32(0x542) << uint32(0x0); // 66
7495 data << uint32(0x540) << uint32(0x0); // 67
7496 data << uint32(0x53f) << uint32(0x0); // 68
7497 data << uint32(0x53e) << uint32(0x0); // 69
7498 data << uint32(0x53d) << uint32(0x0); // 70
7499 data << uint32(0x53c) << uint32(0x0); // 71
7500 data << uint32(0x53b) << uint32(0x0); // 72
7501 data << uint32(0x53a) << uint32(0x1); // 73
7502 data << uint32(0x539) << uint32(0x0); // 74
7503 data << uint32(0x538) << uint32(0x0); // 75
7504 data << uint32(0x537) << uint32(0x0); // 76
7505 data << uint32(0x534) << uint32(0x0); // 77
7506 data << uint32(0x533) << uint32(0x0); // 78
7507 data << uint32(0x530) << uint32(0x0); // 79
7508 data << uint32(0x52f) << uint32(0x0); // 80
7509 data << uint32(0x52d) << uint32(0x1); // 81
7510 break;
7511 case 3277: // WS
7512 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7513 bg->FillInitialWorldStates(data);
7514 else
7516 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7517 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7518 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7519 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7520 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7521 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7522 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7523 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7525 break;
7526 case 3358: // AB
7527 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7528 bg->FillInitialWorldStates(data);
7529 else
7531 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7532 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7533 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7534 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7535 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7536 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7537 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7538 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7539 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7540 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7541 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7542 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7543 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7544 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7545 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7546 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7547 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7548 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7549 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7550 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7551 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7552 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7553 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7554 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7555 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7556 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7557 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7558 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7559 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7560 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7561 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7562 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7564 break;
7565 case 3820: // EY
7566 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7567 bg->FillInitialWorldStates(data);
7568 else
7570 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7571 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7572 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7573 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7574 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7575 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7576 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7577 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7578 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7579 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7580 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7581 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7582 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7583 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7584 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7585 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7586 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7587 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7588 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontroled (1 - yes, 0 - no)
7589 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7590 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7591 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7592 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7593 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7594 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7595 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7596 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7597 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7598 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7599 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7600 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7601 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7602 // and some more ... unknown
7604 break;
7605 case 3483: // Hellfire Peninsula
7606 data << uint32(0x9ba) << uint32(0x1); // 10
7607 data << uint32(0x9b9) << uint32(0x1); // 11
7608 data << uint32(0x9b5) << uint32(0x0); // 12
7609 data << uint32(0x9b4) << uint32(0x1); // 13
7610 data << uint32(0x9b3) << uint32(0x0); // 14
7611 data << uint32(0x9b2) << uint32(0x0); // 15
7612 data << uint32(0x9b1) << uint32(0x1); // 16
7613 data << uint32(0x9b0) << uint32(0x0); // 17
7614 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7615 data << uint32(0x9ac) << uint32(0x0); // 19
7616 data << uint32(0x9a8) << uint32(0x0); // 20
7617 data << uint32(0x9a7) << uint32(0x0); // 21
7618 data << uint32(0x9a6) << uint32(0x1); // 22
7619 break;
7620 case 3519: // Terokkar Forest
7621 data << uint32(0xa41) << uint32(0x0); // 10
7622 data << uint32(0xa40) << uint32(0x14); // 11
7623 data << uint32(0xa3f) << uint32(0x0); // 12
7624 data << uint32(0xa3e) << uint32(0x0); // 13
7625 data << uint32(0xa3d) << uint32(0x5); // 14
7626 data << uint32(0xa3c) << uint32(0x0); // 15
7627 data << uint32(0xa87) << uint32(0x0); // 16
7628 data << uint32(0xa86) << uint32(0x0); // 17
7629 data << uint32(0xa85) << uint32(0x0); // 18
7630 data << uint32(0xa84) << uint32(0x0); // 19
7631 data << uint32(0xa83) << uint32(0x0); // 20
7632 data << uint32(0xa82) << uint32(0x0); // 21
7633 data << uint32(0xa81) << uint32(0x0); // 22
7634 data << uint32(0xa80) << uint32(0x0); // 23
7635 data << uint32(0xa7e) << uint32(0x0); // 24
7636 data << uint32(0xa7d) << uint32(0x0); // 25
7637 data << uint32(0xa7c) << uint32(0x0); // 26
7638 data << uint32(0xa7b) << uint32(0x0); // 27
7639 data << uint32(0xa7a) << uint32(0x0); // 28
7640 data << uint32(0xa79) << uint32(0x0); // 29
7641 data << uint32(0x9d0) << uint32(0x5); // 30
7642 data << uint32(0x9ce) << uint32(0x0); // 31
7643 data << uint32(0x9cd) << uint32(0x0); // 32
7644 data << uint32(0x9cc) << uint32(0x0); // 33
7645 data << uint32(0xa88) << uint32(0x0); // 34
7646 data << uint32(0xad0) << uint32(0x0); // 35
7647 data << uint32(0xacf) << uint32(0x1); // 36
7648 break;
7649 case 3521: // Zangarmarsh
7650 data << uint32(0x9e1) << uint32(0x0); // 10
7651 data << uint32(0x9e0) << uint32(0x0); // 11
7652 data << uint32(0x9df) << uint32(0x0); // 12
7653 data << uint32(0xa5d) << uint32(0x1); // 13
7654 data << uint32(0xa5c) << uint32(0x0); // 14
7655 data << uint32(0xa5b) << uint32(0x1); // 15
7656 data << uint32(0xa5a) << uint32(0x0); // 16
7657 data << uint32(0xa59) << uint32(0x1); // 17
7658 data << uint32(0xa58) << uint32(0x0); // 18
7659 data << uint32(0xa57) << uint32(0x0); // 19
7660 data << uint32(0xa56) << uint32(0x0); // 20
7661 data << uint32(0xa55) << uint32(0x1); // 21
7662 data << uint32(0xa54) << uint32(0x0); // 22
7663 data << uint32(0x9e7) << uint32(0x0); // 23
7664 data << uint32(0x9e6) << uint32(0x0); // 24
7665 data << uint32(0x9e5) << uint32(0x0); // 25
7666 data << uint32(0xa00) << uint32(0x0); // 26
7667 data << uint32(0x9ff) << uint32(0x1); // 27
7668 data << uint32(0x9fe) << uint32(0x0); // 28
7669 data << uint32(0x9fd) << uint32(0x0); // 29
7670 data << uint32(0x9fc) << uint32(0x1); // 30
7671 data << uint32(0x9fb) << uint32(0x0); // 31
7672 data << uint32(0xa62) << uint32(0x0); // 32
7673 data << uint32(0xa61) << uint32(0x1); // 33
7674 data << uint32(0xa60) << uint32(0x1); // 34
7675 data << uint32(0xa5f) << uint32(0x0); // 35
7676 break;
7677 case 3698: // Nagrand Arena
7678 data << uint32(0xa0f) << uint32(0x0); // 7
7679 data << uint32(0xa10) << uint32(0x0); // 8
7680 data << uint32(0xa11) << uint32(0x0); // 9
7681 break;
7682 case 3702: // Blade's Edge Arena
7683 data << uint32(0x9f0) << uint32(0x0); // 7
7684 data << uint32(0x9f1) << uint32(0x0); // 8
7685 data << uint32(0x9f3) << uint32(0x0); // 9
7686 break;
7687 case 3968: // Ruins of Lordaeron
7688 data << uint32(0xbb8) << uint32(0x0); // 7
7689 data << uint32(0xbb9) << uint32(0x0); // 8
7690 data << uint32(0xbba) << uint32(0x0); // 9
7691 break;
7692 case 3703: // Shattrath City
7693 break;
7694 default:
7695 data << uint32(0x914) << uint32(0x0); // 7
7696 data << uint32(0x913) << uint32(0x0); // 8
7697 data << uint32(0x912) << uint32(0x0); // 9
7698 data << uint32(0x915) << uint32(0x0); // 10
7699 break;
7701 GetSession()->SendPacket(&data);
7704 uint32 Player::GetXPRestBonus(uint32 xp)
7706 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
7708 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
7709 rested_bonus = xp;
7711 SetRestBonus( GetRestBonus() - rested_bonus);
7713 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
7714 return rested_bonus;
7717 void Player::SetBindPoint(uint64 guid)
7719 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
7720 data << uint64(guid);
7721 GetSession()->SendPacket( &data );
7724 void Player::SendTalentWipeConfirm(uint64 guid)
7726 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
7727 data << uint64(guid);
7728 data << uint32(resetTalentsCost());
7729 GetSession()->SendPacket( &data );
7732 void Player::SendPetSkillWipeConfirm()
7734 Pet* pet = GetPet();
7735 if(!pet)
7736 return;
7737 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
7738 data << pet->GetGUID();
7739 data << uint32(pet->resetTalentsCost());
7740 GetSession()->SendPacket( &data );
7743 /*********************************************************/
7744 /*** STORAGE SYSTEM ***/
7745 /*********************************************************/
7747 void Player::SetVirtualItemSlot( uint8 i, Item* item)
7749 assert(i < 3);
7750 if(i < 2 && item)
7752 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
7753 return;
7754 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
7755 if(charges == 0)
7756 return;
7757 if(charges > 1)
7758 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
7759 else if(charges <= 1)
7761 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
7762 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
7767 void Player::SetSheath( uint32 sheathed )
7769 switch (sheathed)
7771 case SHEATH_STATE_UNARMED: // no prepared weapon
7772 SetVirtualItemSlot(0,NULL);
7773 SetVirtualItemSlot(1,NULL);
7774 SetVirtualItemSlot(2,NULL);
7775 break;
7776 case SHEATH_STATE_MELEE: // prepared melee weapon
7778 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
7779 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
7780 SetVirtualItemSlot(2,NULL);
7781 }; break;
7782 case SHEATH_STATE_RANGED: // prepared ranged weapon
7783 SetVirtualItemSlot(0,NULL);
7784 SetVirtualItemSlot(1,NULL);
7785 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
7786 break;
7787 default:
7788 SetVirtualItemSlot(0,NULL);
7789 SetVirtualItemSlot(1,NULL);
7790 SetVirtualItemSlot(2,NULL);
7791 break;
7793 SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); // this must visualize Sheath changing for other players...
7796 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
7798 uint8 pClass = getClass();
7800 uint8 slots[4];
7801 slots[0] = NULL_SLOT;
7802 slots[1] = NULL_SLOT;
7803 slots[2] = NULL_SLOT;
7804 slots[3] = NULL_SLOT;
7805 switch( proto->InventoryType )
7807 case INVTYPE_HEAD:
7808 slots[0] = EQUIPMENT_SLOT_HEAD;
7809 break;
7810 case INVTYPE_NECK:
7811 slots[0] = EQUIPMENT_SLOT_NECK;
7812 break;
7813 case INVTYPE_SHOULDERS:
7814 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
7815 break;
7816 case INVTYPE_BODY:
7817 slots[0] = EQUIPMENT_SLOT_BODY;
7818 break;
7819 case INVTYPE_CHEST:
7820 slots[0] = EQUIPMENT_SLOT_CHEST;
7821 break;
7822 case INVTYPE_ROBE:
7823 slots[0] = EQUIPMENT_SLOT_CHEST;
7824 break;
7825 case INVTYPE_WAIST:
7826 slots[0] = EQUIPMENT_SLOT_WAIST;
7827 break;
7828 case INVTYPE_LEGS:
7829 slots[0] = EQUIPMENT_SLOT_LEGS;
7830 break;
7831 case INVTYPE_FEET:
7832 slots[0] = EQUIPMENT_SLOT_FEET;
7833 break;
7834 case INVTYPE_WRISTS:
7835 slots[0] = EQUIPMENT_SLOT_WRISTS;
7836 break;
7837 case INVTYPE_HANDS:
7838 slots[0] = EQUIPMENT_SLOT_HANDS;
7839 break;
7840 case INVTYPE_FINGER:
7841 slots[0] = EQUIPMENT_SLOT_FINGER1;
7842 slots[1] = EQUIPMENT_SLOT_FINGER2;
7843 break;
7844 case INVTYPE_TRINKET:
7845 slots[0] = EQUIPMENT_SLOT_TRINKET1;
7846 slots[1] = EQUIPMENT_SLOT_TRINKET2;
7847 break;
7848 case INVTYPE_CLOAK:
7849 slots[0] = EQUIPMENT_SLOT_BACK;
7850 break;
7851 case INVTYPE_WEAPON:
7853 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7855 // suggest offhand slot only if know dual wielding
7856 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
7857 if(CanDualWield())
7858 slots[1] = EQUIPMENT_SLOT_OFFHAND;
7859 };break;
7860 case INVTYPE_SHIELD:
7861 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7862 break;
7863 case INVTYPE_RANGED:
7864 slots[0] = EQUIPMENT_SLOT_RANGED;
7865 break;
7866 case INVTYPE_2HWEAPON:
7867 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7868 break;
7869 case INVTYPE_TABARD:
7870 slots[0] = EQUIPMENT_SLOT_TABARD;
7871 break;
7872 case INVTYPE_WEAPONMAINHAND:
7873 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7874 break;
7875 case INVTYPE_WEAPONOFFHAND:
7876 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7877 break;
7878 case INVTYPE_HOLDABLE:
7879 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7880 break;
7881 case INVTYPE_THROWN:
7882 slots[0] = EQUIPMENT_SLOT_RANGED;
7883 break;
7884 case INVTYPE_RANGEDRIGHT:
7885 slots[0] = EQUIPMENT_SLOT_RANGED;
7886 break;
7887 case INVTYPE_BAG:
7888 slots[0] = INVENTORY_SLOT_BAG_1;
7889 slots[1] = INVENTORY_SLOT_BAG_2;
7890 slots[2] = INVENTORY_SLOT_BAG_3;
7891 slots[3] = INVENTORY_SLOT_BAG_4;
7892 break;
7893 case INVTYPE_RELIC:
7895 switch(proto->SubClass)
7897 case ITEM_SUBCLASS_ARMOR_LIBRAM:
7898 if (pClass == CLASS_PALADIN)
7899 slots[0] = EQUIPMENT_SLOT_RANGED;
7900 break;
7901 case ITEM_SUBCLASS_ARMOR_IDOL:
7902 if (pClass == CLASS_DRUID)
7903 slots[0] = EQUIPMENT_SLOT_RANGED;
7904 break;
7905 case ITEM_SUBCLASS_ARMOR_TOTEM:
7906 if (pClass == CLASS_SHAMAN)
7907 slots[0] = EQUIPMENT_SLOT_RANGED;
7908 break;
7909 case ITEM_SUBCLASS_ARMOR_MISC:
7910 if (pClass == CLASS_WARLOCK)
7911 slots[0] = EQUIPMENT_SLOT_RANGED;
7912 break;
7914 break;
7916 default :
7917 return NULL_SLOT;
7920 if( slot != NULL_SLOT )
7922 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
7924 for (int i = 0; i < 4; i++)
7926 if ( slots[i] == slot )
7927 return slot;
7931 else
7933 // search free slot at first
7934 for (int i = 0; i < 4; i++)
7936 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
7938 // in case 2hand equipped weapon offhand slot empty but not free
7939 if(slots[i]==EQUIPMENT_SLOT_OFFHAND)
7941 Item* mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );
7942 if(!mainItem || mainItem->GetProto()->InventoryType != INVTYPE_2HWEAPON)
7943 return slots[i];
7945 else
7946 return slots[i];
7950 // if not found free and can swap return first appropriate from used
7951 for (int i = 0; i < 4; i++)
7953 if ( slots[i] != NULL_SLOT && swap )
7954 return slots[i];
7958 // no free position
7959 return NULL_SLOT;
7962 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
7964 Item *pItem;
7965 uint32 tempcount = 0;
7967 uint8 res = EQUIP_ERR_OK;
7969 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
7971 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
7972 if( pItem && pItem->GetEntry() == item )
7974 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
7975 if(ires==EQUIP_ERR_OK)
7977 tempcount += pItem->GetCount();
7978 if( tempcount >= count )
7979 return EQUIP_ERR_OK;
7981 else
7982 res = ires;
7985 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
7987 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
7988 if( pItem && pItem->GetEntry() == item )
7990 tempcount += pItem->GetCount();
7991 if( tempcount >= count )
7992 return EQUIP_ERR_OK;
7995 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
7997 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
7998 if( pItem && pItem->GetEntry() == item )
8000 tempcount += pItem->GetCount();
8001 if( tempcount >= count )
8002 return EQUIP_ERR_OK;
8005 Bag *pBag;
8006 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8008 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8009 if( pBag )
8011 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8013 pItem = GetItemByPos( i, j );
8014 if( pItem && pItem->GetEntry() == item )
8016 tempcount += pItem->GetCount();
8017 if( tempcount >= count )
8018 return EQUIP_ERR_OK;
8024 // not found req. item count and have unequippable items
8025 return res;
8028 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8030 uint32 count = 0;
8031 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8033 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8034 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8035 count += pItem->GetCount();
8037 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
8039 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8040 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8041 count += pItem->GetCount();
8043 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8045 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8046 if( pBag )
8047 count += pBag->GetItemCount(item,skipItem);
8050 if(skipItem && skipItem->GetProto()->GemProperties)
8052 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8054 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8055 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8056 count += pItem->GetGemCountWithID(item);
8060 if(inBankAlso)
8062 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8064 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8065 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8066 count += pItem->GetCount();
8068 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8070 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8071 if( pBag )
8072 count += pBag->GetItemCount(item,skipItem);
8075 if(skipItem && skipItem->GetProto()->GemProperties)
8077 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8079 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8080 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8081 count += pItem->GetGemCountWithID(item);
8086 return count;
8089 Item* Player::GetItemByGuid( uint64 guid ) const
8091 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8093 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8094 if( pItem && pItem->GetGUID() == guid )
8095 return pItem;
8097 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
8099 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8100 if( pItem && pItem->GetGUID() == guid )
8101 return pItem;
8104 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8106 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8107 if( pBag )
8109 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8111 Item* pItem = pBag->GetItemByPos( j );
8112 if( pItem && pItem->GetGUID() == guid )
8113 return pItem;
8117 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8119 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8120 if( pBag )
8122 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8124 Item* pItem = pBag->GetItemByPos( j );
8125 if( pItem && pItem->GetGUID() == guid )
8126 return pItem;
8131 return NULL;
8134 Item* Player::GetItemByPos( uint16 pos ) const
8136 uint8 bag = pos >> 8;
8137 uint8 slot = pos & 255;
8138 return GetItemByPos( bag, slot );
8141 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8143 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END ) )
8144 return m_items[slot];
8145 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8146 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8148 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8149 if ( pBag )
8150 return pBag->GetItemByPos(slot);
8152 return NULL;
8155 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8157 uint16 slot;
8158 switch (attackType)
8160 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8161 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8162 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8163 default: return NULL;
8166 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8167 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8168 return NULL;
8170 if(!useable)
8171 return item;
8173 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8174 return NULL;
8176 return item;
8179 Item* Player::GetShield(bool useable) const
8181 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8182 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8183 return NULL;
8185 if(!useable)
8186 return item;
8188 if( item->IsBroken())
8189 return NULL;
8191 return item;
8194 uint32 Player::GetAttackBySlot( uint8 slot )
8196 switch(slot)
8198 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8199 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8200 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8201 default: return MAX_ATTACK;
8205 bool Player::HasBankBagSlot( uint8 slot ) const
8207 uint32 maxslot = GetByteValue(PLAYER_BYTES_2, 2) + BANK_SLOT_BAG_START;
8208 if( slot < maxslot )
8209 return true;
8210 return false;
8213 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8215 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8216 return true;
8217 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8218 return true;
8219 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8220 return true;
8221 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END ) )
8222 return true;
8223 return false;
8226 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8228 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8229 return true;
8230 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8231 return true;
8232 return false;
8235 bool Player::IsBankPos( uint8 bag, uint8 slot )
8237 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8238 return true;
8239 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8240 return true;
8241 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8242 return true;
8243 return false;
8246 bool Player::IsBagPos( uint16 pos )
8248 uint8 bag = pos >> 8;
8249 uint8 slot = pos & 255;
8250 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8251 return true;
8252 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8253 return true;
8254 return false;
8257 bool Player::IsValidPos( uint8 bag, uint8 slot )
8259 // post selected
8260 if(bag == NULL_BAG)
8261 return true;
8263 if (bag == INVENTORY_SLOT_BAG_0)
8265 // any post selected
8266 if (slot == NULL_SLOT)
8267 return true;
8269 // equipment
8270 if (slot < EQUIPMENT_SLOT_END)
8271 return true;
8273 // bag equip slots
8274 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8275 return true;
8277 // backpack slots
8278 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8279 return true;
8281 // keyring slots
8282 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8283 return true;
8285 // bank main slots
8286 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8287 return true;
8289 // bank bag slots
8290 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8291 return true;
8293 return false;
8296 // bag content slots
8297 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8299 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8300 if(!pBag)
8301 return false;
8303 // any post selected
8304 if (slot == NULL_SLOT)
8305 return true;
8307 return slot < pBag->GetBagSize();
8310 // bank bag content slots
8311 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8313 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8314 if(!pBag)
8315 return false;
8317 // any post selected
8318 if (slot == NULL_SLOT)
8319 return true;
8321 return slot < pBag->GetBagSize();
8324 // where this?
8325 return false;
8329 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8331 uint32 tempcount = 0;
8332 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8334 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8335 if( pItem && pItem->GetEntry() == item )
8337 tempcount += pItem->GetCount();
8338 if( tempcount >= count )
8339 return true;
8342 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
8344 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8345 if( pItem && pItem->GetEntry() == item )
8347 tempcount += pItem->GetCount();
8348 if( tempcount >= count )
8349 return true;
8352 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8354 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8356 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8358 Item* pItem = GetItemByPos( i, j );
8359 if( pItem && pItem->GetEntry() == item )
8361 tempcount += pItem->GetCount();
8362 if( tempcount >= count )
8363 return true;
8369 if(inBankAlso)
8371 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8373 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8374 if( pItem && pItem->GetEntry() == item )
8376 tempcount += pItem->GetCount();
8377 if( tempcount >= count )
8378 return true;
8381 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8383 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8385 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8387 Item* pItem = GetItemByPos( i, j );
8388 if( pItem && pItem->GetEntry() == item )
8390 tempcount += pItem->GetCount();
8391 if( tempcount >= count )
8392 return true;
8399 return false;
8402 Item* Player::GetItemOrItemWithGemEquipped( uint32 item ) const
8404 Item *pItem;
8405 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
8407 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8408 if( pItem && pItem->GetEntry() == item )
8409 return pItem;
8412 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8413 if (pProto && pProto->GemProperties)
8415 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
8417 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8418 if( pItem && pItem->GetProto()->Socket[0].Color )
8420 if (pItem->GetGemCountWithID(item) > 0 )
8421 return pItem;
8426 return NULL;
8429 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8431 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8432 if( !pProto )
8434 if(no_space_count)
8435 *no_space_count = count;
8436 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8439 // no maximum
8440 if(pProto->MaxCount == 0)
8441 return EQUIP_ERR_OK;
8443 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8445 if( curcount + count > pProto->MaxCount )
8447 if(no_space_count)
8448 *no_space_count = count +curcount - pProto->MaxCount;
8449 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8452 return EQUIP_ERR_OK;
8455 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8457 Item *pItem;
8458 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8460 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8461 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8462 return true;
8464 for(uint8 i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; ++i)
8466 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8467 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8468 return true;
8470 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8472 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8474 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8476 pItem = GetItemByPos( i, j );
8477 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8478 return true;
8482 return false;
8485 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8487 Item* pItem2 = GetItemByPos( bag, slot );
8489 // ignore move item (this slot will be empty at move)
8490 if(pItem2==pSrcItem)
8491 pItem2 = NULL;
8493 uint32 need_space;
8495 // empty specific slot - check item fit to slot
8496 if( !pItem2 || swap )
8498 if( bag == INVENTORY_SLOT_BAG_0 )
8500 // keyring case
8501 if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8502 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8504 // prevent cheating
8505 if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8506 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8508 else
8510 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8511 if( !pBag )
8512 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8514 ItemPrototype const* pBagProto = pBag->GetProto();
8515 if( !pBagProto )
8516 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8518 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8519 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8522 // non empty stack with space
8523 need_space = pProto->Stackable;
8525 // non empty slot, check item type
8526 else
8528 // check item type
8529 if(pItem2->GetEntry() != pProto->ItemId)
8530 return EQUIP_ERR_ITEM_CANT_STACK;
8532 // check free space
8533 if(pItem2->GetCount() >= pProto->Stackable)
8534 return EQUIP_ERR_ITEM_CANT_STACK;
8536 need_space = pProto->Stackable - pItem2->GetCount();
8539 if(need_space > count)
8540 need_space = count;
8542 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8543 if(!newPosition.isContainedIn(dest))
8545 dest.push_back(newPosition);
8546 count -= need_space;
8548 return EQUIP_ERR_OK;
8551 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
8553 // skip specific bag already processed in first called _CanStoreItem_InBag
8554 if(bag==skip_bag)
8555 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8557 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8558 if( !pBag )
8559 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8561 ItemPrototype const* pBagProto = pBag->GetProto();
8562 if( !pBagProto )
8563 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8565 // specialized bag mode or non-specilized
8566 if( non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) )
8567 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8569 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8570 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8572 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8574 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8575 if(j==skip_slot)
8576 continue;
8578 Item* pItem2 = GetItemByPos( bag, j );
8580 // ignore move item (this slot will be empty at move)
8581 if(pItem2==pSrcItem)
8582 pItem2 = NULL;
8584 // if merge skip empty, if !merge skip non-empty
8585 if((pItem2!=NULL)!=merge)
8586 continue;
8588 if( pItem2 )
8590 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->Stackable )
8592 uint32 need_space = pProto->Stackable - pItem2->GetCount();
8593 if(need_space > count)
8594 need_space = count;
8596 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8597 if(!newPosition.isContainedIn(dest))
8599 dest.push_back(newPosition);
8600 count -= need_space;
8602 if(count==0)
8603 return EQUIP_ERR_OK;
8607 else
8609 uint32 need_space = pProto->Stackable;
8610 if(need_space > count)
8611 need_space = count;
8613 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8614 if(!newPosition.isContainedIn(dest))
8616 dest.push_back(newPosition);
8617 count -= need_space;
8619 if(count==0)
8620 return EQUIP_ERR_OK;
8624 return EQUIP_ERR_OK;
8627 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
8629 for(uint32 j = slot_begin; j < slot_end; j++)
8631 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8632 if(INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
8633 continue;
8635 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
8637 // ignore move item (this slot will be empty at move)
8638 if(pItem2==pSrcItem)
8639 pItem2 = NULL;
8641 // if merge skip empty, if !merge skip non-empty
8642 if((pItem2!=NULL)!=merge)
8643 continue;
8645 if( pItem2 )
8647 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->Stackable )
8649 uint32 need_space = pProto->Stackable - pItem2->GetCount();
8650 if(need_space > count)
8651 need_space = count;
8652 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8653 if(!newPosition.isContainedIn(dest))
8655 dest.push_back(newPosition);
8656 count -= need_space;
8658 if(count==0)
8659 return EQUIP_ERR_OK;
8663 else
8665 uint32 need_space = pProto->Stackable;
8666 if(need_space > count)
8667 need_space = count;
8669 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8670 if(!newPosition.isContainedIn(dest))
8672 dest.push_back(newPosition);
8673 count -= need_space;
8675 if(count==0)
8676 return EQUIP_ERR_OK;
8680 return EQUIP_ERR_OK;
8683 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
8685 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
8687 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8688 if( !pProto )
8690 if(no_space_count)
8691 *no_space_count = count;
8692 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
8695 if(pItem && pItem->IsBindedNotWith(GetGUID()))
8697 if(no_space_count)
8698 *no_space_count = count;
8699 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
8702 // check count of items (skip for auto move for same player from bank)
8703 uint32 no_similar_count = 0; // can't store this amount similar items
8704 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
8705 if(res!=EQUIP_ERR_OK)
8707 if(count==no_similar_count)
8709 if(no_space_count)
8710 *no_space_count = no_similar_count;
8711 return res;
8713 count -= no_similar_count;
8716 // in specific slot
8717 if( bag != NULL_BAG && slot != NULL_SLOT )
8719 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
8720 if(res!=EQUIP_ERR_OK)
8722 if(no_space_count)
8723 *no_space_count = count + no_similar_count;
8724 return res;
8727 if(count==0)
8729 if(no_similar_count==0)
8730 return EQUIP_ERR_OK;
8732 if(no_space_count)
8733 *no_space_count = count + no_similar_count;
8734 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8738 // not specific slot or have spece for partly store only in specific slot
8740 // in specific bag
8741 if( bag != NULL_BAG )
8743 // search stack in bag for merge to
8744 if( pProto->Stackable > 1 )
8746 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8748 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
8749 if(res!=EQUIP_ERR_OK)
8751 if(no_space_count)
8752 *no_space_count = count + no_similar_count;
8753 return res;
8756 if(count==0)
8758 if(no_similar_count==0)
8759 return EQUIP_ERR_OK;
8761 if(no_space_count)
8762 *no_space_count = count + no_similar_count;
8763 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8766 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
8767 if(res!=EQUIP_ERR_OK)
8769 if(no_space_count)
8770 *no_space_count = count + no_similar_count;
8771 return res;
8774 if(count==0)
8776 if(no_similar_count==0)
8777 return EQUIP_ERR_OK;
8779 if(no_space_count)
8780 *no_space_count = count + no_similar_count;
8781 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8784 else // equipped bag
8786 // we need check 2 time (specilized/non_specialized), use NULL_BAG to prevent skipping bag
8787 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
8788 if(res!=EQUIP_ERR_OK)
8789 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
8791 if(res!=EQUIP_ERR_OK)
8793 if(no_space_count)
8794 *no_space_count = count + no_similar_count;
8795 return res;
8798 if(count==0)
8800 if(no_similar_count==0)
8801 return EQUIP_ERR_OK;
8803 if(no_space_count)
8804 *no_space_count = count + no_similar_count;
8805 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8810 // search free slot in bag for place to
8811 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8813 // search free slot - keyring case
8814 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
8816 uint32 keyringSize = GetMaxKeyringSize();
8817 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
8818 if(res!=EQUIP_ERR_OK)
8820 if(no_space_count)
8821 *no_space_count = count + no_similar_count;
8822 return res;
8825 if(count==0)
8827 if(no_similar_count==0)
8828 return EQUIP_ERR_OK;
8830 if(no_space_count)
8831 *no_space_count = count + no_similar_count;
8832 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8836 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
8837 if(res!=EQUIP_ERR_OK)
8839 if(no_space_count)
8840 *no_space_count = count + no_similar_count;
8841 return res;
8844 if(count==0)
8846 if(no_similar_count==0)
8847 return EQUIP_ERR_OK;
8849 if(no_space_count)
8850 *no_space_count = count + no_similar_count;
8851 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8854 else // equipped bag
8856 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
8857 if(res!=EQUIP_ERR_OK)
8858 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
8860 if(res!=EQUIP_ERR_OK)
8862 if(no_space_count)
8863 *no_space_count = count + no_similar_count;
8864 return res;
8867 if(count==0)
8869 if(no_similar_count==0)
8870 return EQUIP_ERR_OK;
8872 if(no_space_count)
8873 *no_space_count = count + no_similar_count;
8874 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8879 // not specific bag or have space for partly store only in specific bag
8881 // search stack for merge to
8882 if( pProto->Stackable > 1 )
8884 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
8885 if(res!=EQUIP_ERR_OK)
8887 if(no_space_count)
8888 *no_space_count = count + no_similar_count;
8889 return res;
8892 if(count==0)
8894 if(no_similar_count==0)
8895 return EQUIP_ERR_OK;
8897 if(no_space_count)
8898 *no_space_count = count + no_similar_count;
8899 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8902 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
8903 if(res!=EQUIP_ERR_OK)
8905 if(no_space_count)
8906 *no_space_count = count + no_similar_count;
8907 return res;
8910 if(count==0)
8912 if(no_similar_count==0)
8913 return EQUIP_ERR_OK;
8915 if(no_space_count)
8916 *no_space_count = count + no_similar_count;
8917 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8920 if( pProto->BagFamily )
8922 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8924 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
8925 if(res!=EQUIP_ERR_OK)
8926 continue;
8928 if(count==0)
8930 if(no_similar_count==0)
8931 return EQUIP_ERR_OK;
8933 if(no_space_count)
8934 *no_space_count = count + no_similar_count;
8935 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8940 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8942 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
8943 if(res!=EQUIP_ERR_OK)
8944 continue;
8946 if(count==0)
8948 if(no_similar_count==0)
8949 return EQUIP_ERR_OK;
8951 if(no_space_count)
8952 *no_space_count = count + no_similar_count;
8953 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8958 // search free slot - special bag case
8959 if( pProto->BagFamily )
8961 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
8963 uint32 keyringSize = GetMaxKeyringSize();
8964 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
8965 if(res!=EQUIP_ERR_OK)
8967 if(no_space_count)
8968 *no_space_count = count + no_similar_count;
8969 return res;
8972 if(count==0)
8974 if(no_similar_count==0)
8975 return EQUIP_ERR_OK;
8977 if(no_space_count)
8978 *no_space_count = count + no_similar_count;
8979 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8983 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8985 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
8986 if(res!=EQUIP_ERR_OK)
8987 continue;
8989 if(count==0)
8991 if(no_similar_count==0)
8992 return EQUIP_ERR_OK;
8994 if(no_space_count)
8995 *no_space_count = count + no_similar_count;
8996 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9001 // search free slot
9002 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9003 if(res!=EQUIP_ERR_OK)
9005 if(no_space_count)
9006 *no_space_count = count + no_similar_count;
9007 return res;
9010 if(count==0)
9012 if(no_similar_count==0)
9013 return EQUIP_ERR_OK;
9015 if(no_space_count)
9016 *no_space_count = count + no_similar_count;
9017 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9020 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9022 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9023 if(res!=EQUIP_ERR_OK)
9024 continue;
9026 if(count==0)
9028 if(no_similar_count==0)
9029 return EQUIP_ERR_OK;
9031 if(no_space_count)
9032 *no_space_count = count + no_similar_count;
9033 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9037 if(no_space_count)
9038 *no_space_count = count + no_similar_count;
9040 return EQUIP_ERR_INVENTORY_FULL;
9043 //////////////////////////////////////////////////////////////////////////
9044 uint8 Player::CanStoreItems( Item **pItems,int count) const
9046 Item *pItem2;
9048 // fill space table
9049 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9050 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9051 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9053 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9054 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9055 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9057 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
9059 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9061 if (pItem2 && !pItem2->IsInTrade())
9063 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9067 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
9069 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9071 if (pItem2 && !pItem2->IsInTrade())
9073 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9077 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9079 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9081 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9083 pItem2 = GetItemByPos( i, j );
9084 if (pItem2 && !pItem2->IsInTrade())
9086 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9092 // check free space for all items
9093 for (int k=0;k<count;k++)
9095 Item *pItem = pItems[k];
9097 // no item
9098 if (!pItem) continue;
9100 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9101 ItemPrototype const *pProto = pItem->GetProto();
9103 // strange item
9104 if( !pProto )
9105 return EQUIP_ERR_ITEM_NOT_FOUND;
9107 // item it 'bind'
9108 if(pItem->IsBindedNotWith(GetGUID()))
9109 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9111 Bag *pBag;
9112 ItemPrototype const *pBagProto;
9114 // item is 'one item only'
9115 uint8 res = CanTakeMoreSimilarItems(pItem);
9116 if(res != EQUIP_ERR_OK)
9117 return res;
9119 // search stack for merge to
9120 if( pProto->Stackable > 1 )
9122 bool b_found = false;
9124 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; t++)
9126 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9127 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->Stackable )
9129 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9130 b_found = true;
9131 break;
9134 if (b_found) continue;
9136 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9138 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9139 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->Stackable )
9141 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9142 b_found = true;
9143 break;
9146 if (b_found) continue;
9148 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9150 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9151 if( pBag )
9153 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9155 pItem2 = GetItemByPos( t, j );
9156 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->Stackable )
9158 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9159 b_found = true;
9160 break;
9165 if (b_found) continue;
9168 // special bag case
9169 if( pProto->BagFamily )
9171 bool b_found = false;
9172 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9174 uint32 keyringSize = GetMaxKeyringSize();
9175 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9177 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9179 inv_keys[t-KEYRING_SLOT_START] = 1;
9180 b_found = true;
9181 break;
9186 if (b_found) continue;
9188 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9190 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9191 if( pBag )
9193 pBagProto = pBag->GetProto();
9195 // not plain container check
9196 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9197 ItemCanGoIntoBag(pProto,pBagProto) )
9199 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9201 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9203 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9204 b_found = true;
9205 break;
9211 if (b_found) continue;
9214 // search free slot
9215 bool b_found = false;
9216 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9218 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9220 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9221 b_found = true;
9222 break;
9225 if (b_found) continue;
9227 // search free slot in bags
9228 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9230 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9231 if( pBag )
9233 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9235 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9237 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9238 b_found = true;
9239 break;
9245 // no free slot found?
9246 if (!b_found)
9247 return EQUIP_ERR_INVENTORY_FULL;
9250 return EQUIP_ERR_OK;
9253 //////////////////////////////////////////////////////////////////////////
9254 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, uint32 count, bool swap ) const
9256 dest = 0;
9257 Item *pItem = Item::CreateItem( item, count, this );
9258 if( pItem )
9260 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9261 delete pItem;
9262 return result;
9265 return EQUIP_ERR_ITEM_NOT_FOUND;
9268 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9270 dest = 0;
9271 if( pItem )
9273 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9274 ItemPrototype const *pProto = pItem->GetProto();
9275 if( pProto )
9277 // May be here should be more stronger checks; STUNNED checked
9278 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9279 if (not_loading && hasUnitState(UNIT_STAT_STUNNED))
9280 return EQUIP_ERR_YOU_ARE_STUNNED;
9282 if(pItem->IsBindedNotWith(GetGUID()))
9283 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9285 // check count of items (skip for auto move for same player from bank)
9286 uint8 res = CanTakeMoreSimilarItems(pItem);
9287 if(res != EQUIP_ERR_OK)
9288 return res;
9290 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9291 // - combat
9292 // - in-progress arenas
9293 if( !pProto->CanChangeEquipStateInCombat() )
9295 if( isInCombat() )
9296 return EQUIP_ERR_NOT_IN_COMBAT;
9298 if(BattleGround* bg = GetBattleGround())
9299 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9300 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9303 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9304 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9306 if(IsNonMeleeSpellCasted(false))
9307 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9309 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9310 if( eslot == NULL_SLOT )
9311 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9313 uint8 msg = CanUseItem( pItem , not_loading );
9314 if( msg != EQUIP_ERR_OK )
9315 return msg;
9316 if( !swap && GetItemByPos( INVENTORY_SLOT_BAG_0, eslot ) )
9317 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9319 // check unique-equipped on item
9320 if (pProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
9322 // there is an equip limit on this item
9323 Item* tItem = GetItemOrItemWithGemEquipped(pProto->ItemId);
9324 if (tItem && (!swap || tItem->GetSlot() != eslot ) )
9325 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
9328 // check unique-equipped on gems
9329 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
9331 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
9332 if(!enchant_id)
9333 continue;
9334 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
9335 if(!enchantEntry)
9336 continue;
9338 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
9339 if(pGem && (pGem->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED))
9341 Item* tItem = GetItemOrItemWithGemEquipped(enchantEntry->GemID);
9342 if(tItem && (!swap || tItem->GetSlot() != eslot ))
9343 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
9347 // check unique-equipped special item classes
9348 if (pProto->Class == ITEM_CLASS_QUIVER)
9350 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9352 if( Item* pBag = GetItemByPos( INVENTORY_SLOT_BAG_0, i ) )
9354 if( ItemPrototype const* pBagProto = pBag->GetProto() )
9356 if( pBagProto->Class==pProto->Class && pBagProto->SubClass==pProto->SubClass &&
9357 (!swap || pBag->GetSlot() != eslot ) )
9359 if(pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9360 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH;
9361 else
9362 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9369 uint32 type = pProto->InventoryType;
9371 if(eslot == EQUIPMENT_SLOT_OFFHAND)
9373 if( type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND )
9375 if(!CanDualWield())
9376 return EQUIP_ERR_CANT_DUAL_WIELD;
9379 Item *mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );
9380 if(mainItem)
9382 if(mainItem->GetProto()->InventoryType == INVTYPE_2HWEAPON)
9383 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9387 // equip two-hand weapon case (with possible unequip 2 items)
9388 if( type == INVTYPE_2HWEAPON )
9390 if(eslot != EQUIPMENT_SLOT_MAINHAND)
9391 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9393 // offhand item must can be stored in inventitory for offhand item and it also must be unequipped
9394 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9395 ItemPosCountVec off_dest;
9396 if( offItem && (!not_loading ||
9397 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9398 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ) )
9399 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9401 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9402 return EQUIP_ERR_OK;
9405 if( !swap )
9406 return EQUIP_ERR_ITEM_NOT_FOUND;
9407 else
9408 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9411 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9413 // Applied only to equipped items and bank bags
9414 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9415 return EQUIP_ERR_OK;
9417 Item* pItem = GetItemByPos(pos);
9419 // Applied only to existed equipped item
9420 if( !pItem )
9421 return EQUIP_ERR_OK;
9423 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9425 ItemPrototype const *pProto = pItem->GetProto();
9426 if( !pProto )
9427 return EQUIP_ERR_ITEM_NOT_FOUND;
9429 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9430 // - combat
9431 // - in-progress arenas
9432 if( !pProto->CanChangeEquipStateInCombat() )
9434 if( isInCombat() )
9435 return EQUIP_ERR_NOT_IN_COMBAT;
9437 if(BattleGround* bg = GetBattleGround())
9438 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9439 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9442 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9443 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9445 return EQUIP_ERR_OK;
9448 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
9450 if( !pItem )
9451 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9453 uint32 count = pItem->GetCount();
9455 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
9456 ItemPrototype const *pProto = pItem->GetProto();
9457 if( !pProto )
9458 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9460 if( pItem->IsBindedNotWith(GetGUID()) )
9461 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9463 // check count of items (skip for auto move for same player from bank)
9464 uint8 res = CanTakeMoreSimilarItems(pItem);
9465 if(res != EQUIP_ERR_OK)
9466 return res;
9468 // in specific slot
9469 if( bag != NULL_BAG && slot != NULL_SLOT )
9471 if( pProto->InventoryType == INVTYPE_BAG )
9473 Bag *pBag = (Bag*)pItem;
9474 if( pBag )
9476 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9478 if( !HasBankBagSlot( slot ) )
9479 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
9480 if( uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK )
9481 return cantuse;
9483 else
9485 if( !pBag->IsEmpty() )
9486 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9490 else
9492 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9493 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
9496 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9497 if(res!=EQUIP_ERR_OK)
9498 return res;
9500 if(count==0)
9501 return EQUIP_ERR_OK;
9504 // not specific slot or have spece for partly store only in specific slot
9506 // in specific bag
9507 if( bag != NULL_BAG )
9509 if( pProto->InventoryType == INVTYPE_BAG )
9511 Bag *pBag = (Bag*)pItem;
9512 if( pBag && !pBag->IsEmpty() )
9513 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9516 // search stack in bag for merge to
9517 if( pProto->Stackable > 1 )
9519 if( bag == INVENTORY_SLOT_BAG_0 )
9521 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9522 if(res!=EQUIP_ERR_OK)
9523 return res;
9525 if(count==0)
9526 return EQUIP_ERR_OK;
9528 else
9530 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9531 if(res!=EQUIP_ERR_OK)
9532 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9534 if(res!=EQUIP_ERR_OK)
9535 return res;
9537 if(count==0)
9538 return EQUIP_ERR_OK;
9542 // search free slot in bag
9543 if( bag == INVENTORY_SLOT_BAG_0 )
9545 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9546 if(res!=EQUIP_ERR_OK)
9547 return res;
9549 if(count==0)
9550 return EQUIP_ERR_OK;
9552 else
9554 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9555 if(res!=EQUIP_ERR_OK)
9556 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9558 if(res!=EQUIP_ERR_OK)
9559 return res;
9561 if(count==0)
9562 return EQUIP_ERR_OK;
9566 // not specific bag or have spece for partly store only in specific bag
9568 // search stack for merge to
9569 if( pProto->Stackable > 1 )
9571 // in slots
9572 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9573 if(res!=EQUIP_ERR_OK)
9574 return res;
9576 if(count==0)
9577 return EQUIP_ERR_OK;
9579 // in special bags
9580 if( pProto->BagFamily )
9582 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9584 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9585 if(res!=EQUIP_ERR_OK)
9586 continue;
9588 if(count==0)
9589 return EQUIP_ERR_OK;
9593 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9595 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9596 if(res!=EQUIP_ERR_OK)
9597 continue;
9599 if(count==0)
9600 return EQUIP_ERR_OK;
9604 // search free place in special bag
9605 if( pProto->BagFamily )
9607 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9609 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9610 if(res!=EQUIP_ERR_OK)
9611 continue;
9613 if(count==0)
9614 return EQUIP_ERR_OK;
9618 // search free space
9619 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9620 if(res!=EQUIP_ERR_OK)
9621 return res;
9623 if(count==0)
9624 return EQUIP_ERR_OK;
9626 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9628 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9629 if(res!=EQUIP_ERR_OK)
9630 continue;
9632 if(count==0)
9633 return EQUIP_ERR_OK;
9635 return EQUIP_ERR_BANK_FULL;
9638 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
9640 if( pItem )
9642 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
9643 if( !isAlive() && not_loading )
9644 return EQUIP_ERR_YOU_ARE_DEAD;
9645 //if( isStunned() )
9646 // return EQUIP_ERR_YOU_ARE_STUNNED;
9647 ItemPrototype const *pProto = pItem->GetProto();
9648 if( pProto )
9650 if( pItem->IsBindedNotWith(GetGUID()) )
9651 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9652 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9653 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9654 if( pItem->GetSkill() != 0 )
9656 if( GetSkillValue( pItem->GetSkill() ) == 0 )
9657 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9659 if( pProto->RequiredSkill != 0 )
9661 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9662 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9663 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9664 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9666 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9667 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9668 if( pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank )
9669 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9670 if( getLevel() < pProto->RequiredLevel )
9671 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9672 return EQUIP_ERR_OK;
9675 return EQUIP_ERR_ITEM_NOT_FOUND;
9678 bool Player::CanUseItem( ItemPrototype const *pProto )
9680 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
9682 if( pProto )
9684 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9685 return false;
9686 if( pProto->RequiredSkill != 0 )
9688 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9689 return false;
9690 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9691 return false;
9693 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9694 return false;
9695 if( getLevel() < pProto->RequiredLevel )
9696 return false;
9697 return true;
9699 return false;
9702 uint8 Player::CanUseAmmo( uint32 item ) const
9704 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
9705 if( !isAlive() )
9706 return EQUIP_ERR_YOU_ARE_DEAD;
9707 //if( isStunned() )
9708 // return EQUIP_ERR_YOU_ARE_STUNNED;
9709 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
9710 if( pProto )
9712 if( pProto->InventoryType!= INVTYPE_AMMO )
9713 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
9714 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9715 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9716 if( pProto->RequiredSkill != 0 )
9718 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9719 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9720 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9721 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9723 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9724 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9725 /*if( GetReputation() < pProto->RequiredReputation )
9726 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9728 if( getLevel() < pProto->RequiredLevel )
9729 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9731 // Requires No Ammo
9732 if(GetDummyAura(46699))
9733 return EQUIP_ERR_BAG_FULL6;
9735 return EQUIP_ERR_OK;
9737 return EQUIP_ERR_ITEM_NOT_FOUND;
9740 void Player::SetAmmo( uint32 item )
9742 if(!item)
9743 return;
9745 // already set
9746 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
9747 return;
9749 // check ammo
9750 if(item)
9752 uint8 msg = CanUseAmmo( item );
9753 if( msg != EQUIP_ERR_OK )
9755 SendEquipError( msg, NULL, NULL );
9756 return;
9760 SetUInt32Value(PLAYER_AMMO_ID, item);
9762 _ApplyAmmoBonuses();
9765 void Player::RemoveAmmo()
9767 SetUInt32Value(PLAYER_AMMO_ID, 0);
9769 m_ammoDPS = 0.0f;
9771 if(CanModifyStats())
9772 UpdateDamagePhysical(RANGED_ATTACK);
9775 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
9776 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
9778 uint32 count = 0;
9779 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
9780 count += itr->count;
9782 Item *pItem = Item::CreateItem( item, count, this );
9783 if( pItem )
9785 ItemAddedQuestCheck( item, count );
9786 if(randomPropertyId)
9787 pItem->SetItemRandomProperties(randomPropertyId);
9788 pItem = StoreItem( dest, pItem, update );
9790 return pItem;
9793 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
9795 if( !pItem )
9796 return NULL;
9798 Item* lastItem = pItem;
9800 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
9802 uint16 pos = itr->pos;
9803 uint32 count = itr->count;
9805 ++itr;
9807 if(itr == dest.end())
9809 lastItem = _StoreItem(pos,pItem,count,false,update);
9810 break;
9813 lastItem = _StoreItem(pos,pItem,count,true,update);
9816 return lastItem;
9819 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
9820 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
9822 if( !pItem )
9823 return NULL;
9825 uint8 bag = pos >> 8;
9826 uint8 slot = pos & 255;
9828 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
9830 Item *pItem2 = GetItemByPos( bag, slot );
9832 if( !pItem2 )
9834 if(clone)
9835 pItem = pItem->CloneItem(count,this);
9836 else
9837 pItem->SetCount(count);
9839 if(!pItem)
9840 return NULL;
9842 if( pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
9843 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
9844 pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
9845 pItem->SetBinding( true );
9847 if( bag == INVENTORY_SLOT_BAG_0 )
9849 m_items[slot] = pItem;
9850 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
9851 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
9852 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
9854 pItem->SetSlot( slot );
9855 pItem->SetContainer( NULL );
9857 if( IsInWorld() && update )
9859 pItem->AddToWorld();
9860 pItem->SendUpdateToPlayer( this );
9863 pItem->SetState(ITEM_CHANGED, this);
9865 else
9867 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
9868 if( pBag )
9870 pBag->StoreItem( slot, pItem, update );
9871 if( IsInWorld() && update )
9873 pItem->AddToWorld();
9874 pItem->SendUpdateToPlayer( this );
9876 pItem->SetState(ITEM_CHANGED, this);
9877 pBag->SetState(ITEM_CHANGED, this);
9881 AddEnchantmentDurations(pItem);
9882 AddItemDurations(pItem);
9884 return pItem;
9886 else
9888 if( pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
9889 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
9890 pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
9891 pItem2->SetBinding( true );
9893 pItem2->SetCount( pItem2->GetCount() + count );
9894 if( IsInWorld() && update )
9895 pItem2->SendUpdateToPlayer( this );
9897 if(!clone)
9899 // delete item (it not in any slot currently)
9900 if( IsInWorld() && update )
9902 pItem->RemoveFromWorld();
9903 pItem->DestroyForPlayer( this );
9906 RemoveEnchantmentDurations(pItem);
9907 RemoveItemDurations(pItem);
9909 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
9910 pItem->SetState(ITEM_REMOVED, this);
9912 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
9913 AddEnchantmentDurations(pItem2);
9915 pItem2->SetState(ITEM_CHANGED, this);
9917 return pItem2;
9921 Item* Player::EquipNewItem( uint16 pos, uint32 item, uint32 count, bool update )
9923 Item *pItem = Item::CreateItem( item, count, this );
9924 if( pItem )
9926 ItemAddedQuestCheck( item, count );
9927 Item * retItem = EquipItem( pos, pItem, update );
9929 return retItem;
9931 return NULL;
9934 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
9936 if( pItem )
9938 AddEnchantmentDurations(pItem);
9939 AddItemDurations(pItem);
9941 uint8 bag = pos >> 8;
9942 uint8 slot = pos & 255;
9944 Item *pItem2 = GetItemByPos( bag, slot );
9946 if( !pItem2 )
9948 VisualizeItem( slot, pItem);
9950 if(isAlive())
9952 ItemPrototype const *pProto = pItem->GetProto();
9954 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
9955 if(pProto && pProto->ItemSet)
9956 AddItemsSetItem(this,pItem);
9958 _ApplyItemMods(pItem, slot, true);
9960 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
9962 m_weaponChangeTimer = DEFAULT_SWITCH_WEAPON;
9963 if (getClass() == CLASS_ROGUE)
9964 m_weaponChangeTimer = ROGUE_SWITCH_WEAPON;
9968 if( IsInWorld() && update )
9970 pItem->AddToWorld();
9971 pItem->SendUpdateToPlayer( this );
9974 ApplyEquipCooldown(pItem);
9976 if( slot == EQUIPMENT_SLOT_MAINHAND )
9977 UpdateExpertise(BASE_ATTACK);
9978 else if( slot == EQUIPMENT_SLOT_OFFHAND )
9979 UpdateExpertise(OFF_ATTACK);
9981 else
9983 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
9984 if( IsInWorld() && update )
9985 pItem2->SendUpdateToPlayer( this );
9987 // delete item (it not in any slot currently)
9988 //pItem->DeleteFromDB();
9989 if( IsInWorld() && update )
9991 pItem->RemoveFromWorld();
9992 pItem->DestroyForPlayer( this );
9995 RemoveEnchantmentDurations(pItem);
9996 RemoveItemDurations(pItem);
9998 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
9999 pItem->SetState(ITEM_REMOVED, this);
10000 pItem2->SetState(ITEM_CHANGED, this);
10002 ApplyEquipCooldown(pItem2);
10004 return pItem2;
10008 return pItem;
10011 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10013 if( pItem )
10015 AddEnchantmentDurations(pItem);
10016 AddItemDurations(pItem);
10018 uint8 slot = pos & 255;
10019 VisualizeItem( slot, pItem);
10021 if( IsInWorld() )
10023 pItem->AddToWorld();
10024 pItem->SendUpdateToPlayer( this );
10029 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10031 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10032 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10033 // entry // Size: 1
10034 // inspected enchantments // Size: 6
10035 // ? // Size: 5
10036 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10037 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10038 // // = 16
10040 if(pItem)
10042 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetUInt64Value(ITEM_FIELD_CREATOR));
10044 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10045 SetUInt32Value(VisibleBase + 0, pItem->GetEntry());
10047 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10048 SetUInt32Value(VisibleBase + 1 + i, pItem->GetEnchantmentId(EnchantmentSlot(i)));
10050 // Use SetInt16Value to prevent set high part to FFFF for negative value
10051 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES + (slot * MAX_VISIBLE_ITEM_OFFSET), 0, pItem->GetItemRandomPropertyId());
10052 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetItemSuffixFactor());
10054 else
10056 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10058 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10059 SetUInt32Value(VisibleBase + 0, 0);
10061 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10062 SetUInt32Value(VisibleBase + 1 + i, 0);
10064 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 0 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10065 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10069 void Player::VisualizeItem( uint8 slot, Item *pItem)
10071 if(!pItem)
10072 return;
10074 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10075 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10076 pItem->SetBinding( true );
10078 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10080 m_items[slot] = pItem;
10081 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10082 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10083 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10084 pItem->SetSlot( slot );
10085 pItem->SetContainer( NULL );
10087 if( slot < EQUIPMENT_SLOT_END )
10088 SetVisibleItemSlot(slot,pItem);
10090 pItem->SetState(ITEM_CHANGED, this);
10093 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10095 // note: removeitem does not actually change the item
10096 // it only takes the item out of storage temporarily
10097 // note2: if removeitem is to be used for delinking
10098 // the item must be removed from the player's updatequeue
10100 Item *pItem = GetItemByPos( bag, slot );
10101 if( pItem )
10103 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10105 RemoveEnchantmentDurations(pItem);
10106 RemoveItemDurations(pItem);
10108 if( bag == INVENTORY_SLOT_BAG_0 )
10110 if ( slot < INVENTORY_SLOT_BAG_END )
10112 ItemPrototype const *pProto = pItem->GetProto();
10113 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10115 if(pProto && pProto->ItemSet)
10116 RemoveItemsSetItem(this,pProto);
10118 _ApplyItemMods(pItem, slot, false);
10120 // remove item dependent auras and casts (only weapon and armor slots)
10121 if(slot < EQUIPMENT_SLOT_END)
10122 RemoveItemDependentAurasAndCasts(pItem);
10124 // remove held enchantments
10125 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10127 if (pItem->GetItemSuffixFactor())
10129 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10130 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10132 else
10134 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10135 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10140 m_items[slot] = NULL;
10141 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10143 if ( slot < EQUIPMENT_SLOT_END )
10144 SetVisibleItemSlot(slot,NULL);
10146 else
10148 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10149 if( pBag )
10150 pBag->RemoveItem(slot, update);
10152 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10153 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10154 pItem->SetSlot( NULL_SLOT );
10155 if( IsInWorld() && update )
10156 pItem->SendUpdateToPlayer( this );
10158 if( slot == EQUIPMENT_SLOT_MAINHAND )
10159 UpdateExpertise(BASE_ATTACK);
10160 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10161 UpdateExpertise(OFF_ATTACK);
10165 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10166 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10168 if(Item* it = GetItemByPos(bag,slot))
10170 ItemRemovedQuestCheck(it->GetEntry(),it->GetCount());
10171 RemoveItem( bag,slot,update);
10172 it->RemoveFromUpdateQueueOf(this);
10173 if(it->IsInWorld())
10175 it->RemoveFromWorld();
10176 it->DestroyForPlayer( this );
10181 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10182 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10184 // update quest counters
10185 ItemAddedQuestCheck(pItem->GetEntry(),pItem->GetCount());
10187 // store item
10188 Item* pLastItem = StoreItem( dest, pItem, update);
10190 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10191 if(pLastItem==pItem)
10193 // update owner for last item (this can be original item with wrong owner
10194 if(pLastItem->GetOwnerGUID() != GetGUID())
10195 pLastItem->SetOwnerGUID(GetGUID());
10197 // if this original item then it need create record in inventory
10198 // in case trade we laready have item in other player inventory
10199 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10203 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10205 Item *pItem = GetItemByPos( bag, slot );
10206 if( pItem )
10208 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10210 // start from destroy contained items (only equipped bag can have its)
10211 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10213 for (int i = 0; i < MAX_BAG_SIZE; i++)
10214 DestroyItem(slot,i,update);
10217 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10218 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10220 ItemPrototype const *pProto = pItem->GetProto();
10222 RemoveEnchantmentDurations(pItem);
10223 RemoveItemDurations(pItem);
10225 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10227 if( bag == INVENTORY_SLOT_BAG_0 )
10230 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10232 // equipment and equipped bags can have applied bonuses
10233 if ( slot < INVENTORY_SLOT_BAG_END )
10235 ItemPrototype const *pProto = pItem->GetProto();
10237 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10238 if(pProto && pProto->ItemSet)
10239 RemoveItemsSetItem(this,pProto);
10241 _ApplyItemMods(pItem, slot, false);
10244 if ( slot < EQUIPMENT_SLOT_END )
10246 // remove item dependent auras and casts (only weapon and armor slots)
10247 RemoveItemDependentAurasAndCasts(pItem);
10249 // equipment visual show
10250 SetVisibleItemSlot(slot,NULL);
10253 m_items[slot] = NULL;
10255 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10256 pBag->RemoveItem(slot, update);
10258 if( IsInWorld() && update )
10260 pItem->RemoveFromWorld();
10261 pItem->DestroyForPlayer(this);
10264 //pItem->SetOwnerGUID(0);
10265 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10266 pItem->SetSlot( NULL_SLOT );
10267 pItem->SetState(ITEM_REMOVED, this);
10271 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10273 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10274 Item *pItem;
10275 ItemPrototype const *pProto;
10276 uint32 remcount = 0;
10278 // in inventory
10279 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10281 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10282 if( pItem && pItem->GetEntry() == item )
10284 if( pItem->GetCount() + remcount <= count )
10286 // all items in inventory can unequipped
10287 remcount += pItem->GetCount();
10288 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10290 if(remcount >=count)
10291 return;
10293 else
10295 pProto = pItem->GetProto();
10296 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10297 pItem->SetCount( pItem->GetCount() - count + remcount );
10298 if( IsInWorld() & update )
10299 pItem->SendUpdateToPlayer( this );
10300 pItem->SetState(ITEM_CHANGED, this);
10301 return;
10305 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
10307 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10308 if( pItem && pItem->GetEntry() == item )
10310 if( pItem->GetCount() + remcount <= count )
10312 // all keys can be unequipped
10313 remcount += pItem->GetCount();
10314 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10316 if(remcount >=count)
10317 return;
10319 else
10321 pProto = pItem->GetProto();
10322 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10323 pItem->SetCount( pItem->GetCount() - count + remcount );
10324 if( IsInWorld() & update )
10325 pItem->SendUpdateToPlayer( this );
10326 pItem->SetState(ITEM_CHANGED, this);
10327 return;
10332 // in inventory bags
10333 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10335 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10337 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10339 pItem = pBag->GetItemByPos(j);
10340 if( pItem && pItem->GetEntry() == item )
10342 // all items in bags can be unequipped
10343 if( pItem->GetCount() + remcount <= count )
10345 remcount += pItem->GetCount();
10346 DestroyItem( i, j, update );
10348 if(remcount >=count)
10349 return;
10351 else
10353 pProto = pItem->GetProto();
10354 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10355 pItem->SetCount( pItem->GetCount() - count + remcount );
10356 if( IsInWorld() && update )
10357 pItem->SendUpdateToPlayer( this );
10358 pItem->SetState(ITEM_CHANGED, this);
10359 return;
10366 // in equipment and bag list
10367 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10369 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10370 if( pItem && pItem->GetEntry() == item )
10372 if( pItem->GetCount() + remcount <= count )
10374 if(!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i,false) == EQUIP_ERR_OK )
10376 remcount += pItem->GetCount();
10377 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10379 if(remcount >=count)
10380 return;
10383 else
10385 pProto = pItem->GetProto();
10386 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10387 pItem->SetCount( pItem->GetCount() - count + remcount );
10388 if( IsInWorld() & update )
10389 pItem->SendUpdateToPlayer( this );
10390 pItem->SetState(ITEM_CHANGED, this);
10391 return;
10397 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10399 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10401 // in inventory
10402 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10404 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10405 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10406 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10408 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
10410 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10411 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10412 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10415 // in inventory bags
10416 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10418 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10419 if( pBag )
10421 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10423 Item* pItem = pBag->GetItemByPos(j);
10424 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10425 DestroyItem( i, j, update);
10430 // in equipment and bag list
10431 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10433 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10434 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10435 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10439 void Player::DestroyConjuredItems( bool update )
10441 // used when entering arena
10442 // distroys all conjured items
10443 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
10445 // in inventory
10446 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10448 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10449 if( pItem && pItem->GetProto() &&
10450 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10451 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10452 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10455 // in inventory bags
10456 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10458 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10459 if( pBag )
10461 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10463 Item* pItem = pBag->GetItemByPos(j);
10464 if( pItem && pItem->GetProto() &&
10465 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10466 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10467 DestroyItem( i, j, update);
10472 // in equipment and bag list
10473 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10475 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10476 if( pItem && pItem->GetProto() &&
10477 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10478 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10479 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10483 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
10485 if(!pItem)
10486 return;
10488 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
10490 if( pItem->GetCount() <= count )
10492 count-= pItem->GetCount();
10494 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
10496 else
10498 ItemRemovedQuestCheck( pItem->GetEntry(), count);
10499 pItem->SetCount( pItem->GetCount() - count );
10500 count = 0;
10501 if( IsInWorld() & update )
10502 pItem->SendUpdateToPlayer( this );
10503 pItem->SetState(ITEM_CHANGED, this);
10507 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
10509 uint8 srcbag = src >> 8;
10510 uint8 srcslot = src & 255;
10512 uint8 dstbag = dst >> 8;
10513 uint8 dstslot = dst & 255;
10515 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10516 if( !pSrcItem )
10518 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10519 return;
10522 // not let split all items (can be only at cheating)
10523 if(pSrcItem->GetCount() == count)
10525 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10526 return;
10529 // not let split more existed items (can be only at cheating)
10530 if(pSrcItem->GetCount() < count)
10532 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
10533 return;
10536 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
10538 //best error message found for attempting to split while looting
10539 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10540 return;
10543 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
10544 Item *pNewItem = pSrcItem->CloneItem( count, this );
10545 if( !pNewItem )
10547 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10548 return;
10551 if( IsInventoryPos( dst ) )
10553 // change item amount before check (for unique max count check)
10554 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10556 ItemPosCountVec dest;
10557 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
10558 if( msg != EQUIP_ERR_OK )
10560 delete pNewItem;
10561 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10562 SendEquipError( msg, pSrcItem, NULL );
10563 return;
10566 if( IsInWorld() )
10567 pSrcItem->SendUpdateToPlayer( this );
10568 pSrcItem->SetState(ITEM_CHANGED, this);
10569 StoreItem( dest, pNewItem, true);
10571 else if( IsBankPos ( dst ) )
10573 // change item amount before check (for unique max count check)
10574 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10576 ItemPosCountVec dest;
10577 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
10578 if( msg != EQUIP_ERR_OK )
10580 delete pNewItem;
10581 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10582 SendEquipError( msg, pSrcItem, NULL );
10583 return;
10586 if( IsInWorld() )
10587 pSrcItem->SendUpdateToPlayer( this );
10588 pSrcItem->SetState(ITEM_CHANGED, this);
10589 BankItem( dest, pNewItem, true);
10591 else if( IsEquipmentPos ( dst ) )
10593 // change item amount before check (for unique max count check), provide space for splitted items
10594 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10596 uint16 dest;
10597 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
10598 if( msg != EQUIP_ERR_OK )
10600 delete pNewItem;
10601 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10602 SendEquipError( msg, pSrcItem, NULL );
10603 return;
10606 if( IsInWorld() )
10607 pSrcItem->SendUpdateToPlayer( this );
10608 pSrcItem->SetState(ITEM_CHANGED, this);
10609 EquipItem( dest, pNewItem, true);
10610 AutoUnequipOffhandIfNeed();
10614 void Player::SwapItem( uint16 src, uint16 dst )
10616 uint8 srcbag = src >> 8;
10617 uint8 srcslot = src & 255;
10619 uint8 dstbag = dst >> 8;
10620 uint8 dstslot = dst & 255;
10622 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10623 Item *pDstItem = GetItemByPos( dstbag, dstslot );
10625 if( !pSrcItem )
10626 return;
10628 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
10630 if(!isAlive() )
10632 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
10633 return;
10636 if(pSrcItem->m_lootGenerated) // prevent swap looting item
10638 //best error message found for attempting to swap while looting
10639 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
10640 return;
10643 // check unequip potability for equipped items and bank bags
10644 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
10646 // bags can be swapped with empty bag slots
10647 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ));
10648 if(msg != EQUIP_ERR_OK)
10650 SendEquipError( msg, pSrcItem, pDstItem );
10651 return;
10655 // prevent put equipped/bank bag in self
10656 if( IsBagPos ( src ) && srcslot == dstbag)
10658 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
10659 return;
10662 if( !pDstItem )
10664 if( IsInventoryPos( dst ) )
10666 ItemPosCountVec dest;
10667 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
10668 if( msg != EQUIP_ERR_OK )
10670 SendEquipError( msg, pSrcItem, NULL );
10671 return;
10674 RemoveItem(srcbag, srcslot, true);
10675 StoreItem( dest, pSrcItem, true);
10677 else if( IsBankPos ( dst ) )
10679 ItemPosCountVec dest;
10680 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
10681 if( msg != EQUIP_ERR_OK )
10683 SendEquipError( msg, pSrcItem, NULL );
10684 return;
10687 RemoveItem(srcbag, srcslot, true);
10688 BankItem( dest, pSrcItem, true);
10690 else if( IsEquipmentPos ( dst ) )
10692 uint16 dest;
10693 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
10694 if( msg != EQUIP_ERR_OK )
10696 SendEquipError( msg, pSrcItem, NULL );
10697 return;
10700 RemoveItem(srcbag, srcslot, true);
10701 EquipItem( dest, pSrcItem, true);
10702 AutoUnequipOffhandIfNeed();
10705 else // if (!pDstItem)
10707 if(pDstItem->m_lootGenerated) // prevent swap looting item
10709 //best error message found for attempting to swap while looting
10710 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
10711 return;
10714 // check unequip potability for equipped items and bank bags
10715 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
10717 // bags can be swapped with empty bag slots
10718 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) );
10719 if(msg != EQUIP_ERR_OK)
10721 SendEquipError( msg, pSrcItem, pDstItem );
10722 return;
10726 // attempt merge to / fill target item
10728 uint8 msg;
10729 ItemPosCountVec sDest;
10730 uint16 eDest;
10731 if( IsInventoryPos( dst ) )
10732 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
10733 else if( IsBankPos ( dst ) )
10734 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
10735 else if( IsEquipmentPos ( dst ) )
10736 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
10737 else
10738 return;
10740 // can be merge/fill
10741 if(msg == EQUIP_ERR_OK)
10743 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->Stackable )
10745 RemoveItem(srcbag, srcslot, true);
10747 if( IsInventoryPos( dst ) )
10748 StoreItem( sDest, pSrcItem, true);
10749 else if( IsBankPos ( dst ) )
10750 BankItem( sDest, pSrcItem, true);
10751 else if( IsEquipmentPos ( dst ) )
10753 EquipItem( eDest, pSrcItem, true);
10754 AutoUnequipOffhandIfNeed();
10757 else
10759 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->Stackable );
10760 pDstItem->SetCount( pSrcItem->GetProto()->Stackable );
10761 pSrcItem->SetState(ITEM_CHANGED, this);
10762 pDstItem->SetState(ITEM_CHANGED, this);
10763 if( IsInWorld() )
10765 pSrcItem->SendUpdateToPlayer( this );
10766 pDstItem->SendUpdateToPlayer( this );
10769 return;
10773 // impossible merge/fill, do real swap
10774 uint8 msg;
10776 // check src->dest move possibility
10777 ItemPosCountVec sDest;
10778 uint16 eDest;
10779 if( IsInventoryPos( dst ) )
10780 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
10781 else if( IsBankPos( dst ) )
10782 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
10783 else if( IsEquipmentPos( dst ) )
10785 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
10786 if( msg == EQUIP_ERR_OK )
10787 msg = CanUnequipItem( eDest, true );
10790 if( msg != EQUIP_ERR_OK )
10792 SendEquipError( msg, pSrcItem, pDstItem );
10793 return;
10796 // check dest->src move possibility
10797 ItemPosCountVec sDest2;
10798 uint16 eDest2;
10799 if( IsInventoryPos( src ) )
10800 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
10801 else if( IsBankPos( src ) )
10802 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
10803 else if( IsEquipmentPos( src ) )
10805 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
10806 if( msg == EQUIP_ERR_OK )
10807 msg = CanUnequipItem( eDest2, true);
10810 if( msg != EQUIP_ERR_OK )
10812 SendEquipError( msg, pDstItem, pSrcItem );
10813 return;
10816 // now do moves, remove...
10817 RemoveItem(dstbag, dstslot, false);
10818 RemoveItem(srcbag, srcslot, false);
10820 // add to dest
10821 if( IsInventoryPos( dst ) )
10822 StoreItem(sDest, pSrcItem, true);
10823 else if( IsBankPos( dst ) )
10824 BankItem(sDest, pSrcItem, true);
10825 else if( IsEquipmentPos( dst ) )
10826 EquipItem(eDest, pSrcItem, true);
10828 // add to src
10829 if( IsInventoryPos( src ) )
10830 StoreItem(sDest2, pDstItem, true);
10831 else if( IsBankPos( src ) )
10832 BankItem(sDest2, pDstItem, true);
10833 else if( IsEquipmentPos( src ) )
10834 EquipItem(eDest2, pDstItem, true);
10836 AutoUnequipOffhandIfNeed();
10840 void Player::AddItemToBuyBackSlot( Item *pItem )
10842 if( pItem )
10844 uint32 slot = m_currentBuybackSlot;
10845 // if current back slot non-empty search oldest or free
10846 if(m_items[slot])
10848 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
10849 uint32 oldest_slot = BUYBACK_SLOT_START;
10851 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
10853 // found empty
10854 if(!m_items[i])
10856 slot = i;
10857 break;
10860 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
10862 if(oldest_time > i_time)
10864 oldest_time = i_time;
10865 oldest_slot = i;
10869 // find oldest
10870 slot = oldest_slot;
10873 RemoveItemFromBuyBackSlot( slot, true );
10874 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
10876 m_items[slot] = pItem;
10877 time_t base = time(NULL);
10878 uint32 etime = uint32(base - m_logintime + (30 * 3600));
10879 uint32 eslot = slot - BUYBACK_SLOT_START;
10881 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, pItem->GetGUID() );
10882 ItemPrototype const *pProto = pItem->GetProto();
10883 if( pProto )
10884 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
10885 else
10886 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
10887 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
10889 // move to next (for non filled list is move most optimized choice)
10890 if(m_currentBuybackSlot < BUYBACK_SLOT_END-1)
10891 ++m_currentBuybackSlot;
10895 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
10897 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
10898 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
10899 return m_items[slot];
10900 return NULL;
10903 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
10905 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
10906 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
10908 Item *pItem = m_items[slot];
10909 if( pItem )
10911 pItem->RemoveFromWorld();
10912 if(del) pItem->SetState(ITEM_REMOVED, this);
10915 m_items[slot] = NULL;
10917 uint32 eslot = slot - BUYBACK_SLOT_START;
10918 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, 0 );
10919 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
10920 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
10922 // if current backslot is filled set to now free slot
10923 if(m_items[m_currentBuybackSlot])
10924 m_currentBuybackSlot = slot;
10928 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
10930 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg);
10931 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
10932 data << uint8(msg);
10934 if(msg)
10936 data << uint64(pItem ? pItem->GetGUID() : 0);
10937 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
10938 data << uint8(0); // not 0 there...
10940 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
10942 uint32 level = 0;
10944 if(pItem)
10945 if(ItemPrototype const* proto = pItem->GetProto())
10946 level = proto->RequiredLevel;
10948 data << uint32(level); // new 2.4.0
10951 GetSession()->SendPacket(&data);
10954 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
10956 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
10957 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
10958 data << uint64(pCreature ? pCreature->GetGUID() : 0);
10959 data << uint32(item);
10960 if( param > 0 )
10961 data << uint32(param);
10962 data << uint8(msg);
10963 GetSession()->SendPacket(&data);
10966 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
10968 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
10969 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
10970 data << uint64(pCreature ? pCreature->GetGUID() : 0);
10971 data << uint64(guid);
10972 if( param > 0 )
10973 data << uint32(param);
10974 data << uint8(msg);
10975 GetSession()->SendPacket(&data);
10978 void Player::ClearTrade()
10980 tradeGold = 0;
10981 acceptTrade = false;
10982 for(int i = 0; i < TRADE_SLOT_COUNT; i++)
10983 tradeItems[i] = NULL_SLOT;
10986 void Player::TradeCancel(bool sendback)
10988 if(pTrader)
10990 // send yellow "Trade cancelled" message to both traders
10991 WorldSession* ws;
10992 ws = GetSession();
10993 if(sendback)
10994 ws->SendCancelTrade();
10995 ws = pTrader->GetSession();
10996 if(!ws->PlayerLogout())
10997 ws->SendCancelTrade();
10999 // cleanup
11000 ClearTrade();
11001 pTrader->ClearTrade();
11002 // prevent loss of reference
11003 pTrader->pTrader = NULL;
11004 pTrader = NULL;
11008 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11010 if(m_itemDuration.empty())
11011 return;
11013 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time,realtimeonly);
11015 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); )
11017 Item* item = *itr;
11018 ++itr; // current element can be erased in UpdateDuration
11020 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11021 item->UpdateDuration(this,time);
11025 void Player::UpdateEnchantTime(uint32 time)
11027 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11029 assert(itr->item);
11030 next=itr;
11031 if(!itr->item->GetEnchantmentId(itr->slot))
11033 next = m_enchantDuration.erase(itr);
11035 else if(itr->leftduration <= time)
11037 ApplyEnchantment(itr->item,itr->slot,false,false);
11038 itr->item->ClearEnchantment(itr->slot);
11039 next = m_enchantDuration.erase(itr);
11041 else if(itr->leftduration > time)
11043 itr->leftduration -= time;
11044 ++next;
11049 void Player::AddEnchantmentDurations(Item *item)
11051 for(int x=0;x<MAX_ENCHANTMENT_SLOT;++x)
11053 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11054 continue;
11056 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11057 if( duration > 0 )
11058 AddEnchantmentDuration(item,EnchantmentSlot(x),duration);
11062 void Player::RemoveEnchantmentDurations(Item *item)
11064 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();)
11066 if(itr->item == item)
11068 // save duration in item
11069 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot),itr->leftduration);
11070 itr = m_enchantDuration.erase(itr);
11072 else
11073 ++itr;
11077 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11079 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11080 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11082 next = itr;
11083 if(itr->slot==slot)
11085 if(itr->item && itr->item->GetEnchantmentId(slot))
11087 // remove from stats
11088 ApplyEnchantment(itr->item,slot,false,false);
11089 // remove visual
11090 itr->item->ClearEnchantment(slot);
11092 // remove from update list
11093 next = m_enchantDuration.erase(itr);
11095 else
11096 ++next;
11099 // remove enchants from inventory items
11100 // NOTE: no need to remove these from stats, since these aren't equipped
11101 // in inventory
11102 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
11104 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11105 if( pItem && pItem->GetEnchantmentId(slot) )
11106 pItem->ClearEnchantment(slot);
11109 // in inventory bags
11110 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11112 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11113 if( pBag )
11115 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
11117 Item* pItem = pBag->GetItemByPos(j);
11118 if( pItem && pItem->GetEnchantmentId(slot) )
11119 pItem->ClearEnchantment(slot);
11125 // duration == 0 will remove item enchant
11126 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11128 if(!item)
11129 return;
11131 if(slot >= MAX_ENCHANTMENT_SLOT)
11132 return;
11134 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11136 if(itr->item == item && itr->slot == slot)
11138 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
11139 m_enchantDuration.erase(itr);
11140 break;
11143 if(item && duration > 0 )
11145 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(),slot,uint32(duration/1000));
11146 m_enchantDuration.push_back(EnchantDuration(item,slot,duration));
11150 void Player::ApplyEnchantment(Item *item,bool apply)
11152 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11153 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11156 void Player::ApplyEnchantment(Item *item,EnchantmentSlot slot,bool apply, bool apply_dur, bool ignore_condition)
11158 if(!item)
11159 return;
11161 if(!item->IsEquipped())
11162 return;
11164 if(slot >= MAX_ENCHANTMENT_SLOT)
11165 return;
11167 uint32 enchant_id = item->GetEnchantmentId(slot);
11168 if(!enchant_id)
11169 return;
11171 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11172 if(!pEnchant)
11173 return;
11175 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11176 return;
11178 for (int s=0; s<3; s++)
11180 uint32 enchant_display_type = pEnchant->type[s];
11181 uint32 enchant_amount = pEnchant->amount[s];
11182 uint32 enchant_spell_id = pEnchant->spellid[s];
11184 switch(enchant_display_type)
11186 case ITEM_ENCHANTMENT_TYPE_NONE:
11187 break;
11188 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11189 // processed in Player::CastItemCombatSpell
11190 break;
11191 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11192 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11193 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11194 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11195 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11196 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11197 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11198 break;
11199 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11200 if(enchant_spell_id)
11202 if(apply)
11204 int32 basepoints = int32(enchant_amount);
11205 // Random Property Exist - try found basepoints for spell (basepoints depencs from item suffix factor)
11206 if (item->GetItemRandomPropertyId() !=0 && !enchant_amount)
11208 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11209 if (item_rand)
11211 // Search enchant_amount
11212 for (int k=0; k<3; k++)
11214 if(item_rand->enchant_id[k] == enchant_id)
11216 basepoints = int32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11217 break;
11222 // Cast custom spell vs all equal basepoints getted from enchant_amount
11223 if (basepoints)
11224 CastCustomSpell(this,enchant_spell_id,&basepoints,&basepoints,&basepoints,true,item);
11225 else
11226 CastSpell(this,enchant_spell_id,true,item);
11228 else
11229 RemoveAurasDueToItemSpell(item,enchant_spell_id);
11231 break;
11232 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11233 if (!enchant_amount)
11235 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11236 if(item_rand)
11238 for (int k=0; k<3; k++)
11240 if(item_rand->enchant_id[k] == enchant_id)
11242 enchant_amount = uint32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11243 break;
11249 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11250 break;
11251 case ITEM_ENCHANTMENT_TYPE_STAT:
11253 if (!enchant_amount)
11255 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11256 if(item_rand_suffix)
11258 for (int k=0; k<3; k++)
11260 if(item_rand_suffix->enchant_id[k] == enchant_id)
11262 enchant_amount = uint32((item_rand_suffix->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11263 break;
11269 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11270 switch (enchant_spell_id)
11272 case ITEM_MOD_AGILITY:
11273 sLog.outDebug("+ %u AGILITY",enchant_amount);
11274 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11275 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11276 break;
11277 case ITEM_MOD_STRENGTH:
11278 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11279 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11280 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11281 break;
11282 case ITEM_MOD_INTELLECT:
11283 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11284 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11285 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11286 break;
11287 case ITEM_MOD_SPIRIT:
11288 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11289 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11290 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11291 break;
11292 case ITEM_MOD_STAMINA:
11293 sLog.outDebug("+ %u STAMINA",enchant_amount);
11294 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11295 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11296 break;
11297 case ITEM_MOD_DEFENSE_SKILL_RATING:
11298 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11299 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11300 break;
11301 case ITEM_MOD_DODGE_RATING:
11302 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11303 sLog.outDebug("+ %u DODGE", enchant_amount);
11304 break;
11305 case ITEM_MOD_PARRY_RATING:
11306 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11307 sLog.outDebug("+ %u PARRY", enchant_amount);
11308 break;
11309 case ITEM_MOD_BLOCK_RATING:
11310 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11311 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11312 break;
11313 case ITEM_MOD_HIT_MELEE_RATING:
11314 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11315 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11316 break;
11317 case ITEM_MOD_HIT_RANGED_RATING:
11318 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11319 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11320 break;
11321 case ITEM_MOD_HIT_SPELL_RATING:
11322 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11323 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11324 break;
11325 case ITEM_MOD_CRIT_MELEE_RATING:
11326 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11327 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11328 break;
11329 case ITEM_MOD_CRIT_RANGED_RATING:
11330 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11331 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11332 break;
11333 case ITEM_MOD_CRIT_SPELL_RATING:
11334 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11335 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11336 break;
11337 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11338 // in Enchantments
11339 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11340 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11341 // break;
11342 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11343 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11344 // break;
11345 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11346 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11347 // break;
11348 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11349 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11350 // break;
11351 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11352 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11353 // break;
11354 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11355 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11356 // break;
11357 // case ITEM_MOD_HASTE_MELEE_RATING:
11358 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11359 // break;
11360 // case ITEM_MOD_HASTE_RANGED_RATING:
11361 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11362 // break;
11363 case ITEM_MOD_HASTE_SPELL_RATING:
11364 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11365 break;
11366 case ITEM_MOD_HIT_RATING:
11367 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11368 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11369 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11370 sLog.outDebug("+ %u HIT", enchant_amount);
11371 break;
11372 case ITEM_MOD_CRIT_RATING:
11373 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11374 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11375 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11376 sLog.outDebug("+ %u CRITICAL", enchant_amount);
11377 break;
11378 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11379 // case ITEM_MOD_HIT_TAKEN_RATING:
11380 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11381 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11382 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11383 // break;
11384 // case ITEM_MOD_CRIT_TAKEN_RATING:
11385 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11386 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11387 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11388 // break;
11389 case ITEM_MOD_RESILIENCE_RATING:
11390 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11391 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11392 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11393 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
11394 break;
11395 case ITEM_MOD_HASTE_RATING:
11396 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11397 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11398 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11399 sLog.outDebug("+ %u HASTE", enchant_amount);
11400 break;
11401 case ITEM_MOD_EXPERTISE_RATING:
11402 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
11403 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
11404 break;
11405 default:
11406 break;
11408 break;
11410 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
11412 if(getClass() == CLASS_SHAMAN)
11414 float addValue = 0.0f;
11415 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11417 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11418 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
11420 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
11422 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11423 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
11426 break;
11428 default:
11429 sLog.outError("Unknown item enchantment display type: %d",enchant_display_type);
11430 break;
11431 } /*switch(enchant_display_type)*/
11432 } /*for*/
11434 // visualize enchantment at player and equipped items
11435 if(slot < MAX_INSPECTED_ENCHANTMENT_SLOT)
11437 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (item->GetSlot() * MAX_VISIBLE_ITEM_OFFSET);
11438 SetUInt32Value(VisibleBase + 1 + slot, apply? item->GetEnchantmentId(slot) : 0);
11441 if(apply_dur)
11443 if(apply)
11445 // set duration
11446 uint32 duration = item->GetEnchantmentDuration(slot);
11447 if(duration > 0)
11448 AddEnchantmentDuration(item,slot,duration);
11450 else
11452 // duration == 0 will remove EnchantDuration
11453 AddEnchantmentDuration(item,slot,0);
11458 void Player::SendEnchantmentDurations()
11460 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11462 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(),itr->slot,uint32(itr->leftduration)/1000);
11466 void Player::SendItemDurations()
11468 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end();++itr)
11470 (*itr)->SendTimeUpdate(this);
11474 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
11476 if(!item) // prevent crash
11477 return;
11479 // last check 2.0.10
11480 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
11481 data << GetGUID(); // player GUID
11482 data << uint32(received); // 0=looted, 1=from npc
11483 data << uint32(created); // 0=received, 1=created
11484 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
11485 data << (uint8)item->GetBagSlot(); // bagslot
11486 // item slot, but when added to stack: 0xFFFFFFFF
11487 data << (uint32) ((item->GetCount()==count) ? item->GetSlot() : -1);
11488 data << uint32(item->GetEntry()); // item id
11489 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
11490 data << uint32(item->GetItemRandomPropertyId()); // random item property id
11491 data << uint32(count); // count of items
11492 data << GetItemCount(item->GetEntry()); // count of items in inventory
11494 if (broadcast && GetGroup())
11495 GetGroup()->BroadcastPacket(&data);
11496 else
11497 GetSession()->SendPacket(&data);
11500 /*********************************************************/
11501 /*** QUEST SYSTEM ***/
11502 /*********************************************************/
11504 void Player::PrepareQuestMenu( uint64 guid )
11506 Object *pObject;
11507 QuestRelations* pObjectQR;
11508 QuestRelations* pObjectQIR;
11509 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11510 if( pCreature )
11512 pObject = (Object*)pCreature;
11513 pObjectQR = &objmgr.mCreatureQuestRelations;
11514 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11516 else
11518 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
11519 if( pGameObject )
11521 pObject = (Object*)pGameObject;
11522 pObjectQR = &objmgr.mGOQuestRelations;
11523 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11525 else
11526 return;
11529 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
11530 qm.ClearMenu();
11532 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
11534 uint32 quest_id = i->second;
11535 QuestStatus status = GetQuestStatus( quest_id );
11536 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
11537 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11538 else if ( status == QUEST_STATUS_INCOMPLETE )
11539 qm.AddMenuItem(quest_id, DIALOG_STATUS_INCOMPLETE);
11540 else if (status == QUEST_STATUS_AVAILABLE )
11541 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
11544 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
11546 uint32 quest_id = i->second;
11547 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11548 if(!pQuest) continue;
11550 QuestStatus status = GetQuestStatus( quest_id );
11552 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
11553 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11554 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
11555 qm.AddMenuItem(quest_id, DIALOG_STATUS_AVAILABLE);
11559 void Player::SendPreparedQuest( uint64 guid )
11561 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
11562 if( questMenu.Empty() )
11563 return;
11565 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
11567 uint32 status = qmi0.m_qIcon;
11569 // single element case
11570 if ( questMenu.MenuItemCount() == 1 )
11572 // Auto open -- maybe also should verify there is no greeting
11573 uint32 quest_id = qmi0.m_qId;
11574 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11575 if ( pQuest )
11577 if( status == DIALOG_STATUS_REWARD_REP && !GetQuestRewardStatus( quest_id ) )
11578 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest,false), true );
11579 else if( status == DIALOG_STATUS_INCOMPLETE )
11580 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, false, true );
11581 // Send completable on repeatable quest if player don't have quest
11582 else if( pQuest->IsRepeatable() )
11583 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
11584 else
11585 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
11588 // multiply entries
11589 else
11591 QEmote qe;
11592 qe._Delay = 0;
11593 qe._Emote = 0;
11594 std::string title = "";
11595 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11596 if( pCreature )
11598 uint32 textid = pCreature->GetNpcTextId();
11599 GossipText * gossiptext = objmgr.GetGossipText(textid);
11600 if( !gossiptext )
11602 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
11603 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
11604 title = "";
11606 else
11608 qe = gossiptext->Options[0].Emotes[0];
11610 if(!gossiptext->Options[0].Text_0.empty())
11612 title = gossiptext->Options[0].Text_0;
11614 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
11615 if (loc_idx >= 0)
11617 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
11618 if (nl)
11620 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
11621 title = nl->Text_0[0][loc_idx];
11625 else
11627 title = gossiptext->Options[0].Text_1;
11629 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
11630 if (loc_idx >= 0)
11632 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
11633 if (nl)
11635 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
11636 title = nl->Text_1[0][loc_idx];
11642 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
11646 bool Player::IsActiveQuest( uint32 quest_id ) const
11648 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
11650 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
11653 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
11655 Object *pObject;
11656 QuestRelations* pObjectQR;
11657 QuestRelations* pObjectQIR;
11659 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11660 if( pCreature )
11662 pObject = (Object*)pCreature;
11663 pObjectQR = &objmgr.mCreatureQuestRelations;
11664 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11666 else
11668 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
11669 if( pGameObject )
11671 pObject = (Object*)pGameObject;
11672 pObjectQR = &objmgr.mGOQuestRelations;
11673 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11675 else
11676 return NULL;
11679 uint32 nextQuestID = pQuest->GetNextQuestInChain();
11680 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
11682 if (itr->second == nextQuestID)
11683 return objmgr.GetQuestTemplate(nextQuestID);
11686 return NULL;
11689 bool Player::CanSeeStartQuest( Quest const *pQuest )
11691 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
11692 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
11693 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
11694 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
11696 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
11699 return false;
11702 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
11704 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
11705 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
11706 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
11707 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
11708 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
11709 && SatisfyQuestDay( pQuest, msg );
11712 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
11714 if( !SatisfyQuestLog( msg ) )
11715 return false;
11717 uint32 srcitem = pQuest->GetSrcItemId();
11718 if( srcitem > 0 )
11720 uint32 count = pQuest->GetSrcItemCount();
11721 ItemPosCountVec dest;
11722 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
11724 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
11725 if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
11726 return true;
11727 else if( msg != EQUIP_ERR_OK )
11729 SendEquipError( msg, NULL, NULL );
11730 return false;
11733 return true;
11736 bool Player::CanCompleteQuest( uint32 quest_id )
11738 if( quest_id )
11740 QuestStatusData& q_status = mQuestStatus[quest_id];
11741 if( q_status.m_status == QUEST_STATUS_COMPLETE )
11742 return false; // not allow re-complete quest
11744 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
11746 if(!qInfo)
11747 return false;
11749 // auto complete quest
11750 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
11751 return true;
11753 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
11756 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
11758 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
11760 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
11761 return false;
11765 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
11767 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
11769 if( qInfo->ReqCreatureOrGOId[i] == 0 )
11770 continue;
11772 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
11773 return false;
11777 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
11778 return false;
11780 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
11781 return false;
11783 if ( qInfo->GetRewOrReqMoney() < 0 )
11785 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
11786 return false;
11789 uint32 repFacId = qInfo->GetRepObjectiveFaction();
11790 if ( repFacId && GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
11791 return false;
11793 return true;
11796 return false;
11799 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
11801 // Solve problem that player don't have the quest and try complete it.
11802 // if repeatable she must be able to complete event if player don't have it.
11803 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
11804 if( !CanTakeQuest(pQuest, false) )
11805 return false;
11807 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
11808 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
11809 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
11810 return false;
11812 if( !CanRewardQuest(pQuest, false) )
11813 return false;
11815 return true;
11818 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
11820 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
11821 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
11822 return false;
11824 // daily quest can't be rewarded (10 daily quest already completed)
11825 if(!SatisfyQuestDay(pQuest,true))
11826 return false;
11828 // rewarded and not repeatable quest (only cheating case, then ignore without message)
11829 if(GetQuestRewardStatus(pQuest->GetQuestId()))
11830 return false;
11832 // prevent receive reward with quest items in bank
11833 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
11835 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
11837 if( pQuest->ReqItemCount[i]!= 0 &&
11838 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
11840 if(msg)
11841 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
11842 return false;
11847 // prevent receive reward with low money and GetRewOrReqMoney() < 0
11848 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
11849 return false;
11851 return true;
11854 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
11856 // prevent receive reward with quest items in bank or for not completed quest
11857 if(!CanRewardQuest(pQuest,msg))
11858 return false;
11860 if ( pQuest->GetRewChoiceItemsCount() > 0 )
11862 if( pQuest->RewChoiceItemId[reward] )
11864 ItemPosCountVec dest;
11865 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
11866 if( res != EQUIP_ERR_OK )
11868 SendEquipError( res, NULL, NULL );
11869 return false;
11874 if ( pQuest->GetRewItemsCount() > 0 )
11876 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
11878 if( pQuest->RewItemId[i] )
11880 ItemPosCountVec dest;
11881 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
11882 if( res != EQUIP_ERR_OK )
11884 SendEquipError( res, NULL, NULL );
11885 return false;
11891 return true;
11894 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
11896 uint16 log_slot = FindQuestSlot( 0 );
11897 assert(log_slot < MAX_QUEST_LOG_SIZE);
11899 uint32 quest_id = pQuest->GetQuestId();
11901 // if not exist then created with set uState==NEW and rewarded=false
11902 QuestStatusData& questStatusData = mQuestStatus[quest_id];
11903 if (questStatusData.uState != QUEST_NEW)
11904 questStatusData.uState = QUEST_CHANGED;
11906 // check for repeatable quests status reset
11907 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
11908 questStatusData.m_explored = false;
11910 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
11912 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
11913 questStatusData.m_itemcount[i] = 0;
11916 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
11918 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
11919 questStatusData.m_creatureOrGOcount[i] = 0;
11922 GiveQuestSourceItem( pQuest );
11923 AdjustQuestReqItemCount( pQuest );
11925 if( pQuest->GetRepObjectiveFaction() )
11926 SetFactionVisibleForFactionId(pQuest->GetRepObjectiveFaction());
11928 uint32 qtime = 0;
11929 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
11931 uint32 limittime = pQuest->GetLimitTime();
11933 // shared timed quest
11934 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
11935 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / 1000;
11937 AddTimedQuest( quest_id );
11938 questStatusData.m_timer = limittime * 1000;
11939 qtime = static_cast<uint32>(time(NULL)) + limittime;
11941 else
11942 questStatusData.m_timer = 0;
11944 SetQuestSlot(log_slot, quest_id, qtime);
11946 //starting initial quest script
11947 if(questGiver && pQuest->GetQuestStartScript()!=0)
11948 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
11950 UpdateForQuestsGO();
11953 void Player::CompleteQuest( uint32 quest_id )
11955 if( quest_id )
11957 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
11959 uint16 log_slot = FindQuestSlot( quest_id );
11960 if( log_slot < MAX_QUEST_LOG_SIZE)
11961 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
11963 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
11965 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
11966 RewardQuest(qInfo,0,this,false);
11967 else
11968 SendQuestComplete( quest_id );
11973 void Player::IncompleteQuest( uint32 quest_id )
11975 if( quest_id )
11977 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
11979 uint16 log_slot = FindQuestSlot( quest_id );
11980 if( log_slot < MAX_QUEST_LOG_SIZE)
11981 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
11985 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
11987 uint32 quest_id = pQuest->GetQuestId();
11989 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; i++ )
11991 if ( pQuest->ReqItemId[i] )
11992 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
11995 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
11996 // SetTimedQuest( 0 );
11997 m_timedquests.erase(pQuest->GetQuestId());
11999 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12001 if( pQuest->RewChoiceItemId[reward] )
12003 ItemPosCountVec dest;
12004 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK )
12006 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12007 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12012 if ( pQuest->GetRewItemsCount() > 0 )
12014 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12016 if( pQuest->RewItemId[i] )
12018 ItemPosCountVec dest;
12019 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK )
12021 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12022 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12028 RewardReputation( pQuest );
12030 if( pQuest->GetRewSpellCast() > 0 )
12031 CastSpell( this, pQuest->GetRewSpellCast(), true);
12032 else if( pQuest->GetRewSpell() > 0)
12033 CastSpell( this, pQuest->GetRewSpell(), true);
12035 uint16 log_slot = FindQuestSlot( quest_id );
12036 if( log_slot < MAX_QUEST_LOG_SIZE)
12037 SetQuestSlot(log_slot,0);
12039 QuestStatusData& q_status = mQuestStatus[quest_id];
12041 // Not give XP in case already completed once repeatable quest
12042 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12044 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
12045 GiveXP( XP , NULL );
12046 else
12047 ModifyMoney( int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)) );
12049 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12050 ModifyMoney( pQuest->GetRewOrReqMoney() );
12052 // honor reward
12053 if(pQuest->GetRewHonorableKills())
12054 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12056 // title reward
12057 if(pQuest->GetCharTitleId())
12059 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12060 SetFlag64(PLAYER__FIELD_KNOWN_TITLES, (uint64(1) << titleEntry->bit_index));
12063 // Send reward mail
12064 if(pQuest->GetRewMailTemplateId())
12066 MailMessageType mailType;
12067 uint32 senderGuidOrEntry;
12068 switch(questGiver->GetTypeId())
12070 case TYPEID_UNIT:
12071 mailType = MAIL_CREATURE;
12072 senderGuidOrEntry = questGiver->GetEntry();
12073 break;
12074 case TYPEID_GAMEOBJECT:
12075 mailType = MAIL_GAMEOBJECT;
12076 senderGuidOrEntry = questGiver->GetEntry();
12077 break;
12078 case TYPEID_ITEM:
12079 mailType = MAIL_ITEM;
12080 senderGuidOrEntry = questGiver->GetEntry();
12081 break;
12082 case TYPEID_PLAYER:
12083 mailType = MAIL_NORMAL;
12084 senderGuidOrEntry = questGiver->GetGUIDLow();
12085 break;
12086 default:
12087 mailType = MAIL_NORMAL;
12088 senderGuidOrEntry = GetGUIDLow();
12089 break;
12092 Loot questMailLoot;
12094 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this);
12096 // fill mail
12097 MailItemsInfo mi; // item list preparing
12099 for(size_t i = 0; mi.size() < MAX_MAIL_ITEMS && i < questMailLoot.items.size(); ++i)
12101 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12103 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12105 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12106 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12111 for(size_t i = 0; mi.size() < MAX_MAIL_ITEMS && i < questMailLoot.quest_items.size(); ++i)
12113 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i+questMailLoot.items.size(),this))
12115 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12117 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12118 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12123 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12126 if(pQuest->IsDaily())
12127 SetDailyQuestStatus(quest_id);
12129 if ( !pQuest->IsRepeatable() )
12130 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12131 else
12132 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12134 q_status.m_rewarded = true;
12136 if(announce)
12137 SendQuestReward( pQuest, XP, questGiver );
12139 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12142 void Player::FailQuest( uint32 quest_id )
12144 if( quest_id )
12146 IncompleteQuest( quest_id );
12148 uint16 log_slot = FindQuestSlot( quest_id );
12149 if( log_slot < MAX_QUEST_LOG_SIZE)
12151 SetQuestSlotTimer(log_slot, 1 );
12152 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12154 SendQuestFailed( quest_id );
12158 void Player::FailTimedQuest( uint32 quest_id )
12160 if( quest_id )
12162 QuestStatusData& q_status = mQuestStatus[quest_id];
12164 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12165 q_status.m_timer = 0;
12167 IncompleteQuest( quest_id );
12169 uint16 log_slot = FindQuestSlot( quest_id );
12170 if( log_slot < MAX_QUEST_LOG_SIZE)
12172 SetQuestSlotTimer(log_slot, 1 );
12173 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12175 SendQuestTimerFailed( quest_id );
12179 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12181 int32 zoneOrSort = qInfo->GetZoneOrSort();
12182 int32 skillOrClass = qInfo->GetSkillOrClass();
12184 // skip zone zoneOrSort and 0 case skillOrClass
12185 if( zoneOrSort >= 0 && skillOrClass == 0 )
12186 return true;
12188 int32 questSort = -zoneOrSort;
12189 uint8 reqSortClass = ClassByQuestSort(questSort);
12191 // check class sort cases in zoneOrSort
12192 if( reqSortClass != 0 && getClass() != reqSortClass)
12194 if( msg )
12195 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12196 return false;
12199 // check class
12200 if( skillOrClass < 0 )
12202 uint8 reqClass = -int32(skillOrClass);
12203 if(getClass() != reqClass)
12205 if( msg )
12206 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12207 return false;
12210 // check skill
12211 else if( skillOrClass > 0 )
12213 uint32 reqSkill = skillOrClass;
12214 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12216 if( msg )
12217 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12218 return false;
12222 return true;
12225 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12227 if( getLevel() < qInfo->GetMinLevel() )
12229 if( msg )
12230 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12231 return false;
12233 return true;
12236 bool Player::SatisfyQuestLog( bool msg )
12238 // exist free slot
12239 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12240 return true;
12242 if( msg )
12244 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12245 GetSession()->SendPacket( &data );
12246 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12248 return false;
12251 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12253 // No previous quest (might be first quest in a series)
12254 if( qInfo->prevQuests.empty())
12255 return true;
12257 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12259 uint32 prevId = abs(*iter);
12261 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12262 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12264 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12266 // If any of the positive previous quests completed, return true
12267 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12269 // skip one-from-all exclusive group
12270 if(qPrevInfo->GetExclusiveGroup() >= 0)
12271 return true;
12273 // each-from-all exclusive group ( < 0)
12274 // can be start if only all quests in prev quest exclusive group complited and rewarded
12275 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12276 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12278 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12280 for(; iter != end; ++iter)
12282 uint32 exclude_Id = iter->second;
12284 // skip checked quest id, only state of other quests in group is interesting
12285 if(exclude_Id == prevId)
12286 continue;
12288 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12290 // alternative quest from group also must be completed and rewarded(reported)
12291 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12293 if( msg )
12294 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12295 return false;
12298 return true;
12300 // If any of the negative previous quests active, return true
12301 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12302 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
12304 // skip one-from-all exclusive group
12305 if(qPrevInfo->GetExclusiveGroup() >= 0)
12306 return true;
12308 // each-from-all exclusive group ( < 0)
12309 // can be start if only all quests in prev quest exclusive group active
12310 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12311 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12313 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12315 for(; iter != end; ++iter)
12317 uint32 exclude_Id = iter->second;
12319 // skip checked quest id, only state of other quests in group is interesting
12320 if(exclude_Id == prevId)
12321 continue;
12323 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12325 // alternative quest from group also must be active
12326 if( i_exstatus == mQuestStatus.end() ||
12327 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
12328 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
12330 if( msg )
12331 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12332 return false;
12335 return true;
12340 // Has only positive prev. quests in non-rewarded state
12341 // and negative prev. quests in non-active state
12342 if( msg )
12343 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12345 return false;
12348 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
12350 uint32 reqraces = qInfo->GetRequiredRaces();
12351 if ( reqraces == 0 )
12352 return true;
12353 if( (reqraces & getRaceMask()) == 0 )
12355 if( msg )
12356 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
12357 return false;
12359 return true;
12362 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
12364 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
12365 if(fIdMin && GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
12367 if( msg )
12368 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12369 return false;
12372 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
12373 if(fIdMax && GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
12375 if( msg )
12376 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12377 return false;
12380 return true;
12383 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
12385 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
12386 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
12388 if( msg )
12389 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
12390 return false;
12392 return true;
12395 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
12397 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
12399 if( msg )
12400 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
12401 return false;
12403 return true;
12406 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
12408 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12409 if(qInfo->GetExclusiveGroup() <= 0)
12410 return true;
12412 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
12413 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
12415 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
12417 for(; iter != end; ++iter)
12419 uint32 exclude_Id = iter->second;
12421 // skip checked quest id, only state of other quests in group is interesting
12422 if(exclude_Id == qInfo->GetQuestId())
12423 continue;
12425 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12427 // alternative quest already started or completed
12428 if( i_exstatus != mQuestStatus.end()
12429 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
12431 if( msg )
12432 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12433 return false;
12436 return true;
12439 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
12441 if(!qInfo->GetNextQuestInChain())
12442 return true;
12444 // next quest in chain already started or completed
12445 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
12446 if( itr != mQuestStatus.end()
12447 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
12449 if( msg )
12450 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12451 return false;
12454 // check for all quests further up the chain
12455 // only necessary if there are quest chains with more than one quest that can be skipped
12456 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12457 return true;
12460 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
12462 // No previous quest in chain
12463 if( qInfo->prevChainQuests.empty())
12464 return true;
12466 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
12468 uint32 prevId = *iter;
12470 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12472 if( i_prevstatus != mQuestStatus.end() )
12474 // If any of the previous quests in chain active, return false
12475 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12476 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
12478 if( msg )
12479 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12480 return false;
12484 // check for all quests further down the chain
12485 // only necessary if there are quest chains with more than one quest that can be skipped
12486 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12487 // return false;
12490 // No previous quest in chain active
12491 return true;
12494 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
12496 if(!qInfo->IsDaily())
12497 return true;
12499 bool have_slot = false;
12500 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
12502 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
12503 if(qInfo->GetQuestId()==id)
12504 return false;
12506 if(!id)
12507 have_slot = true;
12510 if(!have_slot)
12512 if( msg )
12513 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
12514 return false;
12517 return true;
12520 bool Player::GiveQuestSourceItem( Quest const *pQuest )
12522 uint32 srcitem = pQuest->GetSrcItemId();
12523 if( srcitem > 0 )
12525 uint32 count = pQuest->GetSrcItemCount();
12526 if( count <= 0 )
12527 count = 1;
12529 ItemPosCountVec dest;
12530 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12531 if( msg == EQUIP_ERR_OK )
12533 Item * item = StoreNewItem(dest, srcitem, true);
12534 SendNewItem(item, count, true, false);
12535 return true;
12537 // player already have max amount required item, just report success
12538 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12539 return true;
12540 else
12541 SendEquipError( msg, NULL, NULL );
12542 return false;
12545 return true;
12548 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
12550 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12551 if( qInfo )
12553 uint32 srcitem = qInfo->GetSrcItemId();
12554 if( srcitem > 0 )
12556 uint32 count = qInfo->GetSrcItemCount();
12557 if( count <= 0 )
12558 count = 1;
12560 // exist one case when destroy source quest item not possible:
12561 // non un-equippable item (equipped non-empty bag, for example)
12562 uint8 res = CanUnequipItems(srcitem,count);
12563 if(res != EQUIP_ERR_OK)
12565 if(msg)
12566 SendEquipError( res, NULL, NULL );
12567 return false;
12570 DestroyItemCount(srcitem, count, true, true);
12573 return true;
12576 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
12578 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12579 if( qInfo )
12581 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
12582 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12583 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
12584 && !qInfo->IsRepeatable() )
12585 return itr->second.m_rewarded;
12587 return false;
12589 return false;
12592 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
12594 if( quest_id )
12596 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12597 if( itr != mQuestStatus.end() )
12598 return itr->second.m_status;
12600 return QUEST_STATUS_NONE;
12603 bool Player::CanShareQuest(uint32 quest_id) const
12605 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12606 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
12608 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12609 if( itr != mQuestStatus.end() )
12610 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
12612 return false;
12615 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
12617 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12618 if( qInfo )
12620 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
12622 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12623 m_timedquests.erase(qInfo->GetQuestId());
12626 QuestStatusData& q_status = mQuestStatus[quest_id];
12628 q_status.m_status = status;
12629 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12632 UpdateForQuestsGO();
12635 // not used in MaNGOS, but used in scripting code
12636 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
12638 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12639 if( !qInfo )
12640 return 0;
12642 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
12643 if ( qInfo->ReqCreatureOrGOId[j] == entry )
12644 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
12646 return 0;
12649 void Player::AdjustQuestReqItemCount( Quest const* pQuest )
12651 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12653 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12655 uint32 reqitemcount = pQuest->ReqItemCount[i];
12656 if( reqitemcount != 0 )
12658 uint32 quest_id = pQuest->GetQuestId();
12659 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
12661 QuestStatusData& q_status = mQuestStatus[quest_id];
12662 q_status.m_itemcount[i] = std::min(curitemcount, reqitemcount);
12663 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12669 uint16 Player::FindQuestSlot( uint32 quest_id ) const
12671 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12672 if ( GetQuestSlotQuestId(i) == quest_id )
12673 return i;
12675 return MAX_QUEST_LOG_SIZE;
12678 void Player::AreaExploredOrEventHappens( uint32 questId )
12680 if( questId )
12682 uint16 log_slot = FindQuestSlot( questId );
12683 if( log_slot < MAX_QUEST_LOG_SIZE)
12685 QuestStatusData& q_status = mQuestStatus[questId];
12687 if(!q_status.m_explored)
12689 q_status.m_explored = true;
12690 if (q_status.uState != QUEST_NEW)
12691 q_status.uState = QUEST_CHANGED;
12694 if( CanCompleteQuest( questId ) )
12695 CompleteQuest( questId );
12699 //not used in mangosd, function for external script library
12700 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
12702 if( Group *pGroup = GetGroup() )
12704 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
12706 Player *pGroupGuy = itr->getSource();
12708 // for any leave or dead (with not released body) group member at appropriate distance
12709 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
12710 pGroupGuy->AreaExploredOrEventHappens(questId);
12713 else
12714 AreaExploredOrEventHappens(questId);
12717 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
12719 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12721 uint32 questid = GetQuestSlotQuestId(i);
12722 if ( questid == 0 )
12723 continue;
12725 QuestStatusData& q_status = mQuestStatus[questid];
12727 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
12728 continue;
12730 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
12731 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12732 continue;
12734 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
12736 uint32 reqitem = qInfo->ReqItemId[j];
12737 if ( reqitem == entry )
12739 uint32 reqitemcount = qInfo->ReqItemCount[j];
12740 uint32 curitemcount = q_status.m_itemcount[j];
12741 if ( curitemcount < reqitemcount )
12743 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
12744 q_status.m_itemcount[j] += additemcount;
12745 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12747 SendQuestUpdateAddItem( qInfo, j, additemcount );
12749 if ( CanCompleteQuest( questid ) )
12750 CompleteQuest( questid );
12751 return;
12755 UpdateForQuestsGO();
12758 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
12760 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12762 uint32 questid = GetQuestSlotQuestId(i);
12763 if(!questid)
12764 continue;
12765 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
12766 if ( !qInfo )
12767 continue;
12768 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12769 continue;
12771 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
12773 uint32 reqitem = qInfo->ReqItemId[j];
12774 if ( reqitem == entry )
12776 QuestStatusData& q_status = mQuestStatus[questid];
12778 uint32 reqitemcount = qInfo->ReqItemCount[j];
12779 uint32 curitemcount;
12780 if( q_status.m_status != QUEST_STATUS_COMPLETE )
12781 curitemcount = q_status.m_itemcount[j];
12782 else
12783 curitemcount = GetItemCount(entry,true);
12784 if ( curitemcount < reqitemcount + count )
12786 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
12787 q_status.m_itemcount[j] = curitemcount - remitemcount;
12788 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12790 IncompleteQuest( questid );
12792 return;
12796 UpdateForQuestsGO();
12799 void Player::KilledMonster( uint32 entry, uint64 guid )
12801 uint32 addkillcount = 1;
12802 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12804 uint32 questid = GetQuestSlotQuestId(i);
12805 if(!questid)
12806 continue;
12808 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
12809 if( !qInfo )
12810 continue;
12811 // just if !ingroup || !noraidgroup || raidgroup
12812 QuestStatusData& q_status = mQuestStatus[questid];
12813 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
12815 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
12817 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
12819 // skip GO activate objective or none
12820 if(qInfo->ReqCreatureOrGOId[j] <=0)
12821 continue;
12823 // skip Cast at creature objective
12824 if(qInfo->ReqSpell[j] !=0 )
12825 continue;
12827 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
12829 if ( reqkill == entry )
12831 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
12832 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
12833 if ( curkillcount < reqkillcount )
12835 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
12836 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12838 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
12840 if ( CanCompleteQuest( questid ) )
12841 CompleteQuest( questid );
12843 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
12844 continue;
12852 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
12854 bool isCreature = IS_CREATURE_GUID(guid);
12856 uint32 addCastCount = 1;
12857 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12859 uint32 questid = GetQuestSlotQuestId(i);
12860 if(!questid)
12861 continue;
12863 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
12864 if ( !qInfo )
12865 continue;
12867 QuestStatusData& q_status = mQuestStatus[questid];
12869 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12871 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
12873 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
12875 // skip kill creature objective (0) or wrong spell casts
12876 if(qInfo->ReqSpell[j] != spell_id )
12877 continue;
12879 uint32 reqTarget = 0;
12881 if(isCreature)
12883 // creature activate objectives
12884 if(qInfo->ReqCreatureOrGOId[j] > 0)
12885 // checked at quest_template loading
12886 reqTarget = qInfo->ReqCreatureOrGOId[j];
12888 else
12890 // GO activate objective
12891 if(qInfo->ReqCreatureOrGOId[j] < 0)
12892 // checked at quest_template loading
12893 reqTarget = - qInfo->ReqCreatureOrGOId[j];
12896 // other not this creature/GO related objectives
12897 if( reqTarget != entry )
12898 continue;
12900 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
12901 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
12902 if ( curCastCount < reqCastCount )
12904 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
12905 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12907 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
12910 if ( CanCompleteQuest( questid ) )
12911 CompleteQuest( questid );
12913 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
12914 break;
12921 void Player::TalkedToCreature( uint32 entry, uint64 guid )
12923 uint32 addTalkCount = 1;
12924 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12926 uint32 questid = GetQuestSlotQuestId(i);
12927 if(!questid)
12928 continue;
12930 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
12931 if ( !qInfo )
12932 continue;
12934 QuestStatusData& q_status = mQuestStatus[questid];
12936 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12938 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
12940 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
12942 // skip spell casts and Gameobject objectives
12943 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
12944 continue;
12946 uint32 reqTarget = 0;
12948 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
12949 // checked at quest_template loading
12950 reqTarget = qInfo->ReqCreatureOrGOId[j];
12951 else
12952 continue;
12954 if ( reqTarget == entry )
12956 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
12957 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
12958 if ( curTalkCount < reqTalkCount )
12960 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
12961 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12963 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
12965 if ( CanCompleteQuest( questid ) )
12966 CompleteQuest( questid );
12968 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
12969 continue;
12977 void Player::MoneyChanged( uint32 count )
12979 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12981 uint32 questid = GetQuestSlotQuestId(i);
12982 if (!questid)
12983 continue;
12985 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
12986 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
12988 QuestStatusData& q_status = mQuestStatus[questid];
12990 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12992 if(int32(count) >= -qInfo->GetRewOrReqMoney())
12994 if ( CanCompleteQuest( questid ) )
12995 CompleteQuest( questid );
12998 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13000 if(int32(count) < -qInfo->GetRewOrReqMoney())
13001 IncompleteQuest( questid );
13007 bool Player::HasQuestForItem( uint32 itemid ) const
13009 for( QuestStatusMap::const_iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
13011 QuestStatusData const& q_status = i->second;
13013 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13015 Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
13016 if(!qinfo)
13017 continue;
13019 // hide quest if player is in raid-group and quest is no raid quest
13020 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13021 continue;
13023 // There should be no mixed ReqItem/ReqSource drop
13024 // This part for ReqItem drop
13025 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13027 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13028 return true;
13030 // This part - for ReqSource
13031 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; j++)
13033 // examined item is a source item
13034 if (qinfo->ReqSourceId[j] == itemid && qinfo->ReqSourceRef[j] > 0 && qinfo->ReqSourceRef[j] <= QUEST_OBJECTIVES_COUNT)
13036 uint32 idx = qinfo->ReqSourceRef[j]-1;
13038 // total count of created ReqItems and SourceItems is less than ReqItemCount
13039 if(qinfo->ReqItemId[idx] != 0 &&
13040 q_status.m_itemcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid,true) < qinfo->ReqItemCount[idx] * qinfo->ReqSourceCount[j])
13041 return true;
13043 // total count of casted ReqCreatureOrGOs and SourceItems is less than ReqCreatureOrGOCount
13044 if (qinfo->ReqCreatureOrGOId[idx] != 0)
13046 if(q_status.m_creatureOrGOcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid,true) < qinfo->ReqCreatureOrGOCount[idx] * qinfo->ReqSourceCount[j])
13047 return true;
13049 // spell with SPELL_EFFECT_QUEST_COMPLETE or SPELL_EFFECT_SEND_EVENT (with script) case
13050 else if(qinfo->ReqSpell[idx] != 0)
13052 // not casted and need more reagents/item for use.
13053 if(!q_status.m_explored && GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13054 return true;
13060 return false;
13063 void Player::SendQuestComplete( uint32 quest_id )
13065 if( quest_id )
13067 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13068 data << quest_id;
13069 GetSession()->SendPacket( &data );
13070 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13074 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13076 uint32 questid = pQuest->GetQuestId();
13077 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13078 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4+4+pQuest->GetRewItemsCount()*8) );
13079 data << questid;
13080 data << uint32(0x03);
13082 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13084 data << XP;
13085 data << uint32(pQuest->GetRewOrReqMoney());
13087 else
13089 data << uint32(0);
13090 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13092 data << uint32(0); // new 2.3.0, HonorPoints?
13093 data << uint32( pQuest->GetRewItemsCount() ); // max is 5
13095 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
13097 if ( pQuest->RewItemId[i] > 0 )
13098 data << pQuest->RewItemId[i] << pQuest->RewItemCount[i];
13099 else
13100 data << uint32(0) << uint32(0);
13102 GetSession()->SendPacket( &data );
13104 if (pQuest->GetQuestCompleteScript() != 0)
13105 sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13108 void Player::SendQuestFailed( uint32 quest_id )
13110 if( quest_id )
13112 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4 );
13113 data << quest_id;
13114 GetSession()->SendPacket( &data );
13115 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13119 void Player::SendQuestTimerFailed( uint32 quest_id )
13121 if( quest_id )
13123 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13124 data << quest_id;
13125 GetSession()->SendPacket( &data );
13126 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13130 void Player::SendCanTakeQuestResponse( uint32 msg )
13132 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13133 data << uint32(msg);
13134 GetSession()->SendPacket( &data );
13135 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13138 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13140 if( pPlayer )
13142 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13143 data << uint64(pPlayer->GetGUID());
13144 data << uint8(msg); // valid values: 0-8
13145 GetSession()->SendPacket( &data );
13146 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13150 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13152 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, (4+4) );
13153 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13154 data << pQuest->ReqItemId[item_idx];
13155 data << count;
13156 GetSession()->SendPacket( &data );
13159 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13161 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13163 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13164 if (entry < 0)
13165 // client expected gameobject template id in form (id|0x80000000)
13166 entry = (-entry) | 0x80000000;
13168 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13169 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13170 data << uint32(pQuest->GetQuestId());
13171 data << uint32(entry);
13172 data << uint32(old_count + add_count);
13173 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13174 data << uint64(guid);
13175 GetSession()->SendPacket(&data);
13177 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13178 if( log_slot < MAX_QUEST_LOG_SIZE)
13179 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13182 /*********************************************************/
13183 /*** LOAD SYSTEM ***/
13184 /*********************************************************/
13186 bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
13188 bool delete_result = true;
13189 if(!result)
13191 // 0 1 2 3 4 5 6 7 8 9
13192 result = CharacterDatabase.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid);
13193 if(!result) return false;
13195 else delete_result = false;
13197 Field *fields = result->Fetch();
13199 if(!LoadValues( fields[1].GetString()))
13201 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
13202 if(delete_result) delete result;
13203 return false;
13206 // overwrite possible wrong/corrupted guid
13207 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13209 m_name = fields[2].GetCppString();
13211 Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
13212 SetMapId(fields[6].GetUInt32());
13213 // the instance id is not needed at character enum
13215 m_Played_time[0] = fields[7].GetUInt32();
13216 m_Played_time[1] = fields[8].GetUInt32();
13218 m_atLoginFlags = fields[9].GetUInt32();
13220 // I don't see these used anywhere ..
13221 /*_LoadGroup();
13223 _LoadBoundInstances();*/
13225 if (delete_result) delete result;
13227 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
13228 m_items[i] = NULL;
13230 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
13231 m_deathState = DEAD;
13233 return true;
13236 void Player::_LoadDeclinedNames(QueryResult* result)
13238 if(!result)
13239 return;
13241 if(m_declinedname)
13242 delete m_declinedname;
13244 m_declinedname = new DeclinedName;
13245 Field *fields = result->Fetch();
13246 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13247 m_declinedname->name[i] = fields[i].GetCppString();
13249 delete result;
13252 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
13254 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
13255 if(!result)
13256 return false;
13258 Field *fields = result->Fetch();
13260 x = fields[0].GetFloat();
13261 y = fields[1].GetFloat();
13262 z = fields[2].GetFloat();
13263 o = fields[3].GetFloat();
13264 mapid = fields[4].GetUInt32();
13265 in_flight = !fields[5].GetCppString().empty();
13267 delete result;
13268 return true;
13271 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
13273 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
13274 if( !result )
13275 return false;
13277 Field *fields = result->Fetch();
13279 data = StrSplit(fields[0].GetCppString(), " ");
13281 delete result;
13283 return true;
13286 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
13288 if(index >= data.size())
13289 return 0;
13291 return (uint32)atoi(data[index].c_str());
13294 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
13296 float result;
13297 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
13298 memcpy(&result, &temp, sizeof(result));
13300 return result;
13303 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
13305 Tokens data;
13306 if(!LoadValuesArrayFromDB(data,guid))
13307 return 0;
13309 return GetUInt32ValueFromArray(data,index);
13312 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
13314 float result;
13315 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
13316 memcpy(&result, &temp, sizeof(result));
13318 return result;
13321 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
13323 //// 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
13324 //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);
13325 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
13327 if(!result)
13329 sLog.outError("ERROR: Player (GUID: %u) not found in table `characters`, can't load. ",guid);
13330 return false;
13333 Field *fields = result->Fetch();
13335 uint32 dbAccountId = fields[1].GetUInt32();
13337 // check if the character's account in the db and the logged in account match.
13338 // player should be able to load/delete character only with correct account!
13339 if( dbAccountId != GetSession()->GetAccountId() )
13341 sLog.outError("ERROR: Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
13342 delete result;
13343 return false;
13346 Object::_Create( guid, 0, HIGHGUID_PLAYER );
13348 m_name = fields[3].GetCppString();
13350 // check name limitations
13351 if(!ObjectMgr::IsValidName(m_name) || GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name))
13353 delete result;
13354 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
13355 return false;
13358 if(!LoadValues( fields[2].GetString()))
13360 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
13361 delete result;
13362 return false;
13365 // overwrite possible wrong/corrupted guid
13366 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13368 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13369 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
13371 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), 0 );
13372 SetVisibleItemSlot(slot,NULL);
13374 if (m_items[slot])
13376 delete m_items[slot];
13377 m_items[slot] = NULL;
13381 // update money limits
13382 if(GetMoney() > MAX_MONEY_AMOUNT)
13383 SetMoney(MAX_MONEY_AMOUNT);
13385 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
13386 outDebugValues();
13388 m_race = fields[4].GetUInt8();
13389 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13390 //Other way is to saves m_team into characters table.
13391 setFactionForRace(m_race);
13392 SetCharm(0);
13394 m_class = fields[5].GetUInt8();
13396 PlayerInfo const *info = objmgr.GetPlayerInfo(m_race, m_class);
13397 if(!info)
13399 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
13400 delete result;
13401 return false;
13404 InitPrimaryProffesions(); // to max set before any spell loaded
13406 uint32 transGUID = fields[24].GetUInt32();
13407 Relocate(fields[6].GetFloat(),fields[7].GetFloat(),fields[8].GetFloat(),fields[10].GetFloat());
13408 SetMapId(fields[9].GetUInt32());
13409 SetDifficulty(fields[32].GetUInt32()); // may be changed in _LoadGroup
13411 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
13413 // check arena teams integrity
13414 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
13416 uint32 arena_team_id = GetArenaTeamId(arena_slot);
13417 if(!arena_team_id)
13418 continue;
13420 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
13421 if(at->HaveMember(GetGUID()))
13422 continue;
13424 // arena team not exist or not member, cleanup fields
13425 for(int j =0; j < 6; ++j)
13426 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
13429 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
13431 if(!IsPositionValid())
13433 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());
13435 SetMapId(info->mapId);
13436 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
13438 transGUID = 0;
13440 m_movementInfo.t_x = 0.0f;
13441 m_movementInfo.t_y = 0.0f;
13442 m_movementInfo.t_z = 0.0f;
13443 m_movementInfo.t_o = 0.0f;
13446 // load the player's map here if it's not already loaded
13447 Map *map = GetMap();
13448 // since the player may not be bound to the map yet, make sure subsequent
13449 // getmap calls won't create new maps
13450 SetInstanceId(map->GetInstanceId());
13452 SaveRecallPosition();
13454 if (transGUID != 0)
13456 m_movementInfo.t_x = fields[20].GetFloat();
13457 m_movementInfo.t_y = fields[21].GetFloat();
13458 m_movementInfo.t_z = fields[22].GetFloat();
13459 m_movementInfo.t_o = fields[23].GetFloat();
13461 if( !MaNGOS::IsValidMapCoord(
13462 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13463 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
13464 // transport size limited
13465 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
13467 sLog.outError("ERROR: Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
13468 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13469 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
13471 SetMapId(info->mapId);
13472 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
13474 m_movementInfo.t_x = 0.0f;
13475 m_movementInfo.t_y = 0.0f;
13476 m_movementInfo.t_z = 0.0f;
13477 m_movementInfo.t_o = 0.0f;
13479 transGUID = 0;
13483 if (transGUID != 0)
13485 for (MapManager::TransportSet::iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
13487 if( (*iter)->GetGUIDLow() == transGUID)
13489 m_transport = *iter;
13490 m_transport->AddPassenger(this);
13491 SetMapId(m_transport->GetMapId());
13492 break;
13496 if(!m_transport)
13498 sLog.outError("ERROR: Player (guidlow %d) have invalid transport guid (%u). Teleport to default race/class locations.",
13499 guid,transGUID);
13501 SetMapId(info->mapId);
13502 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
13504 m_movementInfo.t_x = 0.0f;
13505 m_movementInfo.t_y = 0.0f;
13506 m_movementInfo.t_z = 0.0f;
13507 m_movementInfo.t_o = 0.0f;
13509 transGUID = 0;
13513 time_t now = time(NULL);
13514 time_t logoutTime = time_t(fields[16].GetUInt64());
13516 // since last logout (in seconds)
13517 uint64 time_diff = uint64(now - logoutTime);
13519 // set value, including drunk invisibility detection
13520 // calculate sobering. after 15 minutes logged out, the player will be sober again
13521 float soberFactor;
13522 if(time_diff > 15*MINUTE)
13523 soberFactor = 0;
13524 else
13525 soberFactor = 1-time_diff/(15.0f*MINUTE);
13526 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
13527 SetDrunkValue(newDrunkenValue);
13529 m_rest_bonus = fields[15].GetFloat();
13530 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
13531 float bubble0 = 0.031;
13532 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
13533 float bubble1 = 0.125;
13535 if((int32)fields[16].GetUInt32() > 0)
13537 float bubble = fields[17].GetUInt32() > 0
13538 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
13539 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
13541 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
13544 m_cinematic = fields[12].GetUInt32();
13545 m_Played_time[0]= fields[13].GetUInt32();
13546 m_Played_time[1]= fields[14].GetUInt32();
13548 m_resetTalentsCost = fields[18].GetUInt32();
13549 m_resetTalentsTime = time_t(fields[19].GetUInt64());
13551 // reserve some flags
13552 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
13554 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
13555 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
13557 m_taxi.LoadTaxiMask( fields[11].GetString() ); // must be before InitTaxiNodesForLevel
13559 uint32 extraflags = fields[25].GetUInt32();
13561 m_stableSlots = fields[26].GetUInt32();
13562 if(m_stableSlots > 2)
13564 sLog.outError("Player can have not more 2 stable slots, but have in DB %u",uint32(m_stableSlots));
13565 m_stableSlots = 2;
13568 m_atLoginFlags = fields[27].GetUInt32();
13570 // Honor system
13571 // Update Honor kills data
13572 m_lastHonorUpdateTime = logoutTime;
13573 UpdateHonorFields();
13575 m_deathExpireTime = (time_t)fields[30].GetUInt64();
13576 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
13577 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
13579 std::string taxi_nodes = fields[31].GetCppString();
13581 delete result;
13583 // clear channel spell data (if saved at channel spell casting)
13584 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
13585 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
13587 // clear charm/summon related fields
13588 SetUInt64Value(UNIT_FIELD_CHARM,0);
13589 SetUInt64Value(UNIT_FIELD_SUMMON,0);
13590 SetUInt64Value(UNIT_FIELD_CHARMEDBY,0);
13591 SetUInt64Value(UNIT_FIELD_SUMMONEDBY,0);
13592 SetUInt64Value(UNIT_FIELD_CREATEDBY,0);
13594 // reset some aura modifiers before aura apply
13595 SetUInt64Value(PLAYER_FARSIGHT, 0);
13596 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
13597 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
13599 // reset skill modifiers and set correct unlearn flags
13600 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; i++)
13602 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
13604 // set correct unlearn bit
13605 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
13606 if(!id) continue;
13608 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
13609 if(!pSkill) continue;
13611 // enable unlearn button for primary professions only
13612 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
13613 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
13614 else
13615 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
13618 // make sure the unit is considered out of combat for proper loading
13619 ClearInCombat();
13621 // make sure the unit is considered not in duel for proper loading
13622 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
13623 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
13625 // remember loaded power/health values to restore after stats initialization and modifier applying
13626 uint32 savedHealth = GetHealth();
13627 uint32 savedPower[MAX_POWERS];
13628 for(uint32 i = 0; i < MAX_POWERS; ++i)
13629 savedPower[i] = GetPower(Powers(i));
13631 // reset stats before loading any modifiers
13632 InitStatsForLevel();
13633 InitTaxiNodesForLevel();
13635 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
13637 //mails are loaded only when needed ;-) - when player in game click on mailbox.
13638 //_LoadMail();
13640 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
13642 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
13643 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
13644 m_deathState = DEAD;
13646 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
13648 // after spell load
13649 InitTalentForLevel();
13650 learnSkillRewardedSpells();
13652 // after spell load, learn rewarded spell if need also
13653 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
13654 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
13656 _LoadTutorials(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS));
13658 // must be before inventory (some items required reputation check)
13659 _LoadReputation(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
13661 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
13663 // update items with duration and realtime
13664 UpdateItemDuration(time_diff, true);
13666 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
13668 // unread mails and next delivery time, actual mails not loaded
13669 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
13671 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
13673 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
13674 return false;
13676 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
13677 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
13678 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
13680 if(!HasFlag64(PLAYER__FIELD_KNOWN_TITLES,uint64(1) << curTitle))
13681 SetUInt32Value(PLAYER_CHOSEN_TITLE,0);
13684 // Not finish taxi flight path
13685 if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes))
13687 // problems with taxi path loading
13688 TaxiNodesEntry const* nodeEntry = NULL;
13689 if(uint32 node_id = m_taxi.GetTaxiSource())
13690 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
13692 if(!nodeEntry) // don't know taxi start node, to homebind
13694 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
13695 SetMapId(m_homebindMapId);
13696 Relocate( m_homebindX, m_homebindY, m_homebindZ,0.0f);
13697 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
13699 else // have start node, to it
13701 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
13702 SetMapId(nodeEntry->map_id);
13703 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
13704 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
13706 m_taxi.ClearTaxiDestinations();
13708 else if(uint32 node_id = m_taxi.GetTaxiSource())
13710 // save source node as recall coord to prevent recall and fall from sky
13711 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
13712 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
13713 m_recallMap = nodeEntry->map_id;
13714 m_recallX = nodeEntry->x;
13715 m_recallY = nodeEntry->y;
13716 m_recallZ = nodeEntry->z;
13718 // flight will started later
13721 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
13723 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
13724 // Do now before stats re-calculation cleanup for ghost state unexpected auras
13725 if(!isAlive())
13726 RemoveAllAurasOnDeath();
13728 //apply all stat bonuses from items and auras
13729 SetCanModifyStats(true);
13730 UpdateAllStats();
13732 // restore remembered power/health values (but not more max values)
13733 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
13734 for(uint32 i = 0; i < MAX_POWERS; ++i)
13735 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
13737 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
13738 outDebugValues();
13740 // GM state
13741 if(GetSession()->GetSecurity() > SEC_PLAYER)
13743 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
13745 default:
13746 case 0: break; // disable
13747 case 1: SetGameMaster(true); break; // enable
13748 case 2: // save state
13749 if(extraflags & PLAYER_EXTRA_GM_ON)
13750 SetGameMaster(true);
13751 break;
13754 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
13756 default:
13757 case 0: break; // disable
13758 case 1: SetAcceptTicket(true); break; // enable
13759 case 2: // save state
13760 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
13761 SetAcceptTicket(true);
13762 break;
13765 switch(sWorld.getConfig(CONFIG_GM_CHAT))
13767 default:
13768 case 0: break; // disable
13769 case 1: SetGMChat(true); break; // enable
13770 case 2: // save state
13771 if(extraflags & PLAYER_EXTRA_GM_CHAT)
13772 SetGMChat(true);
13773 break;
13776 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
13778 default:
13779 case 0: break; // disable
13780 case 1: SetAcceptWhispers(true); break; // enable
13781 case 2: // save state
13782 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
13783 SetAcceptWhispers(true);
13784 break;
13788 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
13790 return true;
13793 bool Player::isAllowedToLoot(Creature* creature)
13795 if(Player* recipient = creature->GetLootRecipient())
13797 if (recipient == this)
13798 return true;
13799 if( Group* otherGroup = recipient->GetGroup())
13801 Group* thisGroup = GetGroup();
13802 if(!thisGroup)
13803 return false;
13804 return thisGroup == otherGroup;
13806 return false;
13808 else
13809 // prevent other players from looting if the recipient got disconnected
13810 return !creature->hasLootRecipient();
13813 void Player::_LoadActions(QueryResult *result)
13815 m_actionButtons.clear();
13817 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
13819 if(result)
13823 Field *fields = result->Fetch();
13825 uint8 button = fields[0].GetUInt8();
13827 addActionButton(button, fields[1].GetUInt16(), fields[2].GetUInt8(), fields[3].GetUInt8());
13829 m_actionButtons[button].uState = ACTIONBUTTON_UNCHANGED;
13831 while( result->NextRow() );
13833 delete result;
13837 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
13839 m_Auras.clear();
13840 for (int i = 0; i < TOTAL_AURAS; i++)
13841 m_modAuras[i].clear();
13843 // all aura related fields
13844 for(int i = UNIT_FIELD_AURA; i <= UNIT_FIELD_AURASTATE; ++i)
13845 SetUInt32Value(i, 0);
13847 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
13849 if(result)
13853 Field *fields = result->Fetch();
13854 uint64 caster_guid = fields[0].GetUInt64();
13855 uint32 spellid = fields[1].GetUInt32();
13856 uint32 effindex = fields[2].GetUInt32();
13857 int32 damage = (int32)fields[3].GetUInt32();
13858 int32 maxduration = (int32)fields[4].GetUInt32();
13859 int32 remaintime = (int32)fields[5].GetUInt32();
13860 int32 remaincharges = (int32)fields[6].GetUInt32();
13862 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
13863 if(!spellproto)
13865 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
13866 continue;
13869 if(effindex >= 3)
13871 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
13872 continue;
13875 // negative effects should continue counting down after logout
13876 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
13878 if(remaintime <= int32(timediff))
13879 continue;
13881 remaintime -= timediff;
13884 // prevent wrong values of remaincharges
13885 if(spellproto->procCharges)
13887 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
13888 remaincharges = spellproto->procCharges;
13890 else
13891 remaincharges = -1;
13893 //do not load single target auras (unless they were cast by the player)
13894 if (caster_guid != GetGUID() && IsSingleTargetSpell(spellproto))
13895 continue;
13897 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
13898 if(!damage)
13899 damage = aura->GetModifier()->m_amount;
13900 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
13901 AddAura(aura);
13903 while( result->NextRow() );
13905 delete result;
13908 if(m_class == CLASS_WARRIOR)
13909 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
13912 void Player::LoadCorpse()
13914 if( isAlive() )
13916 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
13918 else
13920 if(Corpse *corpse = GetCorpse())
13922 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
13924 else
13926 //Prevent Dead Player login without corpse
13927 ResurrectPlayer(0.5f);
13932 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
13934 //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());
13935 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
13936 //NOTE: the "order by `bag`" is important because it makes sure
13937 //the bagMap is filled before items in the bags are loaded
13938 //NOTE2: the "order by `slot`" is needed becaue mainhand weapons are (wrongly?)
13939 //expected to be equipped before offhand items (TODO: fixme)
13941 uint32 zone = GetZoneId();
13943 if (result)
13945 std::list<Item*> problematicItems;
13947 // prevent items from being added to the queue when stored
13948 m_itemUpdateQueueBlocked = true;
13951 Field *fields = result->Fetch();
13952 uint32 bag_guid = fields[1].GetUInt32();
13953 uint8 slot = fields[2].GetUInt8();
13954 uint32 item_guid = fields[3].GetUInt32();
13955 uint32 item_id = fields[4].GetUInt32();
13957 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
13959 if(!proto)
13961 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
13962 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
13963 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
13964 continue;
13967 Item *item = NewItemOrBag(proto);
13969 if(!item->LoadFromDB(item_guid, GetGUID(), result))
13971 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
13972 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
13973 item->FSetState(ITEM_REMOVED);
13974 item->SaveToDB(); // it also deletes item object !
13975 continue;
13978 // not allow have in alive state item limited to another map/zone
13979 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
13981 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
13982 item->FSetState(ITEM_REMOVED);
13983 item->SaveToDB(); // it also deletes item object !
13984 continue;
13987 // "Conjured items disappear if you are logged out for more than 15 minutes"
13988 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
13990 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
13991 item->FSetState(ITEM_REMOVED);
13992 item->SaveToDB(); // it also deletes item object !
13993 continue;
13996 bool success = true;
13998 if (!bag_guid)
14000 // the item is not in a bag
14001 item->SetContainer( NULL );
14002 item->SetSlot(slot);
14004 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14006 ItemPosCountVec dest;
14007 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14008 item = StoreItem(dest, item, true);
14009 else
14010 success = false;
14012 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14014 uint16 dest;
14015 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14016 QuickEquipItem(dest, item);
14017 else
14018 success = false;
14020 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14022 ItemPosCountVec dest;
14023 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14024 item = BankItem(dest, item, true);
14025 else
14026 success = false;
14029 if(success)
14031 // store bags that may contain items in them
14032 if(item->IsBag() && IsBagPos(item->GetPos()))
14033 bagMap[item_guid] = (Bag*)item;
14036 else
14038 item->SetSlot(NULL_SLOT);
14039 // the item is in a bag, find the bag
14040 std::map<uint64, Bag*>::iterator itr = bagMap.find(bag_guid);
14041 if(itr != bagMap.end())
14042 itr->second->StoreItem(slot, item, true );
14043 else
14044 success = false;
14047 // item's state may have changed after stored
14048 if (success)
14049 item->SetState(ITEM_UNCHANGED, this);
14050 else
14052 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);
14053 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14054 problematicItems.push_back(item);
14056 } while (result->NextRow());
14058 delete result;
14059 m_itemUpdateQueueBlocked = false;
14061 // send by mail problematic items
14062 while(!problematicItems.empty())
14064 // fill mail
14065 MailItemsInfo mi; // item list prepering
14067 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14069 Item* item = problematicItems.front();
14070 problematicItems.pop_front();
14072 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14075 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14077 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14080 //if(isAlive())
14081 _ApplyAllItemMods();
14084 // load mailed item which should receive current player
14085 void Player::_LoadMailedItems(Mail *mail)
14087 QueryResult* result = CharacterDatabase.PQuery("SELECT item_guid, item_template FROM mail_items WHERE mail_id='%u'", mail->messageID);
14088 if(!result)
14089 return;
14093 Field *fields = result->Fetch();
14094 uint32 item_guid_low = fields[0].GetUInt32();
14095 uint32 item_template = fields[1].GetUInt32();
14097 mail->AddItem(item_guid_low, item_template);
14099 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
14101 if(!proto)
14103 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);
14104 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14105 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
14106 continue;
14109 Item *item = NewItemOrBag(proto);
14111 if(!item->LoadFromDB(item_guid_low, 0))
14113 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
14114 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14115 item->FSetState(ITEM_REMOVED);
14116 item->SaveToDB(); // it also deletes item object !
14117 continue;
14120 AddMItem(item);
14121 } while (result->NextRow());
14123 delete result;
14126 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
14128 //set a count of unread mails
14129 //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);
14130 if (resultUnread)
14132 Field *fieldMail = resultUnread->Fetch();
14133 unReadMails = fieldMail[0].GetUInt8();
14134 delete resultUnread;
14137 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14138 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14139 if (resultDelivery)
14141 Field *fieldMail = resultDelivery->Fetch();
14142 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
14143 delete resultDelivery;
14147 void Player::_LoadMail()
14149 m_mail.clear();
14150 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14151 QueryResult *result = CharacterDatabase.PQuery("SELECT id,messageType,sender,receiver,subject,itemTextId,has_items,expire_time,deliver_time,money,cod,checked,stationery,mailTemplateId FROM mail WHERE receiver = '%u' ORDER BY id DESC",GetGUIDLow());
14152 if(result)
14156 Field *fields = result->Fetch();
14157 Mail *m = new Mail;
14158 m->messageID = fields[0].GetUInt32();
14159 m->messageType = fields[1].GetUInt8();
14160 m->sender = fields[2].GetUInt32();
14161 m->receiver = fields[3].GetUInt32();
14162 m->subject = fields[4].GetCppString();
14163 m->itemTextId = fields[5].GetUInt32();
14164 bool has_items = fields[6].GetBool();
14165 m->expire_time = (time_t)fields[7].GetUInt64();
14166 m->deliver_time = (time_t)fields[8].GetUInt64();
14167 m->money = fields[9].GetUInt32();
14168 m->COD = fields[10].GetUInt32();
14169 m->checked = fields[11].GetUInt32();
14170 m->stationery = fields[12].GetUInt8();
14171 m->mailTemplateId = fields[13].GetInt16();
14173 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
14175 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
14176 m->mailTemplateId = 0;
14179 m->state = MAIL_STATE_UNCHANGED;
14181 if (has_items)
14182 _LoadMailedItems(m);
14184 m_mail.push_back(m);
14185 } while( result->NextRow() );
14186 delete result;
14188 m_mailsLoaded = true;
14191 void Player::LoadPet()
14193 //fixme: the pet should still be loaded if the player is not in world
14194 // just not added to the map
14195 if(IsInWorld())
14197 Pet *pet = new Pet;
14198 if(!pet->LoadPetFromDB(this,0,0,true))
14199 delete pet;
14203 void Player::_LoadQuestStatus(QueryResult *result)
14205 mQuestStatus.clear();
14207 uint32 slot = 0;
14209 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14210 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest, status, rewarded, explored, timer, mobcount1, mobcount2, mobcount3, mobcount4, itemcount1, itemcount2, itemcount3, itemcount4 FROM character_queststatus WHERE guid = '%u'", GetGUIDLow());
14212 if(result)
14216 Field *fields = result->Fetch();
14218 uint32 quest_id = fields[0].GetUInt32();
14219 // used to be new, no delete?
14220 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14221 if( pQuest )
14223 // find or create
14224 QuestStatusData& questStatusData = mQuestStatus[quest_id];
14226 uint32 qstatus = fields[1].GetUInt32();
14227 if(qstatus < MAX_QUEST_STATUS)
14228 questStatusData.m_status = QuestStatus(qstatus);
14229 else
14231 questStatusData.m_status = QUEST_STATUS_NONE;
14232 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
14235 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
14236 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
14238 time_t quest_time = time_t(fields[4].GetUInt64());
14240 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
14242 AddTimedQuest( quest_id );
14244 if (quest_time <= sWorld.GetGameTime())
14245 questStatusData.m_timer = 1;
14246 else
14247 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * 1000;
14249 else
14250 quest_time = 0;
14252 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
14253 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
14254 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
14255 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
14256 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
14257 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
14258 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
14259 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
14261 questStatusData.uState = QUEST_UNCHANGED;
14263 // add to quest log
14264 if( slot < MAX_QUEST_LOG_SIZE &&
14265 ( questStatusData.m_status==QUEST_STATUS_INCOMPLETE ||
14266 questStatusData.m_status==QUEST_STATUS_COMPLETE && !questStatusData.m_rewarded ) )
14268 SetQuestSlot(slot,quest_id,quest_time);
14270 if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
14271 SetQuestSlotState(slot,QUEST_STATE_COMPLETE);
14273 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
14274 if(questStatusData.m_creatureOrGOcount[idx])
14275 SetQuestSlotCounter(slot,idx,questStatusData.m_creatureOrGOcount[idx]);
14277 ++slot;
14280 if(questStatusData.m_rewarded)
14282 // learn rewarded spell if unknown
14283 learnQuestRewardedSpells(pQuest);
14285 // set rewarded title if any
14286 if(pQuest->GetCharTitleId())
14288 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
14289 SetFlag64(PLAYER__FIELD_KNOWN_TITLES, (uint64(1) << titleEntry->bit_index));
14293 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
14296 while( result->NextRow() );
14298 delete result;
14301 // clear quest log tail
14302 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
14303 SetQuestSlot(i,0);
14306 void Player::_LoadDailyQuestStatus(QueryResult *result)
14308 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
14309 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
14311 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14313 if(result)
14315 uint32 quest_daily_idx = 0;
14319 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
14321 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
14322 break;
14325 Field *fields = result->Fetch();
14327 uint32 quest_id = fields[0].GetUInt32();
14329 // save _any_ from daily quest times (it must be after last reset anyway)
14330 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
14332 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14333 if( !pQuest )
14334 continue;
14336 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
14337 ++quest_daily_idx;
14339 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
14341 while( result->NextRow() );
14343 delete result;
14346 m_DailyQuestChanged = false;
14349 void Player::_LoadReputation(QueryResult *result)
14351 m_factions.clear();
14353 // Set initial reputations (so everything is nifty before DB data load)
14354 SetInitialFactions();
14356 //QueryResult *result = CharacterDatabase.PQuery("SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'",GetGUIDLow());
14358 if(result)
14362 Field *fields = result->Fetch();
14364 FactionEntry const *factionEntry = sFactionStore.LookupEntry(fields[0].GetUInt32());
14365 if( factionEntry && (factionEntry->reputationListID >= 0))
14367 FactionState* faction = &m_factions[factionEntry->reputationListID];
14369 // update standing to current
14370 faction->Standing = int32(fields[1].GetUInt32());
14372 uint32 dbFactionFlags = fields[2].GetUInt32();
14374 if( dbFactionFlags & FACTION_FLAG_VISIBLE )
14375 SetFactionVisible(faction); // have internal checks for forced invisibility
14377 if( dbFactionFlags & FACTION_FLAG_INACTIVE)
14378 SetFactionInactive(faction,true); // have internal checks for visibility requirement
14380 if( dbFactionFlags & FACTION_FLAG_AT_WAR ) // DB at war
14381 SetFactionAtWar(faction,true); // have internal checks for FACTION_FLAG_PEACE_FORCED
14382 else // DB not at war
14384 // allow remove if visible (and then not FACTION_FLAG_INVISIBLE_FORCED or FACTION_FLAG_HIDDEN)
14385 if( faction->Flags & FACTION_FLAG_VISIBLE )
14386 SetFactionAtWar(faction,false); // have internal checks for FACTION_FLAG_PEACE_FORCED
14389 // set atWar for hostile
14390 if(GetReputationRank(factionEntry) <= REP_HOSTILE)
14391 SetFactionAtWar(faction,true);
14393 // reset changed flag if values similar to saved in DB
14394 if(faction->Flags==dbFactionFlags)
14395 faction->Changed = false;
14398 while( result->NextRow() );
14400 delete result;
14404 void Player::_LoadSpells(QueryResult *result)
14406 for (PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
14407 delete itr->second;
14408 m_spells.clear();
14410 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,slot,active FROM character_spell WHERE guid = '%u'",GetGUIDLow());
14412 if(result)
14416 Field *fields = result->Fetch();
14418 addSpell(fields[0].GetUInt16(), fields[2].GetBool(), false, true, fields[1].GetUInt16(), fields[3].GetBool());
14420 while( result->NextRow() );
14422 delete result;
14426 void Player::_LoadTutorials(QueryResult *result)
14428 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
14430 if(result)
14434 Field *fields = result->Fetch();
14436 for (int iI=0; iI<8; iI++)
14437 m_Tutorials[iI] = fields[iI].GetUInt32();
14439 while( result->NextRow() );
14441 delete result;
14444 m_TutorialsChanged = false;
14447 void Player::_LoadGroup(QueryResult *result)
14449 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
14450 if(result)
14452 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
14453 delete result;
14454 Group* group = objmgr.GetGroupByLeader(leaderGuid);
14455 if(group)
14457 uint8 subgroup = group->GetMemberGroup(GetGUID());
14458 SetGroup(group, subgroup);
14459 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
14461 // the group leader may change the instance difficulty while the player is offline
14462 SetDifficulty(group->GetDifficulty());
14468 void Player::_LoadBoundInstances(QueryResult *result)
14470 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14471 m_boundInstances[i].clear();
14473 Group *group = GetGroup();
14475 //QueryResult *result = CharacterDatabase.PQuery("SELECT id, permanent, map, difficulty, resettime FROM character_instance LEFT JOIN instance ON instance = id WHERE guid = '%u'", GUID_LOPART(m_guid));
14476 if(result)
14480 Field *fields = result->Fetch();
14481 bool perm = fields[1].GetBool();
14482 uint32 mapId = fields[2].GetUInt32();
14483 uint32 instanceId = fields[0].GetUInt32();
14484 uint8 difficulty = fields[3].GetUInt8();
14485 time_t resetTime = (time_t)fields[4].GetUInt64();
14486 // the resettime for normal instances is only saved when the InstanceSave is unloaded
14487 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
14488 // and in that case it is not used
14490 if(!perm && group)
14492 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);
14493 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
14494 continue;
14497 // since non permanent binds are always solo bind, they can always be reset
14498 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
14499 if(save) BindToInstance(save, perm, true);
14500 } while(result->NextRow());
14501 delete result;
14505 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
14507 // some instances only have one difficulty
14508 const MapEntry* entry = sMapStore.LookupEntry(mapid);
14509 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
14511 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
14512 if(itr != m_boundInstances[difficulty].end())
14513 return &itr->second;
14514 else
14515 return NULL;
14518 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
14520 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
14521 UnbindInstance(itr, difficulty, unload);
14524 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
14526 if(itr != m_boundInstances[difficulty].end())
14528 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
14529 itr->second.save->RemovePlayer(this); // save can become invalid
14530 m_boundInstances[difficulty].erase(itr++);
14534 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
14536 if(save)
14538 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
14539 if(bind.save)
14541 // update the save when the group kills a boss
14542 if(permanent != bind.perm || save != bind.save)
14543 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());
14545 else
14546 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
14548 if(bind.save != save)
14550 if(bind.save) bind.save->RemovePlayer(this);
14551 save->AddPlayer(this);
14554 if(permanent) save->SetCanReset(false);
14556 bind.save = save;
14557 bind.perm = permanent;
14558 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());
14559 return &bind;
14561 else
14562 return NULL;
14565 void Player::SendRaidInfo()
14567 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
14569 uint32 counter = 0, i;
14570 for(i = 0; i < TOTAL_DIFFICULTIES; i++)
14571 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); itr++)
14572 if(itr->second.perm) counter++;
14574 data << counter;
14575 for(i = 0; i < TOTAL_DIFFICULTIES; i++)
14577 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); itr++)
14579 if(itr->second.perm)
14581 InstanceSave *save = itr->second.save;
14582 data << (save->GetMapId());
14583 data << (uint32)(save->GetResetTime() - time(NULL));
14584 data << save->GetInstanceId();
14585 data << uint32(counter);
14586 counter--;
14590 GetSession()->SendPacket(&data);
14594 - called on every successful teleportation to a map
14596 void Player::SendSavedInstances()
14598 bool hasBeenSaved = false;
14599 WorldPacket data;
14601 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14603 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
14605 if(itr->second.perm) // only permanent binds are sent
14607 hasBeenSaved = true;
14608 break;
14613 //Send opcode 811. true or flase means, whether you have current raid/heroic instances
14614 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
14615 data << uint32(hasBeenSaved);
14616 GetSession()->SendPacket(&data);
14618 if(!hasBeenSaved)
14619 return;
14621 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14623 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
14625 if(itr->second.perm)
14627 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
14628 data << uint32(itr->second.save->GetMapId());
14629 GetSession()->SendPacket(&data);
14635 /// convert the player's binds to the group
14636 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
14638 bool has_binds = false;
14639 bool has_solo = false;
14641 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
14642 assert(player_guid);
14644 // copy all binds to the group, when changing leader it's assumed the character
14645 // will not have any solo binds
14647 if(player)
14649 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14651 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
14653 has_binds = true;
14654 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
14655 // permanent binds are not removed
14656 if(!itr->second.perm)
14658 player->UnbindInstance(itr, i, true); // increments itr
14659 has_solo = true;
14661 else
14662 ++itr;
14667 // if the player's not online we don't know what binds it has
14668 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));
14669 // the following should not get executed when changing leaders
14670 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
14673 bool Player::_LoadHomeBind(QueryResult *result)
14675 bool ok = false;
14676 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
14677 if (result)
14679 Field *fields = result->Fetch();
14680 m_homebindMapId = fields[0].GetUInt32();
14681 m_homebindZoneId = fields[1].GetUInt16();
14682 m_homebindX = fields[2].GetFloat();
14683 m_homebindY = fields[3].GetFloat();
14684 m_homebindZ = fields[4].GetFloat();
14685 delete result;
14687 // accept saved data only for valid position (and non instanceable)
14688 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
14689 !sMapStore.LookupEntry(m_homebindMapId)->Instanceable() )
14691 ok = true;
14693 else
14694 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
14697 if(!ok)
14699 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
14700 if(!info) return false;
14702 m_homebindMapId = info->mapId;
14703 m_homebindZoneId = info->zoneId;
14704 m_homebindX = info->positionX;
14705 m_homebindY = info->positionY;
14706 m_homebindZ = info->positionZ;
14708 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);
14711 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",
14712 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
14714 return true;
14717 /*********************************************************/
14718 /*** SAVE SYSTEM ***/
14719 /*********************************************************/
14721 void Player::SaveToDB()
14723 // delay auto save at any saves (manual, in code, or autosave)
14724 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
14726 // first save/honor gain after midnight will also update the player's honor fields
14727 UpdateHonorFields();
14729 // Must saved before enter into BattleGround
14730 if(InBattleGround())
14731 return;
14733 int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
14734 //save, far from tavern/city
14735 //save, but in tavern/city
14736 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
14737 outDebugValues();
14739 // save state (after auras removing), if aura remove some flags then it must set it back by self)
14740 uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
14741 uint32 tmp_bytes2 = GetUInt32Value(UNIT_FIELD_BYTES_2);
14742 uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
14743 uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
14744 uint32 tmp_displayid = GetDisplayId();
14746 // Set player sit state to standing on save, also stealth and shifted form
14747 SetByteValue(UNIT_FIELD_BYTES_1, 0, 0); // stand state
14748 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0); // shapeshift
14749 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0); // stand flags?
14750 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_ROTATE);
14751 SetDisplayId(GetNativeDisplayId());
14753 bool inworld = IsInWorld();
14755 CharacterDatabase.BeginTransaction();
14757 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
14759 std::string sql_name = m_name;
14760 CharacterDatabase.escape_string(sql_name);
14762 std::ostringstream ss;
14763 ss << "INSERT INTO characters (guid,account,name,race,class,"
14764 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
14765 "taximask, online, cinematic, "
14766 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
14767 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
14768 "death_expire_time, taxi_path) VALUES ("
14769 << GetGUIDLow() << ", "
14770 << GetSession()->GetAccountId() << ", '"
14771 << sql_name << "', "
14772 << m_race << ", "
14773 << m_class << ", ";
14775 bool save_to_dest = false;
14776 if(IsBeingTeleported())
14778 // don't save to battlegrounds or arenas
14779 const MapEntry *entry = sMapStore.LookupEntry(GetTeleportDest().mapid);
14780 if(entry && entry->map_type != MAP_BATTLEGROUND && entry->map_type != MAP_ARENA)
14781 save_to_dest = true;
14784 if(!save_to_dest)
14786 ss << GetMapId() << ", "
14787 << (uint32)GetDifficulty() << ", "
14788 << finiteAlways(GetPositionX()) << ", "
14789 << finiteAlways(GetPositionY()) << ", "
14790 << finiteAlways(GetPositionZ()) << ", "
14791 << finiteAlways(GetOrientation()) << ", '";
14793 else
14795 ss << GetTeleportDest().mapid << ", "
14796 << (uint32)GetDifficulty() << ", "
14797 << finiteAlways(GetTeleportDest().x) << ", "
14798 << finiteAlways(GetTeleportDest().y) << ", "
14799 << finiteAlways(GetTeleportDest().z) << ", "
14800 << finiteAlways(GetTeleportDest().o) << ", '";
14803 uint16 i;
14804 for( i = 0; i < m_valuesCount; i++ )
14806 ss << GetUInt32Value(i) << " ";
14809 ss << "', '";
14811 for( i = 0; i < 8; i++ )
14812 ss << m_taxi.GetTaximask(i) << " ";
14814 ss << "', ";
14815 ss << (inworld ? 1 : 0);
14817 ss << ", ";
14818 ss << m_cinematic;
14820 ss << ", ";
14821 ss << m_Played_time[0];
14822 ss << ", ";
14823 ss << m_Played_time[1];
14825 ss << ", ";
14826 ss << finiteAlways(m_rest_bonus);
14827 ss << ", ";
14828 ss << (uint64)time(NULL);
14829 ss << ", ";
14830 ss << is_save_resting;
14831 ss << ", ";
14832 ss << m_resetTalentsCost;
14833 ss << ", ";
14834 ss << (uint64)m_resetTalentsTime;
14836 ss << ", ";
14837 ss << finiteAlways(m_movementInfo.t_x);
14838 ss << ", ";
14839 ss << finiteAlways(m_movementInfo.t_y);
14840 ss << ", ";
14841 ss << finiteAlways(m_movementInfo.t_z);
14842 ss << ", ";
14843 ss << finiteAlways(m_movementInfo.t_o);
14844 ss << ", ";
14845 if (m_transport)
14846 ss << m_transport->GetGUIDLow();
14847 else
14848 ss << "0";
14850 ss << ", ";
14851 ss << m_ExtraFlags;
14853 ss << ", ";
14854 ss << uint32(m_stableSlots); // to prevent save uint8 as char
14856 ss << ", ";
14857 ss << uint32(m_atLoginFlags);
14859 ss << ", ";
14860 ss << GetZoneId();
14862 ss << ", ";
14863 ss << (uint64)m_deathExpireTime;
14865 ss << ", '";
14866 ss << m_taxi.SaveTaxiDestinationsToString();
14867 ss << "' )";
14869 CharacterDatabase.Execute( ss.str().c_str() );
14871 if(m_mailsUpdated) //save mails only when needed
14872 _SaveMail();
14874 _SaveInventory();
14875 _SaveQuestStatus();
14876 _SaveDailyQuestStatus();
14877 _SaveTutorials();
14878 _SaveSpells();
14879 _SaveSpellCooldowns();
14880 _SaveActions();
14881 _SaveAuras();
14882 _SaveReputation();
14884 CharacterDatabase.CommitTransaction();
14886 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
14887 SetDisplayId(tmp_displayid);
14888 SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
14889 SetUInt32Value(UNIT_FIELD_BYTES_2, tmp_bytes2);
14890 SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
14891 SetUInt32Value(PLAYER_FLAGS, tmp_pflags);
14893 // save pet (hunter pet level and experience and all type pets health/mana).
14894 if(Pet* pet = GetPet())
14895 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
14898 // fast save function for item/money cheating preventing - save only inventory and money state
14899 void Player::SaveInventoryAndGoldToDB()
14901 _SaveInventory();
14902 SetUInt32ValueInDB(PLAYER_FIELD_COINAGE,GetMoney(),GetGUID());
14905 void Player::_SaveActions()
14907 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
14909 switch (itr->second.uState)
14911 case ACTIONBUTTON_NEW:
14912 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
14913 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc );
14914 itr->second.uState = ACTIONBUTTON_UNCHANGED;
14915 ++itr;
14916 break;
14917 case ACTIONBUTTON_CHANGED:
14918 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
14919 (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc, GetGUIDLow(), (uint32)itr->first );
14920 itr->second.uState = ACTIONBUTTON_UNCHANGED;
14921 ++itr;
14922 break;
14923 case ACTIONBUTTON_DELETED:
14924 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
14925 m_actionButtons.erase(itr++);
14926 break;
14927 default:
14928 ++itr;
14929 break;
14934 void Player::_SaveAuras()
14936 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14938 AuraMap const& auras = GetAuras();
14939 for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
14941 SpellEntry const *spellInfo = itr->second->GetSpellProto();
14943 //skip all auras from spells that are passive or need a shapeshift
14944 if (itr->second->IsPassive() || itr->second->IsRemovedOnShapeLost())
14945 continue;
14947 //do not save single target auras (unless they were cast by the player)
14948 if (itr->second->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo))
14949 continue;
14951 uint8 i;
14952 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
14953 for (i = 0; i < 3; i++)
14954 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
14955 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
14956 break;
14958 if (i == 3)
14960 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());
14961 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges) "
14962 "VALUES ('%u', '" I64FMTD "' ,'%u', '%u', '%d', '%d', '%d', '%d')",
14963 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));
14968 void Player::_SaveInventory()
14970 // force items in buyback slots to new state
14971 // and remove those that aren't already
14972 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; i++)
14974 Item *item = m_items[i];
14975 if (!item || item->GetState() == ITEM_NEW) continue;
14976 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
14977 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
14978 m_items[i]->FSetState(ITEM_NEW);
14981 // update enchantment durations
14982 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
14984 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
14987 // if no changes
14988 if (m_itemUpdateQueue.empty()) return;
14990 // do not save if the update queue is corrupt
14991 bool error = false;
14992 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
14994 Item *item = m_itemUpdateQueue[i];
14995 if(!item || item->GetState() == ITEM_REMOVED) continue;
14996 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
14998 if (test == NULL)
15000 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());
15001 error = true;
15003 else if (test != item)
15005 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());
15006 error = true;
15010 if (error)
15012 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15013 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15014 return;
15017 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15019 Item *item = m_itemUpdateQueue[i];
15020 if(!item) continue;
15022 Bag *container = item->GetContainer();
15023 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15025 switch(item->GetState())
15027 case ITEM_NEW:
15028 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());
15029 break;
15030 case ITEM_CHANGED:
15031 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());
15032 break;
15033 case ITEM_REMOVED:
15034 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15035 break;
15036 case ITEM_UNCHANGED:
15037 break;
15040 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15042 m_itemUpdateQueue.clear();
15045 void Player::_SaveMail()
15047 if (!m_mailsLoaded)
15048 return;
15050 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); itr++)
15052 Mail *m = (*itr);
15053 if (m->state == MAIL_STATE_CHANGED)
15055 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'",
15056 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15057 if(m->removedItems.size())
15059 for(std::vector<uint32>::iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15060 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15061 m->removedItems.clear();
15063 m->state = MAIL_STATE_UNCHANGED;
15065 else if (m->state == MAIL_STATE_DELETED)
15067 if (m->HasItems())
15068 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15069 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15070 if (m->itemTextId)
15071 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15072 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15073 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15077 //deallocate deleted mails...
15078 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15080 if ((*itr)->state == MAIL_STATE_DELETED)
15082 Mail* m = *itr;
15083 m_mail.erase(itr);
15084 delete m;
15085 itr = m_mail.begin();
15087 else
15088 ++itr;
15091 m_mailsUpdated = false;
15094 void Player::_SaveQuestStatus()
15096 // we don't need transactions here.
15097 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15099 switch (i->second.uState)
15101 case QUEST_NEW :
15102 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15103 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15104 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]);
15105 break;
15106 case QUEST_CHANGED :
15107 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' ",
15108 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 );
15109 break;
15110 case QUEST_UNCHANGED:
15111 break;
15113 i->second.uState = QUEST_UNCHANGED;
15117 void Player::_SaveDailyQuestStatus()
15119 if(!m_DailyQuestChanged)
15120 return;
15122 m_DailyQuestChanged = false;
15124 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15126 // we don't need transactions here.
15127 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15128 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15129 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
15130 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD "')",
15131 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
15134 void Player::_SaveReputation()
15136 for(FactionStateList::iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
15138 if (itr->second.Changed)
15140 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u' AND faction='%u'", GetGUIDLow(), itr->second.ID);
15141 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);
15142 itr->second.Changed = false;
15147 void Player::_SaveSpells()
15149 for (PlayerSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
15151 ++next;
15152 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
15153 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
15154 if (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED)
15155 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);
15157 if (itr->second->state == PLAYERSPELL_REMOVED)
15158 _removeSpell(itr->first);
15159 else
15160 itr->second->state = PLAYERSPELL_UNCHANGED;
15164 void Player::_SaveTutorials()
15166 if(!m_TutorialsChanged)
15167 return;
15169 uint32 Rows=0;
15170 // it's better than rebuilding indexes multiple times
15171 QueryResult *result = CharacterDatabase.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID );
15172 if(result)
15174 Rows = result->Fetch()[0].GetUInt32();
15175 delete result;
15178 if (Rows)
15180 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'",
15181 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 );
15183 else
15185 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]);
15188 m_TutorialsChanged = false;
15191 void Player::outDebugValues() const
15193 if(!sLog.IsOutDebug()) // optimize disabled debug output
15194 return;
15196 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
15197 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
15198 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
15199 sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
15200 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
15201 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
15202 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
15203 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
15204 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
15205 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
15206 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
15207 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
15210 /*********************************************************/
15211 /*** FLOOD FILTER SYSTEM ***/
15212 /*********************************************************/
15214 void Player::UpdateSpeakTime()
15216 // ignore chat spam protection for GMs in any mode
15217 if(GetSession()->GetSecurity() > SEC_PLAYER)
15218 return;
15220 time_t current = time (NULL);
15221 if(m_speakTime > current)
15223 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
15224 if(!max_count)
15225 return;
15227 ++m_speakCount;
15228 if(m_speakCount >= max_count)
15230 // prevent overwrite mute time, if message send just before mutes set, for example.
15231 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
15232 if(GetSession()->m_muteTime < new_mute)
15233 GetSession()->m_muteTime = new_mute;
15235 m_speakCount = 0;
15238 else
15239 m_speakCount = 0;
15241 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
15244 bool Player::CanSpeak() const
15246 return GetSession()->m_muteTime <= time (NULL);
15249 /*********************************************************/
15250 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15251 /*********************************************************/
15253 void Player::SendAttackSwingNotInRange()
15255 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
15256 GetSession()->SendPacket( &data );
15259 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
15261 std::ostringstream ss;
15262 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
15263 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
15264 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
15265 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15266 sLog.outDebug(ss.str().c_str());
15267 CharacterDatabase.Execute(ss.str().c_str());
15270 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
15272 std::ostringstream ss2;
15273 ss2<<"UPDATE characters SET data='";
15274 int i=0;
15275 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
15277 ss2<<tokens[i]<<" ";
15279 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15281 return CharacterDatabase.Execute(ss2.str().c_str());
15284 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
15286 char buf[11];
15287 snprintf(buf,11,"%u",value);
15289 if(index >= tokens.size())
15290 return;
15292 tokens[index] = buf;
15295 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
15297 Tokens tokens;
15298 if(!LoadValuesArrayFromDB(tokens,guid))
15299 return;
15301 if(index >= tokens.size())
15302 return;
15304 char buf[11];
15305 snprintf(buf,11,"%u",value);
15306 tokens[index] = buf;
15308 SaveValuesArrayInDB(tokens,guid);
15311 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
15313 uint32 temp;
15314 memcpy(&temp, &value, sizeof(value));
15315 Player::SetUInt32ValueInDB(index, temp, guid);
15318 void Player::SendAttackSwingNotStanding()
15320 WorldPacket data(SMSG_ATTACKSWING_NOTSTANDING, 0);
15321 GetSession()->SendPacket( &data );
15324 void Player::SendAttackSwingDeadTarget()
15326 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
15327 GetSession()->SendPacket( &data );
15330 void Player::SendAttackSwingCantAttack()
15332 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
15333 GetSession()->SendPacket( &data );
15336 void Player::SendAttackSwingCancelAttack()
15338 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
15339 GetSession()->SendPacket( &data );
15342 void Player::SendAttackSwingBadFacingAttack()
15344 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
15345 GetSession()->SendPacket( &data );
15348 void Player::SendAutoRepeatCancel()
15350 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, 0);
15351 GetSession()->SendPacket( &data );
15354 void Player::PlaySound(uint32 Sound, bool OnlySelf)
15356 WorldPacket data(SMSG_PLAY_SOUND, 4);
15357 data << Sound;
15358 if (OnlySelf)
15359 GetSession()->SendPacket( &data );
15360 else
15361 SendMessageToSet( &data, true );
15364 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
15366 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
15367 data << Area;
15368 data << Experience;
15369 GetSession()->SendPacket(&data);
15372 void Player::SendDungeonDifficulty(bool IsInGroup)
15374 uint8 val = 0x00000001;
15375 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
15376 data << (uint32)GetDifficulty();
15377 data << uint32(val);
15378 data << uint32(IsInGroup);
15379 GetSession()->SendPacket(&data);
15382 void Player::SendResetFailedNotify(uint32 mapid)
15384 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
15385 data << uint32(mapid);
15386 GetSession()->SendPacket(&data);
15389 /// Reset all solo instances and optionally send a message on success for each
15390 void Player::ResetInstances(uint8 method)
15392 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
15394 // we assume that when the difficulty changes, all instances that can be reset will be
15395 uint8 dif = GetDifficulty();
15397 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
15399 InstanceSave *p = itr->second.save;
15400 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
15401 if(!entry || !p->CanReset())
15403 ++itr;
15404 continue;
15407 if(method == INSTANCE_RESET_ALL)
15409 // the "reset all instances" method can only reset normal maps
15410 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
15412 ++itr;
15413 continue;
15417 // if the map is loaded, reset it
15418 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
15419 if(map && map->IsDungeon())
15420 ((InstanceMap*)map)->Reset(method);
15422 // since this is a solo instance there should not be any players inside
15423 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
15424 SendResetInstanceSuccess(p->GetMapId());
15426 p->DeleteFromDB();
15427 m_boundInstances[dif].erase(itr++);
15429 // the following should remove the instance save from the manager and delete it as well
15430 p->RemovePlayer(this);
15434 void Player::SendResetInstanceSuccess(uint32 MapId)
15436 WorldPacket data(SMSG_INSTANCE_RESET, 4);
15437 data << MapId;
15438 GetSession()->SendPacket(&data);
15441 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
15443 // TODO: find what other fail reasons there are besides players in the instance
15444 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
15445 data << reason;
15446 data << MapId;
15447 GetSession()->SendPacket(&data);
15450 /*********************************************************/
15451 /*** Update timers ***/
15452 /*********************************************************/
15454 ///checks the 15 afk reports per 5 minutes limit
15455 void Player::UpdateAfkReport(time_t currTime)
15457 if(m_bgAfkReportedTimer <= currTime)
15459 m_bgAfkReportedCount = 0;
15460 m_bgAfkReportedTimer = currTime+5*MINUTE;
15464 void Player::UpdateContestedPvP(uint32 diff)
15466 if(!m_contestedPvPTimer||isInCombat())
15467 return;
15468 if(m_contestedPvPTimer <= diff)
15470 ResetContestedPvP();
15472 else
15473 m_contestedPvPTimer -= diff;
15476 void Player::UpdatePvPFlag(time_t currTime)
15478 if(!IsPvP())
15479 return;
15480 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
15481 return;
15483 UpdatePvP(false);
15486 void Player::UpdateDuelFlag(time_t currTime)
15488 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
15489 return;
15491 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
15492 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
15494 duel->startTimer = 0;
15495 duel->startTime = currTime;
15496 duel->opponent->duel->startTimer = 0;
15497 duel->opponent->duel->startTime = currTime;
15500 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
15502 if(!pet)
15503 pet = GetPet();
15505 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
15507 //returning of reagents only for players, so best done here
15508 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
15509 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
15511 if(spellInfo)
15513 for(uint32 i = 0; i < 7; ++i)
15515 if(spellInfo->Reagent[i] > 0)
15517 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
15518 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
15519 if( msg == EQUIP_ERR_OK )
15521 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
15522 if(IsInWorld())
15523 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
15528 m_temporaryUnsummonedPetNumber = 0;
15531 if(!pet || pet->GetOwnerGUID()!=GetGUID())
15532 return;
15534 // only if current pet in slot
15535 switch(pet->getPetType())
15537 case MINI_PET:
15538 m_miniPet = 0;
15539 break;
15540 case GUARDIAN_PET:
15541 m_guardianPets.erase(pet->GetGUID());
15542 break;
15543 default:
15544 if(GetPetGUID()==pet->GetGUID())
15545 SetPet(0);
15546 break;
15549 pet->CombatStop();
15551 if(returnreagent)
15553 switch(pet->GetEntry())
15555 //warlock pets except imp are removed(?) when logging out
15556 case 1860:
15557 case 1863:
15558 case 417:
15559 case 17252:
15560 mode = PET_SAVE_NOT_IN_SLOT;
15561 break;
15565 pet->SavePetToDB(mode);
15567 pet->CleanupsBeforeDelete();
15568 pet->AddObjectToRemoveList();
15569 pet->m_removed = true;
15571 if(pet->isControlled())
15573 WorldPacket data(SMSG_PET_SPELLS, 8);
15574 data << uint64(0);
15575 GetSession()->SendPacket(&data);
15577 if(GetGroup())
15578 SetGroupUpdateFlag(GROUP_UPDATE_PET);
15582 void Player::RemoveMiniPet()
15584 if(Pet* pet = GetMiniPet())
15586 pet->Remove(PET_SAVE_AS_DELETED);
15587 m_miniPet = 0;
15591 Pet* Player::GetMiniPet()
15593 if(!m_miniPet)
15594 return NULL;
15595 return ObjectAccessor::GetPet(m_miniPet);
15598 void Player::RemoveGuardians()
15600 while(!m_guardianPets.empty())
15602 uint64 guid = *m_guardianPets.begin();
15603 if(Pet* pet = ObjectAccessor::GetPet(guid))
15604 pet->Remove(PET_SAVE_AS_DELETED);
15606 m_guardianPets.erase(guid);
15610 bool Player::HasGuardianWithEntry(uint32 entry)
15612 // pet guid middle part is entry (and creature also)
15613 // and in guardian list must be guardians with same entry _always_
15614 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
15615 if(GUID_ENPART(*itr)==entry)
15616 return true;
15618 return false;
15621 void Player::Uncharm()
15623 Unit* charm = GetCharm();
15624 if(!charm)
15625 return;
15627 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
15628 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
15631 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, std::string text, uint32 language) const
15633 *data << (uint8)msgtype;
15634 *data << (uint32)language;
15635 *data << (uint64)GetGUID();
15636 *data << (uint32)language; //language 2.1.0 ?
15637 *data << (uint64)GetGUID();
15638 *data << (uint32)(text.length()+1);
15639 *data << text;
15640 *data << (uint8)chatTag();
15643 void Player::Say(const std::string text, const uint32 language)
15645 WorldPacket data(SMSG_MESSAGECHAT, 200);
15646 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
15647 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
15650 void Player::Yell(const std::string text, const uint32 language)
15652 WorldPacket data(SMSG_MESSAGECHAT, 200);
15653 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
15654 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
15657 void Player::TextEmote(const std::string text)
15659 WorldPacket data(SMSG_MESSAGECHAT, 200);
15660 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
15661 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
15664 void Player::Whisper(std::string text, uint32 language,uint64 receiver)
15666 if (language != LANG_ADDON) // if not addon data
15667 language = LANG_UNIVERSAL; // whispers should always be readable
15669 Player *rPlayer = objmgr.GetPlayer(receiver);
15671 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
15672 if(!rPlayer->isDND() || isGameMaster())
15674 WorldPacket data(SMSG_MESSAGECHAT, 200);
15675 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
15676 rPlayer->GetSession()->SendPacket(&data);
15678 data.Initialize(SMSG_MESSAGECHAT, 200);
15679 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
15680 GetSession()->SendPacket(&data);
15682 else
15684 // announce to player that player he is whispering to is dnd and cannot receive his message
15685 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
15688 if(!isAcceptWhispers())
15690 SetAcceptWhispers(true);
15691 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
15694 // announce to player that player he is whispering to is afk
15695 if(rPlayer->isAFK())
15696 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
15698 // if player whisper someone, auto turn of dnd to be able to receive an answer
15699 if(isDND() && !rPlayer->isGameMaster())
15700 ToggleDND();
15703 void Player::PetSpellInitialize()
15705 Pet* pet = GetPet();
15707 if(pet)
15709 uint8 addlist = 0;
15711 sLog.outDebug("Pet Spells Groups");
15713 CreatureInfo const *cinfo = pet->GetCreatureInfo();
15715 if(pet->isControlled() && (pet->getPetType() == HUNTER_PET || cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK))
15717 for(PetSpellMap::iterator itr = pet->m_spells.begin();itr != pet->m_spells.end();itr++)
15719 if(itr->second->state == PETSPELL_REMOVED)
15720 continue;
15721 ++addlist;
15725 // first line + actionbar + spellcount + spells + last adds
15726 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);
15728 CharmInfo *charmInfo = pet->GetCharmInfo();
15730 //16
15731 data << (uint64)pet->GetGUID() << uint32(0x00000000) << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
15733 for(uint32 i = 0; i < 10; i++) //40
15735 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
15738 data << uint8(addlist); //1
15740 if(addlist && pet->isControlled())
15742 for (PetSpellMap::iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
15744 if(itr->second->state == PETSPELL_REMOVED)
15745 continue;
15747 data << uint16(itr->first);
15748 data << uint16(itr->second->active); // pet spell active state isn't boolean
15752 //data << uint8(0x01) << uint32(0x6010) << uint32(0x01) << uint32(0x05) << uint16(0x00); //15
15753 uint8 count = 3; //1+8+8+8=25
15755 // if count = 0, then end of packet...
15756 data << count;
15757 // uint32 value is spell id...
15758 // uint64 value is constant 0, unknown...
15759 data << uint32(0x6010) << uint64(0); // if count = 1, 2 or 3
15760 //data << uint32(0x5fd1) << uint64(0); // if count = 2
15761 data << uint32(0x8e8c) << uint64(0); // if count = 3
15762 data << uint32(0x8e8b) << uint64(0); // if count = 3
15764 GetSession()->SendPacket(&data);
15768 void Player::PossessSpellInitialize()
15770 Unit* charm = GetCharm();
15772 if(!charm)
15773 return;
15775 CharmInfo *charmInfo = charm->GetCharmInfo();
15777 if(!charmInfo)
15779 sLog.outError("Player::PossessSpellInitialize(): charm ("I64FMTD") has no charminfo!", charm->GetGUID());
15780 return;
15783 uint8 addlist = 0;
15784 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
15786 //16
15787 data << (uint64)charm->GetGUID() << uint32(0x00000000) << uint8(0) << uint8(0) << uint16(0);
15789 for(uint32 i = 0; i < 10; i++) //40
15791 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
15794 data << uint8(addlist); //1
15796 uint8 count = 3;
15797 data << count;
15798 data << uint32(0x6010) << uint64(0); // if count = 1, 2 or 3
15799 data << uint32(0x8e8c) << uint64(0); // if count = 3
15800 data << uint32(0x8e8b) << uint64(0); // if count = 3
15802 GetSession()->SendPacket(&data);
15805 void Player::CharmSpellInitialize()
15807 Unit* charm = GetCharm();
15809 if(!charm)
15810 return;
15812 CharmInfo *charmInfo = charm->GetCharmInfo();
15813 if(!charmInfo)
15815 sLog.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD") has no charminfo!", charm->GetGUID());
15816 return;
15819 uint8 addlist = 0;
15821 if(charm->GetTypeId() != TYPEID_PLAYER)
15823 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
15825 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
15827 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
15829 if(charmInfo->GetCharmSpell(i)->spellId)
15830 ++addlist;
15835 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
15837 data << (uint64)charm->GetGUID() << uint32(0x00000000);
15839 if(charm->GetTypeId() != TYPEID_PLAYER)
15840 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState());
15841 else
15842 data << uint8(0) << uint8(0);
15844 data << uint16(0);
15846 for(uint32 i = 0; i < 10; i++) //40
15848 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
15851 data << uint8(addlist); //1
15853 if(addlist)
15855 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
15857 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
15858 if(cspell->spellId)
15860 data << uint16(cspell->spellId);
15861 data << uint16(cspell->active);
15866 uint8 count = 3;
15867 data << count;
15868 data << uint32(0x6010) << uint64(0); // if count = 1, 2 or 3
15869 data << uint32(0x8e8c) << uint64(0); // if count = 3
15870 data << uint32(0x8e8b) << uint64(0); // if count = 3
15872 GetSession()->SendPacket(&data);
15875 int32 Player::GetTotalFlatMods(uint32 spellId, SpellModOp op)
15877 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
15878 if (!spellInfo) return 0;
15879 int32 total = 0;
15880 for (SpellModList::iterator itr = m_spellMods[op].begin(); itr != m_spellMods[op].end(); ++itr)
15882 SpellModifier *mod = *itr;
15884 if(!IsAffectedBySpellmod(spellInfo,mod))
15885 continue;
15887 if (mod->type == SPELLMOD_FLAT)
15888 total += mod->value;
15890 return total;
15893 int32 Player::GetTotalPctMods(uint32 spellId, SpellModOp op)
15895 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
15896 if (!spellInfo) return 0;
15897 int32 total = 0;
15898 for (SpellModList::iterator itr = m_spellMods[op].begin(); itr != m_spellMods[op].end(); ++itr)
15900 SpellModifier *mod = *itr;
15902 if(!IsAffectedBySpellmod(spellInfo,mod))
15903 continue;
15905 if (mod->type == SPELLMOD_PCT)
15906 total += mod->value;
15908 return total;
15911 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
15913 if (!mod || !spellInfo)
15914 return false;
15916 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
15918 // prevent apply to any spell except spell that trigger expire
15919 if(spell)
15921 if(mod->lastAffected != spell)
15922 return false;
15924 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
15925 return false;
15928 return spellmgr.IsAffectedBySpell(spellInfo,mod->spellId,mod->effectId,mod->mask);
15931 void Player::AddSpellMod(SpellModifier* mod, bool apply)
15933 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
15935 for(int eff=0;eff<64;++eff)
15937 uint64 _mask = uint64(1) << eff;
15938 if ( mod->mask & _mask)
15940 int32 val = 0;
15941 for (SpellModList::iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
15943 if ((*itr)->type == mod->type && (*itr)->mask & _mask)
15944 val += (*itr)->value;
15946 val += apply ? mod->value : -(mod->value);
15947 WorldPacket data(Opcode, (1+1+4));
15948 data << uint8(eff);
15949 data << uint8(mod->op);
15950 data << int32(val);
15951 SendDirectMessage(&data);
15955 if (apply)
15956 m_spellMods[mod->op].push_back(mod);
15957 else
15959 if (mod->charges == -1)
15960 --m_SpellModRemoveCount;
15961 m_spellMods[mod->op].remove(mod);
15962 delete mod;
15966 void Player::RemoveSpellMods(Spell const* spell)
15968 if(!spell || (m_SpellModRemoveCount == 0))
15969 return;
15971 for(int i=0;i<MAX_SPELLMOD;++i)
15973 for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
15975 SpellModifier *mod = *itr;
15976 ++itr;
15978 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
15980 RemoveAurasDueToSpell(mod->spellId);
15981 if (m_spellMods[i].empty())
15982 break;
15983 else
15984 itr = m_spellMods[i].begin();
15990 // send Proficiency
15991 void Player::SendProficiency(uint8 pr1, uint32 pr2)
15993 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
15994 data << pr1 << pr2;
15995 GetSession()->SendPacket (&data);
15998 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16000 QueryResult *result = NULL;
16001 if(type==10)
16002 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16003 else
16004 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16005 if(result)
16007 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.
16008 { // and SendPetitionQueryOpcode reads data from the DB
16009 Field *fields = result->Fetch();
16010 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16011 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16013 // send update if charter owner in game
16014 Player* owner = objmgr.GetPlayer(ownerguid);
16015 if(owner)
16016 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16018 } while ( result->NextRow() );
16020 delete result;
16022 if(type==10)
16023 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16024 else
16025 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16028 CharacterDatabase.BeginTransaction();
16029 if(type == 10)
16031 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16032 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16034 else
16036 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16037 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16039 CharacterDatabase.CommitTransaction();
16042 void Player::SetRestBonus (float rest_bonus_new)
16044 // Prevent resting on max level
16045 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16046 rest_bonus_new = 0;
16048 if(rest_bonus_new < 0)
16049 rest_bonus_new = 0;
16051 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16053 if(rest_bonus_new > rest_bonus_max)
16054 m_rest_bonus = rest_bonus_max;
16055 else
16056 m_rest_bonus = rest_bonus_new;
16058 // update data for client
16059 if(m_rest_bonus>10)
16060 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16061 else if(m_rest_bonus<=1)
16062 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16064 //RestTickUpdate
16065 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16068 void Player::HandleStealthedUnitsDetection()
16070 std::list<Unit*> stealthedUnits;
16072 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16073 Cell cell(p);
16074 cell.data.Part.reserved = ALL_DISTRICT;
16075 cell.SetNoCreate();
16077 MaNGOS::AnyStealthedCheck u_check;
16078 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(stealthedUnits, u_check);
16080 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16081 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16083 CellLock<GridReadGuard> cell_lock(cell, p);
16084 cell_lock->Visit(cell_lock, world_unit_searcher, *MapManager::Instance().GetMap(GetMapId(), this));
16085 cell_lock->Visit(cell_lock, grid_unit_searcher, *MapManager::Instance().GetMap(GetMapId(), this));
16087 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
16089 if((*i)==this)
16091 i = stealthedUnits.erase(i);
16092 continue;
16095 if ((*i)->isVisibleForOrDetect(this,true))
16098 (*i)->SendUpdateToPlayer(this);
16099 m_clientGUIDs.insert((*i)->GetGUID());
16101 #ifdef MANGOS_DEBUG
16102 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16103 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
16104 #endif
16106 // target aura duration for caster show only if target exist at caster client
16107 // send data at target visibility change (adding to client)
16108 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
16109 SendAuraDurationsForTarget(*i);
16111 i = stealthedUnits.erase(i);
16112 continue;
16115 ++i;
16119 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, uint32 mount_id, Creature* npc)
16121 if(nodes.size() < 2)
16122 return false;
16124 // not let cheating with start flight mounted
16125 if(IsMounted())
16127 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16128 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
16129 GetSession()->SendPacket(&data);
16130 return false;
16133 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16135 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16136 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
16137 GetSession()->SendPacket(&data);
16138 return false;
16141 // 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
16142 if(GetSession()->isLogingOut() ||
16143 (!m_currentSpells[CURRENT_GENERIC_SPELL] ||
16144 m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Effect[0] != SPELL_EFFECT_SEND_TAXI)&&
16145 IsNonMeleeSpellCasted(false) ||
16146 isInCombat())
16148 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16149 data << uint32(ERR_TAXIPLAYERBUSY);
16150 GetSession()->SendPacket(&data);
16151 return false;
16154 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
16155 return false;
16157 uint32 sourcenode = nodes[0];
16159 // starting node too far away (cheat?)
16160 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
16161 if( !node || node->map_id != GetMapId() ||
16162 (node->x - GetPositionX())*(node->x - GetPositionX())+
16163 (node->y - GetPositionY())*(node->y - GetPositionY())+
16164 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
16165 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE) )
16167 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16168 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16169 GetSession()->SendPacket(&data);
16170 return false;
16173 // Prepare to flight start now
16175 // stop combat at start taxi flight if any
16176 CombatStop();
16178 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16179 TradeCancel(true);
16181 // clean not finished taxi path if any
16182 m_taxi.ClearTaxiDestinations();
16184 // 0 element current node
16185 m_taxi.AddTaxiDestination(sourcenode);
16187 // fill destinations path tail
16188 uint32 sourcepath = 0;
16189 uint32 totalcost = 0;
16191 uint32 prevnode = sourcenode;
16192 uint32 lastnode = 0;
16194 for(uint32 i = 1; i < nodes.size(); ++i)
16196 uint32 path, cost;
16198 lastnode = nodes[i];
16199 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
16201 if(!path)
16203 m_taxi.ClearTaxiDestinations();
16204 return false;
16207 totalcost += cost;
16209 if(prevnode == sourcenode)
16210 sourcepath = path;
16212 m_taxi.AddTaxiDestination(lastnode);
16214 prevnode = lastnode;
16217 if(!mount_id) // if not provide then attempt use default.
16218 mount_id = objmgr.GetTaxiMount(sourcenode, GetTeam());
16220 if (mount_id == 0 || sourcepath == 0)
16222 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16223 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16224 GetSession()->SendPacket(&data);
16225 m_taxi.ClearTaxiDestinations();
16226 return false;
16229 uint32 money = GetMoney();
16231 if(npc)
16233 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
16236 if(money < totalcost)
16238 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16239 data << uint32(ERR_TAXINOTENOUGHMONEY);
16240 GetSession()->SendPacket(&data);
16241 m_taxi.ClearTaxiDestinations();
16242 return false;
16245 //Checks and preparations done, DO FLIGHT
16246 ModifyMoney(-(int32)totalcost);
16248 // prevent stealth flight
16249 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
16251 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16252 data << uint32(ERR_TAXIOK);
16253 GetSession()->SendPacket(&data);
16255 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16257 GetSession()->SendDoFlight(mount_id, sourcepath);
16259 return true;
16262 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
16264 // last check 2.0.10
16265 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
16266 data << GetGUID();
16267 data << uint8(0x0); // flags (0x1, 0x2)
16268 time_t curTime = time(NULL);
16269 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
16271 if (itr->second->state == PLAYERSPELL_REMOVED)
16272 continue;
16273 uint32 unSpellId = itr->first;
16274 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
16275 if (!spellInfo)
16277 ASSERT(spellInfo);
16278 continue;
16281 // Not send cooldown for this spells
16282 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
16283 continue;
16285 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
16287 data << unSpellId;
16288 data << unTimeMs; // in m.secs
16289 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/1000);
16292 GetSession()->SendPacket(&data);
16295 void Player::InitDataForForm(bool reapplyMods)
16297 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
16298 if(ssEntry && ssEntry->attackSpeed)
16300 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
16301 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
16302 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
16304 else
16305 SetRegularAttackTime();
16307 switch(m_form)
16309 case FORM_CAT:
16311 if(getPowerType()!=POWER_ENERGY)
16312 setPowerType(POWER_ENERGY);
16313 break;
16315 case FORM_BEAR:
16316 case FORM_DIREBEAR:
16318 if(getPowerType()!=POWER_RAGE)
16319 setPowerType(POWER_RAGE);
16320 break;
16322 default: // 0, for example
16324 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
16325 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
16326 setPowerType(Powers(cEntry->powerType));
16327 break;
16331 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
16332 if (!reapplyMods)
16333 UpdateEquipSpellsAtFormChange();
16335 UpdateAttackPowerAndDamage();
16336 UpdateAttackPowerAndDamage(true);
16339 // Return true is the bought item has a max count to force refresh of window by caller
16340 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
16342 // cheating attempt
16343 if(count < 1) count = 1;
16345 if(!isAlive())
16346 return false;
16348 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
16349 if( !pProto )
16351 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
16352 return false;
16355 Creature *pCreature = ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid,UNIT_NPC_FLAG_VENDOR);
16356 if (!pCreature)
16358 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
16359 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
16360 return false;
16363 VendorItemData const* vItems = pCreature->GetVendorItems();
16364 if(!vItems || vItems->Empty())
16366 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16367 return false;
16370 size_t vendor_slot = vItems->FindItemSlot(item);
16371 if(vendor_slot >= vItems->GetItemCount())
16373 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16374 return false;
16377 VendorItem const* crItem = vItems->m_items[vendor_slot];
16379 // check current item amount if it limited
16380 if( crItem->maxcount != 0 )
16382 if(pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
16384 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
16385 return false;
16389 if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
16391 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
16392 return false;
16395 if(crItem->ExtendedCost)
16397 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16398 if(!iece)
16400 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
16401 return false;
16404 // honor points price
16405 if(GetHonorPoints() < (iece->reqhonorpoints * count))
16407 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
16408 return false;
16411 // arena points price
16412 if(GetArenaPoints() < (iece->reqarenapoints * count))
16414 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
16415 return false;
16418 // item base price
16419 for (uint8 i = 0; i < 5; ++i)
16421 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
16423 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
16424 return false;
16428 // check for personal arena rating requirement
16429 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
16431 // probably not the proper equip err
16432 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
16433 return false;
16437 uint32 price = pProto->BuyPrice * count;
16439 // reputation discount
16440 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
16442 if( GetMoney() < price )
16444 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
16445 return false;
16448 uint8 bag = 0; // init for case invalid bagGUID
16450 if (bagguid != NULL_BAG && slot != NULL_SLOT)
16452 Bag *pBag;
16453 if( bagguid == GetGUID() )
16455 bag = INVENTORY_SLOT_BAG_0;
16457 else
16459 for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;i++)
16461 pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i);
16462 if( pBag )
16464 if( bagguid == pBag->GetGUID() )
16466 bag = i;
16467 break;
16474 if( IsInventoryPos( bag, slot ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
16476 ItemPosCountVec dest;
16477 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
16478 if( msg != EQUIP_ERR_OK )
16480 SendEquipError( msg, NULL, NULL );
16481 return false;
16484 ModifyMoney( -(int32)price );
16485 if(crItem->ExtendedCost) // case for new honor system
16487 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16488 if(iece->reqhonorpoints)
16489 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
16490 if(iece->reqarenapoints)
16491 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
16492 for (uint8 i = 0; i < 5; ++i)
16494 if(iece->reqitem[i])
16495 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
16499 if(Item *it = StoreNewItem( dest, item, true ))
16501 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
16503 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
16504 data << pCreature->GetGUID();
16505 data << (uint32)(vendor_slot+1); // numbered from 1 at client
16506 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
16507 data << (uint32)count;
16508 GetSession()->SendPacket(&data);
16510 SendNewItem(it, pProto->BuyCount*count, true, false, false);
16513 else if( IsEquipmentPos( bag, slot ) )
16515 uint16 dest;
16516 uint8 msg = CanEquipNewItem( slot, dest, item, pProto->BuyCount * count, false );
16517 if( msg != EQUIP_ERR_OK )
16519 SendEquipError( msg, NULL, NULL );
16520 return false;
16523 ModifyMoney( -(int32)price );
16524 if(crItem->ExtendedCost) // case for new honor system
16526 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16527 if(iece->reqhonorpoints)
16528 ModifyHonorPoints( - int32(iece->reqhonorpoints));
16529 if(iece->reqarenapoints)
16530 ModifyArenaPoints( - int32(iece->reqarenapoints));
16531 for (uint8 i = 0; i < 5; ++i)
16533 if(iece->reqitem[i])
16534 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
16538 if(Item *it = EquipNewItem( dest, item, pProto->BuyCount * count, true ))
16540 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
16542 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
16543 data << pCreature->GetGUID();
16544 data << (uint32)(vendor_slot+1); // numbered from 1 at client
16545 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
16546 data << (uint32)count;
16547 GetSession()->SendPacket(&data);
16549 SendNewItem(it, pProto->BuyCount*count, true, false, false);
16551 AutoUnequipOffhandIfNeed();
16554 else
16556 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
16557 return false;
16560 return crItem->maxcount!=0;
16563 uint32 Player::GetMaxPersonalArenaRatingRequirement()
16565 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
16566 // the personal rating of the arena team must match the required limit as well
16567 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
16568 uint32 max_personal_rating = 0;
16569 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
16571 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
16573 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
16574 uint32 t_rating = at->GetRating();
16575 p_rating = p_rating<t_rating? p_rating : t_rating;
16576 if(max_personal_rating < p_rating)
16577 max_personal_rating = p_rating;
16580 return max_personal_rating;
16583 void Player::UpdateHomebindTime(uint32 time)
16585 // GMs never get homebind timer online
16586 if (m_InstanceValid || isGameMaster())
16588 if(m_HomebindTimer) // instance valid, but timer not reset
16590 // hide reminder
16591 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
16592 data << uint32(0);
16593 data << uint32(0);
16594 GetSession()->SendPacket(&data);
16596 // instance is valid, reset homebind timer
16597 m_HomebindTimer = 0;
16599 else if (m_HomebindTimer > 0)
16601 if (time >= m_HomebindTimer)
16603 // teleport to homebind location
16604 TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
16606 else
16607 m_HomebindTimer -= time;
16609 else
16611 // instance is invalid, start homebind timer
16612 m_HomebindTimer = 60000;
16613 // send message to player
16614 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
16615 data << m_HomebindTimer;
16616 data << uint32(1);
16617 GetSession()->SendPacket(&data);
16618 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
16622 void Player::UpdatePvP(bool state, bool ovrride)
16624 if(!state || ovrride)
16626 SetPvP(state);
16627 if(Pet* pet = GetPet())
16628 pet->SetPvP(state);
16629 if(Unit* charmed = GetCharm())
16630 charmed->SetPvP(state);
16632 pvpInfo.endTimer = 0;
16634 else
16636 if(pvpInfo.endTimer != 0)
16637 pvpInfo.endTimer = time(NULL);
16638 else
16640 SetPvP(state);
16642 if(Pet* pet = GetPet())
16643 pet->SetPvP(state);
16644 if(Unit* charmed = GetCharm())
16645 charmed->SetPvP(state);
16650 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
16652 SpellCooldown sc;
16653 sc.end = end_time;
16654 sc.itemid = itemid;
16655 m_spellCooldowns[spellid] = sc;
16658 void Player::SendCooldownEvent(SpellEntry const *spellInfo)
16660 if ( !(spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE) )
16661 return;
16663 // Get spell cooldwn
16664 int32 cooldown = GetSpellRecoveryTime(spellInfo);
16665 // Apply spellmods
16666 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, cooldown);
16667 if (cooldown < 0)
16668 cooldown = 0;
16669 // Add cooldown
16670 AddSpellCooldown(spellInfo->Id, 0, time(NULL) + cooldown / 1000);
16671 // Send activate
16672 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
16673 data << spellInfo->Id;
16674 data << GetGUID();
16675 SendDirectMessage(&data);
16677 //slot to be excluded while counting
16678 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
16680 if(!enchantmentcondition)
16681 return true;
16683 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
16685 if(!Condition)
16686 return true;
16688 uint8 curcount[4] = {0, 0, 0, 0};
16690 //counting current equipped gem colors
16691 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
16693 if(i == slot)
16694 continue;
16695 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
16696 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
16698 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
16700 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
16701 if(!enchant_id)
16702 continue;
16704 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
16705 if(!enchantEntry)
16706 continue;
16708 uint32 gemid = enchantEntry->GemID;
16709 if(!gemid)
16710 continue;
16712 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
16713 if(!gemProto)
16714 continue;
16716 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
16717 if(!gemProperty)
16718 continue;
16720 uint8 GemColor = gemProperty->color;
16722 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
16724 if(tmpcolormask & GemColor)
16725 ++curcount[b];
16731 bool activate = true;
16733 for(int i = 0; i < 5; i++)
16735 if(!Condition->Color[i])
16736 continue;
16738 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
16740 // if have <CompareColor> use them as count, else use <value> from Condition
16741 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
16743 switch(Condition->Comparator[i])
16745 case 2: // requires less <color> than (<value> || <comparecolor>) gems
16746 activate &= (_cur_gem < _cmp_gem) ? true : false;
16747 break;
16748 case 3: // requires more <color> than (<value> || <comparecolor>) gems
16749 activate &= (_cur_gem > _cmp_gem) ? true : false;
16750 break;
16751 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
16752 activate &= (_cur_gem >= _cmp_gem) ? true : false;
16753 break;
16757 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");
16759 return activate;
16762 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
16764 //cycle all equipped items
16765 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
16767 //enchants for the slot being socketed are handled by Player::ApplyItemMods
16768 if(slot == exceptslot)
16769 continue;
16771 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
16773 if(!pItem || !pItem->GetProto()->Socket[0].Color)
16774 continue;
16776 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
16778 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
16779 if(!enchant_id)
16780 continue;
16782 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
16783 if(!enchantEntry)
16784 continue;
16786 uint32 condition = enchantEntry->EnchantmentCondition;
16787 if(condition)
16789 //was enchant active with/without item?
16790 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
16791 //should it now be?
16792 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
16794 // ignore item gem conditions
16795 //if state changed, (dis)apply enchant
16796 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
16803 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
16804 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
16806 //cycle all equipped items
16807 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
16809 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
16810 if(slot == exceptslot)
16811 continue;
16813 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
16815 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
16816 continue;
16818 //cycle all (gem)enchants
16819 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
16821 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
16822 if(!enchant_id) //if no enchant go to next enchant(slot)
16823 continue;
16825 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
16826 if(!enchantEntry)
16827 continue;
16829 //only metagems to be (de)activated, so only enchants with condition
16830 uint32 condition = enchantEntry->EnchantmentCondition;
16831 if(condition)
16832 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
16837 void Player::LeaveBattleground(bool teleportToEntryPoint)
16839 if(BattleGround *bg = GetBattleGround())
16841 bool need_debuf = bg->isBattleGround() && (bg->GetStatus() == STATUS_IN_PROGRESS) && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER);
16843 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
16845 // call after remove to be sure that player resurrected for correct cast
16846 if(need_debuf)
16847 CastSpell(this, 26013, true); // Deserter
16851 bool Player::CanJoinToBattleground() const
16853 // check Deserter debuff
16854 if(GetDummyAura(26013))
16855 return false;
16857 return true;
16860 bool Player::CanReportAfkDueToLimit()
16862 // a player can complain about 15 people per 5 minutes
16863 if(m_bgAfkReportedCount >= 15)
16864 return false;
16865 ++m_bgAfkReportedCount;
16866 return true;
16869 ///This player has been blamed to be inactive in a battleground
16870 void Player::ReportedAfkBy(Player* reporter)
16872 BattleGround *bg = GetBattleGround();
16873 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
16874 return;
16876 // check if player has 'Idle' or 'Inactive' debuff
16877 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
16879 m_bgAfkReporter.insert(reporter->GetGUIDLow());
16880 // 3 players have to complain to apply debuff
16881 if(m_bgAfkReporter.size() >= 3)
16883 // cast 'Idle' spell
16884 CastSpell(this, 43680, true);
16885 m_bgAfkReporter.clear();
16890 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
16892 // gamemaster in GM mode see all, including ghosts
16893 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
16894 return true;
16896 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
16897 if (InBattleGround())
16899 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
16900 return false;
16901 return true;
16904 // Live player see live player or dead player with not realized corpse
16905 if(pl->isAlive() || pl->m_deathTimer > 0)
16907 return isAlive() || m_deathTimer > 0;
16910 // Ghost see other friendly ghosts, that's for sure
16911 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
16912 return true;
16914 // Dead player see live players near own corpse
16915 if(isAlive())
16917 Corpse *corpse = pl->GetCorpse();
16918 if(corpse)
16920 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
16921 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
16922 return true;
16926 // and not see any other
16927 return false;
16930 bool Player::IsVisibleGloballyFor( Player* u ) const
16932 if(!u)
16933 return false;
16935 // Always can see self
16936 if (u==this)
16937 return true;
16939 // Visible units, always are visible for all players
16940 if (GetVisibility() == VISIBILITY_ON)
16941 return true;
16943 // GMs are visible for higher gms (or players are visible for gms)
16944 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
16945 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
16947 // non faction visibility non-breakable for non-GMs
16948 if (GetVisibility() == VISIBILITY_OFF)
16949 return false;
16951 // non-gm stealth/invisibility not hide from global player lists
16952 return true;
16955 void Player::UpdateVisibilityOf(WorldObject* target)
16957 if(HaveAtClient(target))
16959 if(!target->isVisibleForInState(this,true))
16961 target->DestroyForPlayer(this);
16962 m_clientGUIDs.erase(target->GetGUID());
16964 #ifdef MANGOS_DEBUG
16965 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16966 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
16967 #endif
16970 else
16972 if(target->isVisibleForInState(this,false))
16974 target->SendUpdateToPlayer(this);
16975 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
16976 m_clientGUIDs.insert(target->GetGUID());
16978 #ifdef MANGOS_DEBUG
16979 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16980 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
16981 #endif
16983 // target aura duration for caster show only if target exist at caster client
16984 // send data at target visibility change (adding to client)
16985 if(target!=this && target->isType(TYPEMASK_UNIT))
16986 SendAuraDurationsForTarget((Unit*)target);
16988 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
16989 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
16994 template<class T>
16995 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
16997 s64.insert(target->GetGUID());
17000 template<>
17001 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
17003 if(!target->IsTransport())
17004 s64.insert(target->GetGUID());
17007 template<class T>
17008 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
17010 if(HaveAtClient(target))
17012 if(!target->isVisibleForInState(this,true))
17014 target->BuildOutOfRangeUpdateBlock(&data);
17015 m_clientGUIDs.erase(target->GetGUID());
17017 #ifdef MANGOS_DEBUG
17018 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17019 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));
17020 #endif
17023 else
17025 if(target->isVisibleForInState(this,false))
17027 visibleNow.insert(target);
17028 target->BuildUpdate(data_updates);
17029 target->BuildCreateUpdateBlockForPlayer(&data, this);
17030 UpdateVisibilityOf_helper(m_clientGUIDs,target);
17032 #ifdef MANGOS_DEBUG
17033 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17034 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));
17035 #endif
17040 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17041 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17042 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17043 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17044 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17046 void Player::InitPrimaryProffesions()
17048 SetFreePrimaryProffesions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
17051 void Player::SendComboPoints()
17053 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
17054 if (combotarget)
17056 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
17057 data.append(combotarget->GetPackGUID());
17058 data << uint8(m_comboPoints);
17059 GetSession()->SendPacket(&data);
17063 void Player::AddComboPoints(Unit* target, int8 count)
17065 if(!count)
17066 return;
17068 // without combo points lost (duration checked in aura)
17069 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17071 if(target->GetGUID() == m_comboTarget)
17073 m_comboPoints += count;
17075 else
17077 if(m_comboTarget)
17078 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17079 target->RemoveComboPointHolder(GetGUIDLow());
17081 m_comboTarget = target->GetGUID();
17082 m_comboPoints = count;
17084 target->AddComboPointHolder(GetGUIDLow());
17087 if (m_comboPoints > 5) m_comboPoints = 5;
17088 if (m_comboPoints < 0) m_comboPoints = 0;
17090 SendComboPoints();
17093 void Player::ClearComboPoints()
17095 if(!m_comboTarget)
17096 return;
17098 // without combopoints lost (duration checked in aura)
17099 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17101 m_comboPoints = 0;
17103 SendComboPoints();
17105 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17106 target->RemoveComboPointHolder(GetGUIDLow());
17108 m_comboTarget = 0;
17111 void Player::SetGroup(Group *group, int8 subgroup)
17113 if(group == NULL) m_group.unlink();
17114 else
17116 // never use SetGroup without a subgroup unless you specify NULL for group
17117 assert(subgroup >= 0);
17118 m_group.link(group, this);
17119 m_group.setSubGroup((uint8)subgroup);
17123 void Player::SendInitialPacketsBeforeAddToMap()
17125 WorldPacket data(SMSG_SET_REST_START, 4);
17126 data << uint32(0); // unknown, may be rest state time or expirience
17127 GetSession()->SendPacket(&data);
17129 // Homebind
17130 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
17131 data << m_homebindX << m_homebindY << m_homebindZ;
17132 data << (uint32) m_homebindMapId;
17133 data << (uint32) m_homebindZoneId;
17134 GetSession()->SendPacket(&data);
17136 // SMSG_SET_PROFICIENCY
17137 // SMSG_UPDATE_AURA_DURATION
17139 // tutorial stuff
17140 data.Initialize(SMSG_TUTORIAL_FLAGS, 8*4);
17141 for (int i = 0; i < 8; ++i)
17142 data << uint32( GetTutorialInt(i) );
17143 GetSession()->SendPacket(&data);
17145 SendInitialSpells();
17147 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
17148 data << uint32(0); // count, for(count) uint32;
17149 GetSession()->SendPacket(&data);
17151 SendInitialActionButtons();
17152 SendInitialReputations();
17153 UpdateZone(GetZoneId());
17154 SendInitWorldStates();
17156 // SMSG_SET_AURA_SINGLE
17158 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
17159 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
17160 data << (float)0.01666667f; // game speed
17161 GetSession()->SendPacket( &data );
17163 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17164 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
17165 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2);
17168 void Player::SendInitialPacketsAfterAddToMap()
17170 CastSpell(this, 836, true); // LOGINEFFECT
17172 // set some aura effects that send packet to player client after add player to map
17173 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17174 // same auras state lost at far teleport, send it one more time in this case also
17175 static const AuraType auratypes[] =
17177 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
17178 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
17179 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
17181 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
17183 Unit::AuraList const& auraList = GetAurasByType(*itr);
17184 if(!auraList.empty())
17185 auraList.front()->ApplyModifier(true,true);
17188 if(HasAuraType(SPELL_AURA_MOD_STUN))
17189 SetMovement(MOVE_ROOT);
17191 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17192 if(HasAuraType(SPELL_AURA_MOD_ROOT))
17194 WorldPacket data(SMSG_FORCE_MOVE_ROOT, 10);
17195 data.append(GetPackGUID());
17196 data << (uint32)2;
17197 SendMessageToSet(&data,true);
17200 SendEnchantmentDurations(); // must be after add to map
17201 SendItemDurations(); // must be after add to map
17204 void Player::SendUpdateToOutOfRangeGroupMembers()
17206 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
17207 return;
17208 if(Group* group = GetGroup())
17209 group->UpdatePlayerOutOfRange(this);
17211 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
17212 m_auraUpdateMask = 0;
17213 if(Pet *pet = GetPet())
17214 pet->ResetAuraUpdateMask();
17217 void Player::SendTransferAborted(uint32 mapid, uint16 reason)
17219 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
17220 data << uint32(mapid);
17221 data << uint16(reason); // transfer abort reason
17222 GetSession()->SendPacket(&data);
17225 void Player::SendInstanceResetWarning(uint32 mapid, uint32 time)
17227 // type of warning, based on the time remaining until reset
17228 uint32 type;
17229 if(time > 3600)
17230 type = RAID_INSTANCE_WELCOME;
17231 else if(time > 900 && time <= 3600)
17232 type = RAID_INSTANCE_WARNING_HOURS;
17233 else if(time > 300 && time <= 900)
17234 type = RAID_INSTANCE_WARNING_MIN;
17235 else
17236 type = RAID_INSTANCE_WARNING_MIN_SOON;
17237 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4);
17238 data << uint32(type);
17239 data << uint32(mapid);
17240 data << uint32(time);
17241 GetSession()->SendPacket(&data);
17244 void Player::ApplyEquipCooldown( Item * pItem )
17246 for(int i = 0; i <5; ++i)
17248 _Spell const& spellData = pItem->GetProto()->Spells[i];
17250 // no spell
17251 if( !spellData.SpellId )
17252 continue;
17254 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
17255 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
17256 continue;
17258 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
17260 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
17261 data << pItem->GetGUID();
17262 data << uint32(spellData.SpellId);
17263 GetSession()->SendPacket(&data);
17267 void Player::resetSpells()
17269 // not need after this call
17270 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
17272 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_SPELLS;
17273 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS), GetGUIDLow());
17276 // make full copy of map (spells removed and marked as deleted at another spell remove
17277 // and we can't use original map for safe iterative with visit each spell at loop end
17278 PlayerSpellMap smap = GetSpellMap();
17280 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
17281 removeSpell(iter->first); // only iter->first can be accessed, object by iter->second can be deleted already
17283 learnDefaultSpells();
17284 learnQuestRewardedSpells();
17287 void Player::learnDefaultSpells(bool loading)
17289 // learn default race/class spells
17290 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
17291 std::list<CreateSpellPair>::const_iterator spell_itr;
17292 for (spell_itr = info->spell.begin(); spell_itr!=info->spell.end(); ++spell_itr)
17294 uint16 tspell = spell_itr->first;
17295 if (tspell)
17297 sLog.outDebug("PLAYER: Adding initial spell, id = %u",tspell);
17298 if(loading || !spell_itr->second) // not care about passive spells or loading case
17299 addSpell(tspell,spell_itr->second);
17300 else // but send in normal spell in game learn case
17301 learnSpell(tspell);
17306 void Player::learnQuestRewardedSpells(Quest const* quest)
17308 uint32 spell_id = quest->GetRewSpellCast();
17310 // skip quests without rewarded spell
17311 if( !spell_id )
17312 return;
17314 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
17315 if(!spellInfo)
17316 return;
17318 // check learned spells state
17319 bool found = false;
17320 for(int i=0; i < 3; ++i)
17322 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
17324 found = true;
17325 break;
17329 // skip quests with not teaching spell or already known spell
17330 if(!found)
17331 return;
17333 // prevent learn non first rank unknown profession and second specialization for same profession)
17334 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
17335 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
17337 // not have first rank learned (unlearned prof?)
17338 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
17339 if( !HasSpell(first_spell) )
17340 return;
17342 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
17343 if(!learnedInfo)
17344 return;
17346 // specialization
17347 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
17349 // search other specialization for same prof
17350 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17352 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
17353 continue;
17355 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
17356 if(!itrInfo)
17357 return;
17359 // compare only specializations
17360 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
17361 continue;
17363 // compare same chain spells
17364 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
17365 continue;
17367 // now we have 2 specialization, learn possible only if found is lesser specialization rank
17368 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
17369 return;
17374 CastSpell( this, spell_id, true);
17377 void Player::learnQuestRewardedSpells()
17379 // learn spells received from quest completing
17380 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
17382 // skip no rewarded quests
17383 if(!itr->second.m_rewarded)
17384 continue;
17386 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
17387 if( !quest )
17388 continue;
17390 learnQuestRewardedSpells(quest);
17394 void Player::learnSkillRewardedSpells(uint32 skill_id )
17396 uint32 raceMask = getRaceMask();
17397 uint32 classMask = getClassMask();
17398 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
17400 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
17401 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
17402 continue;
17403 // Check race if set
17404 if (pAbility->racemask && !(pAbility->racemask & raceMask))
17405 continue;
17406 // Check class if set
17407 if (pAbility->classmask && !(pAbility->classmask & classMask))
17408 continue;
17410 if (SpellEntry const* spellentry = sSpellStore.LookupEntry(pAbility->spellId))
17412 // Ok need learn spell
17413 learnSpell(pAbility->spellId);
17418 void Player::learnSkillRewardedSpells()
17420 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
17422 if(!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
17423 continue;
17425 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
17427 learnSkillRewardedSpells(pskill);
17431 void Player::SendAuraDurationsForTarget(Unit* target)
17433 for(Unit::AuraMap::const_iterator itr = target->GetAuras().begin(); itr != target->GetAuras().end(); ++itr)
17435 Aura* aura = itr->second;
17436 if(aura->GetAuraSlot() >= MAX_AURAS || aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
17437 continue;
17439 aura->SendAuraDurationForCaster(this);
17443 void Player::SetDailyQuestStatus( uint32 quest_id )
17445 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
17447 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
17449 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
17450 m_lastDailyQuestTime = time(NULL); // last daily quest time
17451 m_DailyQuestChanged = true;
17452 break;
17457 void Player::ResetDailyQuestStatus()
17459 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
17460 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
17462 // DB data deleted in caller
17463 m_DailyQuestChanged = false;
17464 m_lastDailyQuestTime = 0;
17467 BattleGround* Player::GetBattleGround() const
17469 if(GetBattleGroundId()==0)
17470 return NULL;
17472 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
17475 bool Player::InArena() const
17477 BattleGround *bg = GetBattleGround();
17478 if(!bg || !bg->isArena())
17479 return false;
17481 return true;
17484 bool Player::GetBGAccessByLevel(uint32 bgTypeId) const
17486 BattleGround *bg = sBattleGroundMgr.GetBattleGround(bgTypeId);
17487 if(!bg)
17488 return false;
17490 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
17491 return false;
17493 return true;
17496 uint32 Player::GetMinLevelForBattleGroundQueueId(uint32 queue_id)
17498 if(queue_id < 1)
17499 return 0;
17501 if(queue_id >=6)
17502 queue_id = 6;
17504 return 10*(queue_id+1);
17507 uint32 Player::GetMaxLevelForBattleGroundQueueId(uint32 queue_id)
17509 if(queue_id >=6)
17510 return 255; // hardcoded max level
17512 return 10*(queue_id+2)-1;
17515 uint32 Player::GetBattleGroundQueueIdFromLevel() const
17517 uint32 level = getLevel();
17518 if(level <= 19)
17519 return 0;
17520 else if (level > 69)
17521 return 6;
17522 else
17523 return level/10 - 1; // 20..29 -> 1, 30-39 -> 2, ...
17526 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
17528 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
17529 if(!vendor_faction)
17530 return 1.0f;
17532 ReputationRank rank = GetReputationRank(vendor_faction->faction);
17533 if(rank <= REP_NEUTRAL)
17534 return 1.0f;
17536 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
17539 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
17541 uint32 racemask = getRaceMask();
17542 uint32 classmask = getClassMask();
17544 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
17545 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
17547 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
17549 // skip wrong race skills
17550 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
17551 return false;
17553 // skip wrong class skills
17554 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
17555 return false;
17557 return true;
17560 bool Player::HasQuestForGO(int32 GOId)
17562 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
17564 QuestStatusData qs=i->second;
17565 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
17567 Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
17568 if(!qinfo)
17569 continue;
17571 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
17572 continue;
17574 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
17576 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
17577 continue;
17579 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
17580 return true;
17584 return false;
17587 void Player::UpdateForQuestsGO()
17589 if(m_clientGUIDs.empty())
17590 return;
17592 UpdateData udata;
17593 WorldPacket packet;
17594 for(ClientGUIDs::iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
17596 if(IS_GAMEOBJECT_GUID(*itr))
17598 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
17599 if(obj)
17600 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
17603 udata.BuildPacket(&packet);
17604 GetSession()->SendPacket(&packet);
17607 void Player::SummonIfPossible(bool agree)
17609 if(!agree)
17611 m_summon_expire = 0;
17612 return;
17615 // expire and auto declined
17616 if(m_summon_expire < time(NULL))
17617 return;
17619 // stop taxi flight at summon
17620 if(isInFlight())
17622 GetMotionMaster()->MovementExpired();
17623 m_taxi.ClearTaxiDestinations();
17626 // drop flag at summon
17627 if(BattleGround *bg = GetBattleGround())
17628 bg->EventPlayerDroppedFlag(this);
17630 m_summon_expire = 0;
17632 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
17635 void Player::RemoveItemDurations( Item *item )
17637 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
17639 if(*itr==item)
17641 m_itemDuration.erase(itr);
17642 break;
17647 void Player::AddItemDurations( Item *item )
17649 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
17651 m_itemDuration.push_back(item);
17652 item->SendTimeUpdate(this);
17656 void Player::AutoUnequipOffhandIfNeed()
17658 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
17659 if(!offItem)
17660 return;
17662 Item *mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );
17664 if(!mainItem || mainItem->GetProto()->InventoryType != INVTYPE_2HWEAPON)
17665 return;
17667 ItemPosCountVec off_dest;
17668 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
17669 if( off_msg == EQUIP_ERR_OK )
17671 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
17672 StoreItem( off_dest, offItem, true );
17674 else
17676 sLog.outError("Player::EquipItem: Can's store offhand item at 2hand item equip for player (GUID: %u).",GetGUIDLow());
17680 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
17682 if(spellInfo->EquippedItemClass < 0)
17683 return true;
17685 // scan other equipped items for same requirements (mostly 2 daggers/etc)
17686 // for optimize check 2 used cases only
17687 switch(spellInfo->EquippedItemClass)
17689 case ITEM_CLASS_WEAPON:
17691 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
17692 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
17693 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
17694 return true;
17695 break;
17697 case ITEM_CLASS_ARMOR:
17699 // tabard not have dependent spells
17700 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
17701 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
17702 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
17703 return true;
17705 // shields can be equipped to offhand slot
17706 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
17707 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
17708 return true;
17710 // ranged slot can have some armor subclasses
17711 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
17712 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
17713 return true;
17715 break;
17717 default:
17718 sLog.outError("HasItemFitToSpellReqirements: Not handeled spell reqirement for item class %u",spellInfo->EquippedItemClass);
17719 break;
17722 return false;
17725 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
17727 AuraMap& auras = GetAuras();
17728 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
17730 Aura* aura = itr->second;
17732 // skip passive (passive item dependent spells work in another way) and not self applied auras
17733 SpellEntry const* spellInfo = aura->GetSpellProto();
17734 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
17736 ++itr;
17737 continue;
17740 // skip if not item dependent or have alternative item
17741 if(HasItemFitToSpellReqirements(spellInfo,pItem))
17743 ++itr;
17744 continue;
17747 // no alt item, remove aura, restart check
17748 RemoveAurasDueToSpell(aura->GetId());
17749 itr = auras.begin();
17752 // currently casted spells can be dependent from item
17753 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
17755 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
17756 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
17757 InterruptSpell(i);
17761 uint32 Player::GetResurrectionSpellId()
17763 // search priceless resurrection possabilities
17764 uint32 prio = 0;
17765 uint32 spell_id = 0;
17766 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
17767 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
17769 // Soulstone Resurrection // prio: 3 (max, non death persistent)
17770 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
17772 switch((*itr)->GetId())
17774 case 20707: spell_id = 3026; break; // rank 1
17775 case 20762: spell_id = 20758; break; // rank 2
17776 case 20763: spell_id = 20759; break; // rank 3
17777 case 20764: spell_id = 20760; break; // rank 4
17778 case 20765: spell_id = 20761; break; // rank 5
17779 case 27239: spell_id = 27240; break; // rank 6
17780 default:
17781 sLog.outError("Unhandled spell %%u: S.Resurrection",(*itr)->GetId());
17782 continue;
17785 prio = 3;
17787 // Twisting Nether // prio: 2 (max)
17788 else if((*itr)->GetId()==23701 && roll_chance_i(10))
17790 prio = 2;
17791 spell_id = 23700;
17795 // Reincarnation (passive spell) // prio: 1
17796 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
17797 spell_id = 21169;
17799 return spell_id;
17802 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
17804 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
17806 // prepare data for near group iteration (PvP and !PvP cases)
17807 uint32 xp = 0;
17808 bool honored_kill = false;
17810 if(Group *pGroup = GetGroup())
17812 uint32 count = 0;
17813 uint32 sum_level = 0;
17814 Player* member_with_max_level = NULL;
17815 Player* not_gray_member_with_max_level = NULL;
17817 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
17819 if(member_with_max_level)
17821 /// not get Xp in PvP or no not gray players in group
17822 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
17824 /// skip in check PvP case (for speed, not used)
17825 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
17826 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
17827 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
17829 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
17831 Player* pGroupGuy = itr->getSource();
17832 if(!pGroupGuy)
17833 continue;
17835 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
17836 continue; // member (alive or dead) or his corpse at req. distance
17838 // honor can be in PvP and !PvP (racial leader) cases (for alive)
17839 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
17840 honored_kill = true;
17842 // xp and reputation only in !PvP case
17843 if(!PvP)
17845 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
17847 // if is in dungeon then all receive full reputation at kill
17848 // rewarded any alive/dead/near_corpse group member
17849 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
17851 // XP updated only for alive group member
17852 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
17853 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
17855 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
17857 pGroupGuy->GiveXP(itr_xp, pVictim);
17858 if(Pet* pet = pGroupGuy->GetPet())
17859 pet->GivePetXP(itr_xp/2);
17862 // quest objectives updated only for alive group member or dead but with not released body
17863 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
17865 // normal creature (not pet/etc) can be only in !PvP case
17866 if(pVictim->GetTypeId()==TYPEID_UNIT)
17867 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
17873 else // if (!pGroup)
17875 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
17877 // honor can be in PvP and !PvP (racial leader) cases
17878 if(RewardHonor(pVictim,1))
17879 honored_kill = true;
17881 // xp and reputation only in !PvP case
17882 if(!PvP)
17884 RewardReputation(pVictim,1);
17885 GiveXP(xp, pVictim);
17887 if(Pet* pet = GetPet())
17888 pet->GivePetXP(xp);
17890 // normal creature (not pet/etc) can be only in !PvP case
17891 if(pVictim->GetTypeId()==TYPEID_UNIT)
17892 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
17895 return xp || honored_kill;
17898 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
17900 if(pRewardSource->GetDistance(this) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
17901 return true;
17903 if(isAlive())
17904 return false;
17906 Corpse* corpse = GetCorpse();
17907 if(!corpse)
17908 return false;
17910 return pRewardSource->GetDistance(corpse) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE);
17913 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
17915 Item* item = GetWeaponForAttack(attType,true);
17917 // unarmmed only with base attack
17918 if(attType != BASE_ATTACK && !item)
17919 return 0;
17921 // weapon skill or (unarmed for base attack)
17922 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
17923 return GetBaseSkillValue(skill);
17926 void Player::ResurectUsingRequestData()
17928 ResurrectPlayer(0.0f,false);
17930 if(GetMaxHealth() > m_resurrectHealth)
17931 SetHealth( m_resurrectHealth );
17932 else
17933 SetHealth( GetMaxHealth() );
17935 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
17936 SetPower(POWER_MANA, m_resurrectMana );
17937 else
17938 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
17940 SetPower(POWER_RAGE, 0 );
17942 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
17944 SpawnCorpseBones();
17946 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
17949 void Player::SetClientControl(Unit* target, uint8 allowMove)
17951 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
17952 data.append(target->GetPackGUID());
17953 data << uint8(allowMove);
17954 GetSession()->SendPacket(&data);
17957 void Player::UpdateZoneDependentAuras( uint32 newZone )
17959 // remove new continent flight forms
17960 if( !isGameMaster() &&
17961 GetVirtualMapForMapAndZone(GetMapId(),newZone) != 530)
17963 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
17964 RemoveSpellsCausingAura(SPELL_AURA_FLY);
17967 // Some spells applied at enter into zone (with subzones)
17968 // Human Illusion
17969 // NOTE: these are removed by RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
17970 if ( newZone == 2367 ) // Old Hillsbrad Foothills
17972 uint32 spellid = 0;
17973 // all horde races
17974 if( GetTeam() == HORDE )
17975 spellid = getGender() == GENDER_FEMALE ? 35481 : 35480;
17976 // and some alliance races
17977 else if( getRace() == RACE_NIGHTELF || getRace() == RACE_DRAENEI )
17978 spellid = getGender() == GENDER_FEMALE ? 35483 : 35482;
17980 if(spellid && !HasAura(spellid,0) )
17981 CastSpell(this,spellid,true);
17985 void Player::UpdateAreaDependentAuras( uint32 newArea )
17987 // remove auras from spells with area limitations
17988 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
17990 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
17991 if(!IsSpellAllowedInLocation(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea))
17992 RemoveAura(iter);
17993 else
17994 ++iter;
17997 // unmount if enter in this subzone
17998 if( newArea == 35)
17999 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
18000 // Dragonmaw Illusion
18001 else if( newArea == 3759 || newArea == 3966 || newArea == 3939 )
18003 if( GetDummyAura(40214) )
18005 if( !HasAura(40216,0) )
18006 CastSpell(this,40216,true);
18007 if( !HasAura(42016,0) )
18008 CastSpell(this,42016,true);
18013 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
18015 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18016 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18018 return copseReclaimDelay[0];
18021 time_t now = time(NULL);
18022 // 0..2 full period
18023 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
18024 return copseReclaimDelay[count];
18027 void Player::UpdateCorpseReclaimDelay()
18029 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
18031 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18032 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18033 return;
18035 time_t now = time(NULL);
18036 if(now < m_deathExpireTime)
18038 // full and partly periods 1..3
18039 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
18040 if(count < MAX_DEATH_COUNT)
18041 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
18042 else
18043 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
18045 else
18046 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
18049 void Player::SendCorpseReclaimDelay(bool load)
18051 Corpse* corpse = GetCorpse();
18052 if(!corpse)
18053 return;
18055 uint32 delay;
18056 if(load)
18058 if(corpse->GetGhostTime() > m_deathExpireTime)
18059 return;
18061 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
18063 uint32 count;
18064 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18065 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18067 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
18068 if(count>=MAX_DEATH_COUNT)
18069 count = MAX_DEATH_COUNT-1;
18071 else
18072 count=0;
18074 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
18076 time_t now = time(NULL);
18077 if(now >= expected_time)
18078 return;
18080 delay = expected_time-now;
18082 else
18083 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
18085 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
18086 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
18087 data << uint32(delay*1000);
18088 GetSession()->SendPacket( &data );
18091 Player* Player::GetNextRandomRaidMember(float radius)
18093 Group *pGroup = GetGroup();
18094 if(!pGroup)
18095 return NULL;
18097 std::vector<Player*> nearMembers;
18098 nearMembers.reserve(pGroup->GetMembersCount());
18100 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18102 Player* Target = itr->getSource();
18104 // IsHostileTo check duel and controlled by enemy
18105 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
18106 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
18107 nearMembers.push_back(Target);
18110 if (nearMembers.empty())
18111 return NULL;
18113 uint32 randTarget = urand(0,nearMembers.size()-1);
18114 return nearMembers[randTarget];
18117 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
18119 float water_z = m->GetWaterLevel(x,y);
18120 float height_z = m->GetHeight(x,y,z, false); // use .map base surface height
18121 uint8 flag1 = m->GetTerrainType(x,y);
18123 //!Underwater check, not in water if underground or above water level
18124 if (height_z <= INVALID_HEIGHT || z < (height_z-2) || z > (water_z - 2) )
18125 m_isunderwater &= 0x7A;
18126 else if ((z < (water_z - 2)) && (flag1 & 0x01))
18127 m_isunderwater |= 0x01;
18129 //!in lava check, anywhere under lava level
18130 if ((height_z <= INVALID_HEIGHT || z < (height_z - 0)) && (flag1 == 0x00) && IsInWater())
18131 m_isunderwater |= 0x80;
18134 void Player::SetCanParry( bool value )
18136 if(m_canParry==value)
18137 return;
18139 m_canParry = value;
18140 UpdateParryPercentage();
18143 void Player::SetCanBlock( bool value )
18145 if(m_canBlock==value)
18146 return;
18148 m_canBlock = value;
18149 UpdateBlockPercentage();
18152 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
18154 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
18155 if(itr->pos == this->pos)
18156 return true;
18158 return false;
18161 bool Player::isAllowUseBattleGroundObject()
18163 return ( //InBattleGround() && // in battleground - not need, check in other cases
18164 !IsMounted() && // not mounted
18165 !HasStealthAura() && // not stealthed
18166 !HasInvisibilityAura() && // not invisible
18167 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
18168 isAlive() // live player