Updated some enums
[getmangos.git] / src / game / Player.cpp
blob7323f45daa3555b8870f943d50d83ab3ef1a7528
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"
61 #include "AchievementMgr.h"
63 #include <cmath>
65 #define ZONE_UPDATE_INTERVAL 1000
67 #define PLAYER_SKILL_INDEX(x) (PLAYER_SKILL_INFO_1_1 + ((x)*3))
68 #define PLAYER_SKILL_VALUE_INDEX(x) (PLAYER_SKILL_INDEX(x)+1)
69 #define PLAYER_SKILL_BONUS_INDEX(x) (PLAYER_SKILL_INDEX(x)+2)
71 #define SKILL_VALUE(x) PAIR32_LOPART(x)
72 #define SKILL_MAX(x) PAIR32_HIPART(x)
73 #define MAKE_SKILL_VALUE(v, m) MAKE_PAIR32(v,m)
75 #define SKILL_TEMP_BONUS(x) int16(PAIR32_LOPART(x))
76 #define SKILL_PERM_BONUS(x) int16(PAIR32_HIPART(x))
77 #define MAKE_SKILL_BONUS(t, p) MAKE_PAIR32(t,p)
79 enum CharacterFlags
81 CHARACTER_FLAG_NONE = 0x00000000,
82 CHARACTER_FLAG_UNK1 = 0x00000001,
83 CHARACTER_FLAG_UNK2 = 0x00000002,
84 CHARACTER_LOCKED_FOR_TRANSFER = 0x00000004,
85 CHARACTER_FLAG_UNK4 = 0x00000008,
86 CHARACTER_FLAG_UNK5 = 0x00000010,
87 CHARACTER_FLAG_UNK6 = 0x00000020,
88 CHARACTER_FLAG_UNK7 = 0x00000040,
89 CHARACTER_FLAG_UNK8 = 0x00000080,
90 CHARACTER_FLAG_UNK9 = 0x00000100,
91 CHARACTER_FLAG_UNK10 = 0x00000200,
92 CHARACTER_FLAG_HIDE_HELM = 0x00000400,
93 CHARACTER_FLAG_HIDE_CLOAK = 0x00000800,
94 CHARACTER_FLAG_UNK13 = 0x00001000,
95 CHARACTER_FLAG_GHOST = 0x00002000,
96 CHARACTER_FLAG_RENAME = 0x00004000,
97 CHARACTER_FLAG_UNK16 = 0x00008000,
98 CHARACTER_FLAG_UNK17 = 0x00010000,
99 CHARACTER_FLAG_UNK18 = 0x00020000,
100 CHARACTER_FLAG_UNK19 = 0x00040000,
101 CHARACTER_FLAG_UNK20 = 0x00080000,
102 CHARACTER_FLAG_UNK21 = 0x00100000,
103 CHARACTER_FLAG_UNK22 = 0x00200000,
104 CHARACTER_FLAG_UNK23 = 0x00400000,
105 CHARACTER_FLAG_UNK24 = 0x00800000,
106 CHARACTER_FLAG_LOCKED_BY_BILLING = 0x01000000,
107 CHARACTER_FLAG_DECLINED = 0x02000000,
108 CHARACTER_FLAG_UNK27 = 0x04000000,
109 CHARACTER_FLAG_UNK28 = 0x08000000,
110 CHARACTER_FLAG_UNK29 = 0x10000000,
111 CHARACTER_FLAG_UNK30 = 0x20000000,
112 CHARACTER_FLAG_UNK31 = 0x40000000,
113 CHARACTER_FLAG_UNK32 = 0x80000000
116 // corpse reclaim times
117 #define DEATH_EXPIRE_STEP (5*MINUTE)
118 #define MAX_DEATH_COUNT 3
120 static uint32 copseReclaimDelay[MAX_DEATH_COUNT] = { 30, 60, 120 };
122 //== PlayerTaxi ================================================
124 PlayerTaxi::PlayerTaxi()
126 // Taxi nodes
127 memset(m_taximask, 0, sizeof(m_taximask));
130 void PlayerTaxi::InitTaxiNodesForLevel(uint32 race, uint32 chrClass, uint32 level)
132 // capital and taxi hub masks
133 switch(race)
135 case RACE_HUMAN: SetTaximaskNode(2); break; // Human
136 case RACE_ORC: SetTaximaskNode(23); break; // Orc
137 case RACE_DWARF: SetTaximaskNode(6); break; // Dwarf
138 case RACE_NIGHTELF: SetTaximaskNode(26);
139 SetTaximaskNode(27); break; // Night Elf
140 case RACE_UNDEAD_PLAYER: SetTaximaskNode(11); break;// Undead
141 case RACE_TAUREN: SetTaximaskNode(22); break; // Tauren
142 case RACE_GNOME: SetTaximaskNode(6); break; // Gnome
143 case RACE_TROLL: SetTaximaskNode(23); break; // Troll
144 case RACE_BLOODELF: SetTaximaskNode(82); break; // Blood Elf
145 case RACE_DRAENEI: SetTaximaskNode(94); break; // Draenei
148 switch(chrClass)
150 case CLASS_DEATH_KNIGHT: // TODO: figure out initial known nodes
151 break;
154 // new continent starting masks (It will be accessible only at new map)
155 switch(Player::TeamForRace(race))
157 case ALLIANCE: SetTaximaskNode(100); break;
158 case HORDE: SetTaximaskNode(99); break;
160 // level dependent taxi hubs
161 if(level>=68)
162 SetTaximaskNode(213); //Shattered Sun Staging Area
165 void PlayerTaxi::LoadTaxiMask(const char* data)
167 Tokens tokens = StrSplit(data, " ");
169 int index;
170 Tokens::iterator iter;
171 for (iter = tokens.begin(), index = 0;
172 (index < TaxiMaskSize) && (iter != tokens.end()); ++iter, ++index)
174 // load and set bits only for existed taxi nodes
175 m_taximask[index] = sTaxiNodesMask[index] & uint32(atol((*iter).c_str()));
179 void PlayerTaxi::AppendTaximaskTo( ByteBuffer& data, bool all )
181 if(all)
183 for (uint8 i=0; i<TaxiMaskSize; i++)
184 data << uint32(sTaxiNodesMask[i]); // all existed nodes
186 else
188 for (uint8 i=0; i<TaxiMaskSize; i++)
189 data << uint32(m_taximask[i]); // known nodes
193 bool PlayerTaxi::LoadTaxiDestinationsFromString( std::string values )
195 ClearTaxiDestinations();
197 Tokens tokens = StrSplit(values," ");
199 for(Tokens::iterator iter = tokens.begin(); iter != tokens.end(); ++iter)
201 uint32 node = uint32(atol(iter->c_str()));
202 AddTaxiDestination(node);
205 if(m_TaxiDestinations.empty())
206 return true;
208 // Check integrity
209 if(m_TaxiDestinations.size() < 2)
210 return false;
212 for(size_t i = 1; i < m_TaxiDestinations.size(); ++i)
214 uint32 cost;
215 uint32 path;
216 objmgr.GetTaxiPath(m_TaxiDestinations[i-1],m_TaxiDestinations[i],path,cost);
217 if(!path)
218 return false;
221 return true;
224 std::string PlayerTaxi::SaveTaxiDestinationsToString()
226 if(m_TaxiDestinations.empty())
227 return "";
229 std::ostringstream ss;
231 for(size_t i=0; i < m_TaxiDestinations.size(); ++i)
232 ss << m_TaxiDestinations[i] << " ";
234 return ss.str();
237 uint32 PlayerTaxi::GetCurrentTaxiPath() const
239 if(m_TaxiDestinations.size() < 2)
240 return 0;
242 uint32 path;
243 uint32 cost;
245 objmgr.GetTaxiPath(m_TaxiDestinations[0],m_TaxiDestinations[1],path,cost);
247 return path;
250 //== Player ====================================================
252 const int32 Player::ReputationRank_Length[MAX_REPUTATION_RANK] = {36000, 3000, 3000, 3000, 6000, 12000, 21000, 1000};
254 UpdateMask Player::updateVisualBits;
256 Player::Player (WorldSession *session): Unit(), m_achievementMgr(this)
258 m_transport = 0;
260 m_speakTime = 0;
261 m_speakCount = 0;
263 m_objectType |= TYPEMASK_PLAYER;
264 m_objectTypeId = TYPEID_PLAYER;
266 m_valuesCount = PLAYER_END;
268 m_session = session;
270 m_divider = 0;
272 m_ExtraFlags = 0;
273 if(GetSession()->GetSecurity() >= SEC_GAMEMASTER)
274 SetAcceptTicket(true);
276 // players always accept
277 if(GetSession()->GetSecurity() == SEC_PLAYER)
278 SetAcceptWhispers(true);
280 m_curSelection = 0;
281 m_lootGuid = 0;
283 m_comboTarget = 0;
284 m_comboPoints = 0;
286 m_usedTalentCount = 0;
288 m_regenTimer = 0;
289 m_weaponChangeTimer = 0;
291 m_zoneUpdateId = 0;
292 m_zoneUpdateTimer = 0;
294 m_areaUpdateId = 0;
296 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
298 // randomize first save time in range [CONFIG_INTERVAL_SAVE] around [CONFIG_INTERVAL_SAVE]
299 // this must help in case next save after mass player load after server startup
300 m_nextSave = urand(m_nextSave/2,m_nextSave*3/2);
302 clearResurrectRequestData();
304 m_SpellModRemoveCount = 0;
306 memset(m_items, 0, sizeof(Item*)*PLAYER_SLOTS_COUNT);
308 m_social = NULL;
310 // group is initialized in the reference constructor
311 SetGroupInvite(NULL);
312 m_groupUpdateMask = 0;
313 m_auraUpdateMask = 0;
315 duel = NULL;
317 m_GuildIdInvited = 0;
318 m_ArenaTeamIdInvited = 0;
320 m_atLoginFlags = AT_LOGIN_NONE;
322 m_dontMove = false;
324 pTrader = 0;
325 ClearTrade();
327 m_cinematic = 0;
329 PlayerTalkClass = new PlayerMenu( GetSession() );
330 m_currentBuybackSlot = BUYBACK_SLOT_START;
332 for ( int aX = 0 ; aX < 8 ; aX++ )
333 m_Tutorials[ aX ] = 0x00;
334 m_TutorialsChanged = false;
336 m_DailyQuestChanged = false;
337 m_lastDailyQuestTime = 0;
339 m_regenTimer = 0;
340 m_weaponChangeTimer = 0;
341 m_breathTimer = 0;
342 m_isunderwater = 0;
343 m_isInWater = false;
344 m_drunkTimer = 0;
345 m_drunk = 0;
346 m_restTime = 0;
347 m_deathTimer = 0;
348 m_deathExpireTime = 0;
350 m_swingErrorMsg = 0;
352 m_DetectInvTimer = 1000;
354 m_bgBattleGroundID = 0;
355 for (int j=0; j < PLAYER_MAX_BATTLEGROUND_QUEUES; j++)
357 m_bgBattleGroundQueueID[j].bgType = 0;
358 m_bgBattleGroundQueueID[j].invited = false;
360 m_bgTeam = 0;
362 m_logintime = time(NULL);
363 m_Last_tick = m_logintime;
364 m_WeaponProficiency = 0;
365 m_ArmorProficiency = 0;
366 m_canParry = false;
367 m_canBlock = false;
368 m_canDualWield = false;
369 m_ammoDPS = 0.0f;
371 m_temporaryUnsummonedPetNumber = 0;
372 //cache for UNIT_CREATED_BY_SPELL to allow
373 //returning reagents for temporarily removed pets
374 //when dying/logging out
375 m_oldpetspell = 0;
377 ////////////////////Rest System/////////////////////
378 time_inn_enter=0;
379 inn_pos_mapid=0;
380 inn_pos_x=0;
381 inn_pos_y=0;
382 inn_pos_z=0;
383 m_rest_bonus=0;
384 rest_type=REST_TYPE_NO;
385 ////////////////////Rest System/////////////////////
387 m_mailsLoaded = false;
388 m_mailsUpdated = false;
389 unReadMails = 0;
390 m_nextMailDelivereTime = 0;
392 m_resetTalentsCost = 0;
393 m_resetTalentsTime = 0;
394 m_itemUpdateQueueBlocked = false;
396 for (int i = 0; i < MAX_MOVE_TYPE; ++i)
397 m_forced_speed_changes[i] = 0;
399 m_stableSlots = 0;
401 /////////////////// Instance System /////////////////////
403 m_HomebindTimer = 0;
404 m_InstanceValid = true;
405 m_dungeonDifficulty = DIFFICULTY_NORMAL;
407 for (int i = 0; i < BASEMOD_END; i++)
409 m_auraBaseMod[i][FLAT_MOD] = 0.0f;
410 m_auraBaseMod[i][PCT_MOD] = 1.0f;
413 // Honor System
414 m_lastHonorUpdateTime = time(NULL);
416 // Player summoning
417 m_summon_expire = 0;
418 m_summon_mapid = 0;
419 m_summon_x = 0.0f;
420 m_summon_y = 0.0f;
421 m_summon_z = 0.0f;
423 //Default movement to run mode
424 m_unit_movement_flags = 0;
426 m_miniPet = 0;
427 m_bgAfkReportedTimer = 0;
428 m_contestedPvPTimer = 0;
430 m_declinedname = NULL;
433 Player::~Player ()
435 CleanupsBeforeDelete();
437 // it must be unloaded already in PlayerLogout and accessed only for loggined player
438 //m_social = NULL;
440 // Note: buy back item already deleted from DB when player was saved
441 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
443 if(m_items[i])
444 delete m_items[i];
446 CleanupChannels();
448 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
449 delete itr->second;
451 //all mailed items should be deleted, also all mail should be deallocated
452 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
453 delete *itr;
455 for (ItemMap::iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
456 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
458 delete PlayerTalkClass;
460 if (m_transport)
462 m_transport->RemovePassenger(this);
465 for(size_t x = 0; x < ItemSetEff.size(); x++)
466 if(ItemSetEff[x])
467 delete ItemSetEff[x];
469 // clean up player-instance binds, may unload some instance saves
470 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
471 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
472 itr->second.save->RemovePlayer(this);
474 delete m_declinedname;
477 void Player::CleanupsBeforeDelete()
479 if(m_uint32Values) // only for fully created Object
481 TradeCancel(false);
482 DuelComplete(DUEL_INTERUPTED);
484 Unit::CleanupsBeforeDelete();
487 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 )
489 //FIXME: outfitId not used in player creating
491 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
493 m_name = name;
495 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
496 if(!info)
498 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
499 return false;
502 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
503 m_items[i] = NULL;
505 //for(int j = BUYBACK_SLOT_START; j < BUYBACK_SLOT_END; j++)
507 // SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1+j*2,0);
508 // SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1+j,0);
509 // SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1+j,0);
512 m_race = race;
513 m_class = class_;
515 SetMapId(info->mapId);
516 Relocate(info->positionX,info->positionY,info->positionZ);
518 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
519 if(!cEntry)
521 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
522 return false;
525 uint8 powertype = cEntry->powerType;
527 uint32 unitfield;
529 switch(powertype)
531 case POWER_ENERGY:
532 case POWER_MANA:
533 unitfield = 0x00000000;
534 break;
535 case POWER_RAGE:
536 unitfield = 0x00110000;
537 break;
538 case POWER_RUNIC_POWER:
539 unitfield = 0x0000EE00; //TODO: find correct unitfield here
540 break;
541 default:
542 sLog.outError("Invalid default powertype %u for player (class %u)",powertype,class_);
543 return false;
546 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE );
547 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f );
549 switch(gender)
551 case GENDER_FEMALE:
552 SetDisplayId(info->displayId_f );
553 SetNativeDisplayId(info->displayId_f );
554 break;
555 case GENDER_MALE:
556 SetDisplayId(info->displayId_m );
557 SetNativeDisplayId(info->displayId_m );
558 break;
559 default:
560 sLog.outError("Invalid gender %u for player",gender);
561 return false;
562 break;
565 setFactionForRace(m_race);
567 SetUInt32Value(UNIT_FIELD_BYTES_0, ( ( race ) | ( class_ << 8 ) | ( gender << 16 ) | ( powertype << 24 ) ) );
568 SetUInt32Value(UNIT_FIELD_BYTES_1, unitfield);
569 SetByteValue(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
570 SetUInt32Value(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
571 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
573 //-1 is default value
574 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
576 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
577 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
578 SetByteValue(PLAYER_BYTES_3, 0, gender);
580 SetUInt32Value( PLAYER_GUILDID, 0 );
581 SetUInt32Value( PLAYER_GUILDRANK, 0 );
582 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
584 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
585 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
586 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
587 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
588 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
589 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
591 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
593 GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i);
594 if(gs && gs->Order)
595 SetGlyphSlot(gs->Order - 1, gs->Id);
598 // set starting level
599 if(getClass() == CLASS_DEATH_KNIGHT)
600 SetUInt32Value(UNIT_FIELD_LEVEL, 55);
601 else
602 SetUInt32Value( UNIT_FIELD_LEVEL, sWorld.getConfig(CONFIG_START_PLAYER_LEVEL) );
604 // Played time
605 m_Last_tick = time(NULL);
606 m_Played_time[0] = 0;
607 m_Played_time[1] = 0;
609 // base stats and related field values
610 InitStatsForLevel();
611 InitTaxiNodesForLevel();
612 InitGlyphsForLevel();
613 InitTalentForLevel();
614 InitPrimaryProffesions(); // to max set before any spell added
616 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
617 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
618 SetHealth(GetMaxHealth());
619 if (getPowerType()==POWER_MANA)
621 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
622 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
625 learnDefaultSpells(true);
627 std::list<uint16>::const_iterator action_itr[4];
628 for(int i=0; i<4; i++)
629 action_itr[i] = info->action[i].begin();
631 for (; action_itr[0]!=info->action[0].end() && action_itr[1]!=info->action[1].end();)
633 uint16 taction[4];
634 for(int i=0; i<4 ;i++)
635 taction[i] = (*action_itr[i]);
637 addActionButton((uint8)taction[0], taction[1], (uint8)taction[2], (uint8)taction[3]);
639 for(int i=0; i<4 ;i++)
640 ++action_itr[i];
643 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
645 uint32 titem_id = item_id_itr->item_id;
646 uint32 titem_amount = item_id_itr->item_amount;
648 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
650 // attempt equip
651 uint16 eDest;
652 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, titem_amount, false );
653 if( msg == EQUIP_ERR_OK )
655 EquipNewItem( eDest, titem_id, titem_amount, true);
656 AutoUnequipOffhandIfNeed();
657 continue; // equipped, to next
660 // attempt store
661 ItemPosCountVec sDest;
662 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
663 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
664 if( msg == EQUIP_ERR_OK )
666 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
667 continue; // stored, to next
670 // item can't be added
671 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,race,class_,msg);
674 // bags and main-hand weapon must equipped at this moment
675 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
676 // or ammo not equipped in special bag
677 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
679 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
681 uint16 eDest;
682 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
683 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
684 if( msg == EQUIP_ERR_OK )
686 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
687 EquipItem( eDest, pItem, true);
689 // move other items to more appropriate slots (ammo not equipped in special bag)
690 else
692 ItemPosCountVec sDest;
693 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
694 if( msg == EQUIP_ERR_OK )
696 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
697 pItem = StoreItem( sDest, pItem, true);
700 // if this is ammo then use it
701 uint8 msg = CanUseAmmo( pItem->GetProto()->ItemId );
702 if( msg == EQUIP_ERR_OK )
703 SetAmmo( pItem->GetProto()->ItemId );
707 // all item positions resolved
709 return true;
712 void Player::StartMirrorTimer(MirrorTimerType Type, uint32 MaxValue)
714 uint32 BreathRegen = (uint32)-1;
716 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
717 data << (uint32)Type;
718 data << MaxValue;
719 data << MaxValue;
720 data << BreathRegen;
721 data << (uint8)0;
722 data << (uint32)0; // spell id
723 GetSession()->SendPacket(&data);
726 void Player::ModifyMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, uint32 Regen)
728 if(Type==BREATH_TIMER)
729 m_breathTimer = ((MaxValue + 1000) - CurrentValue) / Regen;
731 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
732 data << (uint32)Type;
733 data << CurrentValue;
734 data << MaxValue;
735 data << Regen;
736 data << (uint8)0;
737 data << (uint32)0; // spell id
738 GetSession()->SendPacket( &data );
741 void Player::StopMirrorTimer(MirrorTimerType Type)
743 if(Type==BREATH_TIMER)
744 m_breathTimer = 0;
746 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
747 data << (uint32)Type;
748 GetSession()->SendPacket( &data );
751 void Player::EnvironmentalDamage(uint64 guid, EnviromentalDamage type, uint32 damage)
753 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
754 data << (uint64)guid;
755 data << (uint8)(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
756 data << (uint32)damage;
757 data << (uint32)0;
758 data << (uint32)0;
759 SendMessageToSet(&data, true);
761 DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
763 if(type==DAMAGE_FALL && !isAlive()) // DealDamage not apply item durability loss at self damage
765 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
766 DurabilityLossAll(0.10f,false);
767 // durability lost message
768 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
769 GetSession()->SendPacket(&data);
773 void Player::HandleDrowning()
775 if(!m_isunderwater)
776 return;
778 //if have water breath , then remove bar
779 if(waterbreath || isGameMaster() || !isAlive())
781 StopMirrorTimer(BREATH_TIMER);
782 m_isunderwater = 0;
783 return;
786 uint32 UnderWaterTime = 1*MINUTE*1000; // default length 1 min
788 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
789 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
790 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
792 if ((m_isunderwater & 0x01) && !(m_isunderwater & 0x80) && isAlive())
794 //single trigger timer
795 if (!(m_isunderwater & 0x02))
797 m_isunderwater|= 0x02;
798 m_breathTimer = UnderWaterTime + 1000;
800 //single trigger "Breathbar"
801 if ( m_breathTimer <= UnderWaterTime && !(m_isunderwater & 0x04))
803 m_isunderwater|= 0x04;
804 StartMirrorTimer(BREATH_TIMER, UnderWaterTime);
806 //continuous trigger drowning "Damage"
807 if ((m_breathTimer == 0) && (m_isunderwater & 0x01))
809 //TODO: Check this formula
810 uint64 guid = GetGUID();
811 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
813 EnvironmentalDamage(guid, DAMAGE_DROWNING,damage);
814 m_breathTimer = 2000;
817 //single trigger retract bar
818 else if (!(m_isunderwater & 0x01) && !(m_isunderwater & 0x08) && (m_isunderwater & 0x02) && (m_breathTimer > 0) && isAlive())
820 m_isunderwater = 0x08;
822 uint32 BreathRegen = 10;
823 ModifyMirrorTimer(BREATH_TIMER, UnderWaterTime, m_breathTimer,BreathRegen);
824 m_isunderwater = 0x10;
826 //remove bar
827 else if ((m_breathTimer < 50) && !(m_isunderwater & 0x01) && (m_isunderwater == 0x10))
829 StopMirrorTimer(BREATH_TIMER);
830 m_isunderwater = 0;
834 void Player::HandleLava()
836 bool ValidArea = false;
838 if ((m_isunderwater & 0x80) && isAlive())
840 //Single trigger Set BreathTimer
841 if (!(m_isunderwater & 0x80))
843 m_isunderwater|= 0x04;
844 m_breathTimer = 1000;
846 //Reset BreathTimer and still in the lava
847 if (!m_breathTimer)
849 uint64 guid = GetGUID();
850 uint32 damage = urand(600, 700); // TODO: Get more detailed information about lava damage
851 uint32 dmgZone = GetZoneId(); // TODO: Find correct "lava dealing zone" flag in Area Table
853 // Deal lava damage only in lava zones.
854 switch(dmgZone)
856 case 0x8D:
857 ValidArea = false;
858 break;
859 case 0x94:
860 ValidArea = false;
861 break;
862 case 0x2CE:
863 ValidArea = false;
864 break;
865 case 0x2CF:
866 ValidArea = false;
867 break;
868 default:
869 if (dmgZone / 5 & 0x408)
870 ValidArea = true;
873 // if is valid area and is not gamemaster then deal damage
874 if ( ValidArea && !isGameMaster() )
875 EnvironmentalDamage(guid, DAMAGE_LAVA, damage);
877 m_breathTimer = 1000;
881 //Death timer disabled and WaterFlags reset
882 else if (m_deathState == DEAD)
884 m_breathTimer = 0;
885 m_isunderwater = 0;
889 ///The player sobers by 256 every 10 seconds
890 void Player::HandleSobering()
892 m_drunkTimer = 0;
894 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
895 SetDrunkValue(drunk);
898 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
900 if(value >= 23000)
901 return DRUNKEN_SMASHED;
902 if(value >= 12800)
903 return DRUNKEN_DRUNK;
904 if(value & 0xFFFE)
905 return DRUNKEN_TIPSY;
906 return DRUNKEN_SOBER;
909 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
911 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
913 m_drunk = newDrunkenValue;
914 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
916 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
918 // special drunk invisibility detection
919 if(newDrunkenState >= DRUNKEN_DRUNK)
920 m_detectInvisibilityMask |= (1<<6);
921 else
922 m_detectInvisibilityMask &= ~(1<<6);
924 if(newDrunkenState == oldDrunkenState)
925 return;
927 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
928 data << uint64(GetGUID());
929 data << uint32(newDrunkenState);
930 data << uint32(itemId);
932 SendMessageToSet(&data, true);
935 void Player::Update( uint32 p_time )
937 if(!IsInWorld())
938 return;
940 // undelivered mail
941 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
943 SendNewMail();
944 ++unReadMails;
946 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
947 m_nextMailDelivereTime = 0;
950 Unit::Update( p_time );
952 // update player only attacks
953 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
955 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
958 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
960 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
963 time_t now = time (NULL);
965 UpdatePvPFlag(now);
967 UpdateContestedPvP(p_time);
969 UpdateDuelFlag(now);
971 CheckDuelDistance(now);
973 UpdateAfkReport(now);
975 CheckExploreSystem();
977 // Update items that have just a limited lifetime
978 if (now>m_Last_tick)
979 UpdateItemDuration(uint32(now- m_Last_tick));
981 if (!m_timedquests.empty())
983 std::set<uint32>::iterator iter = m_timedquests.begin();
984 while (iter != m_timedquests.end())
986 QuestStatusData& q_status = mQuestStatus[*iter];
987 if( q_status.m_timer <= p_time )
989 uint32 quest_id = *iter;
990 ++iter; // current iter will be removed in FailTimedQuest
991 FailTimedQuest( quest_id );
993 else
995 q_status.m_timer -= p_time;
996 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
997 ++iter;
1002 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1004 Unit *pVictim = getVictim();
1005 if( !IsNonMeleeSpellCasted(false) && pVictim)
1007 // default combat reach 10
1008 // TODO add weapon,skill check
1010 float pldistance = ATTACK_DISTANCE;
1012 if (isAttackReady(BASE_ATTACK))
1014 if(!IsWithinDistInMap(pVictim, pldistance))
1016 setAttackTimer(BASE_ATTACK,100);
1017 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1019 SendAttackSwingNotInRange();
1020 m_swingErrorMsg = 1;
1023 //120 degrees of radiant range
1024 else if( !HasInArc( 2*M_PI/3, pVictim ))
1026 setAttackTimer(BASE_ATTACK,100);
1027 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1029 SendAttackSwingBadFacingAttack();
1030 m_swingErrorMsg = 2;
1033 else
1035 m_swingErrorMsg = 0; // reset swing error state
1037 // prevent base and off attack in same time, delay attack at 0.2 sec
1038 if(haveOffhandWeapon())
1040 uint32 off_att = getAttackTimer(OFF_ATTACK);
1041 if(off_att < ATTACK_DISPLAY_DELAY)
1042 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1044 AttackerStateUpdate(pVictim, BASE_ATTACK);
1045 resetAttackTimer(BASE_ATTACK);
1049 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1051 if(!IsWithinDistInMap(pVictim, pldistance))
1053 setAttackTimer(OFF_ATTACK,100);
1055 else if( !HasInArc( 2*M_PI/3, pVictim ))
1057 setAttackTimer(OFF_ATTACK,100);
1059 else
1061 // prevent base and off attack in same time, delay attack at 0.2 sec
1062 uint32 base_att = getAttackTimer(BASE_ATTACK);
1063 if(base_att < ATTACK_DISPLAY_DELAY)
1064 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1065 // do attack
1066 AttackerStateUpdate(pVictim, OFF_ATTACK);
1067 resetAttackTimer(OFF_ATTACK);
1071 Unit *owner = pVictim->GetOwner();
1072 Unit *u = owner ? owner : pVictim;
1073 if(u->IsPvP() && (!duel || duel->opponent != u))
1075 UpdatePvP(true);
1076 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1081 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1083 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1085 int time_inn = time(NULL)-GetTimeInnEnter();
1086 if (time_inn >= 10) //freeze update
1088 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1089 //speed collect rest bonus (section/in hour)
1090 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1091 UpdateInnerTime(time(NULL));
1096 if(m_regenTimer > 0)
1098 if(p_time >= m_regenTimer)
1099 m_regenTimer = 0;
1100 else
1101 m_regenTimer -= p_time;
1104 if (m_weaponChangeTimer > 0)
1106 if(p_time >= m_weaponChangeTimer)
1107 m_weaponChangeTimer = 0;
1108 else
1109 m_weaponChangeTimer -= p_time;
1112 if (m_zoneUpdateTimer > 0)
1114 if(p_time >= m_zoneUpdateTimer)
1116 uint32 newzone = GetZoneId();
1117 if( m_zoneUpdateId != newzone )
1118 UpdateZone(newzone); // also update area
1119 else
1121 // use area updates as well
1122 // needed for free far all arenas for example
1123 uint32 newarea = GetAreaId();
1124 if( m_areaUpdateId != newarea )
1125 UpdateArea(newarea);
1127 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1130 else
1131 m_zoneUpdateTimer -= p_time;
1134 if (isAlive())
1136 RegenerateAll();
1139 if (m_deathState == JUST_DIED)
1141 KillPlayer();
1144 if(m_nextSave > 0)
1146 if(p_time >= m_nextSave)
1148 // m_nextSave reseted in SaveToDB call
1149 SaveToDB();
1150 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1152 else
1154 m_nextSave -= p_time;
1158 //Breathtimer
1159 if(m_breathTimer > 0)
1161 if(p_time >= m_breathTimer)
1162 m_breathTimer = 0;
1163 else
1164 m_breathTimer -= p_time;
1168 //Handle Water/drowning
1169 HandleDrowning();
1171 //Handle lava
1172 HandleLava();
1174 //Handle detect stealth players
1175 if (m_DetectInvTimer > 0)
1177 if (p_time >= m_DetectInvTimer)
1179 m_DetectInvTimer = 3000;
1180 HandleStealthedUnitsDetection();
1182 else
1183 m_DetectInvTimer -= p_time;
1186 // Played time
1187 if (now > m_Last_tick)
1189 uint32 elapsed = uint32(now - m_Last_tick);
1190 m_Played_time[0] += elapsed; // Total played time
1191 m_Played_time[1] += elapsed; // Level played time
1192 m_Last_tick = now;
1195 if (m_drunk)
1197 m_drunkTimer += p_time;
1199 if (m_drunkTimer > 10000)
1200 HandleSobering();
1203 // not auto-free ghost from body in instances
1204 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1206 if(p_time >= m_deathTimer)
1208 m_deathTimer = 0;
1209 BuildPlayerRepop();
1210 RepopAtGraveyard();
1212 else
1213 m_deathTimer -= p_time;
1216 UpdateEnchantTime(p_time);
1217 UpdateHomebindTime(p_time);
1219 // group update
1220 SendUpdateToOutOfRangeGroupMembers();
1222 Pet* pet = GetPet();
1223 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE))
1225 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1226 return;
1230 void Player::setDeathState(DeathState s)
1232 uint32 ressSpellId = 0;
1234 bool cur = isAlive();
1236 if(s == JUST_DIED && cur)
1238 // drunken state is cleared on death
1239 SetDrunkValue(0);
1240 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1241 ClearComboPoints();
1243 clearResurrectRequestData();
1245 // remove form before other mods to prevent incorrect stats calculation
1246 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1248 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1249 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1251 // remove uncontrolled pets
1252 RemoveMiniPet();
1253 RemoveGuardians();
1255 // save value before aura remove in Unit::setDeathState
1256 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1258 // passive spell
1259 if(!ressSpellId)
1260 ressSpellId = GetResurrectionSpellId();
1261 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1263 Unit::setDeathState(s);
1265 // restore resurrection spell id for player after aura remove
1266 if(s == JUST_DIED && cur && ressSpellId)
1267 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1269 if(isAlive() && !cur)
1271 //clear aura case after resurrection by another way (spells will be applied before next death)
1272 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1274 // restore default warrior stance
1275 if(getClass()== CLASS_WARRIOR)
1276 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1280 void Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1282 *p_data << GetGUID();
1283 *p_data << m_name;
1285 *p_data << getRace();
1286 uint8 pClass = getClass();
1287 *p_data << pClass;
1288 *p_data << getGender();
1290 uint32 bytes = GetUInt32Value(PLAYER_BYTES);
1291 *p_data << uint8(bytes);
1292 *p_data << uint8(bytes >> 8);
1293 *p_data << uint8(bytes >> 16);
1294 *p_data << uint8(bytes >> 24);
1296 bytes = GetUInt32Value(PLAYER_BYTES_2);
1297 *p_data << uint8(bytes);
1299 *p_data << uint8(getLevel()); // player level
1300 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1301 uint32 zoneId = MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY());
1302 sLog.outDebug("Player::BuildEnumData: m:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId);
1303 *p_data << zoneId;
1304 *p_data << GetMapId();
1306 *p_data << GetPositionX();
1307 *p_data << GetPositionY();
1308 *p_data << GetPositionZ();
1310 *p_data << GetUInt32Value(PLAYER_GUILDID); // guild id
1312 uint32 char_flags = 0;
1313 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
1314 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1315 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
1316 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1317 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
1318 char_flags |= CHARACTER_FLAG_GHOST;
1319 if(HasAtLoginFlag(AT_LOGIN_RENAME))
1320 char_flags |= CHARACTER_FLAG_RENAME;
1321 // always send the flag if declined names aren't used
1322 // to let the client select a default method of declining the name
1323 if(!sWorld.getConfig(CONFIG_DECLINED_NAMES_USED) || (result && result->Fetch()[13].GetCppString() != ""))
1324 char_flags |= CHARACTER_FLAG_DECLINED;
1326 *p_data << (uint32)char_flags; // character flags
1327 *p_data << (uint32)0; // new wotlk
1328 *p_data << (uint8)1; // unknown
1330 // Pets info
1332 uint32 petDisplayId = 0;
1333 uint32 petLevel = 0;
1334 uint32 petFamily = 0;
1336 // show pet at selection character in character list only for non-ghost character
1337 if(result && isAlive() && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER))
1339 Field* fields = result->Fetch();
1341 uint32 entry = fields[10].GetUInt32();
1342 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1343 if(cInfo)
1345 petDisplayId = fields[11].GetUInt32();
1346 petLevel = fields[12].GetUInt32();
1347 petFamily = cInfo->family;
1351 *p_data << (uint32)petDisplayId;
1352 *p_data << (uint32)petLevel;
1353 *p_data << (uint32)petFamily;
1356 /*ItemPrototype const *items[EQUIPMENT_SLOT_END];
1357 for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
1358 items[i] = NULL;
1360 QueryResult *result = CharacterDatabase.PQuery("SELECT slot,item_template FROM character_inventory WHERE guid = '%u' AND bag = 0",GetGUIDLow());
1361 if (result)
1365 Field *fields = result->Fetch();
1366 uint8 slot = fields[0].GetUInt8() & 255;
1367 uint32 item_id = fields[1].GetUInt32();
1368 if( slot >= EQUIPMENT_SLOT_END )
1369 continue;
1371 items[slot] = objmgr.GetItemPrototype(item_id);
1372 if(!items[slot])
1374 sLog.outError( "Player::BuildEnumData: Player %s have unknown item (id: #%u) in inventory, skipped.", GetName(),item_id );
1375 continue;
1377 } while (result->NextRow());
1378 delete result;
1381 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1383 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
1384 uint32 item_id = GetUInt32Value(visualbase);
1385 const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
1386 SpellItemEnchantmentEntry const *enchant = NULL;
1388 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot<=TEMP_ENCHANTMENT_SLOT; enchantSlot++)
1390 uint32 enchantId = GetUInt32Value(visualbase+1+enchantSlot);
1391 if(enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))
1392 break;
1395 if (proto != NULL)
1397 *p_data << (uint32)proto->DisplayInfoID;
1398 *p_data << (uint8)proto->InventoryType;
1399 *p_data << (uint32)(enchant?enchant->aura_id:0);
1401 else
1403 *p_data << (uint32)0;
1404 *p_data << (uint8)0;
1405 *p_data << (uint32)0; // enchant?
1408 *p_data << (uint32)0; // first bag display id
1409 *p_data << (uint8)0; // first bag inventory type
1410 *p_data << (uint32)0; // enchant?
1413 bool Player::ToggleAFK()
1415 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1417 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1419 // afk player not allowed in battleground
1420 if(state && InBattleGround())
1421 LeaveBattleground();
1423 return state;
1426 bool Player::ToggleDND()
1428 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1430 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1433 uint8 Player::chatTag() const
1435 // it's bitmask
1436 // 0x8 - ??
1437 // 0x4 - gm
1438 // 0x2 - dnd
1439 // 0x1 - afk
1440 if(isGMChat())
1441 return 4;
1442 else if(isDND())
1443 return 3;
1444 if(isAFK())
1445 return 1;
1446 else
1447 return 0;
1450 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1452 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1454 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1455 return false;
1458 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1459 Pet* pet = GetPet();
1461 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1463 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1464 if(!InBattleGround() && mEntry->IsBattleGround() && !GetSession()->GetSecurity())
1465 return false;
1467 // client without expansion support
1468 if(GetSession()->Expansion() < mEntry->Expansion())
1470 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1472 if(GetTransport())
1473 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1475 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1477 return false; // normal client can't teleport to this map...
1479 else
1481 sLog.outDebug("Player %s will teleported to map %u", GetName(), mapid);
1484 // if we were on a transport, leave
1485 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1487 m_transport->RemovePassenger(this);
1488 m_transport = NULL;
1489 m_movementInfo.t_x = 0.0f;
1490 m_movementInfo.t_y = 0.0f;
1491 m_movementInfo.t_z = 0.0f;
1492 m_movementInfo.t_o = 0.0f;
1493 m_movementInfo.t_time = 0;
1496 SetSemaphoreTeleport(true);
1498 // The player was ported to another map and looses the duel immediately.
1499 // We have to perform this check before the teleport, otherwise the
1500 // ObjectAccessor won't find the flag.
1501 if (duel && GetMapId()!=mapid)
1503 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
1504 if (obj)
1505 DuelComplete(DUEL_FLED);
1508 // reset movement flags at teleport, because player will continue move with these flags after teleport
1509 SetUnitMovementFlags(0);
1511 if ((GetMapId() == mapid) && (!m_transport))
1513 // prepare zone change detect
1514 uint32 old_zone = GetZoneId();
1516 // near teleport
1517 if(!GetSession()->PlayerLogout())
1519 WorldPacket data;
1520 BuildTeleportAckMsg(&data, x, y, z, orientation);
1521 GetSession()->SendPacket(&data);
1522 SetPosition( x, y, z, orientation, true);
1524 else
1525 // this will be used instead of the current location in SaveToDB
1526 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1528 //BuildHeartBeatMsg(&data);
1529 //SendMessageToSet(&data, true);
1530 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1532 //same map, only remove pet if out of range
1533 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE))
1535 if(pet->isControlled() && !pet->isTemporarySummoned() )
1536 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1537 else
1538 m_temporaryUnsummonedPetNumber = 0;
1540 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1544 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1545 CombatStop();
1547 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1549 // resummon pet
1550 if(pet && m_temporaryUnsummonedPetNumber)
1552 Pet* NewPet = new Pet;
1553 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
1554 delete NewPet;
1556 m_temporaryUnsummonedPetNumber = 0;
1560 if(!GetSession()->PlayerLogout())
1562 // don't reset teleport semaphore while logging out, otherwise m_teleport_dest won't be used in Player::SaveToDB
1563 SetSemaphoreTeleport(false);
1565 UpdateZone(GetZoneId());
1568 // new zone
1569 if(old_zone != GetZoneId())
1571 // honorless target
1572 if(pvpInfo.inHostileArea)
1573 CastSpell(this, 2479, true);
1576 else
1578 // far teleport to another map
1579 Map* oldmap = IsInWorld() ? MapManager::Instance().GetMap(GetMapId(), this) : NULL;
1580 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1582 // Check enter rights before map getting to avoid creating instance copy for player
1583 // this check not dependent from map instance copy and same for all instance copies of selected map
1584 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1586 SetSemaphoreTeleport(false);
1587 return false;
1590 // If the map is not created, assume it is possible to enter it.
1591 // It will be created in the WorldPortAck.
1592 Map *map = MapManager::Instance().FindMap(mapid);
1593 if (!map || map->CanEnter(this))
1595 SetSelection(0);
1597 CombatStop();
1599 ResetContestedPvP();
1601 // remove player from battleground on far teleport (when changing maps)
1602 if(BattleGround const* bg = GetBattleGround())
1604 // Note: at battleground join battleground id set before teleport
1605 // and we already will found "current" battleground
1606 // just need check that this is targeted map or leave
1607 if(bg->GetMapId() != mapid)
1608 LeaveBattleground(false); // don't teleport to entry point
1611 // remove pet on map change
1612 if (pet)
1614 //leaving map -> delete pet right away (doing this later will cause problems)
1615 if(pet->isControlled() && !pet->isTemporarySummoned())
1616 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1617 else
1618 m_temporaryUnsummonedPetNumber = 0;
1620 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1623 // remove all dyn objects
1624 RemoveAllDynObjects();
1626 // stop spellcasting
1627 // not attempt interrupt teleportation spell at caster teleport
1628 if(!(options & TELE_TO_SPELL))
1629 if(IsNonMeleeSpellCasted(true))
1630 InterruptNonMeleeSpells(true);
1632 if(!GetSession()->PlayerLogout())
1634 // send transfer packets
1635 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1636 data << uint32(mapid);
1637 if (m_transport)
1639 data << m_transport->GetEntry() << GetMapId();
1641 GetSession()->SendPacket(&data);
1643 data.Initialize(SMSG_NEW_WORLD, (20));
1644 if (m_transport)
1646 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1648 else
1650 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1652 GetSession()->SendPacket( &data );
1653 SendSavedInstances();
1655 // remove from old map now
1656 if(oldmap) oldmap->Remove(this, false);
1659 // new final coordinates
1660 float final_x = x;
1661 float final_y = y;
1662 float final_z = z;
1663 float final_o = orientation;
1665 if(m_transport)
1667 final_x += m_movementInfo.t_x;
1668 final_y += m_movementInfo.t_y;
1669 final_z += m_movementInfo.t_z;
1670 final_o += m_movementInfo.t_o;
1673 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1674 // if the player is saved before worldportack (at logout for example)
1675 // this will be used instead of the current location in SaveToDB
1677 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
1679 // move packet sent by client always after far teleport
1680 // SetPosition(final_x, final_y, final_z, final_o, true);
1681 SetDontMove(true);
1683 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1685 else
1686 return false;
1688 return true;
1691 void Player::AddToWorld()
1693 ///- Do not add/remove the player from the object storage
1694 ///- It will crash when updating the ObjectAccessor
1695 ///- The player should only be added when logging in
1696 Unit::AddToWorld();
1698 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1700 if(m_items[i])
1701 m_items[i]->AddToWorld();
1705 void Player::RemoveFromWorld()
1707 // cleanup
1708 if(IsInWorld())
1710 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1711 Uncharm();
1712 UnsummonAllTotems();
1713 RemoveMiniPet();
1714 RemoveGuardians();
1717 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1719 if(m_items[i])
1720 m_items[i]->RemoveFromWorld();
1723 ///- Do not add/remove the player from the object storage
1724 ///- It will crash when updating the ObjectAccessor
1725 ///- The player should only be removed when logging out
1726 Unit::RemoveFromWorld();
1729 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1731 float addRage;
1733 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1735 if(attacker)
1737 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1739 // talent who gave more rage on attack
1740 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1742 else
1744 addRage = damage/rageconversion*2.5;
1746 // Berserker Rage effect
1747 if(HasAura(18499,0))
1748 addRage *= 1.3;
1751 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1753 ModifyPower(POWER_RAGE, uint32(addRage*10));
1756 void Player::RegenerateAll()
1758 if (m_regenTimer != 0)
1759 return;
1760 uint32 regenDelay = 2000;
1762 // Not in combat or they have regeneration
1763 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1764 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1766 RegenerateHealth();
1767 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1768 Regenerate(POWER_RAGE);
1771 Regenerate( POWER_ENERGY );
1773 Regenerate( POWER_MANA );
1775 Regenerate( POWER_RUNIC_POWER );
1777 m_regenTimer = regenDelay;
1780 void Player::Regenerate(Powers power)
1782 uint32 curValue = GetPower(power);
1783 uint32 maxValue = GetMaxPower(power);
1785 float addvalue = 0.0f;
1787 switch (power)
1789 case POWER_MANA:
1791 bool recentCast = IsUnderLastManaUseEffect();
1792 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1793 if (recentCast)
1795 // Mangos Updates Mana in intervals of 2s, which is correct
1796 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1798 else
1800 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1802 } break;
1803 case POWER_RAGE: // Regenerate rage
1805 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1806 addvalue = 30 * RageDecreaseRate; // 3 rage by tick
1807 } break;
1808 case POWER_ENERGY: // Regenerate energy (rogue)
1809 addvalue = 20;
1810 break;
1811 case POWER_RUNIC_POWER:
1812 addvalue = 100; // TODO: find correct regen rate
1813 break;
1814 case POWER_FOCUS:
1815 case POWER_HAPPINESS:
1816 break;
1819 // Mana regen calculated in Player::UpdateManaRegen()
1820 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1821 if(power != POWER_MANA)
1823 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1824 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1825 if ((*i)->GetModifier()->m_miscvalue == power)
1826 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1829 if (power != POWER_RAGE)
1831 curValue += uint32(addvalue);
1832 if (curValue > maxValue)
1833 curValue = maxValue;
1835 else
1837 if(curValue <= uint32(addvalue))
1838 curValue = 0;
1839 else
1840 curValue -= uint32(addvalue);
1842 SetPower(power, curValue);
1845 void Player::RegenerateHealth()
1847 uint32 curValue = GetHealth();
1848 uint32 maxValue = GetMaxHealth();
1850 if (curValue >= maxValue) return;
1852 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
1854 float addvalue = 0.0f;
1856 // polymorphed case
1857 if ( IsPolymorphed() )
1858 addvalue = GetMaxHealth()/3;
1859 // normal regen case (maybe partly in combat case)
1860 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
1862 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
1863 if (!isInCombat())
1865 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
1866 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
1867 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
1869 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
1870 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
1872 if(!IsStandState())
1873 addvalue *= 1.5;
1876 // always regeneration bonus (including combat)
1877 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
1879 if(addvalue < 0)
1880 addvalue = 0;
1882 ModifyHealth(int32(addvalue));
1885 bool Player::CanInteractWithNPCs(bool alive) const
1887 if(alive && !isAlive())
1888 return false;
1889 if(isInFlight())
1890 return false;
1892 return true;
1895 bool Player::IsUnderWater() const
1897 return IsInWater() &&
1898 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
1901 void Player::SetInWater(bool apply)
1903 if(m_isInWater==apply)
1904 return;
1906 //define player in water by opcodes
1907 //move player's guid into HateOfflineList of those mobs
1908 //which can't swim and move guid back into ThreatList when
1909 //on surface.
1910 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
1911 m_isInWater = apply;
1913 // remove auras that need water/land
1914 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
1916 getHostilRefManager().updateThreatTables();
1919 void Player::SetGameMaster(bool on)
1921 if(on)
1923 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
1924 setFaction(35);
1925 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
1927 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
1928 ResetContestedPvP();
1930 getHostilRefManager().setOnlineOfflineState(false);
1931 CombatStop();
1933 else
1935 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
1936 setFactionForRace(getRace());
1937 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
1939 // restore FFA PvP Server state
1940 if(sWorld.IsFFAPvPRealm())
1941 SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
1943 // restore FFA PvP area state, remove not allowed for GM mounts
1944 UpdateArea(m_areaUpdateId);
1946 getHostilRefManager().setOnlineOfflineState(true);
1949 ObjectAccessor::UpdateVisibilityForPlayer(this);
1952 void Player::SetGMVisible(bool on)
1954 if(on)
1956 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
1958 // Reapply stealth/invisibility if active or show if not any
1959 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
1960 SetVisibility(VISIBILITY_GROUP_STEALTH);
1961 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
1962 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
1963 else
1964 SetVisibility(VISIBILITY_ON);
1966 else
1968 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
1970 SetAcceptWhispers(false);
1971 SetGameMaster(true);
1973 SetVisibility(VISIBILITY_OFF);
1977 bool Player::IsGroupVisibleFor(Player* p) const
1979 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
1981 default: return IsInSameGroupWith(p);
1982 case 1: return IsInSameRaidWith(p);
1983 case 2: return GetTeam()==p->GetTeam();
1987 bool Player::IsInSameGroupWith(Player const* p) const
1989 return p==this || GetGroup() != NULL &&
1990 GetGroup() == p->GetGroup() &&
1991 GetGroup()->SameSubGroup((Player*)this, (Player*)p);
1994 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
1995 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
1996 void Player::UninviteFromGroup()
1998 if(GetGroupInvite()) // uninvited invitee
2000 Group* group = GetGroupInvite();
2001 group->RemoveInvite(this);
2003 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2005 if(group->IsCreated())
2007 group->Disband(true);
2008 objmgr.RemoveGroup(group);
2010 else
2011 group->RemoveAllInvites();
2013 delete group;
2018 void Player::RemoveFromGroup(Group* group, uint64 guid)
2020 if(group)
2022 if (group->RemoveMember(guid, 0) <= 1)
2024 // group->Disband(); already disbanded in RemoveMember
2025 objmgr.RemoveGroup(group);
2026 delete group;
2027 // removemember sets the player's group pointer to NULL
2032 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2034 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2035 data << uint64(victim ? victim->GetGUID() : 0); // guid
2036 data << uint32(GivenXP+RestXP); // given experience
2037 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2038 if(victim)
2040 data << uint32(GivenXP); // experience without rested bonus
2041 data << float(1); // 1 - none 0 - 100% group bonus output
2043 data << uint8(0); // new 2.4.0
2044 GetSession()->SendPacket(&data);
2047 void Player::GiveXP(uint32 xp, Unit* victim)
2049 if ( xp < 1 )
2050 return;
2052 if(!isAlive())
2053 return;
2055 uint32 level = getLevel();
2057 // XP to money conversion processed in Player::RewardQuest
2058 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2059 return;
2061 // handle SPELL_AURA_MOD_XP_PCT auras
2062 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2063 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2064 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2066 // XP resting bonus for kill
2067 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2069 SendLogXPGain(xp,victim,rested_bonus_xp);
2071 uint32 curXP = GetUInt32Value(PLAYER_XP);
2072 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2073 uint32 newXP = curXP + xp + rested_bonus_xp;
2075 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2077 newXP -= nextLvlXP;
2079 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2080 GiveLevel(level + 1);
2082 level = getLevel();
2083 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2086 SetUInt32Value(PLAYER_XP, newXP);
2089 // Update player to next level
2090 // Current player experience not update (must be update by caller)
2091 void Player::GiveLevel(uint32 level)
2093 if ( level == getLevel() )
2094 return;
2096 PlayerLevelInfo info;
2097 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2099 PlayerClassLevelInfo classInfo;
2100 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2102 // send levelup info to client
2103 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2104 data << uint32(level);
2105 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2106 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2107 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2108 data << uint32(0);
2109 data << uint32(0);
2110 data << uint32(0);
2111 data << uint32(0);
2112 data << uint32(0);
2113 data << uint32(0);
2114 // end for
2115 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2116 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2118 GetSession()->SendPacket(&data);
2120 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, MaNGOS::XP::xp_to_level(level));
2122 //update level, max level of skills
2123 if(getLevel()!= level)
2124 m_Played_time[1] = 0; // Level Played Time reset
2125 SetLevel(level);
2126 UpdateMaxSkills();
2128 // save base values (bonuses already included in stored stats
2129 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2130 SetCreateStat(Stats(i), info.stats[i]);
2132 SetCreateHealth(classInfo.basehealth);
2133 SetCreateMana(classInfo.basemana);
2135 InitTalentForLevel();
2136 InitTaxiNodesForLevel();
2137 InitGlyphsForLevel();
2139 UpdateAllStats();
2141 // set current level health and mana/energy to maximum after applying all mods.
2142 SetHealth(GetMaxHealth());
2143 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2144 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2145 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2146 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2147 SetPower(POWER_FOCUS, 0);
2148 SetPower(POWER_HAPPINESS, 0);
2150 // give level to summoned pet
2151 Pet* pet = GetPet();
2152 if(pet && pet->getPetType()==SUMMON_PET)
2153 pet->GivePetLevel(level);
2154 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2157 void Player::InitTalentForLevel()
2159 uint32 level = getLevel();
2160 // talents base at level diff ( talents = level - 9 but some can be used already)
2161 if(level < 10)
2163 // Remove all talent points
2164 if(m_usedTalentCount > 0) // Free any used talents
2166 resetTalents(true);
2167 SetFreeTalentPoints(0);
2170 else
2172 uint32 talentPointsForLevel = uint32((level-9)*sWorld.getRate(RATE_TALENT));
2173 // if used more that have then reset
2174 if(m_usedTalentCount > talentPointsForLevel)
2176 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2177 resetTalents(true);
2178 else
2179 SetFreeTalentPoints(0);
2181 // else update amount of free points
2182 else
2183 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2187 void Player::InitStatsForLevel(bool reapplyMods)
2189 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2190 _RemoveAllStatBonuses();
2192 PlayerClassLevelInfo classInfo;
2193 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2195 PlayerLevelInfo info;
2196 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2198 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2199 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, MaNGOS::XP::xp_to_level(getLevel()));
2201 UpdateMaxSkills ();
2203 // set default cast time multiplier
2204 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2206 // reset size before reapply auras
2207 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2209 // save base values (bonuses already included in stored stats
2210 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2211 SetCreateStat(Stats(i), info.stats[i]);
2213 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2214 SetStat(Stats(i), info.stats[i]);
2216 SetCreateHealth(classInfo.basehealth);
2218 //set create powers
2219 SetCreateMana(classInfo.basemana);
2221 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2223 InitStatBuffMods();
2225 //reset rating fields values
2226 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2227 SetUInt32Value(index, 0);
2229 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2230 for (int i = 0; i < 7; i++)
2232 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2233 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2234 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2237 //reset attack power, damage and attack speed fields
2238 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2239 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2240 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2242 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2243 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2244 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2245 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2246 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2247 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2249 SetUInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2250 SetUInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2251 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2252 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2253 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2254 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2256 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2257 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2258 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2259 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2261 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2262 for (uint8 i = 0; i < 7; ++i)
2263 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2265 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2266 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2267 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2269 // Dodge percentage
2270 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2272 // set armor (resistance 0) to original value (create_agility*2)
2273 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2274 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2275 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2276 // set other resistance to original value (0)
2277 for (int i = 1; i < MAX_SPELL_SCHOOL; i++)
2279 SetResistance(SpellSchools(i), 0);
2280 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2281 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2284 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2285 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2286 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2288 SetFloatValue(UNIT_FIELD_POWER_COST_MODIFIER+i,0.0f);
2289 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2291 // Init data for form but skip reapply item mods for form
2292 InitDataForForm(reapplyMods);
2294 // save new stats
2295 for (int i = POWER_MANA; i < MAX_POWERS; i++)
2296 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2298 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2300 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2301 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2303 // cleanup unit flags (will be re-applied if need at aura load).
2304 RemoveFlag( UNIT_FIELD_FLAGS,
2305 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2306 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2307 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2308 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2309 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2310 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2312 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2313 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST | PLAYER_FLAGS_FFA_PVP);
2315 SetByteValue(UNIT_FIELD_BYTES_1, 2, 0x00); // one form stealth modified bytes
2317 // restore if need some important flags
2318 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2320 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2321 _ApplyAllStatBonuses();
2323 // set current level health and mana/energy to maximum after applying all mods.
2324 SetHealth(GetMaxHealth());
2325 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2326 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2327 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2328 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2329 SetPower(POWER_FOCUS, 0);
2330 SetPower(POWER_HAPPINESS, 0);
2331 SetPower(POWER_RUNIC_POWER, 0);
2334 void Player::SendInitialSpells()
2336 uint16 spellCount = 0;
2338 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2339 data << uint8(0);
2341 size_t countPos = data.wpos();
2342 data << uint16(spellCount); // spell count placeholder
2344 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2346 if(itr->second->state == PLAYERSPELL_REMOVED)
2347 continue;
2349 if(!itr->second->active || itr->second->disabled)
2350 continue;
2352 data << uint16(itr->first);
2353 data << uint16(0); // it's not slot id
2355 spellCount +=1;
2358 data.put<uint16>(countPos,spellCount); // write real count value
2360 uint16 spellCooldowns = m_spellCooldowns.size();
2361 data << uint16(spellCooldowns);
2362 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); itr++)
2364 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2365 if(!sEntry)
2366 continue;
2368 data << uint16(itr->first);
2370 time_t cooldown = 0;
2371 time_t curTime = time(NULL);
2372 if(itr->second.end > curTime)
2373 cooldown = (itr->second.end-curTime)*1000;
2375 data << uint16(itr->second.itemid); // cast item id
2376 data << uint16(sEntry->Category); // spell category
2377 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2379 data << uint32(0); // cooldown
2380 data << uint32(cooldown); // category cooldown
2382 else
2384 data << uint32(cooldown); // cooldown
2385 data << uint32(0); // category cooldown
2389 GetSession()->SendPacket(&data);
2391 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2394 void Player::RemoveMail(uint32 id)
2396 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2398 if ((*itr)->messageID == id)
2400 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2401 m_mail.erase(itr);
2402 return;
2407 void Player::SendMailResult(uint32 mailId, uint32 mailAction, uint32 mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2409 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_BAG_FULL?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2410 data << (uint32) mailId;
2411 data << (uint32) mailAction;
2412 data << (uint32) mailError;
2413 if ( mailError == MAIL_ERR_BAG_FULL )
2414 data << (uint32) equipError;
2415 else if( mailAction == MAIL_ITEM_TAKEN )
2417 data << (uint32) item_guid; // item guid low?
2418 data << (uint32) item_count; // item count?
2420 GetSession()->SendPacket(&data);
2423 void Player::SendNewMail()
2425 // deliver undelivered mail
2426 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2427 data << (uint32) 0;
2428 GetSession()->SendPacket(&data);
2431 void Player::UpdateNextMailTimeAndUnreads()
2433 // calculate next delivery time (min. from non-delivered mails
2434 // and recalculate unReadMail
2435 time_t cTime = time(NULL);
2436 m_nextMailDelivereTime = 0;
2437 unReadMails = 0;
2438 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2440 if((*itr)->deliver_time > cTime)
2442 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2443 m_nextMailDelivereTime = (*itr)->deliver_time;
2445 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2446 ++unReadMails;
2450 void Player::AddNewMailDeliverTime(time_t deliver_time)
2452 if(deliver_time <= time(NULL)) // ready now
2454 ++unReadMails;
2455 SendNewMail();
2457 else // not ready and no have ready mails
2459 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2460 m_nextMailDelivereTime = deliver_time;
2464 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool loading, uint16 slot_id, bool disabled)
2466 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2467 if (!spellInfo)
2469 // do character spell book cleanup (all characters)
2470 if(loading && !learning) // spell load case
2472 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2473 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2475 else
2476 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2478 return false;
2481 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2483 // do character spell book cleanup (all characters)
2484 if(loading && !learning) // spell load case
2486 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2487 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2489 else
2490 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2492 return false;
2495 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2497 bool disabled_case = false;
2498 bool superceded_old = false;
2500 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2501 if (itr != m_spells.end())
2503 // update active state for known spell
2504 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2506 itr->second->active = active;
2508 // loading && !learning == explicitly load from DB and then exist in it already and set correctly
2509 if(loading && !learning)
2510 itr->second->state = PLAYERSPELL_UNCHANGED;
2511 else if(itr->second->state != PLAYERSPELL_NEW)
2512 itr->second->state = PLAYERSPELL_CHANGED;
2514 if(!active)
2516 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2517 data << uint16(spell_id);
2518 GetSession()->SendPacket(&data);
2520 return active; // learn (show in spell book if active now)
2523 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2525 if(itr->second->state != PLAYERSPELL_NEW)
2526 itr->second->state = PLAYERSPELL_CHANGED;
2527 itr->second->disabled = disabled;
2529 if(disabled)
2530 return false;
2532 disabled_case = true;
2534 else switch(itr->second->state)
2536 case PLAYERSPELL_UNCHANGED: // known saved spell
2537 return false;
2538 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2540 delete itr->second;
2541 m_spells.erase(itr);
2542 state = PLAYERSPELL_CHANGED;
2543 break; // need re-add
2545 default: // known not saved yet spell (new or modified)
2547 // can be in case spell loading but learned at some previous spell loading
2548 if(loading && !learning)
2549 itr->second->state = PLAYERSPELL_UNCHANGED;
2551 return false;
2556 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2558 // talent: unlearn all other talent ranks (high and low)
2559 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2561 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2563 for(int i=0; i <5; ++i)
2565 // skip learning spell and no rank spell case
2566 uint32 rankSpellId = talentInfo->RankID[i];
2567 if(!rankSpellId || rankSpellId==spell_id)
2568 continue;
2570 // skip unknown ranks
2571 if(!HasSpell(rankSpellId))
2572 continue;
2574 removeSpell(rankSpellId);
2578 // non talent spell: learn low ranks (recursive call)
2579 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2581 if(loading) // at spells loading, no output, but allow save
2582 addSpell(prev_spell,active,true,loading,SPELL_WITHOUT_SLOT_ID,disabled);
2583 else // at normal learning
2584 learnSpell(prev_spell);
2587 PlayerSpell *newspell = new PlayerSpell;
2588 newspell->active = active;
2589 newspell->state = state;
2590 newspell->disabled = disabled;
2592 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2593 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2595 for( PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr )
2597 if(itr->second->state == PLAYERSPELL_REMOVED) continue;
2598 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr->first);
2599 if(!i_spellInfo) continue;
2601 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr->first) )
2603 if(itr->second->active)
2605 if(spellmgr.IsHighRankOfSpell(spell_id,itr->first))
2607 if(!loading) // not send spell (re-/over-)learn packets at loading
2609 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2610 data << uint16(itr->first);
2611 data << uint16(spell_id);
2612 GetSession()->SendPacket( &data );
2615 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2616 itr->second->active = false;
2617 itr->second->state = PLAYERSPELL_CHANGED;
2618 superceded_old = true; // new spell replace old in action bars and spell book.
2620 else if(spellmgr.IsHighRankOfSpell(itr->first,spell_id))
2622 if(!loading) // not send spell (re-/over-)learn packets at loading
2624 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2625 data << uint16(spell_id);
2626 data << uint16(itr->first);
2627 GetSession()->SendPacket( &data );
2630 // mark new spell as disable (not learned yet for client and will not learned)
2631 newspell->active = false;
2632 if(newspell->state != PLAYERSPELL_NEW)
2633 newspell->state = PLAYERSPELL_CHANGED;
2640 uint16 tmpslot=slot_id;
2642 if (tmpslot == SPELL_WITHOUT_SLOT_ID)
2644 uint16 maxid = 0;
2645 PlayerSpellMap::iterator itr;
2646 for (itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2648 if(itr->second->state == PLAYERSPELL_REMOVED)
2649 continue;
2650 if (itr->second->slotId > maxid)
2651 maxid = itr->second->slotId;
2653 tmpslot = maxid + 1;
2656 newspell->slotId = tmpslot;
2657 m_spells[spell_id] = newspell;
2659 // return false if spell disabled
2660 if (newspell->disabled)
2661 return false;
2664 uint32 talentCost = GetTalentSpellCost(spell_id);
2666 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2667 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2668 if( talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL) )
2670 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2671 CastSpell(this, spell_id, true);
2673 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2674 else if (IsPassiveSpell(spell_id))
2676 // if spell doesn't require a stance or the player is in the required stance
2677 if( ( !spellInfo->Stances &&
2678 spell_id != 5420 && spell_id != 5419 && spell_id != 7376 &&
2679 spell_id != 7381 && spell_id != 21156 && spell_id != 21009 &&
2680 spell_id != 21178 && spell_id != 33948 && spell_id != 40121 ) ||
2681 m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))) ||
2682 (spell_id == 5420 && m_form == FORM_TREE) ||
2683 (spell_id == 5419 && m_form == FORM_TRAVEL) ||
2684 (spell_id == 7376 && m_form == FORM_DEFENSIVESTANCE) ||
2685 (spell_id == 7381 && m_form == FORM_BERSERKERSTANCE) ||
2686 (spell_id == 21156 && m_form == FORM_BATTLESTANCE)||
2687 (spell_id == 21178 && (m_form == FORM_BEAR || m_form == FORM_DIREBEAR) ) ||
2688 (spell_id == 33948 && m_form == FORM_FLIGHT) ||
2689 (spell_id == 40121 && m_form == FORM_FLIGHT_EPIC) )
2690 //Check CasterAuraStates
2691 if (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)))
2692 CastSpell(this, spell_id, true);
2694 else if( IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP) )
2696 CastSpell(this, spell_id, true);
2697 return false;
2700 // update used talent points count
2701 m_usedTalentCount += talentCost;
2703 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2704 if(uint32 freeProfs = GetFreePrimaryProffesionPoints())
2706 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2707 SetFreePrimaryProffesions(freeProfs-1);
2710 // add dependent skills
2711 uint16 maxskill = GetMaxSkillValueForLevel();
2713 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2715 if(spellLearnSkill)
2717 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
2718 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
2720 if(skill_value < spellLearnSkill->value)
2721 skill_value = spellLearnSkill->value;
2723 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
2725 if(skill_max_value < new_skill_max_value)
2726 skill_max_value = new_skill_max_value;
2728 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
2730 else
2732 // not ranked skills
2733 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2734 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2736 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2738 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2739 if(!pSkill)
2740 continue;
2742 if(HasSkill(pSkill->id))
2743 continue;
2745 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2746 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2747 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
2749 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
2751 case SKILL_RANGE_LANGUAGE:
2752 SetSkill(pSkill->id, 300, 300 );
2753 break;
2754 case SKILL_RANGE_LEVEL:
2755 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
2756 break;
2757 case SKILL_RANGE_MONO:
2758 SetSkill(pSkill->id, 1, 1 );
2759 break;
2760 default:
2761 break;
2767 // learn dependent spells
2768 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2769 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2771 for(SpellLearnSpellMap::const_iterator itr = spell_begin; itr != spell_end; ++itr)
2773 if(!itr->second.autoLearned)
2775 if(loading) // at spells loading, no output, but allow save
2776 addSpell(itr->second.spell,true,true,loading);
2777 else // at normal learning
2778 learnSpell(itr->second.spell);
2782 if(!loading)
2783 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL);
2785 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2786 return active && !disabled && !superceded_old;
2789 void Player::learnSpell(uint32 spell_id)
2791 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2793 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
2794 bool active = disabled ? itr->second->active : true;
2796 bool learning = addSpell(spell_id,active);
2798 // learn all disabled higher ranks (recursive)
2799 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2800 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
2802 PlayerSpellMap::iterator iter = m_spells.find(i->second);
2803 if (disabled && iter != m_spells.end() && iter->second->disabled)
2804 learnSpell(i->second);
2807 // prevent duplicated entires in spell book
2808 if(!learning)
2809 return;
2811 WorldPacket data(SMSG_LEARNED_SPELL, 4);
2812 data << uint32(spell_id);
2813 GetSession()->SendPacket(&data);
2816 void Player::removeSpell(uint32 spell_id, bool disabled)
2818 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2819 if (itr == m_spells.end())
2820 return;
2822 if(itr->second->state == PLAYERSPELL_REMOVED || disabled && itr->second->disabled)
2823 return;
2825 // unlearn non talent higher ranks (recursive)
2826 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2827 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
2828 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
2829 removeSpell(itr2->second,disabled);
2831 // removing
2832 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2833 data << uint16(spell_id);
2834 GetSession()->SendPacket(&data);
2836 if (disabled)
2838 itr->second->disabled = disabled;
2839 if(itr->second->state != PLAYERSPELL_NEW)
2840 itr->second->state = PLAYERSPELL_CHANGED;
2842 else
2844 if(itr->second->state == PLAYERSPELL_NEW)
2846 delete itr->second;
2847 m_spells.erase(itr);
2849 else
2850 itr->second->state = PLAYERSPELL_REMOVED;
2853 RemoveAurasDueToSpell(spell_id);
2855 // remove pet auras
2856 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id))
2857 RemovePetAura(petSpell);
2859 // free talent points
2860 uint32 talentCosts = GetTalentSpellCost(spell_id);
2861 if(talentCosts > 0)
2863 if(talentCosts < m_usedTalentCount)
2864 m_usedTalentCount -= talentCosts;
2865 else
2866 m_usedTalentCount = 0;
2869 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
2870 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2872 uint32 freeProfs = GetFreePrimaryProffesionPoints()+1;
2873 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
2874 SetFreePrimaryProffesions(freeProfs);
2877 // remove dependent skill
2878 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2879 if(spellLearnSkill)
2881 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
2882 if(!prev_spell) // first rank, remove skill
2883 SetSkill(spellLearnSkill->skill,0,0);
2884 else
2886 // search prev. skill setting by spell ranks chain
2887 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
2888 while(!prevSkill && prev_spell)
2890 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
2891 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
2894 if(!prevSkill) // not found prev skill setting, remove skill
2895 SetSkill(spellLearnSkill->skill,0,0);
2896 else // set to prev. skill setting values
2898 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
2899 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
2901 if(skill_value > prevSkill->value)
2902 skill_value = prevSkill->value;
2904 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
2906 if(skill_max_value > new_skill_max_value)
2907 skill_max_value = new_skill_max_value;
2909 SetSkill(prevSkill->skill,skill_value,skill_max_value);
2914 else
2916 // not ranked skills
2917 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2918 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2920 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2922 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2923 if(!pSkill)
2924 continue;
2926 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2927 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2928 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
2930 // not reset skills for professions and racial abilities
2931 if( (pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
2932 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0) )
2933 continue;
2935 SetSkill(pSkill->id, 0, 0 );
2940 // remove dependent spells
2941 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2942 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2944 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
2945 removeSpell(itr2->second.spell, disabled);
2948 void Player::RemoveArenaSpellCooldowns()
2950 // remove cooldowns on spells that has < 15 min CD
2951 SpellCooldowns::iterator itr, next;
2952 // iterate spell cooldowns
2953 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
2955 next = itr;
2956 ++next;
2957 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
2958 // check if spellentry is present and if the cooldown is less than 15 mins
2959 if( entry &&
2960 entry->RecoveryTime <= 15 * MINUTE * 1000 &&
2961 entry->CategoryRecoveryTime <= 15 * MINUTE * 1000 )
2963 // notify player
2964 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
2965 data << uint32(itr->first);
2966 data << GetGUID();
2967 GetSession()->SendPacket(&data);
2968 // remove cooldown
2969 m_spellCooldowns.erase(itr);
2974 void Player::RemoveAllSpellCooldown()
2976 if(!m_spellCooldowns.empty())
2978 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
2980 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
2981 data << uint32(itr->first);
2982 data << uint64(GetGUID());
2983 GetSession()->SendPacket(&data);
2985 m_spellCooldowns.clear();
2989 void Player::_LoadSpellCooldowns(QueryResult *result)
2991 m_spellCooldowns.clear();
2993 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
2995 if(result)
2997 time_t curTime = time(NULL);
3001 Field *fields = result->Fetch();
3003 uint32 spell_id = fields[0].GetUInt32();
3004 uint32 item_id = fields[1].GetUInt32();
3005 time_t db_time = (time_t)fields[2].GetUInt64();
3007 if(!sSpellStore.LookupEntry(spell_id))
3009 sLog.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3010 continue;
3013 // skip outdated cooldown
3014 if(db_time <= curTime)
3015 continue;
3017 AddSpellCooldown(spell_id, item_id, db_time);
3019 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3021 while( result->NextRow() );
3023 delete result;
3027 void Player::_SaveSpellCooldowns()
3029 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3031 time_t curTime = time(NULL);
3033 // remove outdated and save active
3034 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3036 if(itr->second.end <= curTime)
3037 m_spellCooldowns.erase(itr++);
3038 else
3040 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));
3041 ++itr;
3046 uint32 Player::resetTalentsCost() const
3048 // The first time reset costs 1 gold
3049 if(m_resetTalentsCost < 1*GOLD)
3050 return 1*GOLD;
3051 // then 5 gold
3052 else if(m_resetTalentsCost < 5*GOLD)
3053 return 5*GOLD;
3054 // After that it increases in increments of 5 gold
3055 else if(m_resetTalentsCost < 10*GOLD)
3056 return 10*GOLD;
3057 else
3059 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3060 if(months > 0)
3062 // This cost will be reduced by a rate of 5 gold per month
3063 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3064 // to a minimum of 10 gold.
3065 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3067 else
3069 // After that it increases in increments of 5 gold
3070 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3071 // until it hits a cap of 50 gold.
3072 if(new_cost > 50*GOLD)
3073 new_cost = 50*GOLD;
3074 return new_cost;
3079 bool Player::resetTalents(bool no_cost)
3081 // not need after this call
3082 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3084 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_TALENTS;
3085 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS), GetGUIDLow());
3088 uint32 level = getLevel();
3089 uint32 talentPointsForLevel = level < 10 ? 0 : uint32((level-9)*sWorld.getRate(RATE_TALENT));
3091 if (m_usedTalentCount == 0)
3093 SetFreeTalentPoints(talentPointsForLevel);
3094 return false;
3097 uint32 cost = 0;
3099 if(!no_cost)
3101 cost = resetTalentsCost();
3103 if (GetMoney() < cost)
3105 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3106 return false;
3110 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); i++)
3112 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3114 if (!talentInfo) continue;
3116 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3118 if(!talentTabInfo)
3119 continue;
3121 // unlearn only talents for character class
3122 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3123 // to prevent unexpected lost normal learned spell skip another class talents
3124 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3125 continue;
3127 for (int j = 0; j < 5; j++)
3129 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3131 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3133 ++itr;
3134 continue;
3137 // remove learned spells (all ranks)
3138 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3140 // unlearn if first rank is talent or learned by talent
3141 if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3143 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3144 itr = GetSpellMap().begin();
3145 continue;
3147 else
3148 ++itr;
3153 SetFreeTalentPoints(talentPointsForLevel);
3155 if(!no_cost)
3157 ModifyMoney(-(int32)cost);
3159 m_resetTalentsCost = cost;
3160 m_resetTalentsTime = time(NULL);
3163 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3164 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3166 return true;
3169 bool Player::_removeSpell(uint16 spell_id)
3171 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3172 if (itr != m_spells.end())
3174 delete itr->second;
3175 m_spells.erase(itr);
3176 return true;
3178 return false;
3181 Mail* Player::GetMail(uint32 id)
3183 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); itr++)
3185 if ((*itr)->messageID == id)
3187 return (*itr);
3190 return NULL;
3193 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3195 if(target == this)
3197 Object::_SetCreateBits(updateMask, target);
3199 else
3201 for(uint16 index = 0; index < m_valuesCount; index++)
3203 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3204 updateMask->SetBit(index);
3209 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3211 if(target == this)
3213 Object::_SetUpdateBits(updateMask, target);
3215 else
3217 Object::_SetUpdateBits(updateMask, target);
3218 *updateMask &= updateVisualBits;
3222 void Player::InitVisibleBits()
3224 updateVisualBits.SetCount(PLAYER_END);
3226 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3227 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3228 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3229 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3230 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3231 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3232 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3233 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3234 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3235 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3236 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3237 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3238 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3239 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3240 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3241 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3242 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3243 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3244 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3245 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3246 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3247 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3248 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3249 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3250 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3251 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3252 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3253 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3254 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3255 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3256 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3257 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3258 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3259 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3260 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3261 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3262 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3263 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3264 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3265 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3266 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3267 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3268 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3269 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3270 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3271 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3272 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3273 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3274 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3275 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3276 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3277 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3278 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3279 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3280 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3282 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3283 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3284 updateVisualBits.SetBit(PLAYER_FLAGS);
3285 updateVisualBits.SetBit(PLAYER_GUILDID);
3286 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3287 updateVisualBits.SetBit(PLAYER_BYTES);
3288 updateVisualBits.SetBit(PLAYER_BYTES_2);
3289 updateVisualBits.SetBit(PLAYER_BYTES_3);
3290 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3291 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3293 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3294 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3295 updateVisualBits.SetBit(i);
3297 // Players visible items are not inventory stuff
3298 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3300 uint32 offset = i * MAX_VISIBLE_ITEM_OFFSET;
3302 // item creator
3303 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 0 + offset);
3304 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 1 + offset);
3306 // item entry
3307 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 0 + offset);
3309 // item enchantments
3310 for(uint8 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
3311 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 1 + j + offset);
3313 // random properties
3314 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES + offset);
3315 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_SEED + offset);
3316 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PAD + offset);
3319 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3322 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3324 for(int i = 0; i < EQUIPMENT_SLOT_END; i++)
3326 if(m_items[i] == NULL)
3327 continue;
3329 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3332 if(target == this)
3334 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3336 if(m_items[i] == NULL)
3337 continue;
3339 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3341 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
3343 if(m_items[i] == NULL)
3344 continue;
3346 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3350 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3353 void Player::DestroyForPlayer( Player *target ) const
3355 Unit::DestroyForPlayer( target );
3357 for(int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
3359 if(m_items[i] == NULL)
3360 continue;
3362 m_items[i]->DestroyForPlayer( target );
3365 if(target == this)
3367 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3369 if(m_items[i] == NULL)
3370 continue;
3372 m_items[i]->DestroyForPlayer( target );
3374 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
3376 if(m_items[i] == NULL)
3377 continue;
3379 m_items[i]->DestroyForPlayer( target );
3384 bool Player::HasSpell(uint32 spell) const
3386 PlayerSpellMap::const_iterator itr = m_spells.find((uint16)spell);
3387 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled);
3390 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3392 if (!trainer_spell)
3393 return TRAINER_SPELL_RED;
3395 if (!trainer_spell->spell)
3396 return TRAINER_SPELL_RED;
3398 // known spell
3399 if(HasSpell(trainer_spell->spell))
3400 return TRAINER_SPELL_GRAY;
3402 // check race/class requirement
3403 if(!IsSpellFitByClassAndRace(trainer_spell->spell))
3404 return TRAINER_SPELL_RED;
3406 // check level requirement
3407 if(getLevel() < trainer_spell->reqlevel)
3408 return TRAINER_SPELL_RED;
3410 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->spell))
3412 // check prev.rank requirement
3413 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3414 return TRAINER_SPELL_RED;
3416 // check additional spell requirement
3417 if(spell_chain->req && !HasSpell(spell_chain->req))
3418 return TRAINER_SPELL_RED;
3421 // check skill requirement
3422 if(trainer_spell->reqskill && GetBaseSkillValue(trainer_spell->reqskill) < trainer_spell->reqskillvalue)
3423 return TRAINER_SPELL_RED;
3425 // exist, already checked at loading
3426 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->spell);
3428 // secondary prof. or not prof. spell
3429 uint32 skill = spell->EffectMiscValue[1];
3431 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3432 return TRAINER_SPELL_GREEN;
3434 // check primary prof. limit
3435 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProffesionPoints() == 0)
3436 return TRAINER_SPELL_RED;
3438 return TRAINER_SPELL_GREEN;
3441 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3443 uint32 guid = GUID_LOPART(playerguid);
3445 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3446 // bones will be deleted by corpse/bones deleting thread shortly
3447 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3449 // remove from guild
3450 uint32 guildId = GetGuildIdFromDB(playerguid);
3451 if(guildId != 0)
3453 Guild* guild = objmgr.GetGuildById(guildId);
3454 if(guild)
3455 guild->DelMember(guid);
3458 // the player was uninvited already on logout so just remove from group
3459 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3460 if(resultGroup)
3462 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3463 delete resultGroup;
3464 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3465 if(group)
3467 RemoveFromGroup(group, playerguid);
3471 // remove signs from petitions (also remove petitions if owner);
3472 RemovePetitionsAndSigns(playerguid, 10);
3474 // return back all mails with COD and Item 0 1 2 3 4 5 6
3475 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);
3476 if(resultMail)
3480 Field *fields = resultMail->Fetch();
3482 uint32 mail_id = fields[0].GetUInt32();
3483 uint16 mailTemplateId= fields[1].GetUInt16();
3484 uint32 sender = fields[2].GetUInt32();
3485 std::string subject = fields[3].GetCppString();
3486 uint32 itemTextId = fields[4].GetUInt32();
3487 uint32 money = fields[5].GetUInt32();
3488 bool has_items = fields[6].GetBool();
3490 //we can return mail now
3491 //so firstly delete the old one
3492 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3494 MailItemsInfo mi;
3495 if(has_items)
3497 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", mail_id);
3498 if(resultItems)
3502 Field *fields2 = resultItems->Fetch();
3504 uint32 item_guidlow = fields2[0].GetUInt32();
3505 uint32 item_template = fields2[1].GetUInt32();
3507 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3508 if(!itemProto)
3510 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3511 continue;
3514 Item *pItem = NewItemOrBag(itemProto);
3515 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER)))
3517 pItem->FSetState(ITEM_REMOVED);
3518 pItem->SaveToDB(); // it also deletes item object !
3519 continue;
3522 mi.AddItem(item_guidlow, item_template, pItem);
3524 while (resultItems->NextRow());
3526 delete resultItems;
3530 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3532 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3534 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, mailTemplateId);
3536 while (resultMail->NextRow());
3538 delete resultMail;
3541 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3542 // Get guids of character's pets, will deleted in transaction
3543 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3545 // NOW we can finally clear other DB data related to character
3546 CharacterDatabase.BeginTransaction();
3547 if (resultPets)
3551 Field *fields3 = resultPets->Fetch();
3552 uint32 petguidlow = fields3[0].GetUInt32();
3553 Pet::DeleteFromDB(petguidlow);
3554 } while (resultPets->NextRow());
3555 delete resultPets;
3558 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3559 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3560 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3561 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3562 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3563 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3564 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3565 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3566 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3567 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3568 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3569 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3570 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3571 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3572 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3573 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3574 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3575 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3576 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3577 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
3578 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
3579 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
3580 CharacterDatabase.CommitTransaction();
3582 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3583 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
3586 void Player::SetMovement(PlayerMovementType pType)
3588 WorldPacket data;
3589 switch(pType)
3591 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
3592 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
3593 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
3594 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
3595 default:
3596 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
3597 return;
3599 data.append(GetPackGUID());
3600 data << uint32(0);
3601 GetSession()->SendPacket( &data );
3604 /* Preconditions:
3605 - a resurrectable corpse must not be loaded for the player (only bones)
3606 - the player must be in world
3608 void Player::BuildPlayerRepop()
3610 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
3611 data.append(GetPackGUID());
3612 GetSession()->SendPacket(&data);
3614 if(getRace() == RACE_NIGHTELF)
3615 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)
3616 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3618 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3619 // there must be SMSG.STOP_MIRROR_TIMER
3620 // there we must send 888 opcode
3622 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3623 if(GetCorpse())
3625 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3626 assert(false);
3629 // create a corpse and place it at the player's location
3630 CreateCorpse();
3631 Corpse *corpse = GetCorpse();
3632 if(!corpse)
3634 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3635 return;
3637 GetMap()->Add(corpse);
3639 // convert player body to ghost
3640 SetHealth( 1 );
3642 SetMovement(MOVE_WATER_WALK);
3643 if(!GetSession()->isLogingOut())
3644 SetMovement(MOVE_UNROOT);
3646 // BG - remove insignia related
3647 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
3649 SendCorpseReclaimDelay();
3651 // to prevent cheating
3652 corpse->ResetGhostTime();
3654 StopMirrorTimers(); //disable timers(bars)
3656 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
3658 SetByteValue(UNIT_FIELD_BYTES_1, 3, PLAYER_STATE_FLAG_ALWAYS_STAND);
3661 void Player::SendDelayResponse(const uint32 ml_seconds)
3663 //FIXME: is this delay time arg really need? 50msec by default in code
3664 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
3665 data << (uint32)time(NULL);
3666 data << (uint32)0;
3667 GetSession()->SendPacket( &data );
3670 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
3672 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
3673 data << uint32(-1);
3674 data << float(0);
3675 data << float(0);
3676 data << float(0);
3677 GetSession()->SendPacket(&data);
3679 // speed change, land walk
3681 // remove death flag + set aura
3682 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
3683 if(getRace() == RACE_NIGHTELF)
3684 RemoveAurasDueToSpell(20584); // speed bonuses
3685 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3687 setDeathState(ALIVE);
3689 SetMovement(MOVE_LAND_WALK);
3690 SetMovement(MOVE_UNROOT);
3692 m_deathTimer = 0;
3694 // set health/powers (0- will be set in caller)
3695 if(restore_percent>0.0f)
3697 SetHealth(uint32(GetMaxHealth()*restore_percent));
3698 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
3699 SetPower(POWER_RAGE, 0);
3700 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
3703 // update visibility
3704 ObjectAccessor::UpdateVisibilityForPlayer(this);
3706 // some items limited to specific map
3707 DestroyZoneLimitedItem( true, GetZoneId());
3709 if(!applySickness || getLevel() <= 10)
3710 return;
3712 //Characters from level 1-10 are not affected by resurrection sickness.
3713 //Characters from level 11-19 will suffer from one minute of sickness
3714 //for each level they are above 10.
3715 //Characters level 20 and up suffer from ten minutes of sickness.
3716 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
3718 if(int32(getLevel()) >= startLevel)
3720 // set resurrection sickness
3721 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
3723 // not full duration
3724 if(int32(getLevel()) < startLevel+9)
3726 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
3728 for(int i =0; i < 3; ++i)
3730 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
3732 Aur->SetAuraDuration(delta*1000);
3733 Aur->SendAuraUpdate(false);
3740 void Player::KillPlayer()
3742 SetMovement(MOVE_ROOT);
3744 StopMirrorTimers(); //disable timers(bars)
3746 setDeathState(CORPSE);
3747 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
3749 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
3750 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
3752 // 6 minutes until repop at graveyard
3753 m_deathTimer = 6*MINUTE*1000;
3755 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
3757 // don't create corpse at this moment, player might be falling
3759 // update visibility
3760 ObjectAccessor::UpdateObjectVisibility(this);
3763 void Player::CreateCorpse()
3765 // prevent existence 2 corpse for player
3766 SpawnCorpseBones();
3768 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
3770 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
3771 SetPvPDeath(false);
3773 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this, GetMapId(), GetPositionX(),
3774 GetPositionY(), GetPositionZ(), GetOrientation()))
3776 delete corpse;
3777 return;
3780 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
3781 _pb = GetUInt32Value(PLAYER_BYTES);
3782 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
3784 uint8 race = (uint8)(_uf);
3785 uint8 skin = (uint8)(_pb);
3786 uint8 face = (uint8)(_pb >> 8);
3787 uint8 hairstyle = (uint8)(_pb >> 16);
3788 uint8 haircolor = (uint8)(_pb >> 24);
3789 uint8 facialhair = (uint8)(_pb2);
3791 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
3792 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
3794 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
3795 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
3797 uint32 flags = CORPSE_FLAG_UNK2;
3798 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
3799 flags |= CORPSE_FLAG_HIDE_HELM;
3800 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
3801 flags |= CORPSE_FLAG_HIDE_CLOAK;
3802 if(InBattleGround())
3803 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
3804 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
3806 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
3808 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
3810 uint32 iDisplayID;
3811 uint16 iIventoryType;
3812 uint32 _cfi;
3813 for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
3815 if(m_items[i])
3817 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
3818 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
3820 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
3821 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
3825 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
3826 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
3827 assert(entry);
3828 if(entry->map_type != MAP_BATTLEGROUND)
3829 corpse->SaveToDB();
3831 // register for player, but not show
3832 ObjectAccessor::Instance().AddCorpse(corpse);
3835 void Player::SpawnCorpseBones()
3837 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
3838 SaveToDB(); // prevent loading as ghost without corpse
3841 Corpse* Player::GetCorpse() const
3843 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
3846 void Player::DurabilityLossAll(double percent, bool inventory)
3848 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
3849 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3850 DurabilityLoss(pItem,percent);
3852 if(inventory)
3854 // bags not have durability
3855 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3857 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
3858 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3859 DurabilityLoss(pItem,percent);
3861 // keys not have durability
3862 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3864 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3865 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3866 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
3867 if(Item* pItem = GetItemByPos( i, j ))
3868 DurabilityLoss(pItem,percent);
3872 void Player::DurabilityLoss(Item* item, double percent)
3874 if(!item )
3875 return;
3877 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3879 if(!pMaxDurability)
3880 return;
3882 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
3884 if(pDurabilityLoss < 1 )
3885 pDurabilityLoss = 1;
3887 DurabilityPointsLoss(item,pDurabilityLoss);
3890 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
3892 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
3893 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3894 DurabilityPointsLoss(pItem,points);
3896 if(inventory)
3898 // bags not have durability
3899 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3901 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
3902 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3903 DurabilityPointsLoss(pItem,points);
3905 // keys not have durability
3906 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3908 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3909 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3910 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
3911 if(Item* pItem = GetItemByPos( i, j ))
3912 DurabilityPointsLoss(pItem,points);
3916 void Player::DurabilityPointsLoss(Item* item, int32 points)
3918 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3919 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
3920 int32 pNewDurability = pOldDurability - points;
3922 if (pNewDurability < 0)
3923 pNewDurability = 0;
3924 else if (pNewDurability > pMaxDurability)
3925 pNewDurability = pMaxDurability;
3927 if (pOldDurability != pNewDurability)
3929 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
3930 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
3931 _ApplyItemMods(item,item->GetSlot(), false);
3933 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
3935 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
3936 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
3937 _ApplyItemMods(item,item->GetSlot(), true);
3939 item->SetState(ITEM_CHANGED, this);
3943 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
3945 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
3946 DurabilityPointsLoss(pItem,1);
3949 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
3951 uint32 TotalCost = 0;
3952 // equipped, backpack, bags itself
3953 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
3954 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
3956 // bank, buyback and keys not repaired
3958 // items in inventory bags
3959 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; j++)
3960 for(int i = 0; i < MAX_BAG_SIZE; i++)
3961 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
3962 return TotalCost;
3965 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
3967 Item* item = GetItemByPos(pos);
3969 uint32 TotalCost = 0;
3970 if(!item)
3971 return TotalCost;
3973 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3974 if(!maxDurability)
3975 return TotalCost;
3977 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
3979 if(cost)
3981 uint32 LostDurability = maxDurability - curDurability;
3982 if(LostDurability>0)
3984 ItemPrototype const *ditemProto = item->GetProto();
3986 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
3987 if(!dcost)
3989 sLog.outError("ERROR: RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
3990 return TotalCost;
3993 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
3994 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
3995 if(!dQualitymodEntry)
3997 sLog.outError("ERROR: RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
3998 return TotalCost;
4001 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4002 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4004 costs = uint32(costs * discountMod);
4006 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4007 costs = 1;
4009 if (guildBank)
4011 if (GetGuildId()==0)
4013 DEBUG_LOG("You are not member of a guild");
4014 return TotalCost;
4017 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
4018 if (!pGuild)
4019 return TotalCost;
4021 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4023 DEBUG_LOG("You do not have rights to withdraw for repairs");
4024 return TotalCost;
4027 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4029 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4030 return TotalCost;
4033 if (pGuild->GetGuildBankMoney() < costs)
4035 DEBUG_LOG("There is not enough money in bank");
4036 return TotalCost;
4039 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4040 TotalCost = costs;
4042 else if (GetMoney() < costs)
4044 DEBUG_LOG("You do not have enough money");
4045 return TotalCost;
4047 else
4048 ModifyMoney( -int32(costs) );
4052 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4053 item->SetState(ITEM_CHANGED, this);
4055 // reapply mods for total broken and repaired item if equipped
4056 if(IsEquipmentPos(pos) && !curDurability)
4057 _ApplyItemMods(item,pos & 255, true);
4058 return TotalCost;
4061 void Player::RepopAtGraveyard()
4063 // note: this can be called also when the player is alive
4064 // for example from WorldSession::HandleMovementOpcodes
4066 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4068 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4069 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4071 ResurrectPlayer(0.5f);
4072 SpawnCorpseBones();
4075 WorldSafeLocsEntry const *ClosestGrave = NULL;
4077 // Special handle for battleground maps
4078 BattleGround *bg = sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
4080 if(bg && (bg->GetTypeID() == BATTLEGROUND_AB || bg->GetTypeID() == BATTLEGROUND_EY))
4081 ClosestGrave = bg->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetTeam());
4082 else
4083 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4085 // stop countdown until repop
4086 m_deathTimer = 0;
4088 // if no grave found, stay at the current location
4089 // and don't show spirit healer location
4090 if(ClosestGrave)
4092 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4093 if(isDead()) // not send if alive, because it used in TeleportTo()
4095 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4096 data << ClosestGrave->map_id;
4097 data << ClosestGrave->x;
4098 data << ClosestGrave->y;
4099 data << ClosestGrave->z;
4100 GetSession()->SendPacket(&data);
4105 void Player::JoinedChannel(Channel *c)
4107 m_channels.push_back(c);
4110 void Player::LeftChannel(Channel *c)
4112 m_channels.remove(c);
4115 void Player::CleanupChannels()
4117 while(!m_channels.empty())
4119 Channel* ch = *m_channels.begin();
4120 m_channels.erase(m_channels.begin()); // remove from player's channel list
4121 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4122 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4123 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4126 sLog.outDebug("Player: channels cleaned up!");
4129 void Player::UpdateLocalChannels(uint32 newZone )
4131 if(m_channels.empty())
4132 return;
4134 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4135 if(!current_zone)
4136 return;
4138 ChannelMgr* cMgr = channelMgr(GetTeam());
4139 if(!cMgr)
4140 return;
4142 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4144 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4146 next = i; ++next;
4148 // skip non built-in channels
4149 if(!(*i)->IsConstant())
4150 continue;
4152 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4153 if(!ch)
4154 continue;
4156 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4157 continue;
4159 // new channel
4160 char new_channel_name_buf[100];
4161 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4162 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4164 if((*i)!=new_channel)
4166 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4168 // leave old channel
4169 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4170 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4171 LeftChannel(*i); // remove from player's channel list
4172 cMgr->LeftChannel(name); // delete if empty
4175 sLog.outDebug("Player: channels cleaned up!");
4178 void Player::LeaveLFGChannel()
4180 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4182 if((*i)->IsLFG())
4184 (*i)->Leave(GetGUID());
4185 break;
4190 void Player::UpdateDefense()
4192 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4194 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4196 // update dependent from defense skill part
4197 UpdateDefenseBonusesMod();
4201 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4203 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4205 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4206 return;
4209 float val = 1.0f;
4211 switch(modType)
4213 case FLAT_MOD:
4214 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4215 break;
4216 case PCT_MOD:
4217 if(amount <= -100.0f)
4218 amount = -200.0f;
4220 val = (100.0f + amount) / 100.0f;
4221 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4222 break;
4225 if(!CanModifyStats())
4226 return;
4228 switch(modGroup)
4230 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4231 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4232 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4233 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4234 default: break;
4238 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4240 if(modGroup >= BASEMOD_END || modType > MOD_END)
4242 sLog.outError("ERROR: trial to access non existed BaseModGroup or wrong BaseModType!");
4243 return 0.0f;
4246 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4247 return 0.0f;
4249 return m_auraBaseMod[modGroup][modType];
4252 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4254 if(modGroup >= BASEMOD_END)
4256 sLog.outError("ERROR: wrong BaseModGroup in GetTotalBaseModValue()!");
4257 return 0.0f;
4260 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4261 return 0.0f;
4263 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4266 uint32 Player::GetShieldBlockValue() const
4268 BaseModGroup modGroup = SHIELD_BLOCK_VALUE;
4270 float value = GetTotalBaseModValue(modGroup) + GetStat(STAT_STRENGTH)/20 - 1;
4272 value = (value < 0) ? 0 : value;
4274 return uint32(value);
4277 float Player::GetMeleeCritFromAgility()
4279 uint32 level = getLevel();
4280 uint32 pclass = getClass();
4282 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4284 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4285 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4286 if (critBase==NULL || critRatio==NULL)
4287 return 0.0f;
4289 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4290 return crit*100.0f;
4293 float Player::GetDodgeFromAgility()
4295 // Table for base dodge values
4296 float dodge_base[MAX_CLASSES] = {
4297 0.0075f, // Warrior
4298 0.00652f, // Paladin
4299 -0.0545f, // Hunter
4300 -0.0059f, // Rogue
4301 0.03183f, // Priest
4302 0.0114f, // DK
4303 0.0167f, // Shaman
4304 0.034575f, // Mage
4305 0.02011f, // Warlock
4306 0.0f, // ??
4307 -0.0187f // Druid
4309 // Crit/agility to dodge/agility coefficient multipliers
4310 float crit_to_dodge[MAX_CLASSES] = {
4311 1.1f, // Warrior
4312 1.0f, // Paladin
4313 1.6f, // Hunter
4314 2.0f, // Rogue
4315 1.0f, // Priest
4316 1.0f, // DK?
4317 1.0f, // Shaman
4318 1.0f, // Mage
4319 1.0f, // Warlock
4320 0.0f, // ??
4321 1.7f // Druid
4324 uint32 level = getLevel();
4325 uint32 pclass = getClass();
4327 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4329 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4330 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4331 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4332 return 0.0f;
4334 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4335 return dodge*100.0f;
4338 float Player::GetSpellCritFromIntellect()
4340 uint32 level = getLevel();
4341 uint32 pclass = getClass();
4343 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4345 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4346 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4347 if (critBase==NULL || critRatio==NULL)
4348 return 0.0f;
4350 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4351 return crit*100.0f;
4354 float Player::GetRatingCoefficient(CombatRating cr) const
4356 uint32 level = getLevel();
4358 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4360 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4361 if (Rating == NULL)
4362 return 1.0f; // By default use minimum coefficient (not must be called)
4364 return Rating->ratio;
4367 float Player::GetRatingBonusValue(CombatRating cr) const
4369 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4372 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4374 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.0f;
4375 if (melee>25.0f) melee = 25.0f;
4376 return uint32 (melee * damage /100.0f);
4379 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4381 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.0f;
4382 if (ranged>25.0f) ranged=25.0f;
4383 return uint32 (ranged * damage /100.0f);
4386 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4388 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.0f;
4389 // In wow script resilience limited to 25%
4390 if (spell>25.0f)
4391 spell = 25.0f;
4392 return uint32 (spell * damage / 100.0f);
4395 uint32 Player::GetDotDamageReduction(uint32 damage) const
4397 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4398 // Dot resilience not limited (limit it by 100%)
4399 if (spellDot > 100.0f)
4400 spellDot = 100.0f;
4401 return uint32 (spellDot * damage / 100.0f);
4404 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4406 switch (attType)
4408 case BASE_ATTACK:
4409 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4410 case OFF_ATTACK:
4411 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4412 default:
4413 break;
4415 return 0.0f;
4418 float Player::OCTRegenHPPerSpirit()
4420 uint32 level = getLevel();
4421 uint32 pclass = getClass();
4423 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4425 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4426 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4427 if (baseRatio==NULL || moreRatio==NULL)
4428 return 0.0f;
4430 // Formula from PaperDollFrame script
4431 float spirit = GetStat(STAT_SPIRIT);
4432 float baseSpirit = spirit;
4433 if (baseSpirit>50) baseSpirit = 50;
4434 float moreSpirit = spirit - baseSpirit;
4435 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4436 return regen;
4439 float Player::OCTRegenMPPerSpirit()
4441 uint32 level = getLevel();
4442 uint32 pclass = getClass();
4444 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4446 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4447 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4448 if (moreRatio==NULL)
4449 return 0.0f;
4451 // Formula get from PaperDollFrame script
4452 float spirit = GetStat(STAT_SPIRIT);
4453 float regen = spirit * moreRatio->ratio;
4454 return regen;
4457 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4459 ApplyModUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, value, apply);
4461 float RatingCoeffecient = GetRatingCoefficient(cr);
4462 float RatingChange = 0.0f;
4464 bool affectStats = CanModifyStats();
4466 switch (cr)
4468 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4469 case CR_DEFENSE_SKILL:
4470 UpdateDefenseBonusesMod();
4471 break;
4472 case CR_DODGE:
4473 UpdateDodgePercentage();
4474 break;
4475 case CR_PARRY:
4476 UpdateParryPercentage();
4477 break;
4478 case CR_BLOCK:
4479 UpdateBlockPercentage();
4480 break;
4481 case CR_HIT_MELEE:
4482 RatingChange = value / RatingCoeffecient;
4483 m_modMeleeHitChance += apply ? RatingChange : -RatingChange;
4484 break;
4485 case CR_HIT_RANGED:
4486 RatingChange = value / RatingCoeffecient;
4487 m_modRangedHitChance += apply ? RatingChange : -RatingChange;
4488 break;
4489 case CR_HIT_SPELL:
4490 RatingChange = value / RatingCoeffecient;
4491 m_modSpellHitChance += apply ? RatingChange : -RatingChange;
4492 break;
4493 case CR_CRIT_MELEE:
4494 if(affectStats)
4496 UpdateCritPercentage(BASE_ATTACK);
4497 UpdateCritPercentage(OFF_ATTACK);
4499 break;
4500 case CR_CRIT_RANGED:
4501 if(affectStats)
4502 UpdateCritPercentage(RANGED_ATTACK);
4503 break;
4504 case CR_CRIT_SPELL:
4505 if(affectStats)
4506 UpdateAllSpellCritChances();
4507 break;
4508 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4509 case CR_HIT_TAKEN_RANGED:
4510 break;
4511 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4512 break;
4513 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4514 case CR_CRIT_TAKEN_RANGED:
4515 break;
4516 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4517 break;
4518 case CR_HASTE_MELEE:
4519 RatingChange = value / RatingCoeffecient;
4520 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4521 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4522 break;
4523 case CR_HASTE_RANGED:
4524 RatingChange = value / RatingCoeffecient;
4525 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4526 break;
4527 case CR_HASTE_SPELL:
4528 RatingChange = value / RatingCoeffecient;
4529 ApplyCastTimePercentMod(RatingChange,apply);
4530 break;
4531 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4532 case CR_WEAPON_SKILL_OFFHAND:
4533 case CR_WEAPON_SKILL_RANGED:
4534 break;
4535 case CR_EXPERTISE:
4536 if(affectStats)
4538 UpdateExpertise(BASE_ATTACK);
4539 UpdateExpertise(OFF_ATTACK);
4541 break;
4545 void Player::SetRegularAttackTime()
4547 for(int i = 0; i < MAX_ATTACK; ++i)
4549 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4550 if(tmpitem && !tmpitem->IsBroken())
4552 ItemPrototype const *proto = tmpitem->GetProto();
4553 if(proto->Delay)
4554 SetAttackTime(WeaponAttackType(i), proto->Delay);
4555 else
4556 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4561 //skill+step, checking for max value
4562 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4564 if(!skill_id)
4565 return false;
4567 uint16 i=0;
4568 for (; i < PLAYER_MAX_SKILLS; i++)
4569 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
4570 break;
4572 if(i>=PLAYER_MAX_SKILLS)
4573 return false;
4575 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4576 uint32 value = SKILL_VALUE(data);
4577 uint32 max = SKILL_MAX(data);
4579 if ((!max) || (!value) || (value >= max))
4580 return false;
4582 if (value*512 < max*urand(0,512))
4584 uint32 new_value = value+step;
4585 if(new_value > max)
4586 new_value = max;
4588 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
4589 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4590 return true;
4593 return false;
4596 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
4598 if ( SkillValue >= GrayLevel )
4599 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
4600 if ( SkillValue >= GreenLevel )
4601 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
4602 if ( SkillValue >= YellowLevel )
4603 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
4604 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
4607 bool Player::UpdateCraftSkill(uint32 spellid)
4609 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
4611 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
4612 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
4614 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4616 if(_spell_idx->second->skillId)
4618 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
4620 // Alchemy Discoveries here
4621 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
4622 if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
4624 if(uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
4625 learnSpell(discoveredSpell);
4628 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
4630 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
4631 _spell_idx->second->max_value,
4632 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
4633 _spell_idx->second->min_value),
4634 craft_skill_gain);
4637 return false;
4640 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
4642 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
4644 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4646 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4647 switch (SkillId)
4649 case SKILL_HERBALISM:
4650 case SKILL_LOCKPICKING:
4651 case SKILL_JEWELCRAFTING:
4652 case SKILL_INSCRIPTION:
4653 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4654 case SKILL_SKINNING:
4655 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
4656 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4657 else
4658 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
4659 case SKILL_MINING:
4660 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
4661 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4662 else
4663 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
4665 return false;
4668 bool Player::UpdateFishingSkill()
4670 sLog.outDebug("UpdateFishingSkill");
4672 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
4674 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
4676 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4678 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
4681 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
4683 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
4684 if ( !SkillId )
4685 return false;
4687 if(Chance <= 0) // speedup in 0 chance case
4689 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4690 return false;
4693 uint16 i=0;
4694 for (; i < PLAYER_MAX_SKILLS; i++)
4695 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
4696 if ( i >= PLAYER_MAX_SKILLS )
4697 return false;
4699 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4700 uint16 SkillValue = SKILL_VALUE(data);
4701 uint16 MaxValue = SKILL_MAX(data);
4703 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
4704 return false;
4706 int32 Roll = irand(1,1000);
4708 if ( Roll <= Chance )
4710 uint32 new_value = SkillValue+step;
4711 if(new_value > MaxValue)
4712 new_value = MaxValue;
4714 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
4715 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4716 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
4717 return true;
4720 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4721 return false;
4724 void Player::UpdateWeaponSkill (WeaponAttackType attType)
4726 // no skill gain in pvp
4727 Unit *pVictim = getVictim();
4728 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
4729 return;
4731 if(IsInFeralForm())
4732 return; // always maximized SKILL_FERAL_COMBAT in fact
4734 if(m_form == FORM_TREE)
4735 return; // use weapon but not skill up
4737 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
4739 switch(attType)
4741 case BASE_ATTACK:
4743 Item *tmpitem = GetWeaponForAttack(attType,true);
4745 if (!tmpitem)
4746 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
4747 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
4748 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4749 break;
4751 case OFF_ATTACK:
4752 case RANGED_ATTACK:
4754 Item *tmpitem = GetWeaponForAttack(attType,true);
4755 if (tmpitem)
4756 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4757 break;
4760 UpdateAllCritPercentages();
4763 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, MeleeHitOutcome outcome, bool defence)
4765 switch(outcome)
4767 case MELEE_HIT_CRIT:
4768 case MELEE_HIT_DODGE:
4769 case MELEE_HIT_PARRY:
4770 case MELEE_HIT_BLOCK:
4771 case MELEE_HIT_BLOCK_CRIT:
4772 return;
4774 default:
4775 break;
4778 uint32 plevel = getLevel(); // if defense than pVictim == attacker
4779 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
4780 uint32 moblevel = pVictim->getLevelForTarget(this);
4781 if(moblevel < greylevel)
4782 return;
4784 if (moblevel > plevel + 5)
4785 moblevel = plevel + 5;
4787 uint32 lvldif = moblevel - greylevel;
4788 if(lvldif < 3)
4789 lvldif = 3;
4791 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
4792 if(skilldif <= 0)
4793 return;
4795 float chance = float(3 * lvldif * skilldif) / plevel;
4796 if(!defence)
4798 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
4799 chance *= 0.1f * GetStat(STAT_INTELLECT);
4802 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
4804 if(roll_chance_f(chance))
4806 if(defence)
4807 UpdateDefense();
4808 else
4809 UpdateWeaponSkill(attType);
4811 else
4812 return;
4815 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
4817 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4818 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
4820 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
4821 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
4822 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
4824 if(talent) // permanent bonus stored in high part
4825 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
4826 else // temporary/item bonus stored in low part
4827 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
4828 return;
4832 void Player::UpdateMaxSkills()
4834 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
4836 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4837 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4839 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
4841 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
4842 if(!pSkill)
4843 continue;
4845 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
4846 continue;
4848 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4849 uint32 max = SKILL_MAX(data);
4850 uint32 val = SKILL_VALUE(data);
4852 // update only level dependent max skill values
4853 if(max!=1 && max != maxconfskill)
4855 uint32 max_Skill = GetMaxSkillValueForLevel();
4856 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,max_Skill));
4861 void Player::UpdateSkillsToMaxSkillsForLevel()
4863 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4864 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4866 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
4867 if( IsProfessionSkill(pskill) || pskill == SKILL_RIDING )
4868 continue;
4869 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4871 uint32 max = SKILL_MAX(data);
4873 if(max > 1)
4874 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
4876 if(pskill == SKILL_DEFENSE)
4877 UpdateDefenseBonusesMod();
4881 // This functions sets a skill line value (and adds if doesn't exist yet)
4882 // To "remove" a skill line, set it's values to zero
4883 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
4885 if(!id)
4886 return;
4888 uint16 i=0;
4889 for (; i < PLAYER_MAX_SKILLS; i++)
4890 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
4892 if(i<PLAYER_MAX_SKILLS) //has skill
4894 if(currVal)
4896 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
4897 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4899 else //remove
4901 // clear skill fields
4902 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
4903 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
4904 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
4906 // remove spells that depend on this skill when removing the skill
4907 for (PlayerSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
4909 ++next;
4910 if(itr->second->state == PLAYERSPELL_REMOVED)
4911 continue;
4913 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(itr->first);
4914 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(itr->first);
4916 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4918 if (_spell_idx->second->skillId == id)
4920 // this may remove more than one spell (dependents)
4921 removeSpell(itr->first);
4922 next = m_spells.begin();
4923 break;
4929 else if(currVal) //add
4931 for (i=0; i < PLAYER_MAX_SKILLS; i++)
4932 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4934 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
4935 if(!pSkill)
4937 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
4938 return;
4940 // enable unlearn button for primary professions only
4941 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
4942 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
4943 else
4944 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
4945 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
4946 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4948 // apply skill bonuses
4949 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
4951 // temporary bonuses
4952 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
4953 for(AuraList::const_iterator i = mModSkill.begin(); i != mModSkill.end(); ++i)
4954 if ((*i)->GetModifier()->m_miscvalue == int32(id))
4955 (*i)->ApplyModifier(true);
4957 // permanent bonuses
4958 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
4959 for(AuraList::const_iterator i = mModSkillTalent.begin(); i != mModSkillTalent.end(); ++i)
4960 if ((*i)->GetModifier()->m_miscvalue == int32(id))
4961 (*i)->ApplyModifier(true);
4963 // Learn all spells for skill
4964 learnSkillRewardedSpells(id);
4965 return;
4970 bool Player::HasSkill(uint32 skill) const
4972 if(!skill)return false;
4973 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4975 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
4977 return true;
4980 return false;
4983 uint16 Player::GetSkillValue(uint32 skill) const
4985 if(!skill)
4986 return 0;
4988 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4990 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
4992 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
4994 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
4995 result += SKILL_TEMP_BONUS(bonus);
4996 result += SKILL_PERM_BONUS(bonus);
4997 return result < 0 ? 0 : result;
5000 return 0;
5003 uint16 Player::GetMaxSkillValue(uint32 skill) const
5005 if(!skill)return 0;
5006 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5008 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5010 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5012 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5013 result += SKILL_TEMP_BONUS(bonus);
5014 result += SKILL_PERM_BONUS(bonus);
5015 return result < 0 ? 0 : result;
5018 return 0;
5021 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5023 if(!skill)return 0;
5024 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5026 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5028 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5031 return 0;
5034 uint16 Player::GetBaseSkillValue(uint32 skill) const
5036 if(!skill)return 0;
5037 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5039 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5041 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5042 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5043 return result < 0 ? 0 : result;
5046 return 0;
5049 uint16 Player::GetPureSkillValue(uint32 skill) const
5051 if(!skill)return 0;
5052 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5054 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5056 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5059 return 0;
5062 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5064 if(!skill)
5065 return 0;
5067 for (int i = 0; i < PLAYER_MAX_SKILLS; i++)
5069 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5071 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5075 return 0;
5078 void Player::SendInitialActionButtons()
5080 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5082 WorldPacket data(SMSG_ACTION_BUTTONS, (MAX_ACTION_BUTTONS*4));
5083 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5085 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5086 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5088 data << uint16(itr->second.action);
5089 data << uint8(itr->second.misc);
5090 data << uint8(itr->second.type);
5092 else
5094 data << uint32(0);
5098 GetSession()->SendPacket( &data );
5099 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5102 void Player::addActionButton(const uint8 button, const uint16 action, const uint8 type, const uint8 misc)
5104 if(button >= MAX_ACTION_BUTTONS)
5106 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5107 return;
5110 // check cheating with adding non-known spells to action bar
5111 if(type==ACTION_BUTTON_SPELL)
5113 if(!sSpellStore.LookupEntry(action))
5115 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5116 return;
5119 if(!HasSpell(action))
5121 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5122 return;
5126 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5128 if (buttonItr==m_actionButtons.end())
5129 { // just add new button
5130 m_actionButtons[button] = ActionButton(action,type,misc);
5132 else
5133 { // change state of current button
5134 ActionButtonUpdateState uState = buttonItr->second.uState;
5135 buttonItr->second = ActionButton(action,type,misc);
5136 if (uState != ACTIONBUTTON_NEW) buttonItr->second.uState = ACTIONBUTTON_CHANGED;
5139 sLog.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action, button );
5142 void Player::removeActionButton(uint8 button)
5144 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5145 if (buttonItr==m_actionButtons.end())
5146 return;
5148 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5149 m_actionButtons.erase(buttonItr); // new and not saved
5150 else
5151 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5153 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5156 void Player::SetDontMove(bool dontMove)
5158 m_dontMove = dontMove;
5161 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5163 // prevent crash when a bad coord is sent by the client
5164 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5166 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5167 return false;
5170 Map *m = MapManager::Instance().GetMap(GetMapId(), this);
5172 const float old_x = GetPositionX();
5173 const float old_y = GetPositionY();
5174 const float old_z = GetPositionZ();
5175 const float old_r = GetOrientation();
5177 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5179 if (teleport || old_x != x || old_y != y || old_z != z)
5180 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5181 else
5182 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5184 // move and update visible state if need
5185 m->PlayerRelocation(this, x, y, z, orientation);
5187 // reread after Map::Relocation
5188 m = MapManager::Instance().GetMap(GetMapId(), this);
5189 x = GetPositionX();
5190 y = GetPositionY();
5191 z = GetPositionZ();
5194 // code block for underwater state update
5195 UpdateUnderwaterState(m, x, y, z);
5197 CheckExploreSystem();
5199 // group update
5200 if(GetGroup())
5201 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5203 return true;
5206 void Player::SaveRecallPosition()
5208 m_recallMap = GetMapId();
5209 m_recallX = GetPositionX();
5210 m_recallY = GetPositionY();
5211 m_recallZ = GetPositionZ();
5212 m_recallO = GetOrientation();
5215 void Player::SendMessageToSet(WorldPacket *data, bool self)
5217 MapManager::Instance().GetMap(GetMapId(), this)->MessageBroadcast(this, data, self);
5220 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5222 MapManager::Instance().GetMap(GetMapId(), this)->MessageDistBroadcast(this, data, dist, self);
5225 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5227 MapManager::Instance().GetMap(GetMapId(), this)->MessageDistBroadcast(this, data, dist, self,own_team_only);
5230 void Player::SendDirectMessage(WorldPacket *data)
5232 GetSession()->SendPacket(data);
5235 void Player::CheckExploreSystem()
5237 if (!isAlive())
5238 return;
5240 if (isInFlight())
5241 return;
5243 uint16 areaFlag=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY());
5244 if(areaFlag==0xffff)
5245 return;
5246 int offset = areaFlag / 32;
5248 if(offset >= 128)
5250 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);
5251 return;
5254 uint32 val = (uint32)(1 << (areaFlag % 32));
5255 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5257 if( !(currFields & val) )
5259 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5261 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5262 if(!p)
5264 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5266 else if(p->area_level > 0)
5268 uint32 area = p->ID;
5269 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5271 SendExplorationExperience(area,0);
5273 else
5275 int32 diff = int32(getLevel()) - p->area_level;
5276 uint32 XP = 0;
5277 if (diff < -5)
5279 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5281 else if (diff > 5)
5283 int32 exploration_percent = (100-((diff-5)*5));
5284 if (exploration_percent > 100)
5285 exploration_percent = 100;
5286 else if (exploration_percent < 0)
5287 exploration_percent = 0;
5289 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5291 else
5293 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5296 GiveXP( XP, NULL );
5297 SendExplorationExperience(area,XP);
5299 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5304 uint32 Player::TeamForRace(uint8 race)
5306 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5307 if(!rEntry)
5309 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5310 return ALLIANCE;
5313 switch(rEntry->TeamID)
5315 case 7: return ALLIANCE;
5316 case 1: return HORDE;
5319 sLog.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5320 return ALLIANCE;
5323 uint32 Player::getFactionForRace(uint8 race)
5325 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5326 if(!rEntry)
5328 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5329 return 0;
5332 return rEntry->FactionID;
5335 void Player::setFactionForRace(uint8 race)
5337 m_team = TeamForRace(race);
5338 setFaction( getFactionForRace(race) );
5341 void Player::UpdateReputation() const
5343 sLog.outDetail( "WORLD: Player::UpdateReputation" );
5345 for(FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
5347 SendFactionState(&(itr->second));
5351 void Player::SendFactionState(FactionState const* faction) const
5353 if(faction->Flags & FACTION_FLAG_VISIBLE) //If faction is visible then update it
5355 WorldPacket data(SMSG_SET_FACTION_STANDING, (16)); // last check 2.4.0
5356 data << (float) 0; // unk 2.4.0
5357 data << (uint8) 0; // wotlk 8634
5358 data << (uint32) 1; // count
5359 // for
5360 data << (uint32) faction->ReputationListID;
5361 data << (uint32) faction->Standing;
5362 // end for
5363 GetSession()->SendPacket(&data);
5367 void Player::SendInitialReputations()
5369 WorldPacket data(SMSG_INITIALIZE_FACTIONS, (4+128*5));
5370 data << uint32 (0x00000080);
5372 RepListID a = 0;
5374 for (FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); itr++)
5376 // fill in absent fields
5377 for (; a != itr->first; a++)
5379 data << uint8 (0x00);
5380 data << uint32 (0x00000000);
5383 // fill in encountered data
5384 data << uint8 (itr->second.Flags);
5385 data << uint32 (itr->second.Standing);
5387 ++a;
5390 // fill in absent fields
5391 for (; a != 128; a++)
5393 data << uint8 (0x00);
5394 data << uint32 (0x00000000);
5397 GetSession()->SendPacket(&data);
5400 FactionState const* Player::GetFactionState( FactionEntry const* factionEntry) const
5402 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5403 if (itr != m_factions.end())
5404 return &itr->second;
5406 return NULL;
5409 void Player::SetFactionAtWar(FactionState* faction, bool atWar)
5411 // not allow declare war to own faction
5412 if(atWar && (faction->Flags & FACTION_FLAG_PEACE_FORCED) )
5413 return;
5415 // already set
5416 if(((faction->Flags & FACTION_FLAG_AT_WAR) != 0) == atWar)
5417 return;
5419 if( atWar )
5420 faction->Flags |= FACTION_FLAG_AT_WAR;
5421 else
5422 faction->Flags &= ~FACTION_FLAG_AT_WAR;
5424 faction->Changed = true;
5427 void Player::SetFactionInactive(FactionState* faction, bool inactive)
5429 // always invisible or hidden faction can't be inactive
5430 if(inactive && ((faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN)) || !(faction->Flags & FACTION_FLAG_VISIBLE) ) )
5431 return;
5433 // already set
5434 if(((faction->Flags & FACTION_FLAG_INACTIVE) != 0) == inactive)
5435 return;
5437 if(inactive)
5438 faction->Flags |= FACTION_FLAG_INACTIVE;
5439 else
5440 faction->Flags &= ~FACTION_FLAG_INACTIVE;
5442 faction->Changed = true;
5445 void Player::SetFactionVisibleForFactionTemplateId(uint32 FactionTemplateId)
5447 FactionTemplateEntry const*factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5449 if(!factionTemplateEntry)
5450 return;
5452 SetFactionVisibleForFactionId(factionTemplateEntry->faction);
5455 void Player::SetFactionVisibleForFactionId(uint32 FactionId)
5457 FactionEntry const *factionEntry = sFactionStore.LookupEntry(FactionId);
5458 if(!factionEntry)
5459 return;
5461 if(factionEntry->reputationListID < 0)
5462 return;
5464 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5465 if (itr == m_factions.end())
5466 return;
5468 SetFactionVisible(&itr->second);
5471 void Player::SetFactionVisible(FactionState* faction)
5473 // always invisible or hidden faction can't be make visible
5474 if(faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN))
5475 return;
5477 // already set
5478 if(faction->Flags & FACTION_FLAG_VISIBLE)
5479 return;
5481 faction->Flags |= FACTION_FLAG_VISIBLE;
5482 faction->Changed = true;
5484 if(!m_session->PlayerLoading())
5486 // make faction visible in reputation list at client
5487 WorldPacket data(SMSG_SET_FACTION_VISIBLE, 4);
5488 data << faction->ReputationListID;
5489 GetSession()->SendPacket(&data);
5493 void Player::SetInitialFactions()
5495 for(unsigned int i = 1; i < sFactionStore.GetNumRows(); i++)
5497 FactionEntry const *factionEntry = sFactionStore.LookupEntry(i);
5499 if( factionEntry && (factionEntry->reputationListID >= 0))
5501 FactionState newFaction;
5502 newFaction.ID = factionEntry->ID;
5503 newFaction.ReputationListID = factionEntry->reputationListID;
5504 newFaction.Standing = 0;
5505 newFaction.Flags = GetDefaultReputationFlags(factionEntry);
5506 newFaction.Changed = true;
5508 m_factions[newFaction.ReputationListID] = newFaction;
5513 uint32 Player::GetDefaultReputationFlags(const FactionEntry *factionEntry) const
5515 if (!factionEntry)
5516 return 0;
5518 uint32 raceMask = getRaceMask();
5519 uint32 classMask = getClassMask();
5520 for (int i=0; i < 4; i++)
5522 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5523 (factionEntry->BaseRepClassMask[i]==0 ||
5524 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5525 return factionEntry->ReputationFlags[i];
5527 return 0;
5530 int32 Player::GetBaseReputation(const FactionEntry *factionEntry) const
5532 if (!factionEntry)
5533 return 0;
5535 uint32 raceMask = getRaceMask();
5536 uint32 classMask = getClassMask();
5537 for (int i=0; i < 4; i++)
5539 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5540 (factionEntry->BaseRepClassMask[i]==0 ||
5541 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5542 return factionEntry->BaseRepValue[i];
5545 // in faction.dbc exist factions with (RepListId >=0, listed in character reputation list) with all BaseRepRaceMask[i]==0
5546 return 0;
5549 int32 Player::GetReputation(uint32 faction_id) const
5551 FactionEntry const *factionEntry = sFactionStore.LookupEntry(faction_id);
5553 if (!factionEntry)
5555 sLog.outError("Player::GetReputation: Can't get reputation of %s for unknown faction (faction template id) #%u.",GetName(), faction_id);
5556 return 0;
5559 return GetReputation(factionEntry);
5562 int32 Player::GetReputation(const FactionEntry *factionEntry) const
5564 // Faction without recorded reputation. Just ignore.
5565 if(!factionEntry)
5566 return 0;
5568 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5569 if (itr != m_factions.end())
5570 return GetBaseReputation(factionEntry) + itr->second.Standing;
5572 return 0;
5575 ReputationRank Player::GetReputationRank(uint32 faction) const
5577 FactionEntry const*factionEntry = sFactionStore.LookupEntry(faction);
5578 if(!factionEntry)
5579 return MIN_REPUTATION_RANK;
5581 return GetReputationRank(factionEntry);
5584 ReputationRank Player::ReputationToRank(int32 standing) const
5586 int32 Limit = Reputation_Cap + 1;
5587 for (int i = MAX_REPUTATION_RANK-1; i >= MIN_REPUTATION_RANK; --i)
5589 Limit -= ReputationRank_Length[i];
5590 if (standing >= Limit )
5591 return ReputationRank(i);
5593 return MIN_REPUTATION_RANK;
5596 ReputationRank Player::GetReputationRank(const FactionEntry *factionEntry) const
5598 int32 Reputation = GetReputation(factionEntry);
5599 return ReputationToRank(Reputation);
5602 ReputationRank Player::GetBaseReputationRank(const FactionEntry *factionEntry) const
5604 int32 Reputation = GetBaseReputation(factionEntry);
5605 return ReputationToRank(Reputation);
5608 bool Player::ModifyFactionReputation(uint32 FactionTemplateId, int32 DeltaReputation)
5610 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5612 if(!factionTemplateEntry)
5614 sLog.outError("Player::ModifyFactionReputation: Can't update reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5615 return false;
5618 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5620 // Faction without recorded reputation. Just ignore.
5621 if(!factionEntry)
5622 return false;
5624 return ModifyFactionReputation(factionEntry, DeltaReputation);
5627 bool Player::ModifyFactionReputation(FactionEntry const* factionEntry, int32 standing)
5629 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5630 if (flist)
5632 bool res = false;
5633 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5635 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5636 if(factionEntryCalc)
5637 res = ModifyOneFactionReputation(factionEntryCalc, standing);
5639 return res;
5641 else
5642 return ModifyOneFactionReputation(factionEntry, standing);
5645 bool Player::ModifyOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5647 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5648 if (itr != m_factions.end())
5650 int32 BaseRep = GetBaseReputation(factionEntry);
5651 int32 new_rep = BaseRep + itr->second.Standing + standing;
5653 if (new_rep > Reputation_Cap)
5654 new_rep = Reputation_Cap;
5655 else
5656 if (new_rep < Reputation_Bottom)
5657 new_rep = Reputation_Bottom;
5659 if(ReputationToRank(new_rep) <= REP_HOSTILE)
5660 SetFactionAtWar(&itr->second,true);
5662 itr->second.Standing = new_rep - BaseRep;
5663 itr->second.Changed = true;
5665 SetFactionVisible(&itr->second);
5667 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
5669 if(uint32 questid = GetQuestSlotQuestId(i))
5671 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
5672 if( qInfo && qInfo->GetRepObjectiveFaction() == factionEntry->ID )
5674 QuestStatusData& q_status = mQuestStatus[questid];
5675 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
5677 if(GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
5678 if ( CanCompleteQuest( questid ) )
5679 CompleteQuest( questid );
5681 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
5683 if(GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
5684 IncompleteQuest( questid );
5690 SendFactionState(&(itr->second));
5692 return true;
5694 return false;
5697 bool Player::SetFactionReputation(uint32 FactionTemplateId, int32 standing)
5699 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5701 if(!factionTemplateEntry)
5703 sLog.outError("Player::SetFactionReputation: Can't set reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5704 return false;
5707 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5709 // Faction without recorded reputation. Just ignore.
5710 if(!factionEntry)
5711 return false;
5713 return SetFactionReputation(factionEntry, standing);
5716 bool Player::SetFactionReputation(FactionEntry const* factionEntry, int32 standing)
5718 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5719 if (flist)
5721 bool res = false;
5722 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5724 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5725 if(factionEntryCalc)
5726 res = SetOneFactionReputation(factionEntryCalc, standing);
5728 return res;
5730 else
5731 return SetOneFactionReputation(factionEntry, standing);
5734 bool Player::SetOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5736 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5737 if (itr != m_factions.end())
5739 if (standing > Reputation_Cap)
5740 standing = Reputation_Cap;
5741 else
5742 if (standing < Reputation_Bottom)
5743 standing = Reputation_Bottom;
5745 int32 BaseRep = GetBaseReputation(factionEntry);
5746 itr->second.Standing = standing - BaseRep;
5747 itr->second.Changed = true;
5749 SetFactionVisible(&itr->second);
5751 if(ReputationToRank(standing) <= REP_HOSTILE)
5752 SetFactionAtWar(&itr->second,true);
5754 SendFactionState(&(itr->second));
5755 return true;
5757 return false;
5760 //Calculate total reputation percent player gain with quest/creature level
5761 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, bool for_quest)
5763 // for grey creature kill received 20%, in other case 100.
5764 int32 percent = (!for_quest && (creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))) ? 20 : 100;
5766 int32 repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5768 percent += rep > 0 ? repMod : -repMod;
5770 if(percent <=0)
5771 return 0;
5773 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100);
5776 //Calculates how many reputation points player gains in victim's enemy factions
5777 void Player::RewardReputation(Unit *pVictim, float rate)
5779 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5780 return;
5782 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5784 if(!Rep)
5785 return;
5787 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5789 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue1,false);
5790 donerep1 = int32(donerep1*rate);
5791 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5792 uint32 current_reputation_rank1 = GetReputationRank(factionEntry1);
5793 if(factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5794 ModifyFactionReputation(factionEntry1, donerep1);
5796 // Wiki: Team factions value divided by 2
5797 if(Rep->is_teamaward1)
5799 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5800 if(team1_factionEntry)
5801 ModifyFactionReputation(team1_factionEntry, donerep1 / 2);
5805 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5807 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue2,false);
5808 donerep2 = int32(donerep2*rate);
5809 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5810 uint32 current_reputation_rank2 = GetReputationRank(factionEntry2);
5811 if(factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5812 ModifyFactionReputation(factionEntry2, donerep2);
5814 // Wiki: Team factions value divided by 2
5815 if(Rep->is_teamaward2)
5817 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5818 if(team2_factionEntry)
5819 ModifyFactionReputation(team2_factionEntry, donerep2 / 2);
5824 //Calculate how many reputation points player gain with the quest
5825 void Player::RewardReputation(Quest const *pQuest)
5827 // quest reputation reward/loss
5828 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5830 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5832 int32 rep = CalculateReputationGain(pQuest->GetQuestLevel(),pQuest->RewRepValue[i],true);
5833 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
5834 if(factionEntry)
5835 ModifyFactionReputation(factionEntry, rep);
5839 // TODO: implement reputation spillover
5842 void Player::UpdateArenaFields(void)
5844 /* arena calcs go here */
5847 void Player::UpdateHonorFields()
5849 /// called when rewarding honor and at each save
5850 uint64 now = time(NULL);
5851 uint64 today = uint64(time(NULL) / DAY) * DAY;
5853 if(m_lastHonorUpdateTime < today)
5855 uint64 yesterday = today - DAY;
5857 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
5859 // update yesterday's contribution
5860 if(m_lastHonorUpdateTime >= yesterday )
5862 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
5864 // this is the first update today, reset today's contribution
5865 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
5866 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
5868 else
5870 // no honor/kills yesterday or today, reset
5871 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
5872 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
5876 m_lastHonorUpdateTime = now;
5879 ///Calculate the amount of honor gained based on the victim
5880 ///and the size of the group for which the honor is divided
5881 ///An exact honor value can also be given (overriding the calcs)
5882 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
5884 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5885 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
5886 return false;
5888 uint64 victim_guid = 0;
5889 uint32 victim_rank = 0;
5891 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5892 UpdateHonorFields();
5894 if(honor <= 0)
5896 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
5897 return false;
5899 victim_guid = uVictim->GetGUID();
5901 if( uVictim->GetTypeId() == TYPEID_PLAYER )
5903 Player *pVictim = (Player *)uVictim;
5905 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
5906 return false;
5908 float f = 1; //need for total kills (?? need more info)
5909 uint32 k_grey = 0;
5910 uint32 k_level = getLevel();
5911 uint32 v_level = pVictim->getLevel();
5914 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
5915 // [0] Just name
5916 // [1..14] Alliance honor titles and player name
5917 // [15..28] Horde honor titles and player name
5918 // [29..38] Other title and player name
5919 // [39+] Nothing
5920 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
5921 // Get Killer titles, CharTitlesEntry::bit_index
5922 // Ranks:
5923 // title[1..14] -> rank[5..18]
5924 // title[15..28] -> rank[5..18]
5925 // title[other] -> 0
5926 if (victim_title == 0)
5927 victim_guid = 0; // Don't show HK: <rank> message, only log.
5928 else if (victim_title < 15)
5929 victim_rank = victim_title + 4;
5930 else if (victim_title < 29)
5931 victim_rank = victim_title - 14 + 4;
5932 else
5933 victim_guid = 0; // Don't show HK: <rank> message, only log.
5936 if(k_level <= 5)
5937 k_grey = 0;
5938 else if( k_level <= 39 )
5939 k_grey = k_level - 5 - k_level/10;
5940 else
5941 k_grey = k_level - 1 - k_level/5;
5943 if(v_level<=k_grey)
5944 return false;
5946 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
5948 int32 v_rank =1; //need more info
5950 honor = ((f * diff_level * (190 + v_rank*10))/6);
5951 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
5953 // count the number of playerkills in one day
5954 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
5955 // and those in a lifetime
5956 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
5958 else
5960 Creature *cVictim = (Creature *)uVictim;
5962 if (!cVictim->isRacialLeader())
5963 return false;
5965 honor = 100; // ??? need more info
5966 victim_rank = 19; // HK: Leader
5970 if (uVictim != NULL)
5972 honor *= sWorld.getRate(RATE_HONOR);
5974 if(groupsize > 1)
5975 honor /= groupsize;
5977 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
5980 // honor - for show honor points in log
5981 // victim_guid - for show victim name in log
5982 // victim_rank [1..4] HK: <dishonored rank>
5983 // victim_rank [5..19] HK: <alliance\horde rank>
5984 // victim_rank [0,20+] HK: <>
5985 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
5986 data << (uint32) honor;
5987 data << (uint64) victim_guid;
5988 data << (uint32) victim_rank;
5990 GetSession()->SendPacket(&data);
5992 // add honor points
5993 ModifyHonorPoints(int32(honor));
5995 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
5996 return true;
5999 void Player::ModifyHonorPoints( int32 value )
6001 if(value < 0)
6003 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
6004 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
6005 else
6006 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
6008 else
6009 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
6012 void Player::ModifyArenaPoints( int32 value )
6014 if(value < 0)
6016 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
6017 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
6018 else
6019 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
6021 else
6022 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
6025 uint32 Player::GetGuildIdFromDB(uint64 guid)
6027 std::ostringstream ss;
6028 ss<<"SELECT guildid FROM guild_member WHERE guid='"<<guid<<"'";
6029 QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
6030 if( result )
6032 uint32 v = result->Fetch()[0].GetUInt32();
6033 delete result;
6034 return v;
6036 else
6037 return 0;
6040 uint32 Player::GetRankFromDB(uint64 guid)
6042 std::ostringstream ss;
6043 ss<<"SELECT rank FROM guild_member WHERE guid='"<<guid<<"'";
6044 QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
6045 if( result )
6047 uint32 v = result->Fetch()[0].GetUInt32();
6048 delete result;
6049 return v;
6051 else
6052 return 0;
6055 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6057 QueryResult *result = CharacterDatabase.PQuery("SELECT arena_team_member.arenateamid FROM arena_team_member JOIN arena_team ON arena_team_member.arenateamid = arena_team.arenateamid WHERE guid='%u' AND type='%u' LIMIT 1", GUID_LOPART(guid), type);
6058 if(!result)
6059 return 0;
6061 uint32 id = (*result)[0].GetUInt32();
6062 delete result;
6063 return id;
6066 uint32 Player::GetZoneIdFromDB(uint64 guid)
6068 std::ostringstream ss;
6070 ss<<"SELECT zone FROM characters WHERE guid='"<<GUID_LOPART(guid)<<"'";
6071 QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
6072 if (!result)
6073 return 0;
6074 Field* fields = result->Fetch();
6075 uint32 zone = fields[0].GetUInt32();
6076 delete result;
6078 if (!zone)
6080 // stored zone is zero, use generic and slow zone detection
6081 ss.str("");
6082 ss<<"SELECT map,position_x,position_y FROM characters WHERE guid='"<<GUID_LOPART(guid)<<"'";
6083 result = CharacterDatabase.Query(ss.str().c_str());
6084 if( !result )
6085 return 0;
6086 fields = result->Fetch();
6087 uint32 map = fields[0].GetUInt32();
6088 float posx = fields[1].GetFloat();
6089 float posy = fields[2].GetFloat();
6090 delete result;
6092 zone = MapManager::Instance().GetZoneId(map,posx,posy);
6094 ss.str("");
6095 ss << "UPDATE characters SET zone='"<<zone<<"' WHERE guid='"<<GUID_LOPART(guid)<<"'";
6096 CharacterDatabase.Execute(ss.str().c_str());
6099 return zone;
6102 void Player::UpdateArea(uint32 newArea)
6104 // FFA_PVP flags are area and not zone id dependent
6105 // so apply them accordingly
6106 m_areaUpdateId = newArea;
6108 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6110 if(area && (area->flags & AREA_FLAG_ARENA))
6112 if(!isGameMaster())
6113 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
6115 else
6117 // remove ffa flag only if not ffapvp realm
6118 // removal in sanctuaries and capitals is handled in zone update
6119 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6120 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
6123 UpdateAreaDependentAuras(newArea);
6126 void Player::UpdateZone(uint32 newZone)
6128 m_zoneUpdateId = newZone;
6129 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6131 // zone changed, so area changed as well, update it
6132 UpdateArea(GetAreaId());
6134 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6135 if(!zone)
6136 return;
6138 if (sWorld.getConfig(CONFIG_WEATHER))
6140 Weather *wth = sWorld.FindWeather(zone->ID);
6141 if(wth)
6143 wth->SendWeatherUpdateToPlayer(this);
6145 else
6147 if(!sWorld.AddWeather(zone->ID))
6149 // send fine weather packet to remove old zone's weather
6150 Weather::SendFineWeatherUpdateToPlayer(this);
6155 pvpInfo.inHostileArea =
6156 GetTeam() == ALLIANCE && zone->team == AREATEAM_HORDE ||
6157 GetTeam() == HORDE && zone->team == AREATEAM_ALLY ||
6158 sWorld.IsPvPRealm() && zone->team == AREATEAM_NONE ||
6159 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6161 if(pvpInfo.inHostileArea) // in hostile area
6163 if(!IsPvP() || pvpInfo.endTimer != 0)
6164 UpdatePvP(true, true);
6166 else // in friendly area
6168 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6169 pvpInfo.endTimer = time(0); // start toggle-off
6172 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6174 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_SANCTUARY);
6175 if(sWorld.IsFFAPvPRealm())
6176 RemoveFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6178 else
6180 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_SANCTUARY);
6183 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6185 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6186 SetRestType(REST_TYPE_IN_CITY);
6187 InnEnter(time(0),GetMapId(),0,0,0);
6189 if(sWorld.IsFFAPvPRealm())
6190 RemoveFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6192 else // anywhere else
6194 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6196 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6198 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6200 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6201 SetRestType(REST_TYPE_NO);
6203 if(sWorld.IsFFAPvPRealm())
6204 SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6207 else // not in tavern (leave city then)
6209 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6210 SetRestType(REST_TYPE_NO);
6212 // Set player to FFA PVP when not in rested environment.
6213 if(sWorld.IsFFAPvPRealm())
6214 SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6219 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6220 // if player resurrected at teleport this will be applied in resurrect code
6221 if(isAlive())
6222 DestroyZoneLimitedItem( true, newZone );
6224 // recent client version not send leave/join channel packets for built-in local channels
6225 UpdateLocalChannels( newZone );
6227 // group update
6228 if(GetGroup())
6229 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6231 UpdateZoneDependentAuras(newZone);
6234 //If players are too far way of duel flag... then player loose the duel
6235 void Player::CheckDuelDistance(time_t currTime)
6237 if(!duel)
6238 return;
6240 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6241 GameObject* obj = ObjectAccessor::GetGameObject(*this, duelFlagGUID);
6242 if(!obj)
6243 return;
6245 if(duel->outOfBound == 0)
6247 if(!IsWithinDistInMap(obj, 50))
6249 duel->outOfBound = currTime;
6251 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6252 GetSession()->SendPacket(&data);
6255 else
6257 if(IsWithinDistInMap(obj, 40))
6259 duel->outOfBound = 0;
6261 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6262 GetSession()->SendPacket(&data);
6264 else if(currTime >= (duel->outOfBound+10))
6266 DuelComplete(DUEL_FLED);
6271 void Player::DuelComplete(DuelCompleteType type)
6273 // duel not requested
6274 if(!duel)
6275 return;
6277 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6278 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6279 GetSession()->SendPacket(&data);
6280 duel->opponent->GetSession()->SendPacket(&data);
6282 if(type != DUEL_INTERUPTED)
6284 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6285 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6286 data << duel->opponent->GetName();
6287 data << GetName();
6288 SendMessageToSet(&data,true);
6291 // cool-down duel spell
6292 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6294 data<<GetGUID();
6295 data<<uint8(0x0);
6297 data<<(uint32)7266;
6298 data<<uint32(0x0);
6299 GetSession()->SendPacket(&data);
6300 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6301 data<<duel->opponent->GetGUID();
6302 data<<uint8(0x0);
6303 data<<(uint32)7266;
6304 data<<uint32(0x0);
6305 duel->opponent->GetSession()->SendPacket(&data);*/
6307 //Remove Duel Flag object
6308 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
6309 if(obj)
6310 duel->initiator->RemoveGameObject(obj,true);
6312 /* remove auras */
6313 std::vector<uint32> auras2remove;
6314 AuraMap const& vAuras = duel->opponent->GetAuras();
6315 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); i++)
6317 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6318 auras2remove.push_back(i->second->GetId());
6321 for(size_t i=0; i<auras2remove.size(); i++)
6322 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6324 auras2remove.clear();
6325 AuraMap const& auras = GetAuras();
6326 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); i++)
6328 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6329 auras2remove.push_back(i->second->GetId());
6331 for(size_t i=0; i<auras2remove.size(); i++)
6332 RemoveAurasDueToSpell(auras2remove[i]);
6334 // cleanup combo points
6335 if(GetComboTarget()==duel->opponent->GetGUID())
6336 ClearComboPoints();
6337 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6338 ClearComboPoints();
6340 if(duel->opponent->GetComboTarget()==GetGUID())
6341 duel->opponent->ClearComboPoints();
6342 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6343 duel->opponent->ClearComboPoints();
6345 //cleanups
6346 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6347 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6348 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6349 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6351 delete duel->opponent->duel;
6352 duel->opponent->duel = NULL;
6353 delete duel;
6354 duel = NULL;
6357 //---------------------------------------------------------//
6359 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6361 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6362 return;
6364 // not apply/remove mods for broken item
6365 if(item->IsBroken())
6366 return;
6368 ItemPrototype const *proto = item->GetProto();
6370 if(!proto)
6371 return;
6373 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6375 uint32 attacktype = Player::GetAttackBySlot(slot);
6376 if(attacktype < MAX_ATTACK)
6377 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6379 _ApplyItemBonuses(proto,slot,apply);
6381 if( slot==EQUIPMENT_SLOT_RANGED )
6382 _ApplyAmmoBonuses();
6384 ApplyItemEquipSpell(item,apply);
6385 ApplyEnchantment(item, apply);
6387 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6388 CorrectMetaGemEnchants(slot, apply);
6390 sLog.outDebug("_ApplyItemMods complete.");
6393 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply)
6395 if(slot >= INVENTORY_SLOT_BAG_END || !proto)
6396 return;
6398 for (int i = 0; i < 10; i++)
6400 uint32 statType = 0;
6401 int32 val = 0;
6403 if(proto->ScalingStatDistribution)
6405 if(ScalingStatDistributionEntry const *ssd = sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution))
6407 statType = ssd->StatMod[i];
6409 if(uint32 modifier = ssd->Modifier[i])
6411 uint32 level = ((getLevel() > ssd->MaxLevel) ? ssd->MaxLevel : getLevel());
6412 if(ScalingStatValuesEntry const *ssv = sScalingStatValuesStore.LookupEntry(level))
6414 int multiplier = ssv->Multiplier[proto->GetScalingStatValuesColumn()];
6415 val = (multiplier * modifier) / 10000;
6420 else
6422 statType = proto->ItemStat[i].ItemStatType;
6423 val = float(proto->ItemStat[i].ItemStatValue);
6426 if(val == 0)
6427 continue;
6429 switch (statType)
6431 case ITEM_MOD_MANA:
6432 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6433 break;
6434 case ITEM_MOD_HEALTH: // modify HP
6435 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6436 break;
6437 case ITEM_MOD_AGILITY: // modify agility
6438 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6439 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6440 break;
6441 case ITEM_MOD_STRENGTH: //modify strength
6442 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6443 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6444 break;
6445 case ITEM_MOD_INTELLECT: //modify intellect
6446 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6447 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6448 break;
6449 case ITEM_MOD_SPIRIT: //modify spirit
6450 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6451 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6452 break;
6453 case ITEM_MOD_STAMINA: //modify stamina
6454 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6455 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6456 break;
6457 case ITEM_MOD_DEFENSE_SKILL_RATING:
6458 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6459 break;
6460 case ITEM_MOD_DODGE_RATING:
6461 ApplyRatingMod(CR_DODGE, int32(val), apply);
6462 break;
6463 case ITEM_MOD_PARRY_RATING:
6464 ApplyRatingMod(CR_PARRY, int32(val), apply);
6465 break;
6466 case ITEM_MOD_BLOCK_RATING:
6467 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6468 break;
6469 case ITEM_MOD_HIT_MELEE_RATING:
6470 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6471 break;
6472 case ITEM_MOD_HIT_RANGED_RATING:
6473 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6474 break;
6475 case ITEM_MOD_HIT_SPELL_RATING:
6476 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6477 break;
6478 case ITEM_MOD_CRIT_MELEE_RATING:
6479 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6480 break;
6481 case ITEM_MOD_CRIT_RANGED_RATING:
6482 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6483 break;
6484 case ITEM_MOD_CRIT_SPELL_RATING:
6485 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6486 break;
6487 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6488 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6489 break;
6490 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6491 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6492 break;
6493 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6494 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6495 break;
6496 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6497 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6498 break;
6499 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6500 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6501 break;
6502 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6503 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6504 break;
6505 case ITEM_MOD_HASTE_MELEE_RATING:
6506 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6507 break;
6508 case ITEM_MOD_HASTE_RANGED_RATING:
6509 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6510 break;
6511 case ITEM_MOD_HASTE_SPELL_RATING:
6512 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6513 break;
6514 case ITEM_MOD_HIT_RATING:
6515 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6516 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6517 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6518 break;
6519 case ITEM_MOD_CRIT_RATING:
6520 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6521 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6522 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6523 break;
6524 case ITEM_MOD_HIT_TAKEN_RATING:
6525 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6526 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6527 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6528 break;
6529 case ITEM_MOD_CRIT_TAKEN_RATING:
6530 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6531 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6532 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6533 break;
6534 case ITEM_MOD_RESILIENCE_RATING:
6535 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6536 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6537 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6538 break;
6539 case ITEM_MOD_HASTE_RATING:
6540 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6541 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6542 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6543 break;
6544 case ITEM_MOD_EXPERTISE_RATING:
6545 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6546 break;
6547 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6548 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6549 break;
6553 if (proto->Armor)
6554 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(proto->Armor), apply);
6556 if (proto->Block)
6557 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6559 if (proto->HolyRes)
6560 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6562 if (proto->FireRes)
6563 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6565 if (proto->NatureRes)
6566 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6568 if (proto->FrostRes)
6569 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6571 if (proto->ShadowRes)
6572 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6574 if (proto->ArcaneRes)
6575 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6577 WeaponAttackType attType = BASE_ATTACK;
6578 float damage = 0.0f;
6580 if( slot == EQUIPMENT_SLOT_RANGED && (
6581 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6582 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6584 attType = RANGED_ATTACK;
6586 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6588 attType = OFF_ATTACK;
6591 if (proto->Damage[0].DamageMin > 0 )
6593 damage = apply ? proto->Damage[0].DamageMin : BASE_MINDAMAGE;
6594 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6595 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6598 if (proto->Damage[0].DamageMax > 0 )
6600 damage = apply ? proto->Damage[0].DamageMax : BASE_MAXDAMAGE;
6601 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6604 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6605 return;
6607 if (proto->Delay)
6609 if(slot == EQUIPMENT_SLOT_RANGED)
6610 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6611 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6612 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6613 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6614 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6617 if(CanModifyStats() && (damage || proto->Delay))
6618 UpdateDamagePhysical(attType);
6621 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6623 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6624 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6625 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6627 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6628 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6629 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6631 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6632 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6633 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6636 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6638 // generic not weapon specific case processes in aura code
6639 if(aura->GetSpellProto()->EquippedItemClass == -1)
6640 return;
6642 BaseModGroup mod = BASEMOD_END;
6643 switch(attackType)
6645 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6646 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6647 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6648 default: return;
6651 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6653 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6657 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6659 // ignore spell mods for not wands
6660 Modifier const* modifier = aura->GetModifier();
6661 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6662 return;
6664 // generic not weapon specific case processes in aura code
6665 if(aura->GetSpellProto()->EquippedItemClass == -1)
6666 return;
6668 UnitMods unitMod = UNIT_MOD_END;
6669 switch(attackType)
6671 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6672 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6673 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6674 default: return;
6677 UnitModifierType unitModType = TOTAL_VALUE;
6678 switch(modifier->m_auraname)
6680 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6681 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6682 default: return;
6685 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6687 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6691 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6693 if(!item)
6694 return;
6696 ItemPrototype const *proto = item->GetProto();
6697 if(!proto)
6698 return;
6700 for (int i = 0; i < 5; i++)
6702 _Spell const& spellData = proto->Spells[i];
6704 // no spell
6705 if(!spellData.SpellId )
6706 continue;
6708 // wrong triggering type
6709 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6710 continue;
6712 // check if it is valid spell
6713 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6714 if(!spellproto)
6715 continue;
6717 ApplyEquipSpell(spellproto,item,apply,form_change);
6721 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6723 if(apply)
6725 // Cannot be used in this stance/form
6726 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)!=0)
6727 return;
6729 if(form_change) // check aura active state from other form
6731 bool found = false;
6732 for (int k=0; k < 3; ++k)
6734 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6735 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6737 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6739 found = true;
6740 break;
6743 if(found)
6744 break;
6747 if(found) // and skip re-cast already active aura at form change
6748 return;
6751 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6753 CastSpell(this,spellInfo,true,item);
6755 else
6757 if(form_change) // check aura compatibility
6759 // Cannot be used in this stance/form
6760 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==0)
6761 return; // and remove only not compatible at form change
6764 if(item)
6765 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6766 else
6767 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6771 void Player::UpdateEquipSpellsAtFormChange()
6773 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6775 if(m_items[i] && !m_items[i]->IsBroken())
6777 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6778 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6782 // item set bonuses not dependent from item broken state
6783 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6785 ItemSetEffect* eff = ItemSetEff[setindex];
6786 if(!eff)
6787 continue;
6789 for(uint32 y=0;y<8; ++y)
6791 SpellEntry const* spellInfo = eff->spells[y];
6792 if(!spellInfo)
6793 continue;
6795 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
6796 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
6801 void Player::CastItemCombatSpell(Item *item,Unit* Target, WeaponAttackType attType)
6803 if(!item || item->IsBroken())
6804 return;
6806 ItemPrototype const *proto = item->GetProto();
6807 if(!proto)
6808 return;
6810 if (!Target || Target == this )
6811 return;
6813 for (int i = 0; i < 5; i++)
6815 _Spell const& spellData = proto->Spells[i];
6817 // no spell
6818 if(!spellData.SpellId )
6819 continue;
6821 // wrong triggering type
6822 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
6823 continue;
6825 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6826 if(!spellInfo)
6828 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
6829 continue;
6832 // not allow proc extra attack spell at extra attack
6833 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6834 return;
6836 float chance = spellInfo->procChance;
6838 if(spellData.SpellPPMRate)
6840 uint32 WeaponSpeed = GetAttackTime(attType);
6841 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
6843 else if(chance > 100.0f)
6845 chance = GetWeaponProcChance();
6848 if (roll_chance_f(chance))
6849 CastSpell(Target, spellInfo->Id, true, item);
6852 // item combat enchantments
6853 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6855 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6856 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6857 if(!pEnchant) continue;
6858 for (int s=0;s<3;s++)
6860 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
6861 continue;
6863 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6864 if (!spellInfo)
6866 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6867 continue;
6870 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
6871 if (roll_chance_f(chance))
6873 if(IsPositiveSpell(pEnchant->spellid[s]))
6874 CastSpell(this, pEnchant->spellid[s], true, item);
6875 else
6876 CastSpell(Target, pEnchant->spellid[s], true, item);
6882 void Player::_RemoveAllItemMods()
6884 sLog.outDebug("_RemoveAllItemMods start.");
6886 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6888 if(m_items[i])
6890 ItemPrototype const *proto = m_items[i]->GetProto();
6891 if(!proto)
6892 continue;
6894 // item set bonuses not dependent from item broken state
6895 if(proto->ItemSet)
6896 RemoveItemsSetItem(this,proto);
6898 if(m_items[i]->IsBroken())
6899 continue;
6901 ApplyItemEquipSpell(m_items[i],false);
6902 ApplyEnchantment(m_items[i], false);
6906 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6908 if(m_items[i])
6910 if(m_items[i]->IsBroken())
6911 continue;
6912 ItemPrototype const *proto = m_items[i]->GetProto();
6913 if(!proto)
6914 continue;
6916 uint32 attacktype = Player::GetAttackBySlot(i);
6917 if(attacktype < MAX_ATTACK)
6918 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
6920 _ApplyItemBonuses(proto,i, false);
6922 if( i == EQUIPMENT_SLOT_RANGED )
6923 _ApplyAmmoBonuses();
6927 sLog.outDebug("_RemoveAllItemMods complete.");
6930 void Player::_ApplyAllItemMods()
6932 sLog.outDebug("_ApplyAllItemMods start.");
6934 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6936 if(m_items[i])
6938 if(m_items[i]->IsBroken())
6939 continue;
6941 ItemPrototype const *proto = m_items[i]->GetProto();
6942 if(!proto)
6943 continue;
6945 uint32 attacktype = Player::GetAttackBySlot(i);
6946 if(attacktype < MAX_ATTACK)
6947 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
6949 _ApplyItemBonuses(proto,i, true);
6951 if( i == EQUIPMENT_SLOT_RANGED )
6952 _ApplyAmmoBonuses();
6956 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6958 if(m_items[i])
6960 ItemPrototype const *proto = m_items[i]->GetProto();
6961 if(!proto)
6962 continue;
6964 // item set bonuses not dependent from item broken state
6965 if(proto->ItemSet)
6966 AddItemsSetItem(this,m_items[i]);
6968 if(m_items[i]->IsBroken())
6969 continue;
6971 ApplyItemEquipSpell(m_items[i],true);
6972 ApplyEnchantment(m_items[i], true);
6976 sLog.outDebug("_ApplyAllItemMods complete.");
6979 void Player::_ApplyAmmoBonuses()
6981 // check ammo
6982 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
6983 if(!ammo_id)
6984 return;
6986 float currentAmmoDPS;
6988 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
6989 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
6990 currentAmmoDPS = 0.0f;
6991 else
6992 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
6994 if(currentAmmoDPS == GetAmmoDPS())
6995 return;
6997 m_ammoDPS = currentAmmoDPS;
6999 if(CanModifyStats())
7000 UpdateDamagePhysical(RANGED_ATTACK);
7003 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7005 if(!ammo_proto)
7006 return false;
7008 // check ranged weapon
7009 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
7010 if(!weapon || weapon->IsBroken() )
7011 return false;
7013 ItemPrototype const* weapon_proto = weapon->GetProto();
7014 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7015 return false;
7017 // check ammo ws. weapon compatibility
7018 switch(weapon_proto->SubClass)
7020 case ITEM_SUBCLASS_WEAPON_BOW:
7021 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7022 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7023 return false;
7024 break;
7025 case ITEM_SUBCLASS_WEAPON_GUN:
7026 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7027 return false;
7028 break;
7029 default:
7030 return false;
7033 return true;
7036 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7037 Called by remove insignia spell effect */
7038 void Player::RemovedInsignia(Player* looterPlr)
7040 if (!GetBattleGroundId())
7041 return;
7043 // If not released spirit, do it !
7044 if(m_deathTimer > 0)
7046 m_deathTimer = 0;
7047 BuildPlayerRepop();
7048 RepopAtGraveyard();
7051 Corpse *corpse = GetCorpse();
7052 if (!corpse)
7053 return;
7055 // We have to convert player corpse to bones, not to be able to resurrect there
7056 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7057 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
7058 if (!bones)
7059 return;
7061 // Now we must make bones lootable, and send player loot
7062 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7064 // We store the level of our player in the gold field
7065 // We retrieve this information at Player::SendLoot()
7066 bones->loot.gold = getLevel();
7067 bones->lootRecipient = looterPlr;
7068 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7071 /*Loot type MUST be
7072 1-corpse, go
7073 2-skinning
7074 3-Fishing
7077 void Player::SendLootRelease( uint64 guid )
7079 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7080 data << uint64(guid) << uint8(1);
7081 SendDirectMessage( &data );
7084 void Player::SendLoot(uint64 guid, LootType loot_type)
7086 Loot *loot = 0;
7087 PermissionTypes permission = ALL_PERMISSION;
7089 sLog.outDebug("Player::SendLoot");
7090 if (IS_GAMEOBJECT_GUID(guid))
7092 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7093 GameObject *go =
7094 ObjectAccessor::GetGameObject(*this, guid);
7096 // not check distance for GO in case owned GO (fishing bobber case, for example)
7097 // And permit out of range GO with no owner in case fishing hole
7098 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7100 SendLootRelease(guid);
7101 return;
7104 loot = &go->loot;
7106 if(go->getLootState() == GO_READY)
7108 uint32 lootid = go->GetLootId();
7110 if(lootid)
7112 sLog.outDebug(" if(lootid)");
7113 loot->clear();
7114 loot->FillLoot(lootid, LootTemplates_Gameobject, this);
7117 if(loot_type == LOOT_FISHING)
7118 go->getFishLoot(loot);
7120 go->SetLootState(GO_ACTIVATED);
7123 else if (IS_ITEM_GUID(guid))
7125 Item *item = GetItemByGuid( guid );
7127 if (!item)
7129 SendLootRelease(guid);
7130 return;
7133 if(loot_type == LOOT_DISENCHANTING)
7135 loot = &item->loot;
7137 if(!item->m_lootGenerated)
7139 item->m_lootGenerated = true;
7140 loot->clear();
7141 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this);
7144 else if(loot_type == LOOT_PROSPECTING)
7146 loot = &item->loot;
7148 if(!item->m_lootGenerated)
7150 item->m_lootGenerated = true;
7151 loot->clear();
7152 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this);
7155 else
7157 loot = &item->loot;
7159 if(!item->m_lootGenerated)
7161 item->m_lootGenerated = true;
7162 loot->clear();
7163 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this);
7165 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7169 else if (IS_CORPSE_GUID(guid)) // remove insignia
7171 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7173 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7175 SendLootRelease(guid);
7176 return;
7179 loot = &bones->loot;
7181 if (!bones->lootForBody)
7183 bones->lootForBody = true;
7184 uint32 pLevel = bones->loot.gold;
7185 bones->loot.clear();
7186 // It may need a better formula
7187 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7188 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7191 if (bones->lootRecipient != this)
7192 permission = NONE_PERMISSION;
7194 else
7196 Creature *creature = ObjectAccessor::GetCreature(*this, guid);
7198 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7199 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7201 SendLootRelease(guid);
7202 return;
7205 if(loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7207 SendLootRelease(guid);
7208 return;
7211 loot = &creature->loot;
7213 if(loot_type == LOOT_PICKPOCKETING)
7215 if ( !creature->lootForPickPocketed )
7217 creature->lootForPickPocketed = true;
7218 loot->clear();
7220 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7221 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this);
7223 // Generate extra money for pick pocket loot
7224 const uint32 a = urand(0, creature->getLevel()/2);
7225 const uint32 b = urand(0, getLevel()/2);
7226 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7229 else
7231 // the player whose group may loot the corpse
7232 Player *recipient = creature->GetLootRecipient();
7233 if (!recipient)
7235 creature->SetLootRecipient(this);
7236 recipient = this;
7239 if (creature->lootForPickPocketed)
7241 creature->lootForPickPocketed = false;
7242 loot->clear();
7245 if(!creature->lootForBody)
7247 creature->lootForBody = true;
7248 loot->clear();
7250 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7251 loot->FillLoot(lootid, LootTemplates_Creature, recipient);
7253 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7255 if(Group* group = recipient->GetGroup())
7257 group->UpdateLooterGuid(creature,true);
7259 switch (group->GetLootMethod())
7261 case GROUP_LOOT:
7262 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7263 group->GroupLoot(recipient->GetGUID(), loot, creature);
7264 break;
7265 case NEED_BEFORE_GREED:
7266 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7267 break;
7268 case MASTER_LOOT:
7269 group->MasterLoot(recipient->GetGUID(), loot, creature);
7270 break;
7271 default:
7272 break;
7277 // possible only if creature->lootForBody && loot->empty() at spell cast check
7278 if (loot_type == LOOT_SKINNING)
7280 loot->clear();
7281 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this);
7283 // set group rights only for loot_type != LOOT_SKINNING
7284 else
7286 if(Group* group = GetGroup())
7288 if( group == recipient->GetGroup() )
7290 if(group->GetLootMethod() == FREE_FOR_ALL)
7291 permission = ALL_PERMISSION;
7292 else if(group->GetLooterGuid() == GetGUID())
7294 if(group->GetLootMethod() == MASTER_LOOT)
7295 permission = MASTER_PERMISSION;
7296 else
7297 permission = ALL_PERMISSION;
7299 else
7300 permission = GROUP_PERMISSION;
7302 else
7303 permission = NONE_PERMISSION;
7305 else if(recipient == this)
7306 permission = ALL_PERMISSION;
7307 else
7308 permission = NONE_PERMISSION;
7313 SetLootGUID(guid);
7315 QuestItemList *q_list = 0;
7316 if (permission != NONE_PERMISSION)
7318 QuestItemMap const& lootPlayerQuestItems = loot->GetPlayerQuestItems();
7319 QuestItemMap::const_iterator itr = lootPlayerQuestItems.find(GetGUIDLow());
7320 if (itr == lootPlayerQuestItems.end())
7321 q_list = loot->FillQuestLoot(this);
7322 else
7323 q_list = itr->second;
7326 QuestItemList *ffa_list = 0;
7327 if (permission != NONE_PERMISSION)
7329 QuestItemMap const& lootPlayerFFAItems = loot->GetPlayerFFAItems();
7330 QuestItemMap::const_iterator itr = lootPlayerFFAItems.find(GetGUIDLow());
7331 if (itr == lootPlayerFFAItems.end())
7332 ffa_list = loot->FillFFALoot(this);
7333 else
7334 ffa_list = itr->second;
7337 QuestItemList *conditional_list = 0;
7338 if (permission != NONE_PERMISSION)
7340 QuestItemMap const& lootPlayerNonQuestNonFFAConditionalItems = loot->GetPlayerNonQuestNonFFAConditionalItems();
7341 QuestItemMap::const_iterator itr = lootPlayerNonQuestNonFFAConditionalItems.find(GetGUIDLow());
7342 if (itr == lootPlayerNonQuestNonFFAConditionalItems.end())
7343 conditional_list = loot->FillNonQuestNonFFAConditionalLoot(this);
7344 else
7345 conditional_list = itr->second;
7348 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING and LOOT_INSIGNIA unsupported by client, sending LOOT_SKINNING instead
7349 if(loot_type == LOOT_PICKPOCKETING || loot_type == LOOT_DISENCHANTING || loot_type == LOOT_PROSPECTING || loot_type == LOOT_INSIGNIA)
7350 loot_type = LOOT_SKINNING;
7352 if(loot_type == LOOT_FISHINGHOLE)
7353 loot_type = LOOT_FISHING;
7355 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7357 data << uint64(guid);
7358 data << uint8(loot_type);
7359 data << LootView(*loot, q_list, ffa_list, conditional_list, this, permission);
7361 SendDirectMessage(&data);
7363 // add 'this' player as one of the players that are looting 'loot'
7364 if (permission != NONE_PERMISSION)
7365 loot->AddLooter(GetGUID());
7367 if ( loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid) )
7368 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7371 void Player::SendNotifyLootMoneyRemoved()
7373 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7374 GetSession()->SendPacket( &data );
7377 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7379 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7380 data << uint8(lootSlot);
7381 GetSession()->SendPacket( &data );
7384 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7386 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7387 data << Field;
7388 data << Value;
7389 GetSession()->SendPacket(&data);
7392 void Player::SendInitWorldStates()
7394 // data depends on zoneid/mapid...
7395 BattleGround* bg = GetBattleGround();
7396 uint16 NumberOfFields = 0;
7397 uint32 mapid = GetMapId();
7398 uint32 zoneid = GetZoneId();
7399 uint32 areaid = GetAreaId();
7400 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7401 // may be exist better way to do this...
7402 switch(zoneid)
7404 case 0:
7405 case 1:
7406 case 4:
7407 case 8:
7408 case 10:
7409 case 11:
7410 case 12:
7411 case 36:
7412 case 38:
7413 case 40:
7414 case 41:
7415 case 51:
7416 case 267:
7417 case 1519:
7418 case 1537:
7419 case 2257:
7420 case 2918:
7421 NumberOfFields = 6;
7422 break;
7423 case 2597:
7424 NumberOfFields = 81;
7425 break;
7426 case 3277:
7427 NumberOfFields = 14;
7428 break;
7429 case 3358:
7430 case 3820:
7431 NumberOfFields = 38;
7432 break;
7433 case 3483:
7434 NumberOfFields = 22;
7435 break;
7436 case 3519:
7437 NumberOfFields = 36;
7438 break;
7439 case 3521:
7440 NumberOfFields = 35;
7441 break;
7442 case 3698:
7443 case 3702:
7444 case 3968:
7445 NumberOfFields = 9;
7446 break;
7447 case 3703:
7448 NumberOfFields = 9;
7449 break;
7450 default:
7451 NumberOfFields = 10;
7452 break;
7455 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7456 data << uint32(mapid); // mapid
7457 data << uint32(zoneid); // zone id
7458 data << uint32(areaid); // area id, new 2.1.0
7459 data << uint16(NumberOfFields); // count of uint64 blocks
7460 data << uint32(0x8d8) << uint32(0x0); // 1
7461 data << uint32(0x8d7) << uint32(0x0); // 2
7462 data << uint32(0x8d6) << uint32(0x0); // 3
7463 data << uint32(0x8d5) << uint32(0x0); // 4
7464 data << uint32(0x8d4) << uint32(0x0); // 5
7465 data << uint32(0x8d3) << uint32(0x0); // 6
7466 if(mapid == 530) // Outland
7468 data << uint32(0x9bf) << uint32(0x0); // 7
7469 data << uint32(0x9bd) << uint32(0xF); // 8
7470 data << uint32(0x9bb) << uint32(0xF); // 9
7472 switch(zoneid)
7474 case 1:
7475 case 11:
7476 case 12:
7477 case 38:
7478 case 40:
7479 case 51:
7480 case 1519:
7481 case 1537:
7482 case 2257:
7483 break;
7484 case 2597: // AV
7485 data << uint32(0x7ae) << uint32(0x1); // 7
7486 data << uint32(0x532) << uint32(0x1); // 8
7487 data << uint32(0x531) << uint32(0x0); // 9
7488 data << uint32(0x52e) << uint32(0x0); // 10
7489 data << uint32(0x571) << uint32(0x0); // 11
7490 data << uint32(0x570) << uint32(0x0); // 12
7491 data << uint32(0x567) << uint32(0x1); // 13
7492 data << uint32(0x566) << uint32(0x1); // 14
7493 data << uint32(0x550) << uint32(0x1); // 15
7494 data << uint32(0x544) << uint32(0x0); // 16
7495 data << uint32(0x536) << uint32(0x0); // 17
7496 data << uint32(0x535) << uint32(0x1); // 18
7497 data << uint32(0x518) << uint32(0x0); // 19
7498 data << uint32(0x517) << uint32(0x0); // 20
7499 data << uint32(0x574) << uint32(0x0); // 21
7500 data << uint32(0x573) << uint32(0x0); // 22
7501 data << uint32(0x572) << uint32(0x0); // 23
7502 data << uint32(0x56f) << uint32(0x0); // 24
7503 data << uint32(0x56e) << uint32(0x0); // 25
7504 data << uint32(0x56d) << uint32(0x0); // 26
7505 data << uint32(0x56c) << uint32(0x0); // 27
7506 data << uint32(0x56b) << uint32(0x0); // 28
7507 data << uint32(0x56a) << uint32(0x1); // 29
7508 data << uint32(0x569) << uint32(0x1); // 30
7509 data << uint32(0x568) << uint32(0x1); // 13
7510 data << uint32(0x565) << uint32(0x0); // 32
7511 data << uint32(0x564) << uint32(0x0); // 33
7512 data << uint32(0x563) << uint32(0x0); // 34
7513 data << uint32(0x562) << uint32(0x0); // 35
7514 data << uint32(0x561) << uint32(0x0); // 36
7515 data << uint32(0x560) << uint32(0x0); // 37
7516 data << uint32(0x55f) << uint32(0x0); // 38
7517 data << uint32(0x55e) << uint32(0x0); // 39
7518 data << uint32(0x55d) << uint32(0x0); // 40
7519 data << uint32(0x3c6) << uint32(0x4); // 41
7520 data << uint32(0x3c4) << uint32(0x6); // 42
7521 data << uint32(0x3c2) << uint32(0x4); // 43
7522 data << uint32(0x516) << uint32(0x1); // 44
7523 data << uint32(0x515) << uint32(0x0); // 45
7524 data << uint32(0x3b6) << uint32(0x6); // 46
7525 data << uint32(0x55c) << uint32(0x0); // 47
7526 data << uint32(0x55b) << uint32(0x0); // 48
7527 data << uint32(0x55a) << uint32(0x0); // 49
7528 data << uint32(0x559) << uint32(0x0); // 50
7529 data << uint32(0x558) << uint32(0x0); // 51
7530 data << uint32(0x557) << uint32(0x0); // 52
7531 data << uint32(0x556) << uint32(0x0); // 53
7532 data << uint32(0x555) << uint32(0x0); // 54
7533 data << uint32(0x554) << uint32(0x1); // 55
7534 data << uint32(0x553) << uint32(0x1); // 56
7535 data << uint32(0x552) << uint32(0x1); // 57
7536 data << uint32(0x551) << uint32(0x1); // 58
7537 data << uint32(0x54f) << uint32(0x0); // 59
7538 data << uint32(0x54e) << uint32(0x0); // 60
7539 data << uint32(0x54d) << uint32(0x1); // 61
7540 data << uint32(0x54c) << uint32(0x0); // 62
7541 data << uint32(0x54b) << uint32(0x0); // 63
7542 data << uint32(0x545) << uint32(0x0); // 64
7543 data << uint32(0x543) << uint32(0x1); // 65
7544 data << uint32(0x542) << uint32(0x0); // 66
7545 data << uint32(0x540) << uint32(0x0); // 67
7546 data << uint32(0x53f) << uint32(0x0); // 68
7547 data << uint32(0x53e) << uint32(0x0); // 69
7548 data << uint32(0x53d) << uint32(0x0); // 70
7549 data << uint32(0x53c) << uint32(0x0); // 71
7550 data << uint32(0x53b) << uint32(0x0); // 72
7551 data << uint32(0x53a) << uint32(0x1); // 73
7552 data << uint32(0x539) << uint32(0x0); // 74
7553 data << uint32(0x538) << uint32(0x0); // 75
7554 data << uint32(0x537) << uint32(0x0); // 76
7555 data << uint32(0x534) << uint32(0x0); // 77
7556 data << uint32(0x533) << uint32(0x0); // 78
7557 data << uint32(0x530) << uint32(0x0); // 79
7558 data << uint32(0x52f) << uint32(0x0); // 80
7559 data << uint32(0x52d) << uint32(0x1); // 81
7560 break;
7561 case 3277: // WS
7562 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7563 bg->FillInitialWorldStates(data);
7564 else
7566 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7567 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7568 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7569 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7570 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7571 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7572 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7573 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7575 break;
7576 case 3358: // AB
7577 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7578 bg->FillInitialWorldStates(data);
7579 else
7581 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7582 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7583 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7584 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7585 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7586 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7587 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7588 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7589 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7590 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7591 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7592 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7593 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7594 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7595 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7596 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7597 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7598 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7599 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7600 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7601 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7602 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7603 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7604 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7605 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7606 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7607 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7608 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7609 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7610 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7611 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7612 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7614 break;
7615 case 3820: // EY
7616 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7617 bg->FillInitialWorldStates(data);
7618 else
7620 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7621 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7622 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7623 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7624 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7625 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7626 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7627 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7628 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7629 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7630 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7631 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7632 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7633 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7634 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7635 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7636 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7637 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7638 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7639 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7640 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7641 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7642 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7643 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7644 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7645 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7646 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7647 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7648 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7649 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7650 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7651 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7652 // and some more ... unknown
7654 break;
7655 case 3483: // Hellfire Peninsula
7656 data << uint32(0x9ba) << uint32(0x1); // 10
7657 data << uint32(0x9b9) << uint32(0x1); // 11
7658 data << uint32(0x9b5) << uint32(0x0); // 12
7659 data << uint32(0x9b4) << uint32(0x1); // 13
7660 data << uint32(0x9b3) << uint32(0x0); // 14
7661 data << uint32(0x9b2) << uint32(0x0); // 15
7662 data << uint32(0x9b1) << uint32(0x1); // 16
7663 data << uint32(0x9b0) << uint32(0x0); // 17
7664 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7665 data << uint32(0x9ac) << uint32(0x0); // 19
7666 data << uint32(0x9a8) << uint32(0x0); // 20
7667 data << uint32(0x9a7) << uint32(0x0); // 21
7668 data << uint32(0x9a6) << uint32(0x1); // 22
7669 break;
7670 case 3519: // Terokkar Forest
7671 data << uint32(0xa41) << uint32(0x0); // 10
7672 data << uint32(0xa40) << uint32(0x14); // 11
7673 data << uint32(0xa3f) << uint32(0x0); // 12
7674 data << uint32(0xa3e) << uint32(0x0); // 13
7675 data << uint32(0xa3d) << uint32(0x5); // 14
7676 data << uint32(0xa3c) << uint32(0x0); // 15
7677 data << uint32(0xa87) << uint32(0x0); // 16
7678 data << uint32(0xa86) << uint32(0x0); // 17
7679 data << uint32(0xa85) << uint32(0x0); // 18
7680 data << uint32(0xa84) << uint32(0x0); // 19
7681 data << uint32(0xa83) << uint32(0x0); // 20
7682 data << uint32(0xa82) << uint32(0x0); // 21
7683 data << uint32(0xa81) << uint32(0x0); // 22
7684 data << uint32(0xa80) << uint32(0x0); // 23
7685 data << uint32(0xa7e) << uint32(0x0); // 24
7686 data << uint32(0xa7d) << uint32(0x0); // 25
7687 data << uint32(0xa7c) << uint32(0x0); // 26
7688 data << uint32(0xa7b) << uint32(0x0); // 27
7689 data << uint32(0xa7a) << uint32(0x0); // 28
7690 data << uint32(0xa79) << uint32(0x0); // 29
7691 data << uint32(0x9d0) << uint32(0x5); // 30
7692 data << uint32(0x9ce) << uint32(0x0); // 31
7693 data << uint32(0x9cd) << uint32(0x0); // 32
7694 data << uint32(0x9cc) << uint32(0x0); // 33
7695 data << uint32(0xa88) << uint32(0x0); // 34
7696 data << uint32(0xad0) << uint32(0x0); // 35
7697 data << uint32(0xacf) << uint32(0x1); // 36
7698 break;
7699 case 3521: // Zangarmarsh
7700 data << uint32(0x9e1) << uint32(0x0); // 10
7701 data << uint32(0x9e0) << uint32(0x0); // 11
7702 data << uint32(0x9df) << uint32(0x0); // 12
7703 data << uint32(0xa5d) << uint32(0x1); // 13
7704 data << uint32(0xa5c) << uint32(0x0); // 14
7705 data << uint32(0xa5b) << uint32(0x1); // 15
7706 data << uint32(0xa5a) << uint32(0x0); // 16
7707 data << uint32(0xa59) << uint32(0x1); // 17
7708 data << uint32(0xa58) << uint32(0x0); // 18
7709 data << uint32(0xa57) << uint32(0x0); // 19
7710 data << uint32(0xa56) << uint32(0x0); // 20
7711 data << uint32(0xa55) << uint32(0x1); // 21
7712 data << uint32(0xa54) << uint32(0x0); // 22
7713 data << uint32(0x9e7) << uint32(0x0); // 23
7714 data << uint32(0x9e6) << uint32(0x0); // 24
7715 data << uint32(0x9e5) << uint32(0x0); // 25
7716 data << uint32(0xa00) << uint32(0x0); // 26
7717 data << uint32(0x9ff) << uint32(0x1); // 27
7718 data << uint32(0x9fe) << uint32(0x0); // 28
7719 data << uint32(0x9fd) << uint32(0x0); // 29
7720 data << uint32(0x9fc) << uint32(0x1); // 30
7721 data << uint32(0x9fb) << uint32(0x0); // 31
7722 data << uint32(0xa62) << uint32(0x0); // 32
7723 data << uint32(0xa61) << uint32(0x1); // 33
7724 data << uint32(0xa60) << uint32(0x1); // 34
7725 data << uint32(0xa5f) << uint32(0x0); // 35
7726 break;
7727 case 3698: // Nagrand Arena
7728 data << uint32(0xa0f) << uint32(0x0); // 7
7729 data << uint32(0xa10) << uint32(0x0); // 8
7730 data << uint32(0xa11) << uint32(0x0); // 9
7731 break;
7732 case 3702: // Blade's Edge Arena
7733 data << uint32(0x9f0) << uint32(0x0); // 7
7734 data << uint32(0x9f1) << uint32(0x0); // 8
7735 data << uint32(0x9f3) << uint32(0x0); // 9
7736 break;
7737 case 3968: // Ruins of Lordaeron
7738 data << uint32(0xbb8) << uint32(0x0); // 7
7739 data << uint32(0xbb9) << uint32(0x0); // 8
7740 data << uint32(0xbba) << uint32(0x0); // 9
7741 break;
7742 case 3703: // Shattrath City
7743 break;
7744 default:
7745 data << uint32(0x914) << uint32(0x0); // 7
7746 data << uint32(0x913) << uint32(0x0); // 8
7747 data << uint32(0x912) << uint32(0x0); // 9
7748 data << uint32(0x915) << uint32(0x0); // 10
7749 break;
7751 GetSession()->SendPacket(&data);
7754 uint32 Player::GetXPRestBonus(uint32 xp)
7756 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
7758 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
7759 rested_bonus = xp;
7761 SetRestBonus( GetRestBonus() - rested_bonus);
7763 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
7764 return rested_bonus;
7767 void Player::SetBindPoint(uint64 guid)
7769 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
7770 data << uint64(guid);
7771 GetSession()->SendPacket( &data );
7774 void Player::SendTalentWipeConfirm(uint64 guid)
7776 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
7777 data << uint64(guid);
7778 data << uint32(resetTalentsCost());
7779 GetSession()->SendPacket( &data );
7782 void Player::SendPetSkillWipeConfirm()
7784 Pet* pet = GetPet();
7785 if(!pet)
7786 return;
7787 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
7788 data << pet->GetGUID();
7789 data << uint32(pet->resetTalentsCost());
7790 GetSession()->SendPacket( &data );
7793 /*********************************************************/
7794 /*** STORAGE SYSTEM ***/
7795 /*********************************************************/
7797 void Player::SetVirtualItemSlot( uint8 i, Item* item)
7799 assert(i < 3);
7800 if(i < 2 && item)
7802 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
7803 return;
7804 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
7805 if(charges == 0)
7806 return;
7807 if(charges > 1)
7808 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
7809 else if(charges <= 1)
7811 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
7812 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
7817 void Player::SetSheath( uint32 sheathed )
7819 switch (sheathed)
7821 case SHEATH_STATE_UNARMED: // no prepared weapon
7822 SetVirtualItemSlot(0,NULL);
7823 SetVirtualItemSlot(1,NULL);
7824 SetVirtualItemSlot(2,NULL);
7825 break;
7826 case SHEATH_STATE_MELEE: // prepared melee weapon
7828 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
7829 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
7830 SetVirtualItemSlot(2,NULL);
7831 }; break;
7832 case SHEATH_STATE_RANGED: // prepared ranged weapon
7833 SetVirtualItemSlot(0,NULL);
7834 SetVirtualItemSlot(1,NULL);
7835 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
7836 break;
7837 default:
7838 SetVirtualItemSlot(0,NULL);
7839 SetVirtualItemSlot(1,NULL);
7840 SetVirtualItemSlot(2,NULL);
7841 break;
7843 SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); // this must visualize Sheath changing for other players...
7846 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
7848 uint8 pClass = getClass();
7850 uint8 slots[4];
7851 slots[0] = NULL_SLOT;
7852 slots[1] = NULL_SLOT;
7853 slots[2] = NULL_SLOT;
7854 slots[3] = NULL_SLOT;
7855 switch( proto->InventoryType )
7857 case INVTYPE_HEAD:
7858 slots[0] = EQUIPMENT_SLOT_HEAD;
7859 break;
7860 case INVTYPE_NECK:
7861 slots[0] = EQUIPMENT_SLOT_NECK;
7862 break;
7863 case INVTYPE_SHOULDERS:
7864 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
7865 break;
7866 case INVTYPE_BODY:
7867 slots[0] = EQUIPMENT_SLOT_BODY;
7868 break;
7869 case INVTYPE_CHEST:
7870 slots[0] = EQUIPMENT_SLOT_CHEST;
7871 break;
7872 case INVTYPE_ROBE:
7873 slots[0] = EQUIPMENT_SLOT_CHEST;
7874 break;
7875 case INVTYPE_WAIST:
7876 slots[0] = EQUIPMENT_SLOT_WAIST;
7877 break;
7878 case INVTYPE_LEGS:
7879 slots[0] = EQUIPMENT_SLOT_LEGS;
7880 break;
7881 case INVTYPE_FEET:
7882 slots[0] = EQUIPMENT_SLOT_FEET;
7883 break;
7884 case INVTYPE_WRISTS:
7885 slots[0] = EQUIPMENT_SLOT_WRISTS;
7886 break;
7887 case INVTYPE_HANDS:
7888 slots[0] = EQUIPMENT_SLOT_HANDS;
7889 break;
7890 case INVTYPE_FINGER:
7891 slots[0] = EQUIPMENT_SLOT_FINGER1;
7892 slots[1] = EQUIPMENT_SLOT_FINGER2;
7893 break;
7894 case INVTYPE_TRINKET:
7895 slots[0] = EQUIPMENT_SLOT_TRINKET1;
7896 slots[1] = EQUIPMENT_SLOT_TRINKET2;
7897 break;
7898 case INVTYPE_CLOAK:
7899 slots[0] = EQUIPMENT_SLOT_BACK;
7900 break;
7901 case INVTYPE_WEAPON:
7903 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7905 // suggest offhand slot only if know dual wielding
7906 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
7907 if(CanDualWield())
7908 slots[1] = EQUIPMENT_SLOT_OFFHAND;
7909 };break;
7910 case INVTYPE_SHIELD:
7911 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7912 break;
7913 case INVTYPE_RANGED:
7914 slots[0] = EQUIPMENT_SLOT_RANGED;
7915 break;
7916 case INVTYPE_2HWEAPON:
7917 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7918 break;
7919 case INVTYPE_TABARD:
7920 slots[0] = EQUIPMENT_SLOT_TABARD;
7921 break;
7922 case INVTYPE_WEAPONMAINHAND:
7923 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7924 break;
7925 case INVTYPE_WEAPONOFFHAND:
7926 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7927 break;
7928 case INVTYPE_HOLDABLE:
7929 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7930 break;
7931 case INVTYPE_THROWN:
7932 slots[0] = EQUIPMENT_SLOT_RANGED;
7933 break;
7934 case INVTYPE_RANGEDRIGHT:
7935 slots[0] = EQUIPMENT_SLOT_RANGED;
7936 break;
7937 case INVTYPE_BAG:
7938 slots[0] = INVENTORY_SLOT_BAG_1;
7939 slots[1] = INVENTORY_SLOT_BAG_2;
7940 slots[2] = INVENTORY_SLOT_BAG_3;
7941 slots[3] = INVENTORY_SLOT_BAG_4;
7942 break;
7943 case INVTYPE_RELIC:
7945 switch(proto->SubClass)
7947 case ITEM_SUBCLASS_ARMOR_LIBRAM:
7948 if (pClass == CLASS_PALADIN)
7949 slots[0] = EQUIPMENT_SLOT_RANGED;
7950 break;
7951 case ITEM_SUBCLASS_ARMOR_IDOL:
7952 if (pClass == CLASS_DRUID)
7953 slots[0] = EQUIPMENT_SLOT_RANGED;
7954 break;
7955 case ITEM_SUBCLASS_ARMOR_TOTEM:
7956 if (pClass == CLASS_SHAMAN)
7957 slots[0] = EQUIPMENT_SLOT_RANGED;
7958 break;
7959 case ITEM_SUBCLASS_ARMOR_MISC:
7960 if (pClass == CLASS_WARLOCK)
7961 slots[0] = EQUIPMENT_SLOT_RANGED;
7962 break;
7964 break;
7966 default :
7967 return NULL_SLOT;
7970 if( slot != NULL_SLOT )
7972 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
7974 for (int i = 0; i < 4; i++)
7976 if ( slots[i] == slot )
7977 return slot;
7981 else
7983 // search free slot at first
7984 for (int i = 0; i < 4; i++)
7986 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
7988 // in case 2hand equipped weapon offhand slot empty but not free
7989 if(slots[i]==EQUIPMENT_SLOT_OFFHAND)
7991 Item* mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );
7992 if(!mainItem || mainItem->GetProto()->InventoryType != INVTYPE_2HWEAPON)
7993 return slots[i];
7995 else
7996 return slots[i];
8000 // if not found free and can swap return first appropriate from used
8001 for (int i = 0; i < 4; i++)
8003 if ( slots[i] != NULL_SLOT && swap )
8004 return slots[i];
8008 // no free position
8009 return NULL_SLOT;
8012 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8014 Item *pItem;
8015 uint32 tempcount = 0;
8017 uint8 res = EQUIP_ERR_OK;
8019 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
8021 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8022 if( pItem && pItem->GetEntry() == item )
8024 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8025 if(ires==EQUIP_ERR_OK)
8027 tempcount += pItem->GetCount();
8028 if( tempcount >= count )
8029 return EQUIP_ERR_OK;
8031 else
8032 res = ires;
8035 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
8037 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8038 if( pItem && pItem->GetEntry() == item )
8040 tempcount += pItem->GetCount();
8041 if( tempcount >= count )
8042 return EQUIP_ERR_OK;
8045 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8047 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8048 if( pItem && pItem->GetEntry() == item )
8050 tempcount += pItem->GetCount();
8051 if( tempcount >= count )
8052 return EQUIP_ERR_OK;
8055 Bag *pBag;
8056 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8058 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8059 if( pBag )
8061 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8063 pItem = GetItemByPos( i, j );
8064 if( pItem && pItem->GetEntry() == item )
8066 tempcount += pItem->GetCount();
8067 if( tempcount >= count )
8068 return EQUIP_ERR_OK;
8074 // not found req. item count and have unequippable items
8075 return res;
8078 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8080 uint32 count = 0;
8081 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8083 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8084 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8085 count += pItem->GetCount();
8087 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8089 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8090 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8091 count += pItem->GetCount();
8093 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8095 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8096 if( pBag )
8097 count += pBag->GetItemCount(item,skipItem);
8100 if(skipItem && skipItem->GetProto()->GemProperties)
8102 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8104 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8105 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8106 count += pItem->GetGemCountWithID(item);
8110 if(inBankAlso)
8112 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8114 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8115 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8116 count += pItem->GetCount();
8118 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8120 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8121 if( pBag )
8122 count += pBag->GetItemCount(item,skipItem);
8125 if(skipItem && skipItem->GetProto()->GemProperties)
8127 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8129 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8130 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8131 count += pItem->GetGemCountWithID(item);
8136 return count;
8139 Item* Player::GetItemByGuid( uint64 guid ) const
8141 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8143 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8144 if( pItem && pItem->GetGUID() == guid )
8145 return pItem;
8147 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8149 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8150 if( pItem && pItem->GetGUID() == guid )
8151 return pItem;
8154 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8156 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8157 if( pBag )
8159 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8161 Item* pItem = pBag->GetItemByPos( j );
8162 if( pItem && pItem->GetGUID() == guid )
8163 return pItem;
8167 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8169 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8170 if( pBag )
8172 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8174 Item* pItem = pBag->GetItemByPos( j );
8175 if( pItem && pItem->GetGUID() == guid )
8176 return pItem;
8181 return NULL;
8184 Item* Player::GetItemByPos( uint16 pos ) const
8186 uint8 bag = pos >> 8;
8187 uint8 slot = pos & 255;
8188 return GetItemByPos( bag, slot );
8191 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8193 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8194 return m_items[slot];
8195 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8196 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8198 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8199 if ( pBag )
8200 return pBag->GetItemByPos(slot);
8202 return NULL;
8205 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8207 uint16 slot;
8208 switch (attackType)
8210 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8211 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8212 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8213 default: return NULL;
8216 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8217 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8218 return NULL;
8220 if(!useable)
8221 return item;
8223 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8224 return NULL;
8226 return item;
8229 Item* Player::GetShield(bool useable) const
8231 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8232 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8233 return NULL;
8235 if(!useable)
8236 return item;
8238 if( item->IsBroken())
8239 return NULL;
8241 return item;
8244 uint32 Player::GetAttackBySlot( uint8 slot )
8246 switch(slot)
8248 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8249 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8250 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8251 default: return MAX_ATTACK;
8255 bool Player::HasBankBagSlot( uint8 slot ) const
8257 uint32 maxslot = GetByteValue(PLAYER_BYTES_2, 2) + BANK_SLOT_BAG_START;
8258 if( slot < maxslot )
8259 return true;
8260 return false;
8263 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8265 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8266 return true;
8267 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8268 return true;
8269 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8270 return true;
8271 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8272 return true;
8273 return false;
8276 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8278 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8279 return true;
8280 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8281 return true;
8282 return false;
8285 bool Player::IsBankPos( uint8 bag, uint8 slot )
8287 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8288 return true;
8289 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8290 return true;
8291 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8292 return true;
8293 return false;
8296 bool Player::IsBagPos( uint16 pos )
8298 uint8 bag = pos >> 8;
8299 uint8 slot = pos & 255;
8300 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8301 return true;
8302 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8303 return true;
8304 return false;
8307 bool Player::IsValidPos( uint8 bag, uint8 slot )
8309 // post selected
8310 if(bag == NULL_BAG)
8311 return true;
8313 if (bag == INVENTORY_SLOT_BAG_0)
8315 // any post selected
8316 if (slot == NULL_SLOT)
8317 return true;
8319 // equipment
8320 if (slot < EQUIPMENT_SLOT_END)
8321 return true;
8323 // bag equip slots
8324 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8325 return true;
8327 // backpack slots
8328 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8329 return true;
8331 // keyring slots
8332 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8333 return true;
8335 // bank main slots
8336 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8337 return true;
8339 // bank bag slots
8340 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8341 return true;
8343 return false;
8346 // bag content slots
8347 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8349 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8350 if(!pBag)
8351 return false;
8353 // any post selected
8354 if (slot == NULL_SLOT)
8355 return true;
8357 return slot < pBag->GetBagSize();
8360 // bank bag content slots
8361 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8363 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8364 if(!pBag)
8365 return false;
8367 // any post selected
8368 if (slot == NULL_SLOT)
8369 return true;
8371 return slot < pBag->GetBagSize();
8374 // where this?
8375 return false;
8379 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8381 uint32 tempcount = 0;
8382 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8384 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8385 if( pItem && pItem->GetEntry() == item )
8387 tempcount += pItem->GetCount();
8388 if( tempcount >= count )
8389 return true;
8392 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8394 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8395 if( pItem && pItem->GetEntry() == item )
8397 tempcount += pItem->GetCount();
8398 if( tempcount >= count )
8399 return true;
8402 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8404 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8406 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8408 Item* pItem = GetItemByPos( i, j );
8409 if( pItem && pItem->GetEntry() == item )
8411 tempcount += pItem->GetCount();
8412 if( tempcount >= count )
8413 return true;
8419 if(inBankAlso)
8421 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8423 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8424 if( pItem && pItem->GetEntry() == item )
8426 tempcount += pItem->GetCount();
8427 if( tempcount >= count )
8428 return true;
8431 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8433 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8435 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8437 Item* pItem = GetItemByPos( i, j );
8438 if( pItem && pItem->GetEntry() == item )
8440 tempcount += pItem->GetCount();
8441 if( tempcount >= count )
8442 return true;
8449 return false;
8452 Item* Player::GetItemOrItemWithGemEquipped( uint32 item ) const
8454 Item *pItem;
8455 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
8457 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8458 if( pItem && pItem->GetEntry() == item )
8459 return pItem;
8462 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8463 if (pProto && pProto->GemProperties)
8465 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
8467 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8468 if( pItem && pItem->GetProto()->Socket[0].Color )
8470 if (pItem->GetGemCountWithID(item) > 0 )
8471 return pItem;
8476 return NULL;
8479 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8481 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8482 if( !pProto )
8484 if(no_space_count)
8485 *no_space_count = count;
8486 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8489 // no maximum
8490 if(pProto->MaxCount == 0)
8491 return EQUIP_ERR_OK;
8493 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8495 if( curcount + count > pProto->MaxCount )
8497 if(no_space_count)
8498 *no_space_count = count +curcount - pProto->MaxCount;
8499 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8502 return EQUIP_ERR_OK;
8505 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8507 Item *pItem;
8508 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8510 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8511 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8512 return true;
8514 for(uint8 i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8516 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8517 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8518 return true;
8520 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8522 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8524 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8526 pItem = GetItemByPos( i, j );
8527 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8528 return true;
8532 return false;
8535 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8537 Item* pItem2 = GetItemByPos( bag, slot );
8539 // ignore move item (this slot will be empty at move)
8540 if(pItem2==pSrcItem)
8541 pItem2 = NULL;
8543 uint32 need_space;
8545 // empty specific slot - check item fit to slot
8546 if( !pItem2 || swap )
8548 if( bag == INVENTORY_SLOT_BAG_0 )
8550 // keyring case
8551 if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8552 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8554 // vanitypet case
8555 if(slot >= VANITYPET_SLOT_START && slot < VANITYPET_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS))
8556 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8558 // currencytoken case
8559 if(slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
8560 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8562 // guestbag case
8563 if(slot >= QUESTBAG_SLOT_START && slot < QUESTBAG_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS))
8564 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8566 // prevent cheating
8567 if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8568 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8570 else
8572 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8573 if( !pBag )
8574 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8576 ItemPrototype const* pBagProto = pBag->GetProto();
8577 if( !pBagProto )
8578 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8580 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8581 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8584 // non empty stack with space
8585 need_space = pProto->Stackable;
8587 // non empty slot, check item type
8588 else
8590 // check item type
8591 if(pItem2->GetEntry() != pProto->ItemId)
8592 return EQUIP_ERR_ITEM_CANT_STACK;
8594 // check free space
8595 if(pItem2->GetCount() >= pProto->Stackable)
8596 return EQUIP_ERR_ITEM_CANT_STACK;
8598 need_space = pProto->Stackable - pItem2->GetCount();
8601 if(need_space > count)
8602 need_space = count;
8604 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8605 if(!newPosition.isContainedIn(dest))
8607 dest.push_back(newPosition);
8608 count -= need_space;
8610 return EQUIP_ERR_OK;
8613 uint8 Player::_CanStoreItem_InBag( uint8 bag, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool merge, bool non_specialized, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot ) const
8615 // skip specific bag already processed in first called _CanStoreItem_InBag
8616 if(bag==skip_bag)
8617 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8619 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8620 if( !pBag )
8621 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8623 ItemPrototype const* pBagProto = pBag->GetProto();
8624 if( !pBagProto )
8625 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8627 // specialized bag mode or non-specilized
8628 if( non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) )
8629 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8631 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8632 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8634 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8636 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8637 if(j==skip_slot)
8638 continue;
8640 Item* pItem2 = GetItemByPos( bag, j );
8642 // ignore move item (this slot will be empty at move)
8643 if(pItem2==pSrcItem)
8644 pItem2 = NULL;
8646 // if merge skip empty, if !merge skip non-empty
8647 if((pItem2!=NULL)!=merge)
8648 continue;
8650 if( pItem2 )
8652 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->Stackable )
8654 uint32 need_space = pProto->Stackable - pItem2->GetCount();
8655 if(need_space > count)
8656 need_space = count;
8658 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8659 if(!newPosition.isContainedIn(dest))
8661 dest.push_back(newPosition);
8662 count -= need_space;
8664 if(count==0)
8665 return EQUIP_ERR_OK;
8669 else
8671 uint32 need_space = pProto->Stackable;
8672 if(need_space > count)
8673 need_space = count;
8675 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8676 if(!newPosition.isContainedIn(dest))
8678 dest.push_back(newPosition);
8679 count -= need_space;
8681 if(count==0)
8682 return EQUIP_ERR_OK;
8686 return EQUIP_ERR_OK;
8689 uint8 Player::_CanStoreItem_InInventorySlots( uint8 slot_begin, uint8 slot_end, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool merge, Item* pSrcItem, uint8 skip_bag, uint8 skip_slot ) const
8691 for(uint32 j = slot_begin; j < slot_end; j++)
8693 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8694 if(INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
8695 continue;
8697 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
8699 // ignore move item (this slot will be empty at move)
8700 if(pItem2==pSrcItem)
8701 pItem2 = NULL;
8703 // if merge skip empty, if !merge skip non-empty
8704 if((pItem2!=NULL)!=merge)
8705 continue;
8707 if( pItem2 )
8709 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->Stackable )
8711 uint32 need_space = pProto->Stackable - pItem2->GetCount();
8712 if(need_space > count)
8713 need_space = count;
8714 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8715 if(!newPosition.isContainedIn(dest))
8717 dest.push_back(newPosition);
8718 count -= need_space;
8720 if(count==0)
8721 return EQUIP_ERR_OK;
8725 else
8727 uint32 need_space = pProto->Stackable;
8728 if(need_space > count)
8729 need_space = count;
8731 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8732 if(!newPosition.isContainedIn(dest))
8734 dest.push_back(newPosition);
8735 count -= need_space;
8737 if(count==0)
8738 return EQUIP_ERR_OK;
8742 return EQUIP_ERR_OK;
8745 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
8747 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
8749 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8750 if( !pProto )
8752 if(no_space_count)
8753 *no_space_count = count;
8754 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
8757 if(pItem && pItem->IsBindedNotWith(GetGUID()))
8759 if(no_space_count)
8760 *no_space_count = count;
8761 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
8764 // check count of items (skip for auto move for same player from bank)
8765 uint32 no_similar_count = 0; // can't store this amount similar items
8766 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
8767 if(res!=EQUIP_ERR_OK)
8769 if(count==no_similar_count)
8771 if(no_space_count)
8772 *no_space_count = no_similar_count;
8773 return res;
8775 count -= no_similar_count;
8778 // in specific slot
8779 if( bag != NULL_BAG && slot != NULL_SLOT )
8781 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
8782 if(res!=EQUIP_ERR_OK)
8784 if(no_space_count)
8785 *no_space_count = count + no_similar_count;
8786 return res;
8789 if(count==0)
8791 if(no_similar_count==0)
8792 return EQUIP_ERR_OK;
8794 if(no_space_count)
8795 *no_space_count = count + no_similar_count;
8796 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8800 // not specific slot or have space for partly store only in specific slot
8802 // in specific bag
8803 if( bag != NULL_BAG )
8805 // search stack in bag for merge to
8806 if( pProto->Stackable > 1 )
8808 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8810 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
8811 if(res!=EQUIP_ERR_OK)
8813 if(no_space_count)
8814 *no_space_count = count + no_similar_count;
8815 return res;
8818 if(count==0)
8820 if(no_similar_count==0)
8821 return EQUIP_ERR_OK;
8823 if(no_space_count)
8824 *no_space_count = count + no_similar_count;
8825 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8828 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
8829 if(res!=EQUIP_ERR_OK)
8831 if(no_space_count)
8832 *no_space_count = count + no_similar_count;
8833 return res;
8836 if(count==0)
8838 if(no_similar_count==0)
8839 return EQUIP_ERR_OK;
8841 if(no_space_count)
8842 *no_space_count = count + no_similar_count;
8843 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8846 else // equipped bag
8848 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
8849 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
8850 if(res!=EQUIP_ERR_OK)
8851 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
8853 if(res!=EQUIP_ERR_OK)
8855 if(no_space_count)
8856 *no_space_count = count + no_similar_count;
8857 return res;
8860 if(count==0)
8862 if(no_similar_count==0)
8863 return EQUIP_ERR_OK;
8865 if(no_space_count)
8866 *no_space_count = count + no_similar_count;
8867 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8872 // search free slot in bag for place to
8873 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8875 // search free slot - keyring case
8876 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
8878 uint32 keyringSize = GetMaxKeyringSize();
8879 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
8880 if(res!=EQUIP_ERR_OK)
8882 if(no_space_count)
8883 *no_space_count = count + no_similar_count;
8884 return res;
8887 if(count==0)
8889 if(no_similar_count==0)
8890 return EQUIP_ERR_OK;
8892 if(no_space_count)
8893 *no_space_count = count + no_similar_count;
8894 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8897 else if(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
8899 res = _CanStoreItem_InInventorySlots(VANITYPET_SLOT_START,VANITYPET_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
8900 if(res!=EQUIP_ERR_OK)
8902 if(no_space_count)
8903 *no_space_count = count + no_similar_count;
8904 return res;
8907 if(count==0)
8909 if(no_similar_count==0)
8910 return EQUIP_ERR_OK;
8912 if(no_space_count)
8913 *no_space_count = count + no_similar_count;
8914 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8917 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
8919 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
8920 if(res!=EQUIP_ERR_OK)
8922 if(no_space_count)
8923 *no_space_count = count + no_similar_count;
8924 return res;
8927 if(count==0)
8929 if(no_similar_count==0)
8930 return EQUIP_ERR_OK;
8932 if(no_space_count)
8933 *no_space_count = count + no_similar_count;
8934 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8937 else if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
8939 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
8940 if(res!=EQUIP_ERR_OK)
8942 if(no_space_count)
8943 *no_space_count = count + no_similar_count;
8944 return res;
8947 if(count==0)
8949 if(no_similar_count==0)
8950 return EQUIP_ERR_OK;
8952 if(no_space_count)
8953 *no_space_count = count + no_similar_count;
8954 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8958 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
8959 if(res!=EQUIP_ERR_OK)
8961 if(no_space_count)
8962 *no_space_count = count + no_similar_count;
8963 return res;
8966 if(count==0)
8968 if(no_similar_count==0)
8969 return EQUIP_ERR_OK;
8971 if(no_space_count)
8972 *no_space_count = count + no_similar_count;
8973 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8976 else // equipped bag
8978 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
8979 if(res!=EQUIP_ERR_OK)
8980 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
8982 if(res!=EQUIP_ERR_OK)
8984 if(no_space_count)
8985 *no_space_count = count + no_similar_count;
8986 return res;
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 // not specific bag or have space for partly store only in specific bag
9003 // search stack for merge to
9004 if( pProto->Stackable > 1 )
9006 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9007 if(res!=EQUIP_ERR_OK)
9009 if(no_space_count)
9010 *no_space_count = count + no_similar_count;
9011 return res;
9014 if(count==0)
9016 if(no_similar_count==0)
9017 return EQUIP_ERR_OK;
9019 if(no_space_count)
9020 *no_space_count = count + no_similar_count;
9021 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9024 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9025 if(res!=EQUIP_ERR_OK)
9027 if(no_space_count)
9028 *no_space_count = count + no_similar_count;
9029 return res;
9032 if(count==0)
9034 if(no_similar_count==0)
9035 return EQUIP_ERR_OK;
9037 if(no_space_count)
9038 *no_space_count = count + no_similar_count;
9039 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9042 if( pProto->BagFamily )
9044 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9046 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9047 if(res!=EQUIP_ERR_OK)
9048 continue;
9050 if(count==0)
9052 if(no_similar_count==0)
9053 return EQUIP_ERR_OK;
9055 if(no_space_count)
9056 *no_space_count = count + no_similar_count;
9057 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9062 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9064 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9065 if(res!=EQUIP_ERR_OK)
9066 continue;
9068 if(count==0)
9070 if(no_similar_count==0)
9071 return EQUIP_ERR_OK;
9073 if(no_space_count)
9074 *no_space_count = count + no_similar_count;
9075 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9080 // search free slot - special bag case
9081 if( pProto->BagFamily )
9083 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9085 uint32 keyringSize = GetMaxKeyringSize();
9086 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9087 if(res!=EQUIP_ERR_OK)
9089 if(no_space_count)
9090 *no_space_count = count + no_similar_count;
9091 return res;
9094 if(count==0)
9096 if(no_similar_count==0)
9097 return EQUIP_ERR_OK;
9099 if(no_space_count)
9100 *no_space_count = count + no_similar_count;
9101 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9104 else if(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
9106 res = _CanStoreItem_InInventorySlots(VANITYPET_SLOT_START,VANITYPET_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9107 if(res!=EQUIP_ERR_OK)
9109 if(no_space_count)
9110 *no_space_count = count + no_similar_count;
9111 return res;
9114 if(count==0)
9116 if(no_similar_count==0)
9117 return EQUIP_ERR_OK;
9119 if(no_space_count)
9120 *no_space_count = count + no_similar_count;
9121 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9124 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9126 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9127 if(res!=EQUIP_ERR_OK)
9129 if(no_space_count)
9130 *no_space_count = count + no_similar_count;
9131 return res;
9134 if(count==0)
9136 if(no_similar_count==0)
9137 return EQUIP_ERR_OK;
9139 if(no_space_count)
9140 *no_space_count = count + no_similar_count;
9141 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9144 else if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9146 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9147 if(res!=EQUIP_ERR_OK)
9149 if(no_space_count)
9150 *no_space_count = count + no_similar_count;
9151 return res;
9154 if(count==0)
9156 if(no_similar_count==0)
9157 return EQUIP_ERR_OK;
9159 if(no_space_count)
9160 *no_space_count = count + no_similar_count;
9161 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9165 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9167 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9168 if(res!=EQUIP_ERR_OK)
9169 continue;
9171 if(count==0)
9173 if(no_similar_count==0)
9174 return EQUIP_ERR_OK;
9176 if(no_space_count)
9177 *no_space_count = count + no_similar_count;
9178 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9183 // search free slot
9184 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9185 if(res!=EQUIP_ERR_OK)
9187 if(no_space_count)
9188 *no_space_count = count + no_similar_count;
9189 return res;
9192 if(count==0)
9194 if(no_similar_count==0)
9195 return EQUIP_ERR_OK;
9197 if(no_space_count)
9198 *no_space_count = count + no_similar_count;
9199 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9202 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9204 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9205 if(res!=EQUIP_ERR_OK)
9206 continue;
9208 if(count==0)
9210 if(no_similar_count==0)
9211 return EQUIP_ERR_OK;
9213 if(no_space_count)
9214 *no_space_count = count + no_similar_count;
9215 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9219 if(no_space_count)
9220 *no_space_count = count + no_similar_count;
9222 return EQUIP_ERR_INVENTORY_FULL;
9225 //////////////////////////////////////////////////////////////////////////
9226 uint8 Player::CanStoreItems( Item **pItems,int count) const
9228 Item *pItem2;
9230 // fill space table
9231 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9232 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9233 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9234 int inv_pets[VANITYPET_SLOT_END-VANITYPET_SLOT_START];
9235 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9236 int inv_quests[QUESTBAG_SLOT_END-QUESTBAG_SLOT_START];
9238 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9239 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9240 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9241 memset(inv_pets,0,sizeof(int)*(VANITYPET_SLOT_END-VANITYPET_SLOT_START));
9242 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9243 memset(inv_quests,0,sizeof(int)*(QUESTBAG_SLOT_END-QUESTBAG_SLOT_START));
9245 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
9247 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9249 if (pItem2 && !pItem2->IsInTrade())
9251 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9255 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
9257 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9259 if (pItem2 && !pItem2->IsInTrade())
9261 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9265 for(int i = VANITYPET_SLOT_START; i < VANITYPET_SLOT_END; i++)
9267 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9269 if (pItem2 && !pItem2->IsInTrade())
9271 inv_pets[i-VANITYPET_SLOT_START] = pItem2->GetCount();
9275 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; i++)
9277 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9279 if (pItem2 && !pItem2->IsInTrade())
9281 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9285 for(int i = QUESTBAG_SLOT_START; i < QUESTBAG_SLOT_END; i++)
9287 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9289 if (pItem2 && !pItem2->IsInTrade())
9291 inv_quests[i-QUESTBAG_SLOT_START] = pItem2->GetCount();
9295 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9297 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9299 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9301 pItem2 = GetItemByPos( i, j );
9302 if (pItem2 && !pItem2->IsInTrade())
9304 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9310 // check free space for all items
9311 for (int k=0;k<count;k++)
9313 Item *pItem = pItems[k];
9315 // no item
9316 if (!pItem) continue;
9318 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9319 ItemPrototype const *pProto = pItem->GetProto();
9321 // strange item
9322 if( !pProto )
9323 return EQUIP_ERR_ITEM_NOT_FOUND;
9325 // item it 'bind'
9326 if(pItem->IsBindedNotWith(GetGUID()))
9327 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9329 Bag *pBag;
9330 ItemPrototype const *pBagProto;
9332 // item is 'one item only'
9333 uint8 res = CanTakeMoreSimilarItems(pItem);
9334 if(res != EQUIP_ERR_OK)
9335 return res;
9337 // search stack for merge to
9338 if( pProto->Stackable > 1 )
9340 bool b_found = false;
9342 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; t++)
9344 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9345 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->Stackable )
9347 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9348 b_found = true;
9349 break;
9352 if (b_found) continue;
9354 for(int t = VANITYPET_SLOT_START; t < VANITYPET_SLOT_END; t++)
9356 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9357 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_pets[t-VANITYPET_SLOT_START] + pItem->GetCount() <= pProto->Stackable )
9359 inv_pets[t-VANITYPET_SLOT_START] += pItem->GetCount();
9360 b_found = true;
9361 break;
9364 if (b_found) continue;
9366 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; t++)
9368 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9369 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->Stackable )
9371 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9372 b_found = true;
9373 break;
9376 if (b_found) continue;
9378 for(int t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; t++)
9380 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9381 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_quests[t-QUESTBAG_SLOT_START] + pItem->GetCount() <= pProto->Stackable )
9383 inv_quests[t-QUESTBAG_SLOT_START] += pItem->GetCount();
9384 b_found = true;
9385 break;
9388 if (b_found) continue;
9390 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9392 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9393 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->Stackable )
9395 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9396 b_found = true;
9397 break;
9400 if (b_found) continue;
9402 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9404 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9405 if( pBag )
9407 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9409 pItem2 = GetItemByPos( t, j );
9410 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->Stackable )
9412 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9413 b_found = true;
9414 break;
9419 if (b_found) continue;
9422 // special bag case
9423 if( pProto->BagFamily )
9425 bool b_found = false;
9426 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9428 uint32 keyringSize = GetMaxKeyringSize();
9429 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9431 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9433 inv_keys[t-KEYRING_SLOT_START] = 1;
9434 b_found = true;
9435 break;
9440 if (b_found) continue;
9442 if(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
9444 for(uint32 t = VANITYPET_SLOT_START; t < VANITYPET_SLOT_END; ++t)
9446 if( inv_pets[t-VANITYPET_SLOT_START] == 0 )
9448 inv_pets[t-VANITYPET_SLOT_START] = 1;
9449 b_found = true;
9450 break;
9455 if (b_found) continue;
9457 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9459 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9461 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9463 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9464 b_found = true;
9465 break;
9470 if (b_found) continue;
9472 if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9474 for(uint32 t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; ++t)
9476 if( inv_quests[t-QUESTBAG_SLOT_START] == 0 )
9478 inv_quests[t-QUESTBAG_SLOT_START] = 1;
9479 b_found = true;
9480 break;
9485 if (b_found) continue;
9487 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9489 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9490 if( pBag )
9492 pBagProto = pBag->GetProto();
9494 // not plain container check
9495 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9496 ItemCanGoIntoBag(pProto,pBagProto) )
9498 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9500 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9502 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9503 b_found = true;
9504 break;
9510 if (b_found) continue;
9513 // search free slot
9514 bool b_found = false;
9515 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9517 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9519 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9520 b_found = true;
9521 break;
9524 if (b_found) continue;
9526 // search free slot in bags
9527 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9529 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9530 if( pBag )
9532 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9534 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9536 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9537 b_found = true;
9538 break;
9544 // no free slot found?
9545 if (!b_found)
9546 return EQUIP_ERR_INVENTORY_FULL;
9549 return EQUIP_ERR_OK;
9552 //////////////////////////////////////////////////////////////////////////
9553 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, uint32 count, bool swap ) const
9555 dest = 0;
9556 Item *pItem = Item::CreateItem( item, count, this );
9557 if( pItem )
9559 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9560 delete pItem;
9561 return result;
9564 return EQUIP_ERR_ITEM_NOT_FOUND;
9567 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9569 dest = 0;
9570 if( pItem )
9572 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9573 ItemPrototype const *pProto = pItem->GetProto();
9574 if( pProto )
9576 // May be here should be more stronger checks; STUNNED checked
9577 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9578 if (not_loading && hasUnitState(UNIT_STAT_STUNNED))
9579 return EQUIP_ERR_YOU_ARE_STUNNED;
9581 if(pItem->IsBindedNotWith(GetGUID()))
9582 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9584 // check count of items (skip for auto move for same player from bank)
9585 uint8 res = CanTakeMoreSimilarItems(pItem);
9586 if(res != EQUIP_ERR_OK)
9587 return res;
9589 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9590 // - combat
9591 // - in-progress arenas
9592 if( !pProto->CanChangeEquipStateInCombat() )
9594 if( isInCombat() )
9595 return EQUIP_ERR_NOT_IN_COMBAT;
9597 if(BattleGround* bg = GetBattleGround())
9598 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9599 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9602 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9603 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9605 if(IsNonMeleeSpellCasted(false))
9606 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9608 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9609 if( eslot == NULL_SLOT )
9610 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9612 uint8 msg = CanUseItem( pItem , not_loading );
9613 if( msg != EQUIP_ERR_OK )
9614 return msg;
9615 if( !swap && GetItemByPos( INVENTORY_SLOT_BAG_0, eslot ) )
9616 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9618 // check unique-equipped on item
9619 if (pProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
9621 // there is an equip limit on this item
9622 Item* tItem = GetItemOrItemWithGemEquipped(pProto->ItemId);
9623 if (tItem && (!swap || tItem->GetSlot() != eslot ) )
9624 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
9627 // check unique-equipped on gems
9628 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
9630 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
9631 if(!enchant_id)
9632 continue;
9633 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
9634 if(!enchantEntry)
9635 continue;
9637 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
9638 if(pGem && (pGem->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED))
9640 Item* tItem = GetItemOrItemWithGemEquipped(enchantEntry->GemID);
9641 if(tItem && (!swap || tItem->GetSlot() != eslot ))
9642 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
9646 // check unique-equipped special item classes
9647 if (pProto->Class == ITEM_CLASS_QUIVER)
9649 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9651 if( Item* pBag = GetItemByPos( INVENTORY_SLOT_BAG_0, i ) )
9653 if( ItemPrototype const* pBagProto = pBag->GetProto() )
9655 if( pBagProto->Class==pProto->Class && pBagProto->SubClass==pProto->SubClass &&
9656 (!swap || pBag->GetSlot() != eslot ) )
9658 if(pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9659 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH;
9660 else
9661 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9668 uint32 type = pProto->InventoryType;
9670 if(eslot == EQUIPMENT_SLOT_OFFHAND)
9672 if( type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND )
9674 if(!CanDualWield())
9675 return EQUIP_ERR_CANT_DUAL_WIELD;
9678 Item *mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );
9679 if(mainItem)
9681 if(mainItem->GetProto()->InventoryType == INVTYPE_2HWEAPON)
9682 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9686 // equip two-hand weapon case (with possible unequip 2 items)
9687 if( type == INVTYPE_2HWEAPON )
9689 if(eslot != EQUIPMENT_SLOT_MAINHAND)
9690 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9692 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9693 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9694 ItemPosCountVec off_dest;
9695 if( offItem && (!not_loading ||
9696 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9697 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ) )
9698 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9700 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9701 return EQUIP_ERR_OK;
9704 if( !swap )
9705 return EQUIP_ERR_ITEM_NOT_FOUND;
9706 else
9707 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9710 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9712 // Applied only to equipped items and bank bags
9713 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9714 return EQUIP_ERR_OK;
9716 Item* pItem = GetItemByPos(pos);
9718 // Applied only to existed equipped item
9719 if( !pItem )
9720 return EQUIP_ERR_OK;
9722 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9724 ItemPrototype const *pProto = pItem->GetProto();
9725 if( !pProto )
9726 return EQUIP_ERR_ITEM_NOT_FOUND;
9728 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9729 // - combat
9730 // - in-progress arenas
9731 if( !pProto->CanChangeEquipStateInCombat() )
9733 if( isInCombat() )
9734 return EQUIP_ERR_NOT_IN_COMBAT;
9736 if(BattleGround* bg = GetBattleGround())
9737 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9738 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9741 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9742 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9744 return EQUIP_ERR_OK;
9747 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
9749 if( !pItem )
9750 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9752 uint32 count = pItem->GetCount();
9754 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
9755 ItemPrototype const *pProto = pItem->GetProto();
9756 if( !pProto )
9757 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9759 if( pItem->IsBindedNotWith(GetGUID()) )
9760 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9762 // check count of items (skip for auto move for same player from bank)
9763 uint8 res = CanTakeMoreSimilarItems(pItem);
9764 if(res != EQUIP_ERR_OK)
9765 return res;
9767 // in specific slot
9768 if( bag != NULL_BAG && slot != NULL_SLOT )
9770 if( pProto->InventoryType == INVTYPE_BAG )
9772 Bag *pBag = (Bag*)pItem;
9773 if( pBag )
9775 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9777 if( !HasBankBagSlot( slot ) )
9778 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
9779 if( uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK )
9780 return cantuse;
9782 else
9784 if( !pBag->IsEmpty() )
9785 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9789 else
9791 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9792 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
9795 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9796 if(res!=EQUIP_ERR_OK)
9797 return res;
9799 if(count==0)
9800 return EQUIP_ERR_OK;
9803 // not specific slot or have space for partly store only in specific slot
9805 // in specific bag
9806 if( bag != NULL_BAG )
9808 if( pProto->InventoryType == INVTYPE_BAG )
9810 Bag *pBag = (Bag*)pItem;
9811 if( pBag && !pBag->IsEmpty() )
9812 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9815 // search stack in bag for merge to
9816 if( pProto->Stackable > 1 )
9818 if( bag == INVENTORY_SLOT_BAG_0 )
9820 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9821 if(res!=EQUIP_ERR_OK)
9822 return res;
9824 if(count==0)
9825 return EQUIP_ERR_OK;
9827 else
9829 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9830 if(res!=EQUIP_ERR_OK)
9831 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9833 if(res!=EQUIP_ERR_OK)
9834 return res;
9836 if(count==0)
9837 return EQUIP_ERR_OK;
9841 // search free slot in bag
9842 if( bag == INVENTORY_SLOT_BAG_0 )
9844 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9845 if(res!=EQUIP_ERR_OK)
9846 return res;
9848 if(count==0)
9849 return EQUIP_ERR_OK;
9851 else
9853 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9854 if(res!=EQUIP_ERR_OK)
9855 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9857 if(res!=EQUIP_ERR_OK)
9858 return res;
9860 if(count==0)
9861 return EQUIP_ERR_OK;
9865 // not specific bag or have space for partly store only in specific bag
9867 // search stack for merge to
9868 if( pProto->Stackable > 1 )
9870 // in slots
9871 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9872 if(res!=EQUIP_ERR_OK)
9873 return res;
9875 if(count==0)
9876 return EQUIP_ERR_OK;
9878 // in special bags
9879 if( pProto->BagFamily )
9881 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9883 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9884 if(res!=EQUIP_ERR_OK)
9885 continue;
9887 if(count==0)
9888 return EQUIP_ERR_OK;
9892 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9894 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9895 if(res!=EQUIP_ERR_OK)
9896 continue;
9898 if(count==0)
9899 return EQUIP_ERR_OK;
9903 // search free place in special bag
9904 if( pProto->BagFamily )
9906 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9908 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9909 if(res!=EQUIP_ERR_OK)
9910 continue;
9912 if(count==0)
9913 return EQUIP_ERR_OK;
9917 // search free space
9918 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9919 if(res!=EQUIP_ERR_OK)
9920 return res;
9922 if(count==0)
9923 return EQUIP_ERR_OK;
9925 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9927 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9928 if(res!=EQUIP_ERR_OK)
9929 continue;
9931 if(count==0)
9932 return EQUIP_ERR_OK;
9934 return EQUIP_ERR_BANK_FULL;
9937 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
9939 if( pItem )
9941 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
9942 if( !isAlive() && not_loading )
9943 return EQUIP_ERR_YOU_ARE_DEAD;
9944 //if( isStunned() )
9945 // return EQUIP_ERR_YOU_ARE_STUNNED;
9946 ItemPrototype const *pProto = pItem->GetProto();
9947 if( pProto )
9949 if( pItem->IsBindedNotWith(GetGUID()) )
9950 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9951 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9952 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
9953 if( pItem->GetSkill() != 0 )
9955 if( GetSkillValue( pItem->GetSkill() ) == 0 )
9956 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9958 if( pProto->RequiredSkill != 0 )
9960 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9961 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9962 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9963 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
9965 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9966 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
9967 if( pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank )
9968 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
9969 if( getLevel() < pProto->RequiredLevel )
9970 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
9971 return EQUIP_ERR_OK;
9974 return EQUIP_ERR_ITEM_NOT_FOUND;
9977 bool Player::CanUseItem( ItemPrototype const *pProto )
9979 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
9981 if( pProto )
9983 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
9984 return false;
9985 if( pProto->RequiredSkill != 0 )
9987 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
9988 return false;
9989 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
9990 return false;
9992 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
9993 return false;
9994 if( getLevel() < pProto->RequiredLevel )
9995 return false;
9996 return true;
9998 return false;
10001 uint8 Player::CanUseAmmo( uint32 item ) const
10003 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
10004 if( !isAlive() )
10005 return EQUIP_ERR_YOU_ARE_DEAD;
10006 //if( isStunned() )
10007 // return EQUIP_ERR_YOU_ARE_STUNNED;
10008 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
10009 if( pProto )
10011 if( pProto->InventoryType!= INVTYPE_AMMO )
10012 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
10013 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10014 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10015 if( pProto->RequiredSkill != 0 )
10017 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10018 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10019 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10020 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10022 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10023 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10024 /*if( GetReputation() < pProto->RequiredReputation )
10025 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10027 if( getLevel() < pProto->RequiredLevel )
10028 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10030 // Requires No Ammo
10031 if(GetDummyAura(46699))
10032 return EQUIP_ERR_BAG_FULL6;
10034 return EQUIP_ERR_OK;
10036 return EQUIP_ERR_ITEM_NOT_FOUND;
10039 void Player::SetAmmo( uint32 item )
10041 if(!item)
10042 return;
10044 // already set
10045 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10046 return;
10048 // check ammo
10049 if(item)
10051 uint8 msg = CanUseAmmo( item );
10052 if( msg != EQUIP_ERR_OK )
10054 SendEquipError( msg, NULL, NULL );
10055 return;
10059 SetUInt32Value(PLAYER_AMMO_ID, item);
10061 _ApplyAmmoBonuses();
10064 void Player::RemoveAmmo()
10066 SetUInt32Value(PLAYER_AMMO_ID, 0);
10068 m_ammoDPS = 0.0f;
10070 if(CanModifyStats())
10071 UpdateDamagePhysical(RANGED_ATTACK);
10074 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10075 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10077 uint32 count = 0;
10078 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10079 count += itr->count;
10081 Item *pItem = Item::CreateItem( item, count, this );
10082 if( pItem )
10084 ItemAddedQuestCheck( item, count );
10085 if(randomPropertyId)
10086 pItem->SetItemRandomProperties(randomPropertyId);
10087 pItem = StoreItem( dest, pItem, update );
10089 return pItem;
10092 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10094 if( !pItem )
10095 return NULL;
10097 Item* lastItem = pItem;
10099 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10101 uint16 pos = itr->pos;
10102 uint32 count = itr->count;
10104 ++itr;
10106 if(itr == dest.end())
10108 lastItem = _StoreItem(pos,pItem,count,false,update);
10109 break;
10112 lastItem = _StoreItem(pos,pItem,count,true,update);
10115 return lastItem;
10118 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10119 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10121 if( !pItem )
10122 return NULL;
10124 uint8 bag = pos >> 8;
10125 uint8 slot = pos & 255;
10127 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10129 Item *pItem2 = GetItemByPos( bag, slot );
10131 if( !pItem2 )
10133 if(clone)
10134 pItem = pItem->CloneItem(count,this);
10135 else
10136 pItem->SetCount(count);
10138 if(!pItem)
10139 return NULL;
10141 if( pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10142 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10143 pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
10144 pItem->SetBinding( true );
10146 if( bag == INVENTORY_SLOT_BAG_0 )
10148 m_items[slot] = pItem;
10149 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10150 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10151 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10153 pItem->SetSlot( slot );
10154 pItem->SetContainer( NULL );
10156 if( IsInWorld() && update )
10158 pItem->AddToWorld();
10159 pItem->SendUpdateToPlayer( this );
10162 pItem->SetState(ITEM_CHANGED, this);
10164 else
10166 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10167 if( pBag )
10169 pBag->StoreItem( slot, pItem, update );
10170 if( IsInWorld() && update )
10172 pItem->AddToWorld();
10173 pItem->SendUpdateToPlayer( this );
10175 pItem->SetState(ITEM_CHANGED, this);
10176 pBag->SetState(ITEM_CHANGED, this);
10180 AddEnchantmentDurations(pItem);
10181 AddItemDurations(pItem);
10183 return pItem;
10185 else
10187 if( pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10188 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10189 pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
10190 pItem2->SetBinding( true );
10192 pItem2->SetCount( pItem2->GetCount() + count );
10193 if( IsInWorld() && update )
10194 pItem2->SendUpdateToPlayer( this );
10196 if(!clone)
10198 // delete item (it not in any slot currently)
10199 if( IsInWorld() && update )
10201 pItem->RemoveFromWorld();
10202 pItem->DestroyForPlayer( this );
10205 RemoveEnchantmentDurations(pItem);
10206 RemoveItemDurations(pItem);
10208 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10209 pItem->SetState(ITEM_REMOVED, this);
10211 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10212 AddEnchantmentDurations(pItem2);
10214 pItem2->SetState(ITEM_CHANGED, this);
10216 return pItem2;
10220 Item* Player::EquipNewItem( uint16 pos, uint32 item, uint32 count, bool update )
10222 Item *pItem = Item::CreateItem( item, count, this );
10223 if( pItem )
10225 ItemAddedQuestCheck( item, count );
10226 Item * retItem = EquipItem( pos, pItem, update );
10228 return retItem;
10230 return NULL;
10233 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10235 if( pItem )
10237 AddEnchantmentDurations(pItem);
10238 AddItemDurations(pItem);
10240 uint8 bag = pos >> 8;
10241 uint8 slot = pos & 255;
10243 Item *pItem2 = GetItemByPos( bag, slot );
10245 if( !pItem2 )
10247 VisualizeItem( slot, pItem);
10249 if(isAlive())
10251 ItemPrototype const *pProto = pItem->GetProto();
10253 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10254 if(pProto && pProto->ItemSet)
10255 AddItemsSetItem(this,pItem);
10257 _ApplyItemMods(pItem, slot, true);
10259 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10261 m_weaponChangeTimer = DEFAULT_SWITCH_WEAPON;
10262 if (getClass() == CLASS_ROGUE)
10263 m_weaponChangeTimer = ROGUE_SWITCH_WEAPON;
10267 if( IsInWorld() && update )
10269 pItem->AddToWorld();
10270 pItem->SendUpdateToPlayer( this );
10273 ApplyEquipCooldown(pItem);
10275 if( slot == EQUIPMENT_SLOT_MAINHAND )
10276 UpdateExpertise(BASE_ATTACK);
10277 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10278 UpdateExpertise(OFF_ATTACK);
10280 else
10282 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10283 if( IsInWorld() && update )
10284 pItem2->SendUpdateToPlayer( this );
10286 // delete item (it not in any slot currently)
10287 //pItem->DeleteFromDB();
10288 if( IsInWorld() && update )
10290 pItem->RemoveFromWorld();
10291 pItem->DestroyForPlayer( this );
10294 RemoveEnchantmentDurations(pItem);
10295 RemoveItemDurations(pItem);
10297 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10298 pItem->SetState(ITEM_REMOVED, this);
10299 pItem2->SetState(ITEM_CHANGED, this);
10301 ApplyEquipCooldown(pItem2);
10303 return pItem2;
10307 return pItem;
10310 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10312 if( pItem )
10314 AddEnchantmentDurations(pItem);
10315 AddItemDurations(pItem);
10317 uint8 slot = pos & 255;
10318 VisualizeItem( slot, pItem);
10320 if( IsInWorld() )
10322 pItem->AddToWorld();
10323 pItem->SendUpdateToPlayer( this );
10328 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10330 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10331 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10332 // entry // Size: 1
10333 // inspected enchantments // Size: 6
10334 // ? // Size: 5
10335 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10336 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10337 // // = 16
10339 if(pItem)
10341 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetUInt64Value(ITEM_FIELD_CREATOR));
10343 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10344 SetUInt32Value(VisibleBase + 0, pItem->GetEntry());
10346 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10347 SetUInt32Value(VisibleBase + 1 + i, pItem->GetEnchantmentId(EnchantmentSlot(i)));
10349 // Use SetInt16Value to prevent set high part to FFFF for negative value
10350 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES + (slot * MAX_VISIBLE_ITEM_OFFSET), 0, pItem->GetItemRandomPropertyId());
10351 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetItemSuffixFactor());
10353 else
10355 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10357 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10358 SetUInt32Value(VisibleBase + 0, 0);
10360 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10361 SetUInt32Value(VisibleBase + 1 + i, 0);
10363 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 0 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10364 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10368 void Player::VisualizeItem( uint8 slot, Item *pItem)
10370 if(!pItem)
10371 return;
10373 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10374 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10375 pItem->SetBinding( true );
10377 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10379 m_items[slot] = pItem;
10380 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10381 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10382 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10383 pItem->SetSlot( slot );
10384 pItem->SetContainer( NULL );
10386 if( slot < EQUIPMENT_SLOT_END )
10387 SetVisibleItemSlot(slot,pItem);
10389 pItem->SetState(ITEM_CHANGED, this);
10392 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10394 // note: removeitem does not actually change the item
10395 // it only takes the item out of storage temporarily
10396 // note2: if removeitem is to be used for delinking
10397 // the item must be removed from the player's updatequeue
10399 Item *pItem = GetItemByPos( bag, slot );
10400 if( pItem )
10402 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10404 RemoveEnchantmentDurations(pItem);
10405 RemoveItemDurations(pItem);
10407 if( bag == INVENTORY_SLOT_BAG_0 )
10409 if ( slot < INVENTORY_SLOT_BAG_END )
10411 ItemPrototype const *pProto = pItem->GetProto();
10412 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10414 if(pProto && pProto->ItemSet)
10415 RemoveItemsSetItem(this,pProto);
10417 _ApplyItemMods(pItem, slot, false);
10419 // remove item dependent auras and casts (only weapon and armor slots)
10420 if(slot < EQUIPMENT_SLOT_END)
10421 RemoveItemDependentAurasAndCasts(pItem);
10423 // remove held enchantments
10424 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10426 if (pItem->GetItemSuffixFactor())
10428 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10429 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10431 else
10433 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10434 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10439 m_items[slot] = NULL;
10440 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10442 if ( slot < EQUIPMENT_SLOT_END )
10443 SetVisibleItemSlot(slot,NULL);
10445 else
10447 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10448 if( pBag )
10449 pBag->RemoveItem(slot, update);
10451 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10452 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10453 pItem->SetSlot( NULL_SLOT );
10454 if( IsInWorld() && update )
10455 pItem->SendUpdateToPlayer( this );
10457 if( slot == EQUIPMENT_SLOT_MAINHAND )
10458 UpdateExpertise(BASE_ATTACK);
10459 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10460 UpdateExpertise(OFF_ATTACK);
10464 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10465 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10467 if(Item* it = GetItemByPos(bag,slot))
10469 ItemRemovedQuestCheck(it->GetEntry(),it->GetCount());
10470 RemoveItem( bag,slot,update);
10471 it->RemoveFromUpdateQueueOf(this);
10472 if(it->IsInWorld())
10474 it->RemoveFromWorld();
10475 it->DestroyForPlayer( this );
10480 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10481 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10483 // update quest counters
10484 ItemAddedQuestCheck(pItem->GetEntry(),pItem->GetCount());
10486 // store item
10487 Item* pLastItem = StoreItem( dest, pItem, update);
10489 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10490 if(pLastItem==pItem)
10492 // update owner for last item (this can be original item with wrong owner
10493 if(pLastItem->GetOwnerGUID() != GetGUID())
10494 pLastItem->SetOwnerGUID(GetGUID());
10496 // if this original item then it need create record in inventory
10497 // in case trade we already have item in other player inventory
10498 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10502 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10504 Item *pItem = GetItemByPos( bag, slot );
10505 if( pItem )
10507 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10509 // start from destroy contained items (only equipped bag can have its)
10510 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10512 for (int i = 0; i < MAX_BAG_SIZE; i++)
10513 DestroyItem(slot,i,update);
10516 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10517 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10519 RemoveEnchantmentDurations(pItem);
10520 RemoveItemDurations(pItem);
10522 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10524 if( bag == INVENTORY_SLOT_BAG_0 )
10526 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10528 // equipment and equipped bags can have applied bonuses
10529 if ( slot < INVENTORY_SLOT_BAG_END )
10531 ItemPrototype const *pProto = pItem->GetProto();
10533 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10534 if(pProto && pProto->ItemSet)
10535 RemoveItemsSetItem(this,pProto);
10537 _ApplyItemMods(pItem, slot, false);
10540 if ( slot < EQUIPMENT_SLOT_END )
10542 // remove item dependent auras and casts (only weapon and armor slots)
10543 RemoveItemDependentAurasAndCasts(pItem);
10545 // equipment visual show
10546 SetVisibleItemSlot(slot,NULL);
10549 m_items[slot] = NULL;
10551 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10552 pBag->RemoveItem(slot, update);
10554 if( IsInWorld() && update )
10556 pItem->RemoveFromWorld();
10557 pItem->DestroyForPlayer(this);
10560 //pItem->SetOwnerGUID(0);
10561 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10562 pItem->SetSlot( NULL_SLOT );
10563 pItem->SetState(ITEM_REMOVED, this);
10567 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10569 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10570 Item *pItem;
10571 ItemPrototype const *pProto;
10572 uint32 remcount = 0;
10574 // in inventory
10575 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10577 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10578 if( pItem && pItem->GetEntry() == item )
10580 if( pItem->GetCount() + remcount <= count )
10582 // all items in inventory can unequipped
10583 remcount += pItem->GetCount();
10584 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10586 if(remcount >=count)
10587 return;
10589 else
10591 pProto = pItem->GetProto();
10592 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10593 pItem->SetCount( pItem->GetCount() - count + remcount );
10594 if( IsInWorld() & update )
10595 pItem->SendUpdateToPlayer( this );
10596 pItem->SetState(ITEM_CHANGED, this);
10597 return;
10601 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
10603 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10604 if( pItem && pItem->GetEntry() == item )
10606 if( pItem->GetCount() + remcount <= count )
10608 // all keys can be unequipped
10609 remcount += pItem->GetCount();
10610 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10612 if(remcount >=count)
10613 return;
10615 else
10617 pProto = pItem->GetProto();
10618 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10619 pItem->SetCount( pItem->GetCount() - count + remcount );
10620 if( IsInWorld() & update )
10621 pItem->SendUpdateToPlayer( this );
10622 pItem->SetState(ITEM_CHANGED, this);
10623 return;
10628 // in inventory bags
10629 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10631 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10633 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10635 pItem = pBag->GetItemByPos(j);
10636 if( pItem && pItem->GetEntry() == item )
10638 // all items in bags can be unequipped
10639 if( pItem->GetCount() + remcount <= count )
10641 remcount += pItem->GetCount();
10642 DestroyItem( i, j, update );
10644 if(remcount >=count)
10645 return;
10647 else
10649 pProto = pItem->GetProto();
10650 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10651 pItem->SetCount( pItem->GetCount() - count + remcount );
10652 if( IsInWorld() && update )
10653 pItem->SendUpdateToPlayer( this );
10654 pItem->SetState(ITEM_CHANGED, this);
10655 return;
10662 // in equipment and bag list
10663 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10665 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10666 if( pItem && pItem->GetEntry() == item )
10668 if( pItem->GetCount() + remcount <= count )
10670 if(!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i,false) == EQUIP_ERR_OK )
10672 remcount += pItem->GetCount();
10673 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10675 if(remcount >=count)
10676 return;
10679 else
10681 pProto = pItem->GetProto();
10682 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10683 pItem->SetCount( pItem->GetCount() - count + remcount );
10684 if( IsInWorld() & update )
10685 pItem->SendUpdateToPlayer( this );
10686 pItem->SetState(ITEM_CHANGED, this);
10687 return;
10693 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10695 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10697 // in inventory
10698 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10700 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10701 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10702 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10704 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
10706 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10707 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10708 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10711 // in inventory bags
10712 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10714 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10715 if( pBag )
10717 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10719 Item* pItem = pBag->GetItemByPos(j);
10720 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10721 DestroyItem( i, j, update);
10726 // in equipment and bag list
10727 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10729 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10730 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10731 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10735 void Player::DestroyConjuredItems( bool update )
10737 // used when entering arena
10738 // destroys all conjured items
10739 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
10741 // in inventory
10742 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10744 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10745 if( pItem && pItem->GetProto() &&
10746 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10747 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10748 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10751 // in inventory bags
10752 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10754 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10755 if( pBag )
10757 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10759 Item* pItem = pBag->GetItemByPos(j);
10760 if( pItem && pItem->GetProto() &&
10761 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10762 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10763 DestroyItem( i, j, update);
10768 // in equipment and bag list
10769 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10771 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10772 if( pItem && pItem->GetProto() &&
10773 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10774 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10775 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10779 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
10781 if(!pItem)
10782 return;
10784 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
10786 if( pItem->GetCount() <= count )
10788 count-= pItem->GetCount();
10790 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
10792 else
10794 ItemRemovedQuestCheck( pItem->GetEntry(), count);
10795 pItem->SetCount( pItem->GetCount() - count );
10796 count = 0;
10797 if( IsInWorld() & update )
10798 pItem->SendUpdateToPlayer( this );
10799 pItem->SetState(ITEM_CHANGED, this);
10803 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
10805 uint8 srcbag = src >> 8;
10806 uint8 srcslot = src & 255;
10808 uint8 dstbag = dst >> 8;
10809 uint8 dstslot = dst & 255;
10811 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10812 if( !pSrcItem )
10814 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10815 return;
10818 // not let split all items (can be only at cheating)
10819 if(pSrcItem->GetCount() == count)
10821 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10822 return;
10825 // not let split more existed items (can be only at cheating)
10826 if(pSrcItem->GetCount() < count)
10828 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
10829 return;
10832 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
10834 //best error message found for attempting to split while looting
10835 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10836 return;
10839 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
10840 Item *pNewItem = pSrcItem->CloneItem( count, this );
10841 if( !pNewItem )
10843 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10844 return;
10847 if( IsInventoryPos( dst ) )
10849 // change item amount before check (for unique max count check)
10850 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10852 ItemPosCountVec dest;
10853 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
10854 if( msg != EQUIP_ERR_OK )
10856 delete pNewItem;
10857 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10858 SendEquipError( msg, pSrcItem, NULL );
10859 return;
10862 if( IsInWorld() )
10863 pSrcItem->SendUpdateToPlayer( this );
10864 pSrcItem->SetState(ITEM_CHANGED, this);
10865 StoreItem( dest, pNewItem, true);
10867 else if( IsBankPos ( dst ) )
10869 // change item amount before check (for unique max count check)
10870 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10872 ItemPosCountVec dest;
10873 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
10874 if( msg != EQUIP_ERR_OK )
10876 delete pNewItem;
10877 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10878 SendEquipError( msg, pSrcItem, NULL );
10879 return;
10882 if( IsInWorld() )
10883 pSrcItem->SendUpdateToPlayer( this );
10884 pSrcItem->SetState(ITEM_CHANGED, this);
10885 BankItem( dest, pNewItem, true);
10887 else if( IsEquipmentPos ( dst ) )
10889 // change item amount before check (for unique max count check), provide space for splitted items
10890 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10892 uint16 dest;
10893 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
10894 if( msg != EQUIP_ERR_OK )
10896 delete pNewItem;
10897 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10898 SendEquipError( msg, pSrcItem, NULL );
10899 return;
10902 if( IsInWorld() )
10903 pSrcItem->SendUpdateToPlayer( this );
10904 pSrcItem->SetState(ITEM_CHANGED, this);
10905 EquipItem( dest, pNewItem, true);
10906 AutoUnequipOffhandIfNeed();
10910 void Player::SwapItem( uint16 src, uint16 dst )
10912 uint8 srcbag = src >> 8;
10913 uint8 srcslot = src & 255;
10915 uint8 dstbag = dst >> 8;
10916 uint8 dstslot = dst & 255;
10918 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10919 Item *pDstItem = GetItemByPos( dstbag, dstslot );
10921 if( !pSrcItem )
10922 return;
10924 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
10926 if(!isAlive() )
10928 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
10929 return;
10932 if(pSrcItem->m_lootGenerated) // prevent swap looting item
10934 //best error message found for attempting to swap while looting
10935 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
10936 return;
10939 // check unequip potability for equipped items and bank bags
10940 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
10942 // bags can be swapped with empty bag slots
10943 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ));
10944 if(msg != EQUIP_ERR_OK)
10946 SendEquipError( msg, pSrcItem, pDstItem );
10947 return;
10951 // prevent put equipped/bank bag in self
10952 if( IsBagPos ( src ) && srcslot == dstbag)
10954 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
10955 return;
10958 if( !pDstItem )
10960 if( IsInventoryPos( dst ) )
10962 ItemPosCountVec dest;
10963 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
10964 if( msg != EQUIP_ERR_OK )
10966 SendEquipError( msg, pSrcItem, NULL );
10967 return;
10970 RemoveItem(srcbag, srcslot, true);
10971 StoreItem( dest, pSrcItem, true);
10973 else if( IsBankPos ( dst ) )
10975 ItemPosCountVec dest;
10976 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
10977 if( msg != EQUIP_ERR_OK )
10979 SendEquipError( msg, pSrcItem, NULL );
10980 return;
10983 RemoveItem(srcbag, srcslot, true);
10984 BankItem( dest, pSrcItem, true);
10986 else if( IsEquipmentPos ( dst ) )
10988 uint16 dest;
10989 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
10990 if( msg != EQUIP_ERR_OK )
10992 SendEquipError( msg, pSrcItem, NULL );
10993 return;
10996 RemoveItem(srcbag, srcslot, true);
10997 EquipItem( dest, pSrcItem, true);
10998 AutoUnequipOffhandIfNeed();
11001 else // if (!pDstItem)
11003 if(pDstItem->m_lootGenerated) // prevent swap looting item
11005 //best error message found for attempting to swap while looting
11006 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
11007 return;
11010 // check unequip potability for equipped items and bank bags
11011 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
11013 // bags can be swapped with empty bag slots
11014 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) );
11015 if(msg != EQUIP_ERR_OK)
11017 SendEquipError( msg, pSrcItem, pDstItem );
11018 return;
11022 // attempt merge to / fill target item
11024 uint8 msg;
11025 ItemPosCountVec sDest;
11026 uint16 eDest;
11027 if( IsInventoryPos( dst ) )
11028 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11029 else if( IsBankPos ( dst ) )
11030 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11031 else if( IsEquipmentPos ( dst ) )
11032 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11033 else
11034 return;
11036 // can be merge/fill
11037 if(msg == EQUIP_ERR_OK)
11039 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->Stackable )
11041 RemoveItem(srcbag, srcslot, true);
11043 if( IsInventoryPos( dst ) )
11044 StoreItem( sDest, pSrcItem, true);
11045 else if( IsBankPos ( dst ) )
11046 BankItem( sDest, pSrcItem, true);
11047 else if( IsEquipmentPos ( dst ) )
11049 EquipItem( eDest, pSrcItem, true);
11050 AutoUnequipOffhandIfNeed();
11053 else
11055 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->Stackable );
11056 pDstItem->SetCount( pSrcItem->GetProto()->Stackable );
11057 pSrcItem->SetState(ITEM_CHANGED, this);
11058 pDstItem->SetState(ITEM_CHANGED, this);
11059 if( IsInWorld() )
11061 pSrcItem->SendUpdateToPlayer( this );
11062 pDstItem->SendUpdateToPlayer( this );
11065 return;
11069 // impossible merge/fill, do real swap
11070 uint8 msg;
11072 // check src->dest move possibility
11073 ItemPosCountVec sDest;
11074 uint16 eDest;
11075 if( IsInventoryPos( dst ) )
11076 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11077 else if( IsBankPos( dst ) )
11078 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11079 else if( IsEquipmentPos( dst ) )
11081 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11082 if( msg == EQUIP_ERR_OK )
11083 msg = CanUnequipItem( eDest, true );
11086 if( msg != EQUIP_ERR_OK )
11088 SendEquipError( msg, pSrcItem, pDstItem );
11089 return;
11092 // check dest->src move possibility
11093 ItemPosCountVec sDest2;
11094 uint16 eDest2;
11095 if( IsInventoryPos( src ) )
11096 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11097 else if( IsBankPos( src ) )
11098 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11099 else if( IsEquipmentPos( src ) )
11101 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11102 if( msg == EQUIP_ERR_OK )
11103 msg = CanUnequipItem( eDest2, true);
11106 if( msg != EQUIP_ERR_OK )
11108 SendEquipError( msg, pDstItem, pSrcItem );
11109 return;
11112 // now do moves, remove...
11113 RemoveItem(dstbag, dstslot, false);
11114 RemoveItem(srcbag, srcslot, false);
11116 // add to dest
11117 if( IsInventoryPos( dst ) )
11118 StoreItem(sDest, pSrcItem, true);
11119 else if( IsBankPos( dst ) )
11120 BankItem(sDest, pSrcItem, true);
11121 else if( IsEquipmentPos( dst ) )
11122 EquipItem(eDest, pSrcItem, true);
11124 // add to src
11125 if( IsInventoryPos( src ) )
11126 StoreItem(sDest2, pDstItem, true);
11127 else if( IsBankPos( src ) )
11128 BankItem(sDest2, pDstItem, true);
11129 else if( IsEquipmentPos( src ) )
11130 EquipItem(eDest2, pDstItem, true);
11132 AutoUnequipOffhandIfNeed();
11136 void Player::AddItemToBuyBackSlot( Item *pItem )
11138 if( pItem )
11140 uint32 slot = m_currentBuybackSlot;
11141 // if current back slot non-empty search oldest or free
11142 if(m_items[slot])
11144 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11145 uint32 oldest_slot = BUYBACK_SLOT_START;
11147 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11149 // found empty
11150 if(!m_items[i])
11152 slot = i;
11153 break;
11156 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11158 if(oldest_time > i_time)
11160 oldest_time = i_time;
11161 oldest_slot = i;
11165 // find oldest
11166 slot = oldest_slot;
11169 RemoveItemFromBuyBackSlot( slot, true );
11170 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11172 m_items[slot] = pItem;
11173 time_t base = time(NULL);
11174 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11175 uint32 eslot = slot - BUYBACK_SLOT_START;
11177 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, pItem->GetGUID() );
11178 ItemPrototype const *pProto = pItem->GetProto();
11179 if( pProto )
11180 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11181 else
11182 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11183 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11185 // move to next (for non filled list is move most optimized choice)
11186 if(m_currentBuybackSlot < BUYBACK_SLOT_END-1)
11187 ++m_currentBuybackSlot;
11191 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11193 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11194 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11195 return m_items[slot];
11196 return NULL;
11199 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11201 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11202 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11204 Item *pItem = m_items[slot];
11205 if( pItem )
11207 pItem->RemoveFromWorld();
11208 if(del) pItem->SetState(ITEM_REMOVED, this);
11211 m_items[slot] = NULL;
11213 uint32 eslot = slot - BUYBACK_SLOT_START;
11214 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, 0 );
11215 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11216 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11218 // if current backslot is filled set to now free slot
11219 if(m_items[m_currentBuybackSlot])
11220 m_currentBuybackSlot = slot;
11224 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11226 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg);
11227 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
11228 data << uint8(msg);
11230 if(msg)
11232 data << uint64(pItem ? pItem->GetGUID() : 0);
11233 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11234 data << uint8(0); // not 0 there...
11236 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11238 uint32 level = 0;
11240 if(pItem)
11241 if(ItemPrototype const* proto = pItem->GetProto())
11242 level = proto->RequiredLevel;
11244 data << uint32(level); // new 2.4.0
11247 GetSession()->SendPacket(&data);
11250 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11252 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11253 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11254 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11255 data << uint32(item);
11256 if( param > 0 )
11257 data << uint32(param);
11258 data << uint8(msg);
11259 GetSession()->SendPacket(&data);
11262 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11264 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11265 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11266 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11267 data << uint64(guid);
11268 if( param > 0 )
11269 data << uint32(param);
11270 data << uint8(msg);
11271 GetSession()->SendPacket(&data);
11274 void Player::ClearTrade()
11276 tradeGold = 0;
11277 acceptTrade = false;
11278 for(int i = 0; i < TRADE_SLOT_COUNT; i++)
11279 tradeItems[i] = NULL_SLOT;
11282 void Player::TradeCancel(bool sendback)
11284 if(pTrader)
11286 // send yellow "Trade canceled" message to both traders
11287 WorldSession* ws;
11288 ws = GetSession();
11289 if(sendback)
11290 ws->SendCancelTrade();
11291 ws = pTrader->GetSession();
11292 if(!ws->PlayerLogout())
11293 ws->SendCancelTrade();
11295 // cleanup
11296 ClearTrade();
11297 pTrader->ClearTrade();
11298 // prevent loss of reference
11299 pTrader->pTrader = NULL;
11300 pTrader = NULL;
11304 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11306 if(m_itemDuration.empty())
11307 return;
11309 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time,realtimeonly);
11311 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); )
11313 Item* item = *itr;
11314 ++itr; // current element can be erased in UpdateDuration
11316 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11317 item->UpdateDuration(this,time);
11321 void Player::UpdateEnchantTime(uint32 time)
11323 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11325 assert(itr->item);
11326 next=itr;
11327 if(!itr->item->GetEnchantmentId(itr->slot))
11329 next = m_enchantDuration.erase(itr);
11331 else if(itr->leftduration <= time)
11333 ApplyEnchantment(itr->item,itr->slot,false,false);
11334 itr->item->ClearEnchantment(itr->slot);
11335 next = m_enchantDuration.erase(itr);
11337 else if(itr->leftduration > time)
11339 itr->leftduration -= time;
11340 ++next;
11345 void Player::AddEnchantmentDurations(Item *item)
11347 for(int x=0;x<MAX_ENCHANTMENT_SLOT;++x)
11349 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11350 continue;
11352 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11353 if( duration > 0 )
11354 AddEnchantmentDuration(item,EnchantmentSlot(x),duration);
11358 void Player::RemoveEnchantmentDurations(Item *item)
11360 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();)
11362 if(itr->item == item)
11364 // save duration in item
11365 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot),itr->leftduration);
11366 itr = m_enchantDuration.erase(itr);
11368 else
11369 ++itr;
11373 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11375 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11376 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11378 next = itr;
11379 if(itr->slot==slot)
11381 if(itr->item && itr->item->GetEnchantmentId(slot))
11383 // remove from stats
11384 ApplyEnchantment(itr->item,slot,false,false);
11385 // remove visual
11386 itr->item->ClearEnchantment(slot);
11388 // remove from update list
11389 next = m_enchantDuration.erase(itr);
11391 else
11392 ++next;
11395 // remove enchants from inventory items
11396 // NOTE: no need to remove these from stats, since these aren't equipped
11397 // in inventory
11398 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
11400 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11401 if( pItem && pItem->GetEnchantmentId(slot) )
11402 pItem->ClearEnchantment(slot);
11405 // in inventory bags
11406 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11408 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11409 if( pBag )
11411 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
11413 Item* pItem = pBag->GetItemByPos(j);
11414 if( pItem && pItem->GetEnchantmentId(slot) )
11415 pItem->ClearEnchantment(slot);
11421 // duration == 0 will remove item enchant
11422 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11424 if(!item)
11425 return;
11427 if(slot >= MAX_ENCHANTMENT_SLOT)
11428 return;
11430 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11432 if(itr->item == item && itr->slot == slot)
11434 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
11435 m_enchantDuration.erase(itr);
11436 break;
11439 if(item && duration > 0 )
11441 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(),slot,uint32(duration/1000));
11442 m_enchantDuration.push_back(EnchantDuration(item,slot,duration));
11446 void Player::ApplyEnchantment(Item *item,bool apply)
11448 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11449 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11452 void Player::ApplyEnchantment(Item *item,EnchantmentSlot slot,bool apply, bool apply_dur, bool ignore_condition)
11454 if(!item)
11455 return;
11457 if(!item->IsEquipped())
11458 return;
11460 if(slot >= MAX_ENCHANTMENT_SLOT)
11461 return;
11463 uint32 enchant_id = item->GetEnchantmentId(slot);
11464 if(!enchant_id)
11465 return;
11467 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11468 if(!pEnchant)
11469 return;
11471 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11472 return;
11474 for (int s=0; s<3; s++)
11476 uint32 enchant_display_type = pEnchant->type[s];
11477 uint32 enchant_amount = pEnchant->amount[s];
11478 uint32 enchant_spell_id = pEnchant->spellid[s];
11480 switch(enchant_display_type)
11482 case ITEM_ENCHANTMENT_TYPE_NONE:
11483 break;
11484 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11485 // processed in Player::CastItemCombatSpell
11486 break;
11487 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11488 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11489 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11490 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11491 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11492 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11493 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11494 break;
11495 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11496 if(enchant_spell_id)
11498 if(apply)
11500 int32 basepoints = int32(enchant_amount);
11501 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11502 if (item->GetItemRandomPropertyId() !=0 && !enchant_amount)
11504 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11505 if (item_rand)
11507 // Search enchant_amount
11508 for (int k=0; k<3; k++)
11510 if(item_rand->enchant_id[k] == enchant_id)
11512 basepoints = int32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11513 break;
11518 // Cast custom spell vs all equal basepoints getted from enchant_amount
11519 if (basepoints)
11520 CastCustomSpell(this,enchant_spell_id,&basepoints,&basepoints,&basepoints,true,item);
11521 else
11522 CastSpell(this,enchant_spell_id,true,item);
11524 else
11525 RemoveAurasDueToItemSpell(item,enchant_spell_id);
11527 break;
11528 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11529 if (!enchant_amount)
11531 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11532 if(item_rand)
11534 for (int k=0; k<3; k++)
11536 if(item_rand->enchant_id[k] == enchant_id)
11538 enchant_amount = uint32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11539 break;
11545 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11546 break;
11547 case ITEM_ENCHANTMENT_TYPE_STAT:
11549 if (!enchant_amount)
11551 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11552 if(item_rand_suffix)
11554 for (int k=0; k<3; k++)
11556 if(item_rand_suffix->enchant_id[k] == enchant_id)
11558 enchant_amount = uint32((item_rand_suffix->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11559 break;
11565 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11566 switch (enchant_spell_id)
11568 case ITEM_MOD_AGILITY:
11569 sLog.outDebug("+ %u AGILITY",enchant_amount);
11570 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11571 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11572 break;
11573 case ITEM_MOD_STRENGTH:
11574 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11575 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11576 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11577 break;
11578 case ITEM_MOD_INTELLECT:
11579 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11580 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11581 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11582 break;
11583 case ITEM_MOD_SPIRIT:
11584 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11585 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11586 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11587 break;
11588 case ITEM_MOD_STAMINA:
11589 sLog.outDebug("+ %u STAMINA",enchant_amount);
11590 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11591 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11592 break;
11593 case ITEM_MOD_DEFENSE_SKILL_RATING:
11594 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11595 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11596 break;
11597 case ITEM_MOD_DODGE_RATING:
11598 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11599 sLog.outDebug("+ %u DODGE", enchant_amount);
11600 break;
11601 case ITEM_MOD_PARRY_RATING:
11602 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11603 sLog.outDebug("+ %u PARRY", enchant_amount);
11604 break;
11605 case ITEM_MOD_BLOCK_RATING:
11606 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11607 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11608 break;
11609 case ITEM_MOD_HIT_MELEE_RATING:
11610 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11611 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11612 break;
11613 case ITEM_MOD_HIT_RANGED_RATING:
11614 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11615 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11616 break;
11617 case ITEM_MOD_HIT_SPELL_RATING:
11618 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11619 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11620 break;
11621 case ITEM_MOD_CRIT_MELEE_RATING:
11622 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11623 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11624 break;
11625 case ITEM_MOD_CRIT_RANGED_RATING:
11626 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11627 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11628 break;
11629 case ITEM_MOD_CRIT_SPELL_RATING:
11630 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11631 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11632 break;
11633 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11634 // in Enchantments
11635 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11636 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11637 // break;
11638 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11639 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11640 // break;
11641 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11642 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11643 // break;
11644 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11645 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11646 // break;
11647 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11648 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11649 // break;
11650 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11651 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11652 // break;
11653 // case ITEM_MOD_HASTE_MELEE_RATING:
11654 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11655 // break;
11656 // case ITEM_MOD_HASTE_RANGED_RATING:
11657 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11658 // break;
11659 case ITEM_MOD_HASTE_SPELL_RATING:
11660 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11661 break;
11662 case ITEM_MOD_HIT_RATING:
11663 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11664 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11665 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11666 sLog.outDebug("+ %u HIT", enchant_amount);
11667 break;
11668 case ITEM_MOD_CRIT_RATING:
11669 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11670 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11671 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11672 sLog.outDebug("+ %u CRITICAL", enchant_amount);
11673 break;
11674 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11675 // case ITEM_MOD_HIT_TAKEN_RATING:
11676 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11677 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11678 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11679 // break;
11680 // case ITEM_MOD_CRIT_TAKEN_RATING:
11681 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11682 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11683 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11684 // break;
11685 case ITEM_MOD_RESILIENCE_RATING:
11686 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11687 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11688 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11689 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
11690 break;
11691 case ITEM_MOD_HASTE_RATING:
11692 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11693 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11694 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11695 sLog.outDebug("+ %u HASTE", enchant_amount);
11696 break;
11697 case ITEM_MOD_EXPERTISE_RATING:
11698 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
11699 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
11700 break;
11701 case ITEM_MOD_ARMOR_PENETRATION_RATING:
11702 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
11703 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
11704 break;
11705 default:
11706 break;
11708 break;
11710 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
11712 if(getClass() == CLASS_SHAMAN)
11714 float addValue = 0.0f;
11715 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11717 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11718 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
11720 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
11722 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11723 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
11726 break;
11728 default:
11729 sLog.outError("Unknown item enchantment display type: %d",enchant_display_type);
11730 break;
11731 } /*switch(enchant_display_type)*/
11732 } /*for*/
11734 // visualize enchantment at player and equipped items
11735 if(slot < MAX_INSPECTED_ENCHANTMENT_SLOT)
11737 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (item->GetSlot() * MAX_VISIBLE_ITEM_OFFSET);
11738 SetUInt32Value(VisibleBase + 1 + slot, apply? item->GetEnchantmentId(slot) : 0);
11741 if(apply_dur)
11743 if(apply)
11745 // set duration
11746 uint32 duration = item->GetEnchantmentDuration(slot);
11747 if(duration > 0)
11748 AddEnchantmentDuration(item,slot,duration);
11750 else
11752 // duration == 0 will remove EnchantDuration
11753 AddEnchantmentDuration(item,slot,0);
11758 void Player::SendEnchantmentDurations()
11760 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11762 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(),itr->slot,uint32(itr->leftduration)/1000);
11766 void Player::SendItemDurations()
11768 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end();++itr)
11770 (*itr)->SendTimeUpdate(this);
11774 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
11776 if(!item) // prevent crash
11777 return;
11779 // last check 2.0.10
11780 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
11781 data << GetGUID(); // player GUID
11782 data << uint32(received); // 0=looted, 1=from npc
11783 data << uint32(created); // 0=received, 1=created
11784 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
11785 data << (uint8)item->GetBagSlot(); // bagslot
11786 // item slot, but when added to stack: 0xFFFFFFFF
11787 data << (uint32) ((item->GetCount()==count) ? item->GetSlot() : -1);
11788 data << uint32(item->GetEntry()); // item id
11789 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
11790 data << uint32(item->GetItemRandomPropertyId()); // random item property id
11791 data << uint32(count); // count of items
11792 data << GetItemCount(item->GetEntry()); // count of items in inventory
11794 if (broadcast && GetGroup())
11795 GetGroup()->BroadcastPacket(&data);
11796 else
11797 GetSession()->SendPacket(&data);
11800 /*********************************************************/
11801 /*** QUEST SYSTEM ***/
11802 /*********************************************************/
11804 void Player::PrepareQuestMenu( uint64 guid )
11806 Object *pObject;
11807 QuestRelations* pObjectQR;
11808 QuestRelations* pObjectQIR;
11809 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11810 if( pCreature )
11812 pObject = (Object*)pCreature;
11813 pObjectQR = &objmgr.mCreatureQuestRelations;
11814 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11816 else
11818 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
11819 if( pGameObject )
11821 pObject = (Object*)pGameObject;
11822 pObjectQR = &objmgr.mGOQuestRelations;
11823 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11825 else
11826 return;
11829 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
11830 qm.ClearMenu();
11832 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
11834 uint32 quest_id = i->second;
11835 QuestStatus status = GetQuestStatus( quest_id );
11836 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
11837 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11838 else if ( status == QUEST_STATUS_INCOMPLETE )
11839 qm.AddMenuItem(quest_id, DIALOG_STATUS_INCOMPLETE);
11840 else if (status == QUEST_STATUS_AVAILABLE )
11841 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
11844 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
11846 uint32 quest_id = i->second;
11847 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11848 if(!pQuest) continue;
11850 QuestStatus status = GetQuestStatus( quest_id );
11852 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
11853 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11854 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
11855 qm.AddMenuItem(quest_id, DIALOG_STATUS_AVAILABLE);
11859 void Player::SendPreparedQuest( uint64 guid )
11861 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
11862 if( questMenu.Empty() )
11863 return;
11865 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
11867 uint32 status = qmi0.m_qIcon;
11869 // single element case
11870 if ( questMenu.MenuItemCount() == 1 )
11872 // Auto open -- maybe also should verify there is no greeting
11873 uint32 quest_id = qmi0.m_qId;
11874 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11875 if ( pQuest )
11877 if( status == DIALOG_STATUS_REWARD_REP && !GetQuestRewardStatus( quest_id ) )
11878 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest,false), true );
11879 else if( status == DIALOG_STATUS_INCOMPLETE )
11880 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, false, true );
11881 // Send completable on repeatable quest if player don't have quest
11882 else if( pQuest->IsRepeatable() )
11883 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
11884 else
11885 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
11888 // multiply entries
11889 else
11891 QEmote qe;
11892 qe._Delay = 0;
11893 qe._Emote = 0;
11894 std::string title = "";
11895 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11896 if( pCreature )
11898 uint32 textid = pCreature->GetNpcTextId();
11899 GossipText * gossiptext = objmgr.GetGossipText(textid);
11900 if( !gossiptext )
11902 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
11903 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
11904 title = "";
11906 else
11908 qe = gossiptext->Options[0].Emotes[0];
11910 if(!gossiptext->Options[0].Text_0.empty())
11912 title = gossiptext->Options[0].Text_0;
11914 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
11915 if (loc_idx >= 0)
11917 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
11918 if (nl)
11920 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
11921 title = nl->Text_0[0][loc_idx];
11925 else
11927 title = gossiptext->Options[0].Text_1;
11929 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
11930 if (loc_idx >= 0)
11932 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
11933 if (nl)
11935 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
11936 title = nl->Text_1[0][loc_idx];
11942 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
11946 bool Player::IsActiveQuest( uint32 quest_id ) const
11948 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
11950 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
11953 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
11955 Object *pObject;
11956 QuestRelations* pObjectQR;
11957 QuestRelations* pObjectQIR;
11959 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11960 if( pCreature )
11962 pObject = (Object*)pCreature;
11963 pObjectQR = &objmgr.mCreatureQuestRelations;
11964 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11966 else
11968 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
11969 if( pGameObject )
11971 pObject = (Object*)pGameObject;
11972 pObjectQR = &objmgr.mGOQuestRelations;
11973 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11975 else
11976 return NULL;
11979 uint32 nextQuestID = pQuest->GetNextQuestInChain();
11980 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
11982 if (itr->second == nextQuestID)
11983 return objmgr.GetQuestTemplate(nextQuestID);
11986 return NULL;
11989 bool Player::CanSeeStartQuest( Quest const *pQuest )
11991 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
11992 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
11993 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
11994 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
11996 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
11999 return false;
12002 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12004 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12005 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12006 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12007 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12008 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12009 && SatisfyQuestDay( pQuest, msg );
12012 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12014 if( !SatisfyQuestLog( msg ) )
12015 return false;
12017 uint32 srcitem = pQuest->GetSrcItemId();
12018 if( srcitem > 0 )
12020 uint32 count = pQuest->GetSrcItemCount();
12021 ItemPosCountVec dest;
12022 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12024 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12025 if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12026 return true;
12027 else if( msg != EQUIP_ERR_OK )
12029 SendEquipError( msg, NULL, NULL );
12030 return false;
12033 return true;
12036 bool Player::CanCompleteQuest( uint32 quest_id )
12038 if( quest_id )
12040 QuestStatusData& q_status = mQuestStatus[quest_id];
12041 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12042 return false; // not allow re-complete quest
12044 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12046 if(!qInfo)
12047 return false;
12049 // auto complete quest
12050 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12051 return true;
12053 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12056 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12058 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12060 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12061 return false;
12065 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12067 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12069 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12070 continue;
12072 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12073 return false;
12077 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12078 return false;
12080 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12081 return false;
12083 if ( qInfo->GetRewOrReqMoney() < 0 )
12085 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12086 return false;
12089 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12090 if ( repFacId && GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12091 return false;
12093 return true;
12096 return false;
12099 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12101 // Solve problem that player don't have the quest and try complete it.
12102 // if repeatable she must be able to complete event if player don't have it.
12103 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12104 if( !CanTakeQuest(pQuest, false) )
12105 return false;
12107 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12108 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12109 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
12110 return false;
12112 if( !CanRewardQuest(pQuest, false) )
12113 return false;
12115 return true;
12118 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12120 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12121 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12122 return false;
12124 // daily quest can't be rewarded (10 daily quest already completed)
12125 if(!SatisfyQuestDay(pQuest,true))
12126 return false;
12128 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12129 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12130 return false;
12132 // prevent receive reward with quest items in bank
12133 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12135 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12137 if( pQuest->ReqItemCount[i]!= 0 &&
12138 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12140 if(msg)
12141 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12142 return false;
12147 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12148 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12149 return false;
12151 return true;
12154 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12156 // prevent receive reward with quest items in bank or for not completed quest
12157 if(!CanRewardQuest(pQuest,msg))
12158 return false;
12160 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12162 if( pQuest->RewChoiceItemId[reward] )
12164 ItemPosCountVec dest;
12165 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12166 if( res != EQUIP_ERR_OK )
12168 SendEquipError( res, NULL, NULL );
12169 return false;
12174 if ( pQuest->GetRewItemsCount() > 0 )
12176 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12178 if( pQuest->RewItemId[i] )
12180 ItemPosCountVec dest;
12181 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12182 if( res != EQUIP_ERR_OK )
12184 SendEquipError( res, NULL, NULL );
12185 return false;
12191 return true;
12194 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12196 uint16 log_slot = FindQuestSlot( 0 );
12197 assert(log_slot < MAX_QUEST_LOG_SIZE);
12199 uint32 quest_id = pQuest->GetQuestId();
12201 // if not exist then created with set uState==NEW and rewarded=false
12202 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12203 if (questStatusData.uState != QUEST_NEW)
12204 questStatusData.uState = QUEST_CHANGED;
12206 // check for repeatable quests status reset
12207 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12208 questStatusData.m_explored = false;
12210 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12212 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12213 questStatusData.m_itemcount[i] = 0;
12216 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12218 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12219 questStatusData.m_creatureOrGOcount[i] = 0;
12222 GiveQuestSourceItem( pQuest );
12223 AdjustQuestReqItemCount( pQuest );
12225 if( pQuest->GetRepObjectiveFaction() )
12226 SetFactionVisibleForFactionId(pQuest->GetRepObjectiveFaction());
12228 uint32 qtime = 0;
12229 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12231 uint32 limittime = pQuest->GetLimitTime();
12233 // shared timed quest
12234 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12235 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / 1000;
12237 AddTimedQuest( quest_id );
12238 questStatusData.m_timer = limittime * 1000;
12239 qtime = static_cast<uint32>(time(NULL)) + limittime;
12241 else
12242 questStatusData.m_timer = 0;
12244 SetQuestSlot(log_slot, quest_id, qtime);
12246 //starting initial quest script
12247 if(questGiver && pQuest->GetQuestStartScript()!=0)
12248 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12250 UpdateForQuestsGO();
12253 void Player::CompleteQuest( uint32 quest_id )
12255 if( quest_id )
12257 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12259 uint16 log_slot = FindQuestSlot( quest_id );
12260 if( log_slot < MAX_QUEST_LOG_SIZE)
12261 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12263 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12265 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12266 RewardQuest(qInfo,0,this,false);
12267 else
12268 SendQuestComplete( quest_id );
12273 void Player::IncompleteQuest( uint32 quest_id )
12275 if( quest_id )
12277 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12279 uint16 log_slot = FindQuestSlot( quest_id );
12280 if( log_slot < MAX_QUEST_LOG_SIZE)
12281 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12285 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12287 uint32 quest_id = pQuest->GetQuestId();
12289 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; i++ )
12291 if ( pQuest->ReqItemId[i] )
12292 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12295 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12296 // SetTimedQuest( 0 );
12297 m_timedquests.erase(pQuest->GetQuestId());
12299 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12301 if( pQuest->RewChoiceItemId[reward] )
12303 ItemPosCountVec dest;
12304 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK )
12306 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12307 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12312 if ( pQuest->GetRewItemsCount() > 0 )
12314 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12316 if( pQuest->RewItemId[i] )
12318 ItemPosCountVec dest;
12319 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK )
12321 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12322 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12328 RewardReputation( pQuest );
12330 if( pQuest->GetRewSpellCast() > 0 )
12331 CastSpell( this, pQuest->GetRewSpellCast(), true);
12332 else if( pQuest->GetRewSpell() > 0)
12333 CastSpell( this, pQuest->GetRewSpell(), true);
12335 uint16 log_slot = FindQuestSlot( quest_id );
12336 if( log_slot < MAX_QUEST_LOG_SIZE)
12337 SetQuestSlot(log_slot,0);
12339 QuestStatusData& q_status = mQuestStatus[quest_id];
12341 // Not give XP in case already completed once repeatable quest
12342 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12344 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
12345 GiveXP( XP , NULL );
12346 else
12347 ModifyMoney( int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)) );
12349 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12350 ModifyMoney( pQuest->GetRewOrReqMoney() );
12352 // honor reward
12353 if(pQuest->GetRewHonorableKills())
12354 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12356 // title reward
12357 if(pQuest->GetCharTitleId())
12359 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12360 SetFlag64(PLAYER__FIELD_KNOWN_TITLES, (uint64(1) << titleEntry->bit_index));
12363 // Send reward mail
12364 if(pQuest->GetRewMailTemplateId())
12366 MailMessageType mailType;
12367 uint32 senderGuidOrEntry;
12368 switch(questGiver->GetTypeId())
12370 case TYPEID_UNIT:
12371 mailType = MAIL_CREATURE;
12372 senderGuidOrEntry = questGiver->GetEntry();
12373 break;
12374 case TYPEID_GAMEOBJECT:
12375 mailType = MAIL_GAMEOBJECT;
12376 senderGuidOrEntry = questGiver->GetEntry();
12377 break;
12378 case TYPEID_ITEM:
12379 mailType = MAIL_ITEM;
12380 senderGuidOrEntry = questGiver->GetEntry();
12381 break;
12382 case TYPEID_PLAYER:
12383 mailType = MAIL_NORMAL;
12384 senderGuidOrEntry = questGiver->GetGUIDLow();
12385 break;
12386 default:
12387 mailType = MAIL_NORMAL;
12388 senderGuidOrEntry = GetGUIDLow();
12389 break;
12392 Loot questMailLoot;
12394 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this);
12396 // fill mail
12397 MailItemsInfo mi; // item list preparing
12399 for(size_t i = 0; mi.size() < MAX_MAIL_ITEMS && i < questMailLoot.items.size(); ++i)
12401 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12403 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12405 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12406 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12411 for(size_t i = 0; mi.size() < MAX_MAIL_ITEMS && i < questMailLoot.quest_items.size(); ++i)
12413 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i+questMailLoot.items.size(),this))
12415 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12417 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12418 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12423 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12426 if(pQuest->IsDaily())
12428 SetDailyQuestStatus(quest_id);
12429 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
12432 if ( !pQuest->IsRepeatable() )
12433 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12434 else
12435 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12437 q_status.m_rewarded = true;
12439 if(announce)
12440 SendQuestReward( pQuest, XP, questGiver );
12442 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12443 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
12444 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST);
12447 void Player::FailQuest( uint32 quest_id )
12449 if( quest_id )
12451 IncompleteQuest( quest_id );
12453 uint16 log_slot = FindQuestSlot( quest_id );
12454 if( log_slot < MAX_QUEST_LOG_SIZE)
12456 SetQuestSlotTimer(log_slot, 1 );
12457 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12459 SendQuestFailed( quest_id );
12463 void Player::FailTimedQuest( uint32 quest_id )
12465 if( quest_id )
12467 QuestStatusData& q_status = mQuestStatus[quest_id];
12469 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12470 q_status.m_timer = 0;
12472 IncompleteQuest( quest_id );
12474 uint16 log_slot = FindQuestSlot( quest_id );
12475 if( log_slot < MAX_QUEST_LOG_SIZE)
12477 SetQuestSlotTimer(log_slot, 1 );
12478 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12480 SendQuestTimerFailed( quest_id );
12484 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12486 int32 zoneOrSort = qInfo->GetZoneOrSort();
12487 int32 skillOrClass = qInfo->GetSkillOrClass();
12489 // skip zone zoneOrSort and 0 case skillOrClass
12490 if( zoneOrSort >= 0 && skillOrClass == 0 )
12491 return true;
12493 int32 questSort = -zoneOrSort;
12494 uint8 reqSortClass = ClassByQuestSort(questSort);
12496 // check class sort cases in zoneOrSort
12497 if( reqSortClass != 0 && getClass() != reqSortClass)
12499 if( msg )
12500 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12501 return false;
12504 // check class
12505 if( skillOrClass < 0 )
12507 uint8 reqClass = -int32(skillOrClass);
12508 if(getClass() != reqClass)
12510 if( msg )
12511 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12512 return false;
12515 // check skill
12516 else if( skillOrClass > 0 )
12518 uint32 reqSkill = skillOrClass;
12519 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12521 if( msg )
12522 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12523 return false;
12527 return true;
12530 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12532 if( getLevel() < qInfo->GetMinLevel() )
12534 if( msg )
12535 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12536 return false;
12538 return true;
12541 bool Player::SatisfyQuestLog( bool msg )
12543 // exist free slot
12544 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12545 return true;
12547 if( msg )
12549 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12550 GetSession()->SendPacket( &data );
12551 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12553 return false;
12556 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12558 // No previous quest (might be first quest in a series)
12559 if( qInfo->prevQuests.empty())
12560 return true;
12562 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12564 uint32 prevId = abs(*iter);
12566 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12567 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12569 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12571 // If any of the positive previous quests completed, return true
12572 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12574 // skip one-from-all exclusive group
12575 if(qPrevInfo->GetExclusiveGroup() >= 0)
12576 return true;
12578 // each-from-all exclusive group ( < 0)
12579 // can be start if only all quests in prev quest exclusive group completed and rewarded
12580 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12581 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12583 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12585 for(; iter != end; ++iter)
12587 uint32 exclude_Id = iter->second;
12589 // skip checked quest id, only state of other quests in group is interesting
12590 if(exclude_Id == prevId)
12591 continue;
12593 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12595 // alternative quest from group also must be completed and rewarded(reported)
12596 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12598 if( msg )
12599 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12600 return false;
12603 return true;
12605 // If any of the negative previous quests active, return true
12606 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12607 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
12609 // skip one-from-all exclusive group
12610 if(qPrevInfo->GetExclusiveGroup() >= 0)
12611 return true;
12613 // each-from-all exclusive group ( < 0)
12614 // can be start if only all quests in prev quest exclusive group active
12615 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12616 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12618 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12620 for(; iter != end; ++iter)
12622 uint32 exclude_Id = iter->second;
12624 // skip checked quest id, only state of other quests in group is interesting
12625 if(exclude_Id == prevId)
12626 continue;
12628 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12630 // alternative quest from group also must be active
12631 if( i_exstatus == mQuestStatus.end() ||
12632 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
12633 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
12635 if( msg )
12636 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12637 return false;
12640 return true;
12645 // Has only positive prev. quests in non-rewarded state
12646 // and negative prev. quests in non-active state
12647 if( msg )
12648 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12650 return false;
12653 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
12655 uint32 reqraces = qInfo->GetRequiredRaces();
12656 if ( reqraces == 0 )
12657 return true;
12658 if( (reqraces & getRaceMask()) == 0 )
12660 if( msg )
12661 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
12662 return false;
12664 return true;
12667 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
12669 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
12670 if(fIdMin && GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
12672 if( msg )
12673 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12674 return false;
12677 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
12678 if(fIdMax && GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
12680 if( msg )
12681 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12682 return false;
12685 return true;
12688 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
12690 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
12691 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
12693 if( msg )
12694 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
12695 return false;
12697 return true;
12700 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
12702 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
12704 if( msg )
12705 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
12706 return false;
12708 return true;
12711 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
12713 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12714 if(qInfo->GetExclusiveGroup() <= 0)
12715 return true;
12717 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
12718 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
12720 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
12722 for(; iter != end; ++iter)
12724 uint32 exclude_Id = iter->second;
12726 // skip checked quest id, only state of other quests in group is interesting
12727 if(exclude_Id == qInfo->GetQuestId())
12728 continue;
12730 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12732 // alternative quest already started or completed
12733 if( i_exstatus != mQuestStatus.end()
12734 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
12736 if( msg )
12737 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12738 return false;
12741 return true;
12744 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
12746 if(!qInfo->GetNextQuestInChain())
12747 return true;
12749 // next quest in chain already started or completed
12750 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
12751 if( itr != mQuestStatus.end()
12752 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
12754 if( msg )
12755 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12756 return false;
12759 // check for all quests further up the chain
12760 // only necessary if there are quest chains with more than one quest that can be skipped
12761 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12762 return true;
12765 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
12767 // No previous quest in chain
12768 if( qInfo->prevChainQuests.empty())
12769 return true;
12771 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
12773 uint32 prevId = *iter;
12775 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12777 if( i_prevstatus != mQuestStatus.end() )
12779 // If any of the previous quests in chain active, return false
12780 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12781 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
12783 if( msg )
12784 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12785 return false;
12789 // check for all quests further down the chain
12790 // only necessary if there are quest chains with more than one quest that can be skipped
12791 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12792 // return false;
12795 // No previous quest in chain active
12796 return true;
12799 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
12801 if(!qInfo->IsDaily())
12802 return true;
12804 bool have_slot = false;
12805 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
12807 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
12808 if(qInfo->GetQuestId()==id)
12809 return false;
12811 if(!id)
12812 have_slot = true;
12815 if(!have_slot)
12817 if( msg )
12818 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
12819 return false;
12822 return true;
12825 bool Player::GiveQuestSourceItem( Quest const *pQuest )
12827 uint32 srcitem = pQuest->GetSrcItemId();
12828 if( srcitem > 0 )
12830 uint32 count = pQuest->GetSrcItemCount();
12831 if( count <= 0 )
12832 count = 1;
12834 ItemPosCountVec dest;
12835 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12836 if( msg == EQUIP_ERR_OK )
12838 Item * item = StoreNewItem(dest, srcitem, true);
12839 SendNewItem(item, count, true, false);
12840 return true;
12842 // player already have max amount required item, just report success
12843 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12844 return true;
12845 else
12846 SendEquipError( msg, NULL, NULL );
12847 return false;
12850 return true;
12853 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
12855 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12856 if( qInfo )
12858 uint32 srcitem = qInfo->GetSrcItemId();
12859 if( srcitem > 0 )
12861 uint32 count = qInfo->GetSrcItemCount();
12862 if( count <= 0 )
12863 count = 1;
12865 // exist one case when destroy source quest item not possible:
12866 // non un-equippable item (equipped non-empty bag, for example)
12867 uint8 res = CanUnequipItems(srcitem,count);
12868 if(res != EQUIP_ERR_OK)
12870 if(msg)
12871 SendEquipError( res, NULL, NULL );
12872 return false;
12875 DestroyItemCount(srcitem, count, true, true);
12878 return true;
12881 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
12883 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12884 if( qInfo )
12886 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
12887 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12888 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
12889 && !qInfo->IsRepeatable() )
12890 return itr->second.m_rewarded;
12892 return false;
12894 return false;
12897 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
12899 if( quest_id )
12901 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12902 if( itr != mQuestStatus.end() )
12903 return itr->second.m_status;
12905 return QUEST_STATUS_NONE;
12908 bool Player::CanShareQuest(uint32 quest_id) const
12910 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12911 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
12913 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12914 if( itr != mQuestStatus.end() )
12915 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
12917 return false;
12920 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
12922 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12923 if( qInfo )
12925 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
12927 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12928 m_timedquests.erase(qInfo->GetQuestId());
12931 QuestStatusData& q_status = mQuestStatus[quest_id];
12933 q_status.m_status = status;
12934 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12937 UpdateForQuestsGO();
12940 // not used in MaNGOS, but used in scripting code
12941 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
12943 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12944 if( !qInfo )
12945 return 0;
12947 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
12948 if ( qInfo->ReqCreatureOrGOId[j] == entry )
12949 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
12951 return 0;
12954 void Player::AdjustQuestReqItemCount( Quest const* pQuest )
12956 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12958 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12960 uint32 reqitemcount = pQuest->ReqItemCount[i];
12961 if( reqitemcount != 0 )
12963 uint32 quest_id = pQuest->GetQuestId();
12964 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
12966 QuestStatusData& q_status = mQuestStatus[quest_id];
12967 q_status.m_itemcount[i] = std::min(curitemcount, reqitemcount);
12968 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12974 uint16 Player::FindQuestSlot( uint32 quest_id ) const
12976 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
12977 if ( GetQuestSlotQuestId(i) == quest_id )
12978 return i;
12980 return MAX_QUEST_LOG_SIZE;
12983 void Player::AreaExploredOrEventHappens( uint32 questId )
12985 if( questId )
12987 uint16 log_slot = FindQuestSlot( questId );
12988 if( log_slot < MAX_QUEST_LOG_SIZE)
12990 QuestStatusData& q_status = mQuestStatus[questId];
12992 if(!q_status.m_explored)
12994 q_status.m_explored = true;
12995 if (q_status.uState != QUEST_NEW)
12996 q_status.uState = QUEST_CHANGED;
12999 if( CanCompleteQuest( questId ) )
13000 CompleteQuest( questId );
13004 //not used in mangosd, function for external script library
13005 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13007 if( Group *pGroup = GetGroup() )
13009 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13011 Player *pGroupGuy = itr->getSource();
13013 // for any leave or dead (with not released body) group member at appropriate distance
13014 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13015 pGroupGuy->AreaExploredOrEventHappens(questId);
13018 else
13019 AreaExploredOrEventHappens(questId);
13022 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13024 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13026 uint32 questid = GetQuestSlotQuestId(i);
13027 if ( questid == 0 )
13028 continue;
13030 QuestStatusData& q_status = mQuestStatus[questid];
13032 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13033 continue;
13035 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13036 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13037 continue;
13039 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13041 uint32 reqitem = qInfo->ReqItemId[j];
13042 if ( reqitem == entry )
13044 uint32 reqitemcount = qInfo->ReqItemCount[j];
13045 uint32 curitemcount = q_status.m_itemcount[j];
13046 if ( curitemcount < reqitemcount )
13048 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13049 q_status.m_itemcount[j] += additemcount;
13050 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13052 SendQuestUpdateAddItem( qInfo, j, additemcount );
13054 if ( CanCompleteQuest( questid ) )
13055 CompleteQuest( questid );
13056 return;
13060 UpdateForQuestsGO();
13061 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
13064 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13066 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13068 uint32 questid = GetQuestSlotQuestId(i);
13069 if(!questid)
13070 continue;
13071 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13072 if ( !qInfo )
13073 continue;
13074 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13075 continue;
13077 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13079 uint32 reqitem = qInfo->ReqItemId[j];
13080 if ( reqitem == entry )
13082 QuestStatusData& q_status = mQuestStatus[questid];
13084 uint32 reqitemcount = qInfo->ReqItemCount[j];
13085 uint32 curitemcount;
13086 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13087 curitemcount = q_status.m_itemcount[j];
13088 else
13089 curitemcount = GetItemCount(entry,true);
13090 if ( curitemcount < reqitemcount + count )
13092 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13093 q_status.m_itemcount[j] = curitemcount - remitemcount;
13094 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13096 IncompleteQuest( questid );
13098 return;
13102 UpdateForQuestsGO();
13105 void Player::KilledMonster( uint32 entry, uint64 guid )
13107 uint32 addkillcount = 1;
13108 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13109 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13111 uint32 questid = GetQuestSlotQuestId(i);
13112 if(!questid)
13113 continue;
13115 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13116 if( !qInfo )
13117 continue;
13118 // just if !ingroup || !noraidgroup || raidgroup
13119 QuestStatusData& q_status = mQuestStatus[questid];
13120 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13122 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13124 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13126 // skip GO activate objective or none
13127 if(qInfo->ReqCreatureOrGOId[j] <=0)
13128 continue;
13130 // skip Cast at creature objective
13131 if(qInfo->ReqSpell[j] !=0 )
13132 continue;
13134 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13136 if ( reqkill == entry )
13138 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13139 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13140 if ( curkillcount < reqkillcount )
13142 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13143 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13145 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13147 if ( CanCompleteQuest( questid ) )
13148 CompleteQuest( questid );
13150 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13151 continue;
13159 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13161 bool isCreature = IS_CREATURE_GUID(guid);
13163 uint32 addCastCount = 1;
13164 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13166 uint32 questid = GetQuestSlotQuestId(i);
13167 if(!questid)
13168 continue;
13170 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13171 if ( !qInfo )
13172 continue;
13174 QuestStatusData& q_status = mQuestStatus[questid];
13176 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13178 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13180 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13182 // skip kill creature objective (0) or wrong spell casts
13183 if(qInfo->ReqSpell[j] != spell_id )
13184 continue;
13186 uint32 reqTarget = 0;
13188 if(isCreature)
13190 // creature activate objectives
13191 if(qInfo->ReqCreatureOrGOId[j] > 0)
13192 // checked at quest_template loading
13193 reqTarget = qInfo->ReqCreatureOrGOId[j];
13195 else
13197 // GO activate objective
13198 if(qInfo->ReqCreatureOrGOId[j] < 0)
13199 // checked at quest_template loading
13200 reqTarget = - qInfo->ReqCreatureOrGOId[j];
13203 // other not this creature/GO related objectives
13204 if( reqTarget != entry )
13205 continue;
13207 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
13208 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
13209 if ( curCastCount < reqCastCount )
13211 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
13212 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13214 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
13217 if ( CanCompleteQuest( questid ) )
13218 CompleteQuest( questid );
13220 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13221 break;
13228 void Player::TalkedToCreature( uint32 entry, uint64 guid )
13230 uint32 addTalkCount = 1;
13231 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13233 uint32 questid = GetQuestSlotQuestId(i);
13234 if(!questid)
13235 continue;
13237 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13238 if ( !qInfo )
13239 continue;
13241 QuestStatusData& q_status = mQuestStatus[questid];
13243 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13245 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
13247 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13249 // skip spell casts and Gameobject objectives
13250 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
13251 continue;
13253 uint32 reqTarget = 0;
13255 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
13256 // checked at quest_template loading
13257 reqTarget = qInfo->ReqCreatureOrGOId[j];
13258 else
13259 continue;
13261 if ( reqTarget == entry )
13263 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
13264 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
13265 if ( curTalkCount < reqTalkCount )
13267 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
13268 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13270 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
13272 if ( CanCompleteQuest( questid ) )
13273 CompleteQuest( questid );
13275 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13276 continue;
13284 void Player::MoneyChanged( uint32 count )
13286 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13288 uint32 questid = GetQuestSlotQuestId(i);
13289 if (!questid)
13290 continue;
13292 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13293 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
13295 QuestStatusData& q_status = mQuestStatus[questid];
13297 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13299 if(int32(count) >= -qInfo->GetRewOrReqMoney())
13301 if ( CanCompleteQuest( questid ) )
13302 CompleteQuest( questid );
13305 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13307 if(int32(count) < -qInfo->GetRewOrReqMoney())
13308 IncompleteQuest( questid );
13314 bool Player::HasQuestForItem( uint32 itemid ) const
13316 for( QuestStatusMap::const_iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
13318 QuestStatusData const& q_status = i->second;
13320 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13322 Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
13323 if(!qinfo)
13324 continue;
13326 // hide quest if player is in raid-group and quest is no raid quest
13327 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13328 continue;
13330 // There should be no mixed ReqItem/ReqSource drop
13331 // This part for ReqItem drop
13332 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13334 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13335 return true;
13337 // This part - for ReqSource
13338 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; j++)
13340 // examined item is a source item
13341 if (qinfo->ReqSourceId[j] == itemid && qinfo->ReqSourceRef[j] > 0 && qinfo->ReqSourceRef[j] <= QUEST_OBJECTIVES_COUNT)
13343 uint32 idx = qinfo->ReqSourceRef[j]-1;
13345 // total count of created ReqItems and SourceItems is less than ReqItemCount
13346 if(qinfo->ReqItemId[idx] != 0 &&
13347 q_status.m_itemcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid,true) < qinfo->ReqItemCount[idx] * qinfo->ReqSourceCount[j])
13348 return true;
13350 // total count of casted ReqCreatureOrGOs and SourceItems is less than ReqCreatureOrGOCount
13351 if (qinfo->ReqCreatureOrGOId[idx] != 0)
13353 if(q_status.m_creatureOrGOcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid,true) < qinfo->ReqCreatureOrGOCount[idx] * qinfo->ReqSourceCount[j])
13354 return true;
13356 // spell with SPELL_EFFECT_QUEST_COMPLETE or SPELL_EFFECT_SEND_EVENT (with script) case
13357 else if(qinfo->ReqSpell[idx] != 0)
13359 // not casted and need more reagents/item for use.
13360 if(!q_status.m_explored && GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13361 return true;
13367 return false;
13370 void Player::SendQuestComplete( uint32 quest_id )
13372 if( quest_id )
13374 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13375 data << uint32(quest_id);
13376 GetSession()->SendPacket( &data );
13377 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13381 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13383 uint32 questid = pQuest->GetQuestId();
13384 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13385 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
13386 data << uint32(questid);
13388 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13390 data << uint32(XP);
13391 data << uint32(pQuest->GetRewOrReqMoney());
13393 else
13395 data << uint32(0);
13396 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13399 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13400 data << uint32(pQuest->GetBonusTalents()); // bonus talents
13401 GetSession()->SendPacket( &data );
13403 if (pQuest->GetQuestCompleteScript() != 0)
13404 sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13407 void Player::SendQuestFailed( uint32 quest_id )
13409 if( quest_id )
13411 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
13412 data << quest_id;
13413 data << uint32(0); // failed reason (4 for inventory is full)
13414 GetSession()->SendPacket( &data );
13415 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13419 void Player::SendQuestTimerFailed( uint32 quest_id )
13421 if( quest_id )
13423 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13424 data << quest_id;
13425 GetSession()->SendPacket( &data );
13426 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13430 void Player::SendCanTakeQuestResponse( uint32 msg )
13432 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13433 data << uint32(msg);
13434 GetSession()->SendPacket( &data );
13435 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13438 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13440 if( pPlayer )
13442 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13443 data << uint64(pPlayer->GetGUID());
13444 data << uint8(msg); // valid values: 0-8
13445 GetSession()->SendPacket( &data );
13446 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13450 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13452 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
13453 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13454 //data << pQuest->ReqItemId[item_idx];
13455 //data << count;
13456 GetSession()->SendPacket( &data );
13459 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13461 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13463 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13464 if (entry < 0)
13465 // client expected gameobject template id in form (id|0x80000000)
13466 entry = (-entry) | 0x80000000;
13468 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13469 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13470 data << uint32(pQuest->GetQuestId());
13471 data << uint32(entry);
13472 data << uint32(old_count + add_count);
13473 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13474 data << uint64(guid);
13475 GetSession()->SendPacket(&data);
13477 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13478 if( log_slot < MAX_QUEST_LOG_SIZE)
13479 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13482 /*********************************************************/
13483 /*** LOAD SYSTEM ***/
13484 /*********************************************************/
13486 bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
13488 bool delete_result = true;
13489 if(!result)
13491 // 0 1 2 3 4 5 6 7 8 9
13492 result = CharacterDatabase.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid);
13493 if(!result) return false;
13495 else delete_result = false;
13497 Field *fields = result->Fetch();
13499 if(!LoadValues( fields[1].GetString()))
13501 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
13502 if(delete_result) delete result;
13503 return false;
13506 // overwrite possible wrong/corrupted guid
13507 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13509 m_name = fields[2].GetCppString();
13511 Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
13512 SetMapId(fields[6].GetUInt32());
13513 // the instance id is not needed at character enum
13515 m_Played_time[0] = fields[7].GetUInt32();
13516 m_Played_time[1] = fields[8].GetUInt32();
13518 m_atLoginFlags = fields[9].GetUInt32();
13520 // I don't see these used anywhere ..
13521 /*_LoadGroup();
13523 _LoadBoundInstances();*/
13525 if (delete_result) delete result;
13527 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
13528 m_items[i] = NULL;
13530 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
13531 m_deathState = DEAD;
13533 return true;
13536 void Player::_LoadDeclinedNames(QueryResult* result)
13538 if(!result)
13539 return;
13541 if(m_declinedname)
13542 delete m_declinedname;
13544 m_declinedname = new DeclinedName;
13545 Field *fields = result->Fetch();
13546 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13547 m_declinedname->name[i] = fields[i].GetCppString();
13549 delete result;
13552 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
13554 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
13555 if(!result)
13556 return false;
13558 Field *fields = result->Fetch();
13560 x = fields[0].GetFloat();
13561 y = fields[1].GetFloat();
13562 z = fields[2].GetFloat();
13563 o = fields[3].GetFloat();
13564 mapid = fields[4].GetUInt32();
13565 in_flight = !fields[5].GetCppString().empty();
13567 delete result;
13568 return true;
13571 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
13573 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
13574 if( !result )
13575 return false;
13577 Field *fields = result->Fetch();
13579 data = StrSplit(fields[0].GetCppString(), " ");
13581 delete result;
13583 return true;
13586 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
13588 if(index >= data.size())
13589 return 0;
13591 return (uint32)atoi(data[index].c_str());
13594 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
13596 float result;
13597 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
13598 memcpy(&result, &temp, sizeof(result));
13600 return result;
13603 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
13605 Tokens data;
13606 if(!LoadValuesArrayFromDB(data,guid))
13607 return 0;
13609 return GetUInt32ValueFromArray(data,index);
13612 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
13614 float result;
13615 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
13616 memcpy(&result, &temp, sizeof(result));
13618 return result;
13621 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
13623 //// 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
13624 //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);
13625 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
13627 if(!result)
13629 sLog.outError("ERROR: Player (GUID: %u) not found in table `characters`, can't load. ",guid);
13630 return false;
13633 Field *fields = result->Fetch();
13635 uint32 dbAccountId = fields[1].GetUInt32();
13637 // check if the character's account in the db and the logged in account match.
13638 // player should be able to load/delete character only with correct account!
13639 if( dbAccountId != GetSession()->GetAccountId() )
13641 sLog.outError("ERROR: Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
13642 delete result;
13643 return false;
13646 Object::_Create( guid, 0, HIGHGUID_PLAYER );
13648 m_name = fields[3].GetCppString();
13650 // check name limitations
13651 if(!ObjectMgr::IsValidName(m_name) || GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name))
13653 delete result;
13654 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
13655 return false;
13658 if(!LoadValues( fields[2].GetString()))
13660 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
13661 delete result;
13662 return false;
13665 // overwrite possible wrong/corrupted guid
13666 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13668 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13669 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
13671 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), 0 );
13672 SetVisibleItemSlot(slot,NULL);
13674 if (m_items[slot])
13676 delete m_items[slot];
13677 m_items[slot] = NULL;
13681 // update money limits
13682 if(GetMoney() > MAX_MONEY_AMOUNT)
13683 SetMoney(MAX_MONEY_AMOUNT);
13685 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
13686 outDebugValues();
13688 m_race = fields[4].GetUInt8();
13689 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13690 //Other way is to saves m_team into characters table.
13691 setFactionForRace(m_race);
13692 SetCharm(0);
13694 m_class = fields[5].GetUInt8();
13696 PlayerInfo const *info = objmgr.GetPlayerInfo(m_race, m_class);
13697 if(!info)
13699 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
13700 delete result;
13701 return false;
13704 InitPrimaryProffesions(); // to max set before any spell loaded
13706 uint32 transGUID = fields[24].GetUInt32();
13707 Relocate(fields[6].GetFloat(),fields[7].GetFloat(),fields[8].GetFloat(),fields[10].GetFloat());
13708 SetMapId(fields[9].GetUInt32());
13709 SetDifficulty(fields[32].GetUInt32()); // may be changed in _LoadGroup
13711 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
13713 // check arena teams integrity
13714 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
13716 uint32 arena_team_id = GetArenaTeamId(arena_slot);
13717 if(!arena_team_id)
13718 continue;
13720 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
13721 if(at->HaveMember(GetGUID()))
13722 continue;
13724 // arena team not exist or not member, cleanup fields
13725 for(int j =0; j < 6; ++j)
13726 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
13729 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
13731 if(!IsPositionValid())
13733 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());
13735 SetMapId(info->mapId);
13736 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
13738 transGUID = 0;
13740 m_movementInfo.t_x = 0.0f;
13741 m_movementInfo.t_y = 0.0f;
13742 m_movementInfo.t_z = 0.0f;
13743 m_movementInfo.t_o = 0.0f;
13746 // load the player's map here if it's not already loaded
13747 Map *map = GetMap();
13748 // since the player may not be bound to the map yet, make sure subsequent
13749 // getmap calls won't create new maps
13750 SetInstanceId(map->GetInstanceId());
13752 SaveRecallPosition();
13754 if (transGUID != 0)
13756 m_movementInfo.t_x = fields[20].GetFloat();
13757 m_movementInfo.t_y = fields[21].GetFloat();
13758 m_movementInfo.t_z = fields[22].GetFloat();
13759 m_movementInfo.t_o = fields[23].GetFloat();
13761 if( !MaNGOS::IsValidMapCoord(
13762 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13763 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
13764 // transport size limited
13765 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
13767 sLog.outError("ERROR: Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
13768 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13769 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
13771 SetMapId(info->mapId);
13772 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
13774 m_movementInfo.t_x = 0.0f;
13775 m_movementInfo.t_y = 0.0f;
13776 m_movementInfo.t_z = 0.0f;
13777 m_movementInfo.t_o = 0.0f;
13779 transGUID = 0;
13783 if (transGUID != 0)
13785 for (MapManager::TransportSet::iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
13787 if( (*iter)->GetGUIDLow() == transGUID)
13789 m_transport = *iter;
13790 m_transport->AddPassenger(this);
13791 SetMapId(m_transport->GetMapId());
13792 break;
13796 if(!m_transport)
13798 sLog.outError("ERROR: Player (guidlow %d) have invalid transport guid (%u). Teleport to default race/class locations.",
13799 guid,transGUID);
13801 SetMapId(info->mapId);
13802 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
13804 m_movementInfo.t_x = 0.0f;
13805 m_movementInfo.t_y = 0.0f;
13806 m_movementInfo.t_z = 0.0f;
13807 m_movementInfo.t_o = 0.0f;
13809 transGUID = 0;
13813 time_t now = time(NULL);
13814 time_t logoutTime = time_t(fields[16].GetUInt64());
13816 // since last logout (in seconds)
13817 uint64 time_diff = uint64(now - logoutTime);
13819 // set value, including drunk invisibility detection
13820 // calculate sobering. after 15 minutes logged out, the player will be sober again
13821 float soberFactor;
13822 if(time_diff > 15*MINUTE)
13823 soberFactor = 0;
13824 else
13825 soberFactor = 1-time_diff/(15.0f*MINUTE);
13826 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
13827 SetDrunkValue(newDrunkenValue);
13829 m_rest_bonus = fields[15].GetFloat();
13830 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
13831 float bubble0 = 0.031;
13832 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
13833 float bubble1 = 0.125;
13835 if((int32)fields[16].GetUInt32() > 0)
13837 float bubble = fields[17].GetUInt32() > 0
13838 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
13839 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
13841 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
13844 m_cinematic = fields[12].GetUInt32();
13845 m_Played_time[0]= fields[13].GetUInt32();
13846 m_Played_time[1]= fields[14].GetUInt32();
13848 m_resetTalentsCost = fields[18].GetUInt32();
13849 m_resetTalentsTime = time_t(fields[19].GetUInt64());
13851 // reserve some flags
13852 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
13854 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
13855 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
13857 m_taxi.LoadTaxiMask( fields[11].GetString() ); // must be before InitTaxiNodesForLevel
13859 uint32 extraflags = fields[25].GetUInt32();
13861 m_stableSlots = fields[26].GetUInt32();
13862 if(m_stableSlots > 4)
13864 sLog.outError("Player can have not more 4 stable slots, but have in DB %u",uint32(m_stableSlots));
13865 m_stableSlots = 4;
13868 m_atLoginFlags = fields[27].GetUInt32();
13870 // Honor system
13871 // Update Honor kills data
13872 m_lastHonorUpdateTime = logoutTime;
13873 UpdateHonorFields();
13875 m_deathExpireTime = (time_t)fields[30].GetUInt64();
13876 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
13877 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
13879 std::string taxi_nodes = fields[31].GetCppString();
13881 delete result;
13883 // clear channel spell data (if saved at channel spell casting)
13884 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
13885 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
13887 // clear charm/summon related fields
13888 SetUInt64Value(UNIT_FIELD_CHARM,0);
13889 SetUInt64Value(UNIT_FIELD_SUMMON,0);
13890 SetUInt64Value(UNIT_FIELD_CHARMEDBY,0);
13891 SetUInt64Value(UNIT_FIELD_SUMMONEDBY,0);
13892 SetUInt64Value(UNIT_FIELD_CREATEDBY,0);
13894 // reset some aura modifiers before aura apply
13895 SetUInt64Value(PLAYER_FARSIGHT, 0);
13896 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
13897 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
13899 // reset skill modifiers and set correct unlearn flags
13900 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; i++)
13902 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
13904 // set correct unlearn bit
13905 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
13906 if(!id) continue;
13908 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
13909 if(!pSkill) continue;
13911 // enable unlearn button for primary professions only
13912 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
13913 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
13914 else
13915 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
13918 // make sure the unit is considered out of combat for proper loading
13919 ClearInCombat();
13921 // make sure the unit is considered not in duel for proper loading
13922 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
13923 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
13925 // remember loaded power/health values to restore after stats initialization and modifier applying
13926 uint32 savedHealth = GetHealth();
13927 uint32 savedPower[MAX_POWERS];
13928 for(uint32 i = 0; i < MAX_POWERS; ++i)
13929 savedPower[i] = GetPower(Powers(i));
13931 // reset stats before loading any modifiers
13932 InitStatsForLevel();
13933 InitTaxiNodesForLevel();
13934 InitGlyphsForLevel();
13936 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
13938 //mails are loaded only when needed ;-) - when player in game click on mailbox.
13939 //_LoadMail();
13941 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
13943 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
13944 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
13945 m_deathState = DEAD;
13947 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
13949 // after spell load
13950 InitTalentForLevel();
13951 learnSkillRewardedSpells();
13953 // after spell load, learn rewarded spell if need also
13954 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
13955 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
13957 _LoadTutorials(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS));
13959 // must be before inventory (some items required reputation check)
13960 _LoadReputation(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
13962 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
13964 // update items with duration and realtime
13965 UpdateItemDuration(time_diff, true);
13967 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
13969 // unread mails and next delivery time, actual mails not loaded
13970 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
13972 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
13974 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
13975 return false;
13977 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
13978 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
13979 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
13981 if(!HasFlag64(PLAYER__FIELD_KNOWN_TITLES,uint64(1) << curTitle))
13982 SetUInt32Value(PLAYER_CHOSEN_TITLE,0);
13985 // Not finish taxi flight path
13986 if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes))
13988 // problems with taxi path loading
13989 TaxiNodesEntry const* nodeEntry = NULL;
13990 if(uint32 node_id = m_taxi.GetTaxiSource())
13991 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
13993 if(!nodeEntry) // don't know taxi start node, to homebind
13995 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
13996 SetMapId(m_homebindMapId);
13997 Relocate( m_homebindX, m_homebindY, m_homebindZ,0.0f);
13998 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14000 else // have start node, to it
14002 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14003 SetMapId(nodeEntry->map_id);
14004 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
14005 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14007 m_taxi.ClearTaxiDestinations();
14009 else if(uint32 node_id = m_taxi.GetTaxiSource())
14011 // save source node as recall coord to prevent recall and fall from sky
14012 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14013 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
14014 m_recallMap = nodeEntry->map_id;
14015 m_recallX = nodeEntry->x;
14016 m_recallY = nodeEntry->y;
14017 m_recallZ = nodeEntry->z;
14019 // flight will started later
14022 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
14024 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14025 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14026 if(!isAlive())
14027 RemoveAllAurasOnDeath();
14029 //apply all stat bonuses from items and auras
14030 SetCanModifyStats(true);
14031 UpdateAllStats();
14033 // restore remembered power/health values (but not more max values)
14034 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
14035 for(uint32 i = 0; i < MAX_POWERS; ++i)
14036 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
14038 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
14039 outDebugValues();
14041 // GM state
14042 if(GetSession()->GetSecurity() > SEC_PLAYER)
14044 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
14046 default:
14047 case 0: break; // disable
14048 case 1: SetGameMaster(true); break; // enable
14049 case 2: // save state
14050 if(extraflags & PLAYER_EXTRA_GM_ON)
14051 SetGameMaster(true);
14052 break;
14055 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
14057 default:
14058 case 0: break; // disable
14059 case 1: SetAcceptTicket(true); break; // enable
14060 case 2: // save state
14061 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
14062 SetAcceptTicket(true);
14063 break;
14066 switch(sWorld.getConfig(CONFIG_GM_CHAT))
14068 default:
14069 case 0: break; // disable
14070 case 1: SetGMChat(true); break; // enable
14071 case 2: // save state
14072 if(extraflags & PLAYER_EXTRA_GM_CHAT)
14073 SetGMChat(true);
14074 break;
14077 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
14079 default:
14080 case 0: break; // disable
14081 case 1: SetAcceptWhispers(true); break; // enable
14082 case 2: // save state
14083 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
14084 SetAcceptWhispers(true);
14085 break;
14089 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
14091 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
14092 m_achievementMgr.CheckAllAchievementCriteria();
14093 return true;
14096 bool Player::isAllowedToLoot(Creature* creature)
14098 if(Player* recipient = creature->GetLootRecipient())
14100 if (recipient == this)
14101 return true;
14102 if( Group* otherGroup = recipient->GetGroup())
14104 Group* thisGroup = GetGroup();
14105 if(!thisGroup)
14106 return false;
14107 return thisGroup == otherGroup;
14109 return false;
14111 else
14112 // prevent other players from looting if the recipient got disconnected
14113 return !creature->hasLootRecipient();
14116 void Player::_LoadActions(QueryResult *result)
14118 m_actionButtons.clear();
14120 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14122 if(result)
14126 Field *fields = result->Fetch();
14128 uint8 button = fields[0].GetUInt8();
14130 addActionButton(button, fields[1].GetUInt16(), fields[2].GetUInt8(), fields[3].GetUInt8());
14132 m_actionButtons[button].uState = ACTIONBUTTON_UNCHANGED;
14134 while( result->NextRow() );
14136 delete result;
14140 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
14142 m_Auras.clear();
14143 for (int i = 0; i < TOTAL_AURAS; i++)
14144 m_modAuras[i].clear();
14146 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14148 if(result)
14152 Field *fields = result->Fetch();
14153 uint64 caster_guid = fields[0].GetUInt64();
14154 uint32 spellid = fields[1].GetUInt32();
14155 uint32 effindex = fields[2].GetUInt32();
14156 int32 damage = (int32)fields[3].GetUInt32();
14157 int32 maxduration = (int32)fields[4].GetUInt32();
14158 int32 remaintime = (int32)fields[5].GetUInt32();
14159 int32 remaincharges = (int32)fields[6].GetUInt32();
14161 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
14162 if(!spellproto)
14164 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
14165 continue;
14168 if(effindex >= 3)
14170 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
14171 continue;
14174 // negative effects should continue counting down after logout
14175 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
14177 if(remaintime <= int32(timediff))
14178 continue;
14180 remaintime -= timediff;
14183 // prevent wrong values of remaincharges
14184 if(spellproto->procCharges)
14186 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
14187 remaincharges = spellproto->procCharges;
14189 else
14190 remaincharges = 0;
14192 //do not load single target auras (unless they were cast by the player)
14193 if (caster_guid != GetGUID() && IsSingleTargetSpell(spellproto))
14194 continue;
14196 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
14197 if(!damage)
14198 damage = aura->GetModifier()->m_amount;
14199 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
14200 AddAura(aura);
14202 while( result->NextRow() );
14204 delete result;
14207 if(m_class == CLASS_WARRIOR)
14208 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
14211 void Player::LoadCorpse()
14213 if( isAlive() )
14215 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14217 else
14219 if(Corpse *corpse = GetCorpse())
14221 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
14223 else
14225 //Prevent Dead Player login without corpse
14226 ResurrectPlayer(0.5f);
14231 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
14233 //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());
14234 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
14235 //NOTE: the "order by `bag`" is important because it makes sure
14236 //the bagMap is filled before items in the bags are loaded
14237 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14238 //expected to be equipped before offhand items (TODO: fixme)
14240 uint32 zone = GetZoneId();
14242 if (result)
14244 std::list<Item*> problematicItems;
14246 // prevent items from being added to the queue when stored
14247 m_itemUpdateQueueBlocked = true;
14250 Field *fields = result->Fetch();
14251 uint32 bag_guid = fields[1].GetUInt32();
14252 uint8 slot = fields[2].GetUInt8();
14253 uint32 item_guid = fields[3].GetUInt32();
14254 uint32 item_id = fields[4].GetUInt32();
14256 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
14258 if(!proto)
14260 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14261 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
14262 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
14263 continue;
14266 Item *item = NewItemOrBag(proto);
14268 if(!item->LoadFromDB(item_guid, GetGUID(), result))
14270 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
14271 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14272 item->FSetState(ITEM_REMOVED);
14273 item->SaveToDB(); // it also deletes item object !
14274 continue;
14277 // not allow have in alive state item limited to another map/zone
14278 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
14280 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14281 item->FSetState(ITEM_REMOVED);
14282 item->SaveToDB(); // it also deletes item object !
14283 continue;
14286 // "Conjured items disappear if you are logged out for more than 15 minutes"
14287 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
14289 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14290 item->FSetState(ITEM_REMOVED);
14291 item->SaveToDB(); // it also deletes item object !
14292 continue;
14295 bool success = true;
14297 if (!bag_guid)
14299 // the item is not in a bag
14300 item->SetContainer( NULL );
14301 item->SetSlot(slot);
14303 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14305 ItemPosCountVec dest;
14306 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14307 item = StoreItem(dest, item, true);
14308 else
14309 success = false;
14311 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14313 uint16 dest;
14314 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14315 QuickEquipItem(dest, item);
14316 else
14317 success = false;
14319 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14321 ItemPosCountVec dest;
14322 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14323 item = BankItem(dest, item, true);
14324 else
14325 success = false;
14328 if(success)
14330 // store bags that may contain items in them
14331 if(item->IsBag() && IsBagPos(item->GetPos()))
14332 bagMap[item_guid] = (Bag*)item;
14335 else
14337 item->SetSlot(NULL_SLOT);
14338 // the item is in a bag, find the bag
14339 std::map<uint64, Bag*>::iterator itr = bagMap.find(bag_guid);
14340 if(itr != bagMap.end())
14341 itr->second->StoreItem(slot, item, true );
14342 else
14343 success = false;
14346 // item's state may have changed after stored
14347 if (success)
14348 item->SetState(ITEM_UNCHANGED, this);
14349 else
14351 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);
14352 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14353 problematicItems.push_back(item);
14355 } while (result->NextRow());
14357 delete result;
14358 m_itemUpdateQueueBlocked = false;
14360 // send by mail problematic items
14361 while(!problematicItems.empty())
14363 // fill mail
14364 MailItemsInfo mi; // item list preparing
14366 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14368 Item* item = problematicItems.front();
14369 problematicItems.pop_front();
14371 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14374 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14376 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14379 //if(isAlive())
14380 _ApplyAllItemMods();
14383 // load mailed item which should receive current player
14384 void Player::_LoadMailedItems(Mail *mail)
14386 QueryResult* result = CharacterDatabase.PQuery("SELECT item_guid, item_template FROM mail_items WHERE mail_id='%u'", mail->messageID);
14387 if(!result)
14388 return;
14392 Field *fields = result->Fetch();
14393 uint32 item_guid_low = fields[0].GetUInt32();
14394 uint32 item_template = fields[1].GetUInt32();
14396 mail->AddItem(item_guid_low, item_template);
14398 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
14400 if(!proto)
14402 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);
14403 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14404 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
14405 continue;
14408 Item *item = NewItemOrBag(proto);
14410 if(!item->LoadFromDB(item_guid_low, 0))
14412 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
14413 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14414 item->FSetState(ITEM_REMOVED);
14415 item->SaveToDB(); // it also deletes item object !
14416 continue;
14419 AddMItem(item);
14420 } while (result->NextRow());
14422 delete result;
14425 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
14427 //set a count of unread mails
14428 //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);
14429 if (resultUnread)
14431 Field *fieldMail = resultUnread->Fetch();
14432 unReadMails = fieldMail[0].GetUInt8();
14433 delete resultUnread;
14436 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14437 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14438 if (resultDelivery)
14440 Field *fieldMail = resultDelivery->Fetch();
14441 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
14442 delete resultDelivery;
14446 void Player::_LoadMail()
14448 m_mail.clear();
14449 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14450 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());
14451 if(result)
14455 Field *fields = result->Fetch();
14456 Mail *m = new Mail;
14457 m->messageID = fields[0].GetUInt32();
14458 m->messageType = fields[1].GetUInt8();
14459 m->sender = fields[2].GetUInt32();
14460 m->receiver = fields[3].GetUInt32();
14461 m->subject = fields[4].GetCppString();
14462 m->itemTextId = fields[5].GetUInt32();
14463 bool has_items = fields[6].GetBool();
14464 m->expire_time = (time_t)fields[7].GetUInt64();
14465 m->deliver_time = (time_t)fields[8].GetUInt64();
14466 m->money = fields[9].GetUInt32();
14467 m->COD = fields[10].GetUInt32();
14468 m->checked = fields[11].GetUInt32();
14469 m->stationery = fields[12].GetUInt8();
14470 m->mailTemplateId = fields[13].GetInt16();
14472 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
14474 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
14475 m->mailTemplateId = 0;
14478 m->state = MAIL_STATE_UNCHANGED;
14480 if (has_items)
14481 _LoadMailedItems(m);
14483 m_mail.push_back(m);
14484 } while( result->NextRow() );
14485 delete result;
14487 m_mailsLoaded = true;
14490 void Player::LoadPet()
14492 //fixme: the pet should still be loaded if the player is not in world
14493 // just not added to the map
14494 if(IsInWorld())
14496 Pet *pet = new Pet;
14497 if(!pet->LoadPetFromDB(this,0,0,true))
14498 delete pet;
14502 void Player::_LoadQuestStatus(QueryResult *result)
14504 mQuestStatus.clear();
14506 uint32 slot = 0;
14508 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14509 //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());
14511 if(result)
14515 Field *fields = result->Fetch();
14517 uint32 quest_id = fields[0].GetUInt32();
14518 // used to be new, no delete?
14519 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14520 if( pQuest )
14522 // find or create
14523 QuestStatusData& questStatusData = mQuestStatus[quest_id];
14525 uint32 qstatus = fields[1].GetUInt32();
14526 if(qstatus < MAX_QUEST_STATUS)
14527 questStatusData.m_status = QuestStatus(qstatus);
14528 else
14530 questStatusData.m_status = QUEST_STATUS_NONE;
14531 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
14534 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
14535 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
14537 time_t quest_time = time_t(fields[4].GetUInt64());
14539 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
14541 AddTimedQuest( quest_id );
14543 if (quest_time <= sWorld.GetGameTime())
14544 questStatusData.m_timer = 1;
14545 else
14546 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * 1000;
14548 else
14549 quest_time = 0;
14551 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
14552 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
14553 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
14554 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
14555 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
14556 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
14557 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
14558 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
14560 questStatusData.uState = QUEST_UNCHANGED;
14562 // add to quest log
14563 if( slot < MAX_QUEST_LOG_SIZE &&
14564 ( questStatusData.m_status==QUEST_STATUS_INCOMPLETE ||
14565 questStatusData.m_status==QUEST_STATUS_COMPLETE && !questStatusData.m_rewarded ) )
14567 SetQuestSlot(slot,quest_id,quest_time);
14569 if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
14570 SetQuestSlotState(slot,QUEST_STATE_COMPLETE);
14572 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
14573 if(questStatusData.m_creatureOrGOcount[idx])
14574 SetQuestSlotCounter(slot,idx,questStatusData.m_creatureOrGOcount[idx]);
14576 ++slot;
14579 if(questStatusData.m_rewarded)
14581 // learn rewarded spell if unknown
14582 learnQuestRewardedSpells(pQuest);
14584 // set rewarded title if any
14585 if(pQuest->GetCharTitleId())
14587 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
14588 SetFlag64(PLAYER__FIELD_KNOWN_TITLES, (uint64(1) << titleEntry->bit_index));
14592 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
14595 while( result->NextRow() );
14597 delete result;
14600 // clear quest log tail
14601 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
14602 SetQuestSlot(i,0);
14605 void Player::_LoadDailyQuestStatus(QueryResult *result)
14607 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
14608 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
14610 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14612 if(result)
14614 uint32 quest_daily_idx = 0;
14618 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
14620 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
14621 break;
14624 Field *fields = result->Fetch();
14626 uint32 quest_id = fields[0].GetUInt32();
14628 // save _any_ from daily quest times (it must be after last reset anyway)
14629 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
14631 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14632 if( !pQuest )
14633 continue;
14635 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
14636 ++quest_daily_idx;
14638 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
14640 while( result->NextRow() );
14642 delete result;
14645 m_DailyQuestChanged = false;
14648 void Player::_LoadReputation(QueryResult *result)
14650 m_factions.clear();
14652 // Set initial reputations (so everything is nifty before DB data load)
14653 SetInitialFactions();
14655 //QueryResult *result = CharacterDatabase.PQuery("SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'",GetGUIDLow());
14657 if(result)
14661 Field *fields = result->Fetch();
14663 FactionEntry const *factionEntry = sFactionStore.LookupEntry(fields[0].GetUInt32());
14664 if( factionEntry && (factionEntry->reputationListID >= 0))
14666 FactionState* faction = &m_factions[factionEntry->reputationListID];
14668 // update standing to current
14669 faction->Standing = int32(fields[1].GetUInt32());
14671 uint32 dbFactionFlags = fields[2].GetUInt32();
14673 if( dbFactionFlags & FACTION_FLAG_VISIBLE )
14674 SetFactionVisible(faction); // have internal checks for forced invisibility
14676 if( dbFactionFlags & FACTION_FLAG_INACTIVE)
14677 SetFactionInactive(faction,true); // have internal checks for visibility requirement
14679 if( dbFactionFlags & FACTION_FLAG_AT_WAR ) // DB at war
14680 SetFactionAtWar(faction,true); // have internal checks for FACTION_FLAG_PEACE_FORCED
14681 else // DB not at war
14683 // allow remove if visible (and then not FACTION_FLAG_INVISIBLE_FORCED or FACTION_FLAG_HIDDEN)
14684 if( faction->Flags & FACTION_FLAG_VISIBLE )
14685 SetFactionAtWar(faction,false); // have internal checks for FACTION_FLAG_PEACE_FORCED
14688 // set atWar for hostile
14689 if(GetReputationRank(factionEntry) <= REP_HOSTILE)
14690 SetFactionAtWar(faction,true);
14692 // reset changed flag if values similar to saved in DB
14693 if(faction->Flags==dbFactionFlags)
14694 faction->Changed = false;
14697 while( result->NextRow() );
14699 delete result;
14703 void Player::_LoadSpells(QueryResult *result)
14705 for (PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
14706 delete itr->second;
14707 m_spells.clear();
14709 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,slot,active FROM character_spell WHERE guid = '%u'",GetGUIDLow());
14711 if(result)
14715 Field *fields = result->Fetch();
14717 addSpell(fields[0].GetUInt16(), fields[2].GetBool(), false, true, fields[1].GetUInt16(), fields[3].GetBool());
14719 while( result->NextRow() );
14721 delete result;
14725 void Player::_LoadTutorials(QueryResult *result)
14727 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
14729 if(result)
14733 Field *fields = result->Fetch();
14735 for (int iI=0; iI<8; iI++)
14736 m_Tutorials[iI] = fields[iI].GetUInt32();
14738 while( result->NextRow() );
14740 delete result;
14743 m_TutorialsChanged = false;
14746 void Player::_LoadGroup(QueryResult *result)
14748 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
14749 if(result)
14751 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
14752 delete result;
14753 Group* group = objmgr.GetGroupByLeader(leaderGuid);
14754 if(group)
14756 uint8 subgroup = group->GetMemberGroup(GetGUID());
14757 SetGroup(group, subgroup);
14758 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
14760 // the group leader may change the instance difficulty while the player is offline
14761 SetDifficulty(group->GetDifficulty());
14767 void Player::_LoadBoundInstances(QueryResult *result)
14769 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14770 m_boundInstances[i].clear();
14772 Group *group = GetGroup();
14774 //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));
14775 if(result)
14779 Field *fields = result->Fetch();
14780 bool perm = fields[1].GetBool();
14781 uint32 mapId = fields[2].GetUInt32();
14782 uint32 instanceId = fields[0].GetUInt32();
14783 uint8 difficulty = fields[3].GetUInt8();
14784 time_t resetTime = (time_t)fields[4].GetUInt64();
14785 // the resettime for normal instances is only saved when the InstanceSave is unloaded
14786 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
14787 // and in that case it is not used
14789 if(!perm && group)
14791 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);
14792 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
14793 continue;
14796 // since non permanent binds are always solo bind, they can always be reset
14797 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
14798 if(save) BindToInstance(save, perm, true);
14799 } while(result->NextRow());
14800 delete result;
14804 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
14806 // some instances only have one difficulty
14807 const MapEntry* entry = sMapStore.LookupEntry(mapid);
14808 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
14810 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
14811 if(itr != m_boundInstances[difficulty].end())
14812 return &itr->second;
14813 else
14814 return NULL;
14817 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
14819 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
14820 UnbindInstance(itr, difficulty, unload);
14823 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
14825 if(itr != m_boundInstances[difficulty].end())
14827 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
14828 itr->second.save->RemovePlayer(this); // save can become invalid
14829 m_boundInstances[difficulty].erase(itr++);
14833 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
14835 if(save)
14837 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
14838 if(bind.save)
14840 // update the save when the group kills a boss
14841 if(permanent != bind.perm || save != bind.save)
14842 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());
14844 else
14845 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
14847 if(bind.save != save)
14849 if(bind.save) bind.save->RemovePlayer(this);
14850 save->AddPlayer(this);
14853 if(permanent) save->SetCanReset(false);
14855 bind.save = save;
14856 bind.perm = permanent;
14857 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());
14858 return &bind;
14860 else
14861 return NULL;
14864 void Player::SendRaidInfo()
14866 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
14868 uint32 counter = 0, i;
14869 for(i = 0; i < TOTAL_DIFFICULTIES; i++)
14870 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); itr++)
14871 if(itr->second.perm) counter++;
14873 data << counter;
14874 for(i = 0; i < TOTAL_DIFFICULTIES; i++)
14876 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); itr++)
14878 if(itr->second.perm)
14880 InstanceSave *save = itr->second.save;
14881 data << (save->GetMapId());
14882 data << (uint32)(save->GetResetTime() - time(NULL));
14883 data << save->GetInstanceId();
14884 data << uint32(counter);
14885 counter--;
14889 GetSession()->SendPacket(&data);
14893 - called on every successful teleportation to a map
14895 void Player::SendSavedInstances()
14897 bool hasBeenSaved = false;
14898 WorldPacket data;
14900 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14902 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
14904 if(itr->second.perm) // only permanent binds are sent
14906 hasBeenSaved = true;
14907 break;
14912 //Send opcode 811. true or false means, whether you have current raid/heroic instances
14913 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
14914 data << uint32(hasBeenSaved);
14915 GetSession()->SendPacket(&data);
14917 if(!hasBeenSaved)
14918 return;
14920 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14922 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
14924 if(itr->second.perm)
14926 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
14927 data << uint32(itr->second.save->GetMapId());
14928 GetSession()->SendPacket(&data);
14934 /// convert the player's binds to the group
14935 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
14937 bool has_binds = false;
14938 bool has_solo = false;
14940 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
14941 assert(player_guid);
14943 // copy all binds to the group, when changing leader it's assumed the character
14944 // will not have any solo binds
14946 if(player)
14948 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14950 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
14952 has_binds = true;
14953 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
14954 // permanent binds are not removed
14955 if(!itr->second.perm)
14957 player->UnbindInstance(itr, i, true); // increments itr
14958 has_solo = true;
14960 else
14961 ++itr;
14966 // if the player's not online we don't know what binds it has
14967 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));
14968 // the following should not get executed when changing leaders
14969 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
14972 bool Player::_LoadHomeBind(QueryResult *result)
14974 bool ok = false;
14975 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
14976 if (result)
14978 Field *fields = result->Fetch();
14979 m_homebindMapId = fields[0].GetUInt32();
14980 m_homebindZoneId = fields[1].GetUInt16();
14981 m_homebindX = fields[2].GetFloat();
14982 m_homebindY = fields[3].GetFloat();
14983 m_homebindZ = fields[4].GetFloat();
14984 delete result;
14986 // accept saved data only for valid position (and non instanceable)
14987 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
14988 !sMapStore.LookupEntry(m_homebindMapId)->Instanceable() )
14990 ok = true;
14992 else
14993 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
14996 if(!ok)
14998 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
14999 if(!info) return false;
15001 m_homebindMapId = info->mapId;
15002 m_homebindZoneId = info->zoneId;
15003 m_homebindX = info->positionX;
15004 m_homebindY = info->positionY;
15005 m_homebindZ = info->positionZ;
15007 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);
15010 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",
15011 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15013 return true;
15016 /*********************************************************/
15017 /*** SAVE SYSTEM ***/
15018 /*********************************************************/
15020 void Player::SaveToDB()
15022 // delay auto save at any saves (manual, in code, or autosave)
15023 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
15025 // first save/honor gain after midnight will also update the player's honor fields
15026 UpdateHonorFields();
15028 // Must saved before enter into BattleGround
15029 if(InBattleGround())
15030 return;
15032 int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
15033 //save, far from tavern/city
15034 //save, but in tavern/city
15035 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
15036 outDebugValues();
15038 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15039 uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
15040 uint32 tmp_bytes2 = GetUInt32Value(UNIT_FIELD_BYTES_2);
15041 uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
15042 uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
15043 uint32 tmp_displayid = GetDisplayId();
15045 // Set player sit state to standing on save, also stealth and shifted form
15046 SetByteValue(UNIT_FIELD_BYTES_1, 0, 0); // stand state
15047 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0); // shapeshift
15048 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0); // stand flags?
15049 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
15050 SetDisplayId(GetNativeDisplayId());
15052 bool inworld = IsInWorld();
15054 CharacterDatabase.BeginTransaction();
15056 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15058 std::string sql_name = m_name;
15059 CharacterDatabase.escape_string(sql_name);
15061 std::ostringstream ss;
15062 ss << "INSERT INTO characters (guid,account,name,race,class,"
15063 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15064 "taximask, online, cinematic, "
15065 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15066 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15067 "death_expire_time, taxi_path) VALUES ("
15068 << GetGUIDLow() << ", "
15069 << GetSession()->GetAccountId() << ", '"
15070 << sql_name << "', "
15071 << m_race << ", "
15072 << m_class << ", ";
15074 bool save_to_dest = false;
15075 if(IsBeingTeleported())
15077 // don't save to battlegrounds or arenas
15078 const MapEntry *entry = sMapStore.LookupEntry(GetTeleportDest().mapid);
15079 if(entry && entry->map_type != MAP_BATTLEGROUND && entry->map_type != MAP_ARENA)
15080 save_to_dest = true;
15083 if(!save_to_dest)
15085 ss << GetMapId() << ", "
15086 << (uint32)GetDifficulty() << ", "
15087 << finiteAlways(GetPositionX()) << ", "
15088 << finiteAlways(GetPositionY()) << ", "
15089 << finiteAlways(GetPositionZ()) << ", "
15090 << finiteAlways(GetOrientation()) << ", '";
15092 else
15094 ss << GetTeleportDest().mapid << ", "
15095 << (uint32)GetDifficulty() << ", "
15096 << finiteAlways(GetTeleportDest().x) << ", "
15097 << finiteAlways(GetTeleportDest().y) << ", "
15098 << finiteAlways(GetTeleportDest().z) << ", "
15099 << finiteAlways(GetTeleportDest().o) << ", '";
15102 uint16 i;
15103 for( i = 0; i < m_valuesCount; i++ )
15105 ss << GetUInt32Value(i) << " ";
15108 ss << "', '";
15110 for( i = 0; i < 8; i++ )
15111 ss << m_taxi.GetTaximask(i) << " ";
15113 ss << "', ";
15114 ss << (inworld ? 1 : 0);
15116 ss << ", ";
15117 ss << m_cinematic;
15119 ss << ", ";
15120 ss << m_Played_time[0];
15121 ss << ", ";
15122 ss << m_Played_time[1];
15124 ss << ", ";
15125 ss << finiteAlways(m_rest_bonus);
15126 ss << ", ";
15127 ss << (uint64)time(NULL);
15128 ss << ", ";
15129 ss << is_save_resting;
15130 ss << ", ";
15131 ss << m_resetTalentsCost;
15132 ss << ", ";
15133 ss << (uint64)m_resetTalentsTime;
15135 ss << ", ";
15136 ss << finiteAlways(m_movementInfo.t_x);
15137 ss << ", ";
15138 ss << finiteAlways(m_movementInfo.t_y);
15139 ss << ", ";
15140 ss << finiteAlways(m_movementInfo.t_z);
15141 ss << ", ";
15142 ss << finiteAlways(m_movementInfo.t_o);
15143 ss << ", ";
15144 if (m_transport)
15145 ss << m_transport->GetGUIDLow();
15146 else
15147 ss << "0";
15149 ss << ", ";
15150 ss << m_ExtraFlags;
15152 ss << ", ";
15153 ss << uint32(m_stableSlots); // to prevent save uint8 as char
15155 ss << ", ";
15156 ss << uint32(m_atLoginFlags);
15158 ss << ", ";
15159 ss << GetZoneId();
15161 ss << ", ";
15162 ss << (uint64)m_deathExpireTime;
15164 ss << ", '";
15165 ss << m_taxi.SaveTaxiDestinationsToString();
15166 ss << "' )";
15168 CharacterDatabase.Execute( ss.str().c_str() );
15170 if(m_mailsUpdated) //save mails only when needed
15171 _SaveMail();
15173 _SaveInventory();
15174 _SaveQuestStatus();
15175 _SaveDailyQuestStatus();
15176 _SaveTutorials();
15177 _SaveSpells();
15178 _SaveSpellCooldowns();
15179 _SaveActions();
15180 _SaveAuras();
15181 _SaveReputation();
15183 CharacterDatabase.CommitTransaction();
15185 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15186 SetDisplayId(tmp_displayid);
15187 SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
15188 SetUInt32Value(UNIT_FIELD_BYTES_2, tmp_bytes2);
15189 SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
15190 SetUInt32Value(PLAYER_FLAGS, tmp_pflags);
15192 // save pet (hunter pet level and experience and all type pets health/mana).
15193 if(Pet* pet = GetPet())
15194 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
15195 m_achievementMgr.SaveToDB();
15198 // fast save function for item/money cheating preventing - save only inventory and money state
15199 void Player::SaveInventoryAndGoldToDB()
15201 _SaveInventory();
15202 SetUInt32ValueInDB(PLAYER_FIELD_COINAGE,GetMoney(),GetGUID());
15205 void Player::_SaveActions()
15207 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
15209 switch (itr->second.uState)
15211 case ACTIONBUTTON_NEW:
15212 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15213 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc );
15214 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15215 ++itr;
15216 break;
15217 case ACTIONBUTTON_CHANGED:
15218 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15219 (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc, GetGUIDLow(), (uint32)itr->first );
15220 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15221 ++itr;
15222 break;
15223 case ACTIONBUTTON_DELETED:
15224 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
15225 m_actionButtons.erase(itr++);
15226 break;
15227 default:
15228 ++itr;
15229 break;
15234 void Player::_SaveAuras()
15236 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15238 AuraMap const& auras = GetAuras();
15239 for(AuraMap::const_iterator itr = auras.begin(); itr != auras.end(); ++itr)
15241 SpellEntry const *spellInfo = itr->second->GetSpellProto();
15243 //skip all auras from spells that are passive or need a shapeshift
15244 if (itr->second->IsPassive() || itr->second->IsRemovedOnShapeLost())
15245 continue;
15247 //do not save single target auras (unless they were cast by the player)
15248 if (itr->second->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo))
15249 continue;
15251 uint8 i;
15252 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15253 for (i = 0; i < 3; i++)
15254 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
15255 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
15256 break;
15258 if (i == 3)
15260 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());
15261 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,amount,maxduration,remaintime,remaincharges) "
15262 "VALUES ('%u', '" I64FMTD "' ,'%u', '%u', '%d', '%d', '%d', '%d')",
15263 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));
15268 void Player::_SaveInventory()
15270 // force items in buyback slots to new state
15271 // and remove those that aren't already
15272 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; i++)
15274 Item *item = m_items[i];
15275 if (!item || item->GetState() == ITEM_NEW) continue;
15276 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15277 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
15278 m_items[i]->FSetState(ITEM_NEW);
15281 // update enchantment durations
15282 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
15284 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
15287 // if no changes
15288 if (m_itemUpdateQueue.empty()) return;
15290 // do not save if the update queue is corrupt
15291 bool error = false;
15292 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15294 Item *item = m_itemUpdateQueue[i];
15295 if(!item || item->GetState() == ITEM_REMOVED) continue;
15296 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
15298 if (test == NULL)
15300 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());
15301 error = true;
15303 else if (test != item)
15305 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());
15306 error = true;
15310 if (error)
15312 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15313 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15314 return;
15317 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15319 Item *item = m_itemUpdateQueue[i];
15320 if(!item) continue;
15322 Bag *container = item->GetContainer();
15323 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15325 switch(item->GetState())
15327 case ITEM_NEW:
15328 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());
15329 break;
15330 case ITEM_CHANGED:
15331 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());
15332 break;
15333 case ITEM_REMOVED:
15334 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15335 break;
15336 case ITEM_UNCHANGED:
15337 break;
15340 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15342 m_itemUpdateQueue.clear();
15345 void Player::_SaveMail()
15347 if (!m_mailsLoaded)
15348 return;
15350 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); itr++)
15352 Mail *m = (*itr);
15353 if (m->state == MAIL_STATE_CHANGED)
15355 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'",
15356 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15357 if(m->removedItems.size())
15359 for(std::vector<uint32>::iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15360 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15361 m->removedItems.clear();
15363 m->state = MAIL_STATE_UNCHANGED;
15365 else if (m->state == MAIL_STATE_DELETED)
15367 if (m->HasItems())
15368 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15369 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15370 if (m->itemTextId)
15371 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15372 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15373 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15377 //deallocate deleted mails...
15378 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15380 if ((*itr)->state == MAIL_STATE_DELETED)
15382 Mail* m = *itr;
15383 m_mail.erase(itr);
15384 delete m;
15385 itr = m_mail.begin();
15387 else
15388 ++itr;
15391 m_mailsUpdated = false;
15394 void Player::_SaveQuestStatus()
15396 // we don't need transactions here.
15397 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15399 switch (i->second.uState)
15401 case QUEST_NEW :
15402 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15403 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15404 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]);
15405 break;
15406 case QUEST_CHANGED :
15407 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' ",
15408 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 );
15409 break;
15410 case QUEST_UNCHANGED:
15411 break;
15413 i->second.uState = QUEST_UNCHANGED;
15417 void Player::_SaveDailyQuestStatus()
15419 if(!m_DailyQuestChanged)
15420 return;
15422 m_DailyQuestChanged = false;
15424 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15426 // we don't need transactions here.
15427 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15428 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15429 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
15430 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD "')",
15431 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
15434 void Player::_SaveReputation()
15436 for(FactionStateList::iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
15438 if (itr->second.Changed)
15440 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u' AND faction='%u'", GetGUIDLow(), itr->second.ID);
15441 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);
15442 itr->second.Changed = false;
15447 void Player::_SaveSpells()
15449 for (PlayerSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
15451 ++next;
15452 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
15453 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
15454 if (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED)
15455 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);
15457 if (itr->second->state == PLAYERSPELL_REMOVED)
15458 _removeSpell(itr->first);
15459 else
15460 itr->second->state = PLAYERSPELL_UNCHANGED;
15464 void Player::_SaveTutorials()
15466 if(!m_TutorialsChanged)
15467 return;
15469 uint32 Rows=0;
15470 // it's better than rebuilding indexes multiple times
15471 QueryResult *result = CharacterDatabase.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID );
15472 if(result)
15474 Rows = result->Fetch()[0].GetUInt32();
15475 delete result;
15478 if (Rows)
15480 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'",
15481 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 );
15483 else
15485 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]);
15488 m_TutorialsChanged = false;
15491 void Player::outDebugValues() const
15493 if(!sLog.IsOutDebug()) // optimize disabled debug output
15494 return;
15496 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
15497 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
15498 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
15499 sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
15500 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
15501 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
15502 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
15503 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
15504 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
15505 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
15506 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
15507 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
15510 /*********************************************************/
15511 /*** FLOOD FILTER SYSTEM ***/
15512 /*********************************************************/
15514 void Player::UpdateSpeakTime()
15516 // ignore chat spam protection for GMs in any mode
15517 if(GetSession()->GetSecurity() > SEC_PLAYER)
15518 return;
15520 time_t current = time (NULL);
15521 if(m_speakTime > current)
15523 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
15524 if(!max_count)
15525 return;
15527 ++m_speakCount;
15528 if(m_speakCount >= max_count)
15530 // prevent overwrite mute time, if message send just before mutes set, for example.
15531 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
15532 if(GetSession()->m_muteTime < new_mute)
15533 GetSession()->m_muteTime = new_mute;
15535 m_speakCount = 0;
15538 else
15539 m_speakCount = 0;
15541 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
15544 bool Player::CanSpeak() const
15546 return GetSession()->m_muteTime <= time (NULL);
15549 /*********************************************************/
15550 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15551 /*********************************************************/
15553 void Player::SendAttackSwingNotInRange()
15555 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
15556 GetSession()->SendPacket( &data );
15559 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
15561 std::ostringstream ss;
15562 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
15563 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
15564 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
15565 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15566 sLog.outDebug(ss.str().c_str());
15567 CharacterDatabase.Execute(ss.str().c_str());
15570 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
15572 std::ostringstream ss2;
15573 ss2<<"UPDATE characters SET data='";
15574 int i=0;
15575 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
15577 ss2<<tokens[i]<<" ";
15579 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15581 return CharacterDatabase.Execute(ss2.str().c_str());
15584 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
15586 char buf[11];
15587 snprintf(buf,11,"%u",value);
15589 if(index >= tokens.size())
15590 return;
15592 tokens[index] = buf;
15595 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
15597 Tokens tokens;
15598 if(!LoadValuesArrayFromDB(tokens,guid))
15599 return;
15601 if(index >= tokens.size())
15602 return;
15604 char buf[11];
15605 snprintf(buf,11,"%u",value);
15606 tokens[index] = buf;
15608 SaveValuesArrayInDB(tokens,guid);
15611 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
15613 uint32 temp;
15614 memcpy(&temp, &value, sizeof(value));
15615 Player::SetUInt32ValueInDB(index, temp, guid);
15618 void Player::SendAttackSwingNotStanding()
15620 WorldPacket data(SMSG_ATTACKSWING_NOTSTANDING, 0);
15621 GetSession()->SendPacket( &data );
15624 void Player::SendAttackSwingDeadTarget()
15626 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
15627 GetSession()->SendPacket( &data );
15630 void Player::SendAttackSwingCantAttack()
15632 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
15633 GetSession()->SendPacket( &data );
15636 void Player::SendAttackSwingCancelAttack()
15638 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
15639 GetSession()->SendPacket( &data );
15642 void Player::SendAttackSwingBadFacingAttack()
15644 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
15645 GetSession()->SendPacket( &data );
15648 void Player::SendAutoRepeatCancel()
15650 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, GetPackGUID().size());
15651 data.append(GetPackGUID()); // may be it's target guid
15652 GetSession()->SendPacket( &data );
15655 void Player::PlaySound(uint32 Sound, bool OnlySelf)
15657 WorldPacket data(SMSG_PLAY_SOUND, 4);
15658 data << Sound;
15659 if (OnlySelf)
15660 GetSession()->SendPacket( &data );
15661 else
15662 SendMessageToSet( &data, true );
15665 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
15667 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
15668 data << Area;
15669 data << Experience;
15670 GetSession()->SendPacket(&data);
15673 void Player::SendDungeonDifficulty(bool IsInGroup)
15675 uint8 val = 0x00000001;
15676 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
15677 data << (uint32)GetDifficulty();
15678 data << uint32(val);
15679 data << uint32(IsInGroup);
15680 GetSession()->SendPacket(&data);
15683 void Player::SendResetFailedNotify(uint32 mapid)
15685 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
15686 data << uint32(mapid);
15687 GetSession()->SendPacket(&data);
15690 /// Reset all solo instances and optionally send a message on success for each
15691 void Player::ResetInstances(uint8 method)
15693 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
15695 // we assume that when the difficulty changes, all instances that can be reset will be
15696 uint8 dif = GetDifficulty();
15698 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
15700 InstanceSave *p = itr->second.save;
15701 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
15702 if(!entry || !p->CanReset())
15704 ++itr;
15705 continue;
15708 if(method == INSTANCE_RESET_ALL)
15710 // the "reset all instances" method can only reset normal maps
15711 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
15713 ++itr;
15714 continue;
15718 // if the map is loaded, reset it
15719 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
15720 if(map && map->IsDungeon())
15721 ((InstanceMap*)map)->Reset(method);
15723 // since this is a solo instance there should not be any players inside
15724 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
15725 SendResetInstanceSuccess(p->GetMapId());
15727 p->DeleteFromDB();
15728 m_boundInstances[dif].erase(itr++);
15730 // the following should remove the instance save from the manager and delete it as well
15731 p->RemovePlayer(this);
15735 void Player::SendResetInstanceSuccess(uint32 MapId)
15737 WorldPacket data(SMSG_INSTANCE_RESET, 4);
15738 data << MapId;
15739 GetSession()->SendPacket(&data);
15742 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
15744 // TODO: find what other fail reasons there are besides players in the instance
15745 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
15746 data << reason;
15747 data << MapId;
15748 GetSession()->SendPacket(&data);
15751 /*********************************************************/
15752 /*** Update timers ***/
15753 /*********************************************************/
15755 ///checks the 15 afk reports per 5 minutes limit
15756 void Player::UpdateAfkReport(time_t currTime)
15758 if(m_bgAfkReportedTimer <= currTime)
15760 m_bgAfkReportedCount = 0;
15761 m_bgAfkReportedTimer = currTime+5*MINUTE;
15765 void Player::UpdateContestedPvP(uint32 diff)
15767 if(!m_contestedPvPTimer||isInCombat())
15768 return;
15769 if(m_contestedPvPTimer <= diff)
15771 ResetContestedPvP();
15773 else
15774 m_contestedPvPTimer -= diff;
15777 void Player::UpdatePvPFlag(time_t currTime)
15779 if(!IsPvP())
15780 return;
15781 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
15782 return;
15784 UpdatePvP(false);
15787 void Player::UpdateDuelFlag(time_t currTime)
15789 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
15790 return;
15792 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
15793 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
15795 duel->startTimer = 0;
15796 duel->startTime = currTime;
15797 duel->opponent->duel->startTimer = 0;
15798 duel->opponent->duel->startTime = currTime;
15801 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
15803 if(!pet)
15804 pet = GetPet();
15806 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
15808 //returning of reagents only for players, so best done here
15809 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
15810 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
15812 if(spellInfo)
15814 for(uint32 i = 0; i < 7; ++i)
15816 if(spellInfo->Reagent[i] > 0)
15818 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
15819 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
15820 if( msg == EQUIP_ERR_OK )
15822 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
15823 if(IsInWorld())
15824 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
15829 m_temporaryUnsummonedPetNumber = 0;
15832 if(!pet || pet->GetOwnerGUID()!=GetGUID())
15833 return;
15835 // only if current pet in slot
15836 switch(pet->getPetType())
15838 case MINI_PET:
15839 m_miniPet = 0;
15840 break;
15841 case GUARDIAN_PET:
15842 m_guardianPets.erase(pet->GetGUID());
15843 break;
15844 default:
15845 if(GetPetGUID()==pet->GetGUID())
15846 SetPet(0);
15847 break;
15850 pet->CombatStop();
15852 if(returnreagent)
15854 switch(pet->GetEntry())
15856 //warlock pets except imp are removed(?) when logging out
15857 case 1860:
15858 case 1863:
15859 case 417:
15860 case 17252:
15861 mode = PET_SAVE_NOT_IN_SLOT;
15862 break;
15866 pet->SavePetToDB(mode);
15868 pet->CleanupsBeforeDelete();
15869 pet->AddObjectToRemoveList();
15870 pet->m_removed = true;
15872 if(pet->isControlled())
15874 WorldPacket data(SMSG_PET_SPELLS, 8);
15875 data << uint64(0);
15876 data << uint32(0);
15877 GetSession()->SendPacket(&data);
15879 if(GetGroup())
15880 SetGroupUpdateFlag(GROUP_UPDATE_PET);
15884 void Player::RemoveMiniPet()
15886 if(Pet* pet = GetMiniPet())
15888 pet->Remove(PET_SAVE_AS_DELETED);
15889 m_miniPet = 0;
15893 Pet* Player::GetMiniPet()
15895 if(!m_miniPet)
15896 return NULL;
15897 return ObjectAccessor::GetPet(m_miniPet);
15900 void Player::RemoveGuardians()
15902 while(!m_guardianPets.empty())
15904 uint64 guid = *m_guardianPets.begin();
15905 if(Pet* pet = ObjectAccessor::GetPet(guid))
15906 pet->Remove(PET_SAVE_AS_DELETED);
15908 m_guardianPets.erase(guid);
15912 bool Player::HasGuardianWithEntry(uint32 entry)
15914 // pet guid middle part is entry (and creature also)
15915 // and in guardian list must be guardians with same entry _always_
15916 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
15917 if(GUID_ENPART(*itr)==entry)
15918 return true;
15920 return false;
15923 void Player::Uncharm()
15925 Unit* charm = GetCharm();
15926 if(!charm)
15927 return;
15929 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
15930 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
15933 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, std::string text, uint32 language) const
15935 *data << (uint8)msgtype;
15936 *data << (uint32)language;
15937 *data << (uint64)GetGUID();
15938 *data << (uint32)language; //language 2.1.0 ?
15939 *data << (uint64)GetGUID();
15940 *data << (uint32)(text.length()+1);
15941 *data << text;
15942 *data << (uint8)chatTag();
15945 void Player::Say(const std::string text, const uint32 language)
15947 WorldPacket data(SMSG_MESSAGECHAT, 200);
15948 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
15949 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
15952 void Player::Yell(const std::string text, const uint32 language)
15954 WorldPacket data(SMSG_MESSAGECHAT, 200);
15955 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
15956 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
15959 void Player::TextEmote(const std::string text)
15961 WorldPacket data(SMSG_MESSAGECHAT, 200);
15962 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
15963 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
15966 void Player::Whisper(std::string text, uint32 language,uint64 receiver)
15968 if (language != LANG_ADDON) // if not addon data
15969 language = LANG_UNIVERSAL; // whispers should always be readable
15971 Player *rPlayer = objmgr.GetPlayer(receiver);
15973 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
15974 if(!rPlayer->isDND() || isGameMaster())
15976 WorldPacket data(SMSG_MESSAGECHAT, 200);
15977 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
15978 rPlayer->GetSession()->SendPacket(&data);
15980 data.Initialize(SMSG_MESSAGECHAT, 200);
15981 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
15982 GetSession()->SendPacket(&data);
15984 else
15986 // announce to player that player he is whispering to is dnd and cannot receive his message
15987 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
15990 if(!isAcceptWhispers())
15992 SetAcceptWhispers(true);
15993 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
15996 // announce to player that player he is whispering to is afk
15997 if(rPlayer->isAFK())
15998 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
16000 // if player whisper someone, auto turn of dnd to be able to receive an answer
16001 if(isDND() && !rPlayer->isGameMaster())
16002 ToggleDND();
16005 void Player::PetSpellInitialize()
16007 Pet* pet = GetPet();
16009 if(!pet)
16010 return;
16012 sLog.outDebug("Pet Spells Groups");
16014 CharmInfo *charmInfo = pet->GetCharmInfo();
16016 WorldPacket data(SMSG_PET_SPELLS, 8+4+4+4+10*4);
16017 data << uint64(pet->GetGUID());
16018 data << uint32(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
16019 data << uint32(0);
16020 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16022 // action bar loop
16023 for(uint32 i = 0; i < 10; i++)
16025 data << uint32(charmInfo->GetActionBarEntry(i)->Raw);
16028 size_t spellsCountPos = data.wpos();
16030 // spells count
16031 uint8 addlist = 0;
16032 data << uint8(addlist); // placeholder
16034 if(pet->isControlled() && ((pet->getPetType() == HUNTER_PET) || ((pet->GetCreatureInfo()->type == CREATURE_TYPE_DEMON) && (getClass() == CLASS_WARLOCK))))
16036 // spells loop
16037 for (PetSpellMap::iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
16039 if(itr->second->state == PETSPELL_REMOVED)
16040 continue;
16042 data << uint16(itr->first);
16043 data << uint16(itr->second->active); // pet spell active state isn't boolean
16044 ++addlist;
16048 data.put<uint8>(spellsCountPos, addlist);
16050 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
16051 data << uint8(cooldownsCount);
16053 time_t curTime = time(NULL);
16055 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
16057 time_t cooldown = 0;
16059 if(itr->second > curTime)
16060 cooldown = (itr->second - curTime) * 1000;
16062 data << uint16(itr->first); // spellid
16063 data << uint16(0); // spell category?
16064 data << uint32(itr->second); // cooldown
16065 data << uint32(0); // category cooldown
16068 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
16070 time_t cooldown = 0;
16072 if(itr->second > curTime)
16073 cooldown = (itr->second - curTime) * 1000;
16075 data << uint16(itr->first); // spellid
16076 data << uint16(0); // spell category?
16077 data << uint32(0); // cooldown
16078 data << uint32(itr->second); // category cooldown
16081 GetSession()->SendPacket(&data);
16084 void Player::PossessSpellInitialize()
16086 Unit* charm = GetCharm();
16088 if(!charm)
16089 return;
16091 CharmInfo *charmInfo = charm->GetCharmInfo();
16093 if(!charmInfo)
16095 sLog.outError("Player::PossessSpellInitialize(): charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16096 return;
16099 uint8 addlist = 0;
16100 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16102 //16
16103 data << uint64(charm->GetGUID());
16104 data << uint32(0x00000000);
16105 data << uint32(0);
16106 data << uint8(0) << uint8(0) << uint16(0);
16108 for(uint32 i = 0; i < 10; i++) //40
16110 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16113 data << uint8(addlist); //1
16115 uint8 count = 0;
16116 data << uint8(count); // cooldowns count
16118 GetSession()->SendPacket(&data);
16121 void Player::CharmSpellInitialize()
16123 Unit* charm = GetCharm();
16125 if(!charm)
16126 return;
16128 CharmInfo *charmInfo = charm->GetCharmInfo();
16129 if(!charmInfo)
16131 sLog.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16132 return;
16135 uint8 addlist = 0;
16137 if(charm->GetTypeId() != TYPEID_PLAYER)
16139 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
16141 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
16143 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16145 if(charmInfo->GetCharmSpell(i)->spellId)
16146 ++addlist;
16151 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16153 data << uint64(charm->GetGUID());
16154 data << uint32(0x00000000);
16155 data << uint32(0);
16156 if(charm->GetTypeId() != TYPEID_PLAYER)
16157 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState());
16158 else
16159 data << uint8(0) << uint8(0);
16160 data << uint16(0);
16162 for(uint32 i = 0; i < 10; i++) //40
16164 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16167 data << uint8(addlist); //1
16169 if(addlist)
16171 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16173 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
16174 if(cspell->spellId)
16176 data << uint16(cspell->spellId);
16177 data << uint16(cspell->active);
16182 uint8 count = 0;
16183 data << uint8(count); // cooldowns count
16185 GetSession()->SendPacket(&data);
16188 int32 Player::GetTotalFlatMods(uint32 spellId, SpellModOp op)
16190 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16191 if (!spellInfo) return 0;
16192 int32 total = 0;
16193 for (SpellModList::iterator itr = m_spellMods[op].begin(); itr != m_spellMods[op].end(); ++itr)
16195 SpellModifier *mod = *itr;
16197 if(!IsAffectedBySpellmod(spellInfo,mod))
16198 continue;
16200 if (mod->type == SPELLMOD_FLAT)
16201 total += mod->value;
16203 return total;
16206 int32 Player::GetTotalPctMods(uint32 spellId, SpellModOp op)
16208 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16209 if (!spellInfo) return 0;
16210 int32 total = 0;
16211 for (SpellModList::iterator itr = m_spellMods[op].begin(); itr != m_spellMods[op].end(); ++itr)
16213 SpellModifier *mod = *itr;
16215 if(!IsAffectedBySpellmod(spellInfo,mod))
16216 continue;
16218 if (mod->type == SPELLMOD_PCT)
16219 total += mod->value;
16221 return total;
16224 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16226 if (!mod || !spellInfo)
16227 return false;
16229 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16231 // prevent apply to any spell except spell that trigger expire
16232 if(spell)
16234 if(mod->lastAffected != spell)
16235 return false;
16237 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16238 return false;
16241 return spellmgr.IsAffectedBySpell(spellInfo,mod->spellId,mod->effectId,mod->mask);
16244 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16246 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16248 for(int eff=0;eff<64;++eff)
16250 uint64 _mask = uint64(1) << eff;
16251 if ( mod->mask & _mask)
16253 int32 val = 0;
16254 for (SpellModList::iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16256 if ((*itr)->type == mod->type && (*itr)->mask & _mask)
16257 val += (*itr)->value;
16259 val += apply ? mod->value : -(mod->value);
16260 WorldPacket data(Opcode, (1+1+4));
16261 data << uint8(eff);
16262 data << uint8(mod->op);
16263 data << int32(val);
16264 SendDirectMessage(&data);
16268 if (apply)
16269 m_spellMods[mod->op].push_back(mod);
16270 else
16272 if (mod->charges == -1)
16273 --m_SpellModRemoveCount;
16274 m_spellMods[mod->op].remove(mod);
16275 delete mod;
16279 void Player::RemoveSpellMods(Spell const* spell)
16281 if(!spell || (m_SpellModRemoveCount == 0))
16282 return;
16284 for(int i=0;i<MAX_SPELLMOD;++i)
16286 for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16288 SpellModifier *mod = *itr;
16289 ++itr;
16291 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16293 RemoveAurasDueToSpell(mod->spellId);
16294 if (m_spellMods[i].empty())
16295 break;
16296 else
16297 itr = m_spellMods[i].begin();
16303 // send Proficiency
16304 void Player::SendProficiency(uint8 pr1, uint32 pr2)
16306 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
16307 data << pr1 << pr2;
16308 GetSession()->SendPacket (&data);
16311 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16313 QueryResult *result = NULL;
16314 if(type==10)
16315 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16316 else
16317 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16318 if(result)
16320 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.
16321 { // and SendPetitionQueryOpcode reads data from the DB
16322 Field *fields = result->Fetch();
16323 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16324 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16326 // send update if charter owner in game
16327 Player* owner = objmgr.GetPlayer(ownerguid);
16328 if(owner)
16329 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16331 } while ( result->NextRow() );
16333 delete result;
16335 if(type==10)
16336 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16337 else
16338 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16341 CharacterDatabase.BeginTransaction();
16342 if(type == 10)
16344 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16345 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16347 else
16349 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16350 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16352 CharacterDatabase.CommitTransaction();
16355 void Player::SetRestBonus (float rest_bonus_new)
16357 // Prevent resting on max level
16358 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16359 rest_bonus_new = 0;
16361 if(rest_bonus_new < 0)
16362 rest_bonus_new = 0;
16364 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16366 if(rest_bonus_new > rest_bonus_max)
16367 m_rest_bonus = rest_bonus_max;
16368 else
16369 m_rest_bonus = rest_bonus_new;
16371 // update data for client
16372 if(m_rest_bonus>10)
16373 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16374 else if(m_rest_bonus<=1)
16375 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16377 //RestTickUpdate
16378 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16381 void Player::HandleStealthedUnitsDetection()
16383 std::list<Unit*> stealthedUnits;
16385 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16386 Cell cell(p);
16387 cell.data.Part.reserved = ALL_DISTRICT;
16388 cell.SetNoCreate();
16390 MaNGOS::AnyStealthedCheck u_check;
16391 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(stealthedUnits, u_check);
16393 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16394 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16396 CellLock<GridReadGuard> cell_lock(cell, p);
16397 cell_lock->Visit(cell_lock, world_unit_searcher, *MapManager::Instance().GetMap(GetMapId(), this));
16398 cell_lock->Visit(cell_lock, grid_unit_searcher, *MapManager::Instance().GetMap(GetMapId(), this));
16400 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
16402 if((*i)==this)
16404 i = stealthedUnits.erase(i);
16405 continue;
16408 if ((*i)->isVisibleForOrDetect(this,true))
16411 (*i)->SendUpdateToPlayer(this);
16412 m_clientGUIDs.insert((*i)->GetGUID());
16414 #ifdef MANGOS_DEBUG
16415 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16416 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
16417 #endif
16419 // target aura duration for caster show only if target exist at caster client
16420 // send data at target visibility change (adding to client)
16421 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
16422 SendAurasForTarget(*i);
16424 i = stealthedUnits.erase(i);
16425 continue;
16428 ++i;
16432 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, uint32 mount_id, Creature* npc)
16434 if(nodes.size() < 2)
16435 return false;
16437 // not let cheating with start flight mounted
16438 if(IsMounted())
16440 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16441 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
16442 GetSession()->SendPacket(&data);
16443 return false;
16446 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16448 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16449 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
16450 GetSession()->SendPacket(&data);
16451 return false;
16454 // 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
16455 if(GetSession()->isLogingOut() ||
16456 (!m_currentSpells[CURRENT_GENERIC_SPELL] ||
16457 m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Effect[0] != SPELL_EFFECT_SEND_TAXI)&&
16458 IsNonMeleeSpellCasted(false) ||
16459 isInCombat())
16461 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16462 data << uint32(ERR_TAXIPLAYERBUSY);
16463 GetSession()->SendPacket(&data);
16464 return false;
16467 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
16468 return false;
16470 uint32 sourcenode = nodes[0];
16472 // starting node too far away (cheat?)
16473 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
16474 if( !node || node->map_id != GetMapId() ||
16475 (node->x - GetPositionX())*(node->x - GetPositionX())+
16476 (node->y - GetPositionY())*(node->y - GetPositionY())+
16477 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
16478 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE) )
16480 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16481 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16482 GetSession()->SendPacket(&data);
16483 return false;
16486 // Prepare to flight start now
16488 // stop combat at start taxi flight if any
16489 CombatStop();
16491 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16492 TradeCancel(true);
16494 // clean not finished taxi path if any
16495 m_taxi.ClearTaxiDestinations();
16497 // 0 element current node
16498 m_taxi.AddTaxiDestination(sourcenode);
16500 // fill destinations path tail
16501 uint32 sourcepath = 0;
16502 uint32 totalcost = 0;
16504 uint32 prevnode = sourcenode;
16505 uint32 lastnode = 0;
16507 for(uint32 i = 1; i < nodes.size(); ++i)
16509 uint32 path, cost;
16511 lastnode = nodes[i];
16512 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
16514 if(!path)
16516 m_taxi.ClearTaxiDestinations();
16517 return false;
16520 totalcost += cost;
16522 if(prevnode == sourcenode)
16523 sourcepath = path;
16525 m_taxi.AddTaxiDestination(lastnode);
16527 prevnode = lastnode;
16530 if(!mount_id) // if not provide then attempt use default.
16531 mount_id = objmgr.GetTaxiMount(sourcenode, GetTeam());
16533 if (mount_id == 0 || sourcepath == 0)
16535 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16536 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16537 GetSession()->SendPacket(&data);
16538 m_taxi.ClearTaxiDestinations();
16539 return false;
16542 uint32 money = GetMoney();
16544 if(npc)
16546 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
16549 if(money < totalcost)
16551 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16552 data << uint32(ERR_TAXINOTENOUGHMONEY);
16553 GetSession()->SendPacket(&data);
16554 m_taxi.ClearTaxiDestinations();
16555 return false;
16558 //Checks and preparations done, DO FLIGHT
16559 ModifyMoney(-(int32)totalcost);
16561 // prevent stealth flight
16562 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
16564 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16565 data << uint32(ERR_TAXIOK);
16566 GetSession()->SendPacket(&data);
16568 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16570 GetSession()->SendDoFlight(mount_id, sourcepath);
16572 return true;
16575 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
16577 // last check 2.0.10
16578 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
16579 data << GetGUID();
16580 data << uint8(0x0); // flags (0x1, 0x2)
16581 time_t curTime = time(NULL);
16582 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
16584 if (itr->second->state == PLAYERSPELL_REMOVED)
16585 continue;
16586 uint32 unSpellId = itr->first;
16587 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
16588 if (!spellInfo)
16590 ASSERT(spellInfo);
16591 continue;
16594 // Not send cooldown for this spells
16595 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
16596 continue;
16598 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
16600 data << unSpellId;
16601 data << unTimeMs; // in m.secs
16602 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/1000);
16605 GetSession()->SendPacket(&data);
16608 void Player::InitDataForForm(bool reapplyMods)
16610 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
16611 if(ssEntry && ssEntry->attackSpeed)
16613 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
16614 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
16615 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
16617 else
16618 SetRegularAttackTime();
16620 switch(m_form)
16622 case FORM_CAT:
16624 if(getPowerType()!=POWER_ENERGY)
16625 setPowerType(POWER_ENERGY);
16626 break;
16628 case FORM_BEAR:
16629 case FORM_DIREBEAR:
16631 if(getPowerType()!=POWER_RAGE)
16632 setPowerType(POWER_RAGE);
16633 break;
16635 default: // 0, for example
16637 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
16638 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
16639 setPowerType(Powers(cEntry->powerType));
16640 break;
16644 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
16645 if (!reapplyMods)
16646 UpdateEquipSpellsAtFormChange();
16648 UpdateAttackPowerAndDamage();
16649 UpdateAttackPowerAndDamage(true);
16652 // Return true is the bought item has a max count to force refresh of window by caller
16653 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
16655 // cheating attempt
16656 if(count < 1) count = 1;
16658 if(!isAlive())
16659 return false;
16661 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
16662 if( !pProto )
16664 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
16665 return false;
16668 Creature *pCreature = ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid,UNIT_NPC_FLAG_VENDOR);
16669 if (!pCreature)
16671 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
16672 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
16673 return false;
16676 VendorItemData const* vItems = pCreature->GetVendorItems();
16677 if(!vItems || vItems->Empty())
16679 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16680 return false;
16683 size_t vendor_slot = vItems->FindItemSlot(item);
16684 if(vendor_slot >= vItems->GetItemCount())
16686 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16687 return false;
16690 VendorItem const* crItem = vItems->m_items[vendor_slot];
16692 // check current item amount if it limited
16693 if( crItem->maxcount != 0 )
16695 if(pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
16697 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
16698 return false;
16702 if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
16704 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
16705 return false;
16708 if(crItem->ExtendedCost)
16710 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16711 if(!iece)
16713 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
16714 return false;
16717 // honor points price
16718 if(GetHonorPoints() < (iece->reqhonorpoints * count))
16720 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
16721 return false;
16724 // arena points price
16725 if(GetArenaPoints() < (iece->reqarenapoints * count))
16727 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
16728 return false;
16731 // item base price
16732 for (uint8 i = 0; i < 5; ++i)
16734 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
16736 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
16737 return false;
16741 // check for personal arena rating requirement
16742 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
16744 // probably not the proper equip err
16745 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
16746 return false;
16750 uint32 price = pProto->BuyPrice * count;
16752 // reputation discount
16753 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
16755 if( GetMoney() < price )
16757 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
16758 return false;
16761 uint8 bag = 0; // init for case invalid bagGUID
16763 if (bagguid != NULL_BAG && slot != NULL_SLOT)
16765 Bag *pBag;
16766 if( bagguid == GetGUID() )
16768 bag = INVENTORY_SLOT_BAG_0;
16770 else
16772 for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;i++)
16774 pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i);
16775 if( pBag )
16777 if( bagguid == pBag->GetGUID() )
16779 bag = i;
16780 break;
16787 if( IsInventoryPos( bag, slot ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
16789 ItemPosCountVec dest;
16790 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
16791 if( msg != EQUIP_ERR_OK )
16793 SendEquipError( msg, NULL, NULL );
16794 return false;
16797 ModifyMoney( -(int32)price );
16798 if(crItem->ExtendedCost) // case for new honor system
16800 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16801 if(iece->reqhonorpoints)
16802 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
16803 if(iece->reqarenapoints)
16804 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
16805 for (uint8 i = 0; i < 5; ++i)
16807 if(iece->reqitem[i])
16808 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
16812 if(Item *it = StoreNewItem( dest, item, true ))
16814 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
16816 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
16817 data << pCreature->GetGUID();
16818 data << (uint32)(vendor_slot+1); // numbered from 1 at client
16819 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
16820 data << (uint32)count;
16821 GetSession()->SendPacket(&data);
16823 SendNewItem(it, pProto->BuyCount*count, true, false, false);
16826 else if( IsEquipmentPos( bag, slot ) )
16828 uint16 dest;
16829 uint8 msg = CanEquipNewItem( slot, dest, item, pProto->BuyCount * count, false );
16830 if( msg != EQUIP_ERR_OK )
16832 SendEquipError( msg, NULL, NULL );
16833 return false;
16836 ModifyMoney( -(int32)price );
16837 if(crItem->ExtendedCost) // case for new honor system
16839 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16840 if(iece->reqhonorpoints)
16841 ModifyHonorPoints( - int32(iece->reqhonorpoints));
16842 if(iece->reqarenapoints)
16843 ModifyArenaPoints( - int32(iece->reqarenapoints));
16844 for (uint8 i = 0; i < 5; ++i)
16846 if(iece->reqitem[i])
16847 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
16851 if(Item *it = EquipNewItem( dest, item, pProto->BuyCount * count, true ))
16853 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
16855 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
16856 data << pCreature->GetGUID();
16857 data << (uint32)(vendor_slot+1); // numbered from 1 at client
16858 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
16859 data << (uint32)count;
16860 GetSession()->SendPacket(&data);
16862 SendNewItem(it, pProto->BuyCount*count, true, false, false);
16864 AutoUnequipOffhandIfNeed();
16867 else
16869 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
16870 return false;
16873 return crItem->maxcount!=0;
16876 uint32 Player::GetMaxPersonalArenaRatingRequirement()
16878 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
16879 // the personal rating of the arena team must match the required limit as well
16880 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
16881 uint32 max_personal_rating = 0;
16882 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
16884 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
16886 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
16887 uint32 t_rating = at->GetRating();
16888 p_rating = p_rating<t_rating? p_rating : t_rating;
16889 if(max_personal_rating < p_rating)
16890 max_personal_rating = p_rating;
16893 return max_personal_rating;
16896 void Player::UpdateHomebindTime(uint32 time)
16898 // GMs never get homebind timer online
16899 if (m_InstanceValid || isGameMaster())
16901 if(m_HomebindTimer) // instance valid, but timer not reset
16903 // hide reminder
16904 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
16905 data << uint32(0);
16906 data << uint32(0);
16907 GetSession()->SendPacket(&data);
16909 // instance is valid, reset homebind timer
16910 m_HomebindTimer = 0;
16912 else if (m_HomebindTimer > 0)
16914 if (time >= m_HomebindTimer)
16916 // teleport to homebind location
16917 TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
16919 else
16920 m_HomebindTimer -= time;
16922 else
16924 // instance is invalid, start homebind timer
16925 m_HomebindTimer = 60000;
16926 // send message to player
16927 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
16928 data << m_HomebindTimer;
16929 data << uint32(1);
16930 GetSession()->SendPacket(&data);
16931 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
16935 void Player::UpdatePvP(bool state, bool ovrride)
16937 if(!state || ovrride)
16939 SetPvP(state);
16940 if(Pet* pet = GetPet())
16941 pet->SetPvP(state);
16942 if(Unit* charmed = GetCharm())
16943 charmed->SetPvP(state);
16945 pvpInfo.endTimer = 0;
16947 else
16949 if(pvpInfo.endTimer != 0)
16950 pvpInfo.endTimer = time(NULL);
16951 else
16953 SetPvP(state);
16955 if(Pet* pet = GetPet())
16956 pet->SetPvP(state);
16957 if(Unit* charmed = GetCharm())
16958 charmed->SetPvP(state);
16963 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
16965 SpellCooldown sc;
16966 sc.end = end_time;
16967 sc.itemid = itemid;
16968 m_spellCooldowns[spellid] = sc;
16971 void Player::SendCooldownEvent(SpellEntry const *spellInfo)
16973 if ( !(spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE) )
16974 return;
16976 // Get spell cooldown
16977 int32 cooldown = GetSpellRecoveryTime(spellInfo);
16978 // Apply spellmods
16979 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, cooldown);
16980 if (cooldown < 0)
16981 cooldown = 0;
16982 // Add cooldown
16983 AddSpellCooldown(spellInfo->Id, 0, time(NULL) + cooldown / 1000);
16984 // Send activate
16985 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
16986 data << spellInfo->Id;
16987 data << GetGUID();
16988 SendDirectMessage(&data);
16990 //slot to be excluded while counting
16991 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
16993 if(!enchantmentcondition)
16994 return true;
16996 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
16998 if(!Condition)
16999 return true;
17001 uint8 curcount[4] = {0, 0, 0, 0};
17003 //counting current equipped gem colors
17004 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
17006 if(i == slot)
17007 continue;
17008 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
17009 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
17011 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17013 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17014 if(!enchant_id)
17015 continue;
17017 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17018 if(!enchantEntry)
17019 continue;
17021 uint32 gemid = enchantEntry->GemID;
17022 if(!gemid)
17023 continue;
17025 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
17026 if(!gemProto)
17027 continue;
17029 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
17030 if(!gemProperty)
17031 continue;
17033 uint8 GemColor = gemProperty->color;
17035 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
17037 if(tmpcolormask & GemColor)
17038 ++curcount[b];
17044 bool activate = true;
17046 for(int i = 0; i < 5; i++)
17048 if(!Condition->Color[i])
17049 continue;
17051 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
17053 // if have <CompareColor> use them as count, else use <value> from Condition
17054 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
17056 switch(Condition->Comparator[i])
17058 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17059 activate &= (_cur_gem < _cmp_gem) ? true : false;
17060 break;
17061 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17062 activate &= (_cur_gem > _cmp_gem) ? true : false;
17063 break;
17064 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17065 activate &= (_cur_gem >= _cmp_gem) ? true : false;
17066 break;
17070 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");
17072 return activate;
17075 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
17077 //cycle all equipped items
17078 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17080 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17081 if(slot == exceptslot)
17082 continue;
17084 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17086 if(!pItem || !pItem->GetProto()->Socket[0].Color)
17087 continue;
17089 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17091 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17092 if(!enchant_id)
17093 continue;
17095 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17096 if(!enchantEntry)
17097 continue;
17099 uint32 condition = enchantEntry->EnchantmentCondition;
17100 if(condition)
17102 //was enchant active with/without item?
17103 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
17104 //should it now be?
17105 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
17107 // ignore item gem conditions
17108 //if state changed, (dis)apply enchant
17109 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
17116 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17117 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
17119 //cycle all equipped items
17120 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17122 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17123 if(slot == exceptslot)
17124 continue;
17126 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17128 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
17129 continue;
17131 //cycle all (gem)enchants
17132 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17134 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17135 if(!enchant_id) //if no enchant go to next enchant(slot)
17136 continue;
17138 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17139 if(!enchantEntry)
17140 continue;
17142 //only metagems to be (de)activated, so only enchants with condition
17143 uint32 condition = enchantEntry->EnchantmentCondition;
17144 if(condition)
17145 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
17150 void Player::LeaveBattleground(bool teleportToEntryPoint)
17152 if(BattleGround *bg = GetBattleGround())
17154 bool need_debuf = bg->isBattleGround() && (bg->GetStatus() == STATUS_IN_PROGRESS) && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER);
17156 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
17158 // call after remove to be sure that player resurrected for correct cast
17159 if(need_debuf)
17160 CastSpell(this, 26013, true); // Deserter
17164 bool Player::CanJoinToBattleground() const
17166 // check Deserter debuff
17167 if(GetDummyAura(26013))
17168 return false;
17170 return true;
17173 bool Player::CanReportAfkDueToLimit()
17175 // a player can complain about 15 people per 5 minutes
17176 if(m_bgAfkReportedCount >= 15)
17177 return false;
17178 ++m_bgAfkReportedCount;
17179 return true;
17182 ///This player has been blamed to be inactive in a battleground
17183 void Player::ReportedAfkBy(Player* reporter)
17185 BattleGround *bg = GetBattleGround();
17186 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
17187 return;
17189 // check if player has 'Idle' or 'Inactive' debuff
17190 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
17192 m_bgAfkReporter.insert(reporter->GetGUIDLow());
17193 // 3 players have to complain to apply debuff
17194 if(m_bgAfkReporter.size() >= 3)
17196 // cast 'Idle' spell
17197 CastSpell(this, 43680, true);
17198 m_bgAfkReporter.clear();
17203 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
17205 // gamemaster in GM mode see all, including ghosts
17206 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
17207 return true;
17209 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17210 if (InBattleGround())
17212 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
17213 return false;
17214 return true;
17217 // Live player see live player or dead player with not realized corpse
17218 if(pl->isAlive() || pl->m_deathTimer > 0)
17220 return isAlive() || m_deathTimer > 0;
17223 // Ghost see other friendly ghosts, that's for sure
17224 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
17225 return true;
17227 // Dead player see live players near own corpse
17228 if(isAlive())
17230 Corpse *corpse = pl->GetCorpse();
17231 if(corpse)
17233 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17234 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
17235 return true;
17239 // and not see any other
17240 return false;
17243 bool Player::IsVisibleGloballyFor( Player* u ) const
17245 if(!u)
17246 return false;
17248 // Always can see self
17249 if (u==this)
17250 return true;
17252 // Visible units, always are visible for all players
17253 if (GetVisibility() == VISIBILITY_ON)
17254 return true;
17256 // GMs are visible for higher gms (or players are visible for gms)
17257 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
17258 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
17260 // non faction visibility non-breakable for non-GMs
17261 if (GetVisibility() == VISIBILITY_OFF)
17262 return false;
17264 // non-gm stealth/invisibility not hide from global player lists
17265 return true;
17268 void Player::UpdateVisibilityOf(WorldObject* target)
17270 if(HaveAtClient(target))
17272 if(!target->isVisibleForInState(this,true))
17274 target->DestroyForPlayer(this);
17275 m_clientGUIDs.erase(target->GetGUID());
17277 #ifdef MANGOS_DEBUG
17278 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17279 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17280 #endif
17283 else
17285 if(target->isVisibleForInState(this,false))
17287 target->SendUpdateToPlayer(this);
17288 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
17289 m_clientGUIDs.insert(target->GetGUID());
17291 #ifdef MANGOS_DEBUG
17292 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17293 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17294 #endif
17296 // target aura duration for caster show only if target exist at caster client
17297 // send data at target visibility change (adding to client)
17298 if(target!=this && target->isType(TYPEMASK_UNIT))
17299 SendAurasForTarget((Unit*)target);
17301 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
17302 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17307 template<class T>
17308 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
17310 s64.insert(target->GetGUID());
17313 template<>
17314 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
17316 if(!target->IsTransport())
17317 s64.insert(target->GetGUID());
17320 template<class T>
17321 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
17323 if(HaveAtClient(target))
17325 if(!target->isVisibleForInState(this,true))
17327 target->BuildOutOfRangeUpdateBlock(&data);
17328 m_clientGUIDs.erase(target->GetGUID());
17330 #ifdef MANGOS_DEBUG
17331 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17332 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));
17333 #endif
17336 else
17338 if(target->isVisibleForInState(this,false))
17340 visibleNow.insert(target);
17341 target->BuildUpdate(data_updates);
17342 target->BuildCreateUpdateBlockForPlayer(&data, this);
17343 UpdateVisibilityOf_helper(m_clientGUIDs,target);
17345 #ifdef MANGOS_DEBUG
17346 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17347 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));
17348 #endif
17353 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17354 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17355 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17356 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17357 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17359 void Player::InitPrimaryProffesions()
17361 SetFreePrimaryProffesions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
17364 void Player::SendComboPoints()
17366 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
17367 if (combotarget)
17369 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
17370 data.append(combotarget->GetPackGUID());
17371 data << uint8(m_comboPoints);
17372 GetSession()->SendPacket(&data);
17376 void Player::AddComboPoints(Unit* target, int8 count)
17378 if(!count)
17379 return;
17381 // without combo points lost (duration checked in aura)
17382 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17384 if(target->GetGUID() == m_comboTarget)
17386 m_comboPoints += count;
17388 else
17390 if(m_comboTarget)
17391 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17392 target->RemoveComboPointHolder(GetGUIDLow());
17394 m_comboTarget = target->GetGUID();
17395 m_comboPoints = count;
17397 target->AddComboPointHolder(GetGUIDLow());
17400 if (m_comboPoints > 5) m_comboPoints = 5;
17401 if (m_comboPoints < 0) m_comboPoints = 0;
17403 SendComboPoints();
17406 void Player::ClearComboPoints()
17408 if(!m_comboTarget)
17409 return;
17411 // without combopoints lost (duration checked in aura)
17412 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17414 m_comboPoints = 0;
17416 SendComboPoints();
17418 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17419 target->RemoveComboPointHolder(GetGUIDLow());
17421 m_comboTarget = 0;
17424 void Player::SetGroup(Group *group, int8 subgroup)
17426 if(group == NULL) m_group.unlink();
17427 else
17429 // never use SetGroup without a subgroup unless you specify NULL for group
17430 assert(subgroup >= 0);
17431 m_group.link(group, this);
17432 m_group.setSubGroup((uint8)subgroup);
17436 void Player::SendInitialPacketsBeforeAddToMap()
17438 WorldPacket data(SMSG_SET_REST_START_OBSOLETE, 4);
17439 data << uint32(0); // unknown, may be rest state time or experience
17440 GetSession()->SendPacket(&data);
17442 // Homebind
17443 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
17444 data << m_homebindX << m_homebindY << m_homebindZ;
17445 data << (uint32) m_homebindMapId;
17446 data << (uint32) m_homebindZoneId;
17447 GetSession()->SendPacket(&data);
17449 // SMSG_SET_PROFICIENCY
17450 // SMSG_UPDATE_AURA_DURATION
17452 // tutorial stuff
17453 data.Initialize(SMSG_TUTORIAL_FLAGS, 8*4);
17454 for (int i = 0; i < 8; ++i)
17455 data << uint32( GetTutorialInt(i) );
17456 GetSession()->SendPacket(&data);
17458 SendInitialSpells();
17460 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
17461 data << uint32(0); // count, for(count) uint32;
17462 GetSession()->SendPacket(&data);
17464 SendInitialActionButtons();
17465 SendInitialReputations();
17466 m_achievementMgr.SendAllAchievementData();
17467 UpdateZone(GetZoneId());
17468 SendInitWorldStates();
17470 // SMSG_SET_AURA_SINGLE
17472 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
17473 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
17474 data << (float)0.01666667f; // game speed
17475 GetSession()->SendPacket( &data );
17477 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17478 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
17479 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2);
17482 void Player::SendInitialPacketsAfterAddToMap()
17484 CastSpell(this, 836, true); // LOGINEFFECT
17486 // set some aura effects that send packet to player client after add player to map
17487 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17488 // same auras state lost at far teleport, send it one more time in this case also
17489 static const AuraType auratypes[] =
17491 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
17492 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
17493 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
17495 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
17497 Unit::AuraList const& auraList = GetAurasByType(*itr);
17498 if(!auraList.empty())
17499 auraList.front()->ApplyModifier(true,true);
17502 if(HasAuraType(SPELL_AURA_MOD_STUN))
17503 SetMovement(MOVE_ROOT);
17505 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17506 if(HasAuraType(SPELL_AURA_MOD_ROOT))
17508 WorldPacket data(SMSG_FORCE_MOVE_ROOT, 10);
17509 data.append(GetPackGUID());
17510 data << (uint32)2;
17511 SendMessageToSet(&data,true);
17514 SendAurasForTarget(this);
17515 SendEnchantmentDurations(); // must be after add to map
17516 SendItemDurations(); // must be after add to map
17519 void Player::SendUpdateToOutOfRangeGroupMembers()
17521 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
17522 return;
17523 if(Group* group = GetGroup())
17524 group->UpdatePlayerOutOfRange(this);
17526 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
17527 m_auraUpdateMask = 0;
17528 if(Pet *pet = GetPet())
17529 pet->ResetAuraUpdateMask();
17532 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
17534 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
17535 data << uint32(mapid);
17536 data << uint8(reason); // transfer abort reason
17537 switch(reason)
17539 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
17540 case TRANSFER_ABORT_DIFFICULTY:
17541 case TRANSFER_ABORT_UNIQUE_MESSAGE:
17542 data << uint8(arg);
17543 break;
17545 GetSession()->SendPacket(&data);
17548 void Player::SendInstanceResetWarning(uint32 mapid, uint32 time)
17550 // type of warning, based on the time remaining until reset
17551 uint32 type;
17552 if(time > 3600)
17553 type = RAID_INSTANCE_WELCOME;
17554 else if(time > 900 && time <= 3600)
17555 type = RAID_INSTANCE_WARNING_HOURS;
17556 else if(time > 300 && time <= 900)
17557 type = RAID_INSTANCE_WARNING_MIN;
17558 else
17559 type = RAID_INSTANCE_WARNING_MIN_SOON;
17560 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4);
17561 data << uint32(type);
17562 data << uint32(mapid);
17563 data << uint32(time);
17564 GetSession()->SendPacket(&data);
17567 void Player::ApplyEquipCooldown( Item * pItem )
17569 for(int i = 0; i <5; ++i)
17571 _Spell const& spellData = pItem->GetProto()->Spells[i];
17573 // no spell
17574 if( !spellData.SpellId )
17575 continue;
17577 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
17578 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
17579 continue;
17581 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
17583 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
17584 data << pItem->GetGUID();
17585 data << uint32(spellData.SpellId);
17586 GetSession()->SendPacket(&data);
17590 void Player::resetSpells()
17592 // not need after this call
17593 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
17595 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_SPELLS;
17596 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS), GetGUIDLow());
17599 // make full copy of map (spells removed and marked as deleted at another spell remove
17600 // and we can't use original map for safe iterative with visit each spell at loop end
17601 PlayerSpellMap smap = GetSpellMap();
17603 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
17604 removeSpell(iter->first); // only iter->first can be accessed, object by iter->second can be deleted already
17606 learnDefaultSpells();
17607 learnQuestRewardedSpells();
17610 void Player::learnDefaultSpells(bool loading)
17612 // learn default race/class spells
17613 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
17614 std::list<CreateSpellPair>::const_iterator spell_itr;
17615 for (spell_itr = info->spell.begin(); spell_itr!=info->spell.end(); ++spell_itr)
17617 uint16 tspell = spell_itr->first;
17618 if (tspell)
17620 sLog.outDebug("PLAYER: Adding initial spell, id = %u",tspell);
17621 if(loading || !spell_itr->second) // not care about passive spells or loading case
17622 addSpell(tspell,spell_itr->second);
17623 else // but send in normal spell in game learn case
17624 learnSpell(tspell);
17629 void Player::learnQuestRewardedSpells(Quest const* quest)
17631 uint32 spell_id = quest->GetRewSpellCast();
17633 // skip quests without rewarded spell
17634 if( !spell_id )
17635 return;
17637 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
17638 if(!spellInfo)
17639 return;
17641 // check learned spells state
17642 bool found = false;
17643 for(int i=0; i < 3; ++i)
17645 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
17647 found = true;
17648 break;
17652 // skip quests with not teaching spell or already known spell
17653 if(!found)
17654 return;
17656 // prevent learn non first rank unknown profession and second specialization for same profession)
17657 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
17658 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
17660 // not have first rank learned (unlearned prof?)
17661 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
17662 if( !HasSpell(first_spell) )
17663 return;
17665 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
17666 if(!learnedInfo)
17667 return;
17669 // specialization
17670 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
17672 // search other specialization for same prof
17673 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17675 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
17676 continue;
17678 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
17679 if(!itrInfo)
17680 return;
17682 // compare only specializations
17683 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
17684 continue;
17686 // compare same chain spells
17687 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
17688 continue;
17690 // now we have 2 specialization, learn possible only if found is lesser specialization rank
17691 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
17692 return;
17697 CastSpell( this, spell_id, true);
17700 void Player::learnQuestRewardedSpells()
17702 // learn spells received from quest completing
17703 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
17705 // skip no rewarded quests
17706 if(!itr->second.m_rewarded)
17707 continue;
17709 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
17710 if( !quest )
17711 continue;
17713 learnQuestRewardedSpells(quest);
17717 void Player::learnSkillRewardedSpells(uint32 skill_id )
17719 uint32 raceMask = getRaceMask();
17720 uint32 classMask = getClassMask();
17721 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
17723 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
17724 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
17725 continue;
17726 // Check race if set
17727 if (pAbility->racemask && !(pAbility->racemask & raceMask))
17728 continue;
17729 // Check class if set
17730 if (pAbility->classmask && !(pAbility->classmask & classMask))
17731 continue;
17733 if (sSpellStore.LookupEntry(pAbility->spellId))
17735 // Ok need learn spell
17736 learnSpell(pAbility->spellId);
17741 void Player::learnSkillRewardedSpells()
17743 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
17745 if(!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
17746 continue;
17748 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
17750 learnSkillRewardedSpells(pskill);
17754 void Player::SendAurasForTarget(Unit *target)
17756 WorldPacket data(SMSG_AURA_UPDATE_ALL);
17757 data.append(target->GetPackGUID());
17759 for(Unit::AuraMap::const_iterator itr = target->GetAuras().begin(); itr != target->GetAuras().end(); ++itr)
17761 Aura* aura = itr->second;
17762 if(aura->GetAuraSlot() >= MAX_AURAS || aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
17763 continue;
17765 data << uint8(aura->GetAuraSlot());
17766 data << uint32(aura->GetId());
17768 if(aura->GetId())
17770 uint8 auraFlags = aura->GetAuraFlags();
17771 data << uint8(auraFlags); // flags
17772 data << uint8(aura->GetAuraLevel()); // level
17773 data << uint8(aura->m_procCharges); // charges
17775 /*if(!(auraFlags & AFLAG_NOT_GUID))
17777 data << uint8(0) // packed GUID of someone (caster?)
17780 if(auraFlags & AFLAG_DURATION) // include aura duration
17782 data << uint32(aura->GetAuraMaxDuration());
17783 data << uint32(aura->GetAuraDuration());
17788 GetSession()->SendPacket(&data);
17791 void Player::SetDailyQuestStatus( uint32 quest_id )
17793 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
17795 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
17797 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
17798 m_lastDailyQuestTime = time(NULL); // last daily quest time
17799 m_DailyQuestChanged = true;
17800 break;
17805 void Player::ResetDailyQuestStatus()
17807 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
17808 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
17810 // DB data deleted in caller
17811 m_DailyQuestChanged = false;
17812 m_lastDailyQuestTime = 0;
17815 BattleGround* Player::GetBattleGround() const
17817 if(GetBattleGroundId()==0)
17818 return NULL;
17820 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
17823 bool Player::InArena() const
17825 BattleGround *bg = GetBattleGround();
17826 if(!bg || !bg->isArena())
17827 return false;
17829 return true;
17832 bool Player::GetBGAccessByLevel(uint32 bgTypeId) const
17834 BattleGround *bg = sBattleGroundMgr.GetBattleGround(bgTypeId);
17835 if(!bg)
17836 return false;
17838 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
17839 return false;
17841 return true;
17844 uint32 Player::GetMinLevelForBattleGroundQueueId(uint32 queue_id)
17846 if(queue_id < 1)
17847 return 0;
17849 if(queue_id >=6)
17850 queue_id = 6;
17852 return 10*(queue_id+1);
17855 uint32 Player::GetMaxLevelForBattleGroundQueueId(uint32 queue_id)
17857 if(queue_id >=6)
17858 return 255; // hardcoded max level
17860 return 10*(queue_id+2)-1;
17863 uint32 Player::GetBattleGroundQueueIdFromLevel() const
17865 uint32 level = getLevel();
17866 if(level <= 19)
17867 return 0;
17868 else if (level > 69)
17869 return 6;
17870 else
17871 return level/10 - 1; // 20..29 -> 1, 30-39 -> 2, ...
17874 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
17876 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
17877 if(!vendor_faction)
17878 return 1.0f;
17880 ReputationRank rank = GetReputationRank(vendor_faction->faction);
17881 if(rank <= REP_NEUTRAL)
17882 return 1.0f;
17884 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
17887 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
17889 uint32 racemask = getRaceMask();
17890 uint32 classmask = getClassMask();
17892 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
17893 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
17895 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
17897 // skip wrong race skills
17898 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
17899 return false;
17901 // skip wrong class skills
17902 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
17903 return false;
17905 return true;
17908 bool Player::HasQuestForGO(int32 GOId)
17910 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
17912 QuestStatusData qs=i->second;
17913 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
17915 Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
17916 if(!qinfo)
17917 continue;
17919 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
17920 continue;
17922 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
17924 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
17925 continue;
17927 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
17928 return true;
17932 return false;
17935 void Player::UpdateForQuestsGO()
17937 if(m_clientGUIDs.empty())
17938 return;
17940 UpdateData udata;
17941 WorldPacket packet;
17942 for(ClientGUIDs::iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
17944 if(IS_GAMEOBJECT_GUID(*itr))
17946 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
17947 if(obj)
17948 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
17951 udata.BuildPacket(&packet);
17952 GetSession()->SendPacket(&packet);
17955 void Player::SummonIfPossible(bool agree)
17957 if(!agree)
17959 m_summon_expire = 0;
17960 return;
17963 // expire and auto declined
17964 if(m_summon_expire < time(NULL))
17965 return;
17967 // stop taxi flight at summon
17968 if(isInFlight())
17970 GetMotionMaster()->MovementExpired();
17971 m_taxi.ClearTaxiDestinations();
17974 // drop flag at summon
17975 if(BattleGround *bg = GetBattleGround())
17976 bg->EventPlayerDroppedFlag(this);
17978 m_summon_expire = 0;
17980 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
17983 void Player::RemoveItemDurations( Item *item )
17985 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
17987 if(*itr==item)
17989 m_itemDuration.erase(itr);
17990 break;
17995 void Player::AddItemDurations( Item *item )
17997 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
17999 m_itemDuration.push_back(item);
18000 item->SendTimeUpdate(this);
18004 void Player::AutoUnequipOffhandIfNeed()
18006 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
18007 if(!offItem)
18008 return;
18010 Item *mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );
18012 if(!mainItem || mainItem->GetProto()->InventoryType != INVTYPE_2HWEAPON)
18013 return;
18015 ItemPosCountVec off_dest;
18016 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
18017 if( off_msg == EQUIP_ERR_OK )
18019 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18020 StoreItem( off_dest, offItem, true );
18022 else
18024 sLog.outError("Player::EquipItem: Can's store offhand item at 2hand item equip for player (GUID: %u).",GetGUIDLow());
18028 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
18030 if(spellInfo->EquippedItemClass < 0)
18031 return true;
18033 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18034 // for optimize check 2 used cases only
18035 switch(spellInfo->EquippedItemClass)
18037 case ITEM_CLASS_WEAPON:
18039 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
18040 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18041 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18042 return true;
18043 break;
18045 case ITEM_CLASS_ARMOR:
18047 // tabard not have dependent spells
18048 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
18049 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18050 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18051 return true;
18053 // shields can be equipped to offhand slot
18054 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
18055 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18056 return true;
18058 // ranged slot can have some armor subclasses
18059 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
18060 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18061 return true;
18063 break;
18065 default:
18066 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
18067 break;
18070 return false;
18073 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
18075 AuraMap& auras = GetAuras();
18076 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
18078 Aura* aura = itr->second;
18080 // skip passive (passive item dependent spells work in another way) and not self applied auras
18081 SpellEntry const* spellInfo = aura->GetSpellProto();
18082 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
18084 ++itr;
18085 continue;
18088 // skip if not item dependent or have alternative item
18089 if(HasItemFitToSpellReqirements(spellInfo,pItem))
18091 ++itr;
18092 continue;
18095 // no alt item, remove aura, restart check
18096 RemoveAurasDueToSpell(aura->GetId());
18097 itr = auras.begin();
18100 // currently casted spells can be dependent from item
18101 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
18103 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
18104 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
18105 InterruptSpell(i);
18109 uint32 Player::GetResurrectionSpellId()
18111 // search priceless resurrection possibilities
18112 uint32 prio = 0;
18113 uint32 spell_id = 0;
18114 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
18115 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
18117 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18118 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
18120 switch((*itr)->GetId())
18122 case 20707: spell_id = 3026; break; // rank 1
18123 case 20762: spell_id = 20758; break; // rank 2
18124 case 20763: spell_id = 20759; break; // rank 3
18125 case 20764: spell_id = 20760; break; // rank 4
18126 case 20765: spell_id = 20761; break; // rank 5
18127 case 27239: spell_id = 27240; break; // rank 6
18128 default:
18129 sLog.outError("Unhandled spell %%u: S.Resurrection",(*itr)->GetId());
18130 continue;
18133 prio = 3;
18135 // Twisting Nether // prio: 2 (max)
18136 else if((*itr)->GetId()==23701 && roll_chance_i(10))
18138 prio = 2;
18139 spell_id = 23700;
18143 // Reincarnation (passive spell) // prio: 1
18144 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18145 spell_id = 21169;
18147 return spell_id;
18150 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
18152 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
18154 // prepare data for near group iteration (PvP and !PvP cases)
18155 uint32 xp = 0;
18156 bool honored_kill = false;
18158 if(Group *pGroup = GetGroup())
18160 uint32 count = 0;
18161 uint32 sum_level = 0;
18162 Player* member_with_max_level = NULL;
18163 Player* not_gray_member_with_max_level = NULL;
18165 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
18167 if(member_with_max_level)
18169 /// not get Xp in PvP or no not gray players in group
18170 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
18172 /// skip in check PvP case (for speed, not used)
18173 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
18174 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
18175 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
18177 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18179 Player* pGroupGuy = itr->getSource();
18180 if(!pGroupGuy)
18181 continue;
18183 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
18184 continue; // member (alive or dead) or his corpse at req. distance
18186 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18187 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
18188 honored_kill = true;
18190 // xp and reputation only in !PvP case
18191 if(!PvP)
18193 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
18195 // if is in dungeon then all receive full reputation at kill
18196 // rewarded any alive/dead/near_corpse group member
18197 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
18199 // XP updated only for alive group member
18200 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
18201 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
18203 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
18205 pGroupGuy->GiveXP(itr_xp, pVictim);
18206 if(Pet* pet = pGroupGuy->GetPet())
18207 pet->GivePetXP(itr_xp/2);
18210 // quest objectives updated only for alive group member or dead but with not released body
18211 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18213 // normal creature (not pet/etc) can be only in !PvP case
18214 if(pVictim->GetTypeId()==TYPEID_UNIT)
18215 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
18221 else // if (!pGroup)
18223 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
18225 // honor can be in PvP and !PvP (racial leader) cases
18226 if(RewardHonor(pVictim,1))
18227 honored_kill = true;
18229 // xp and reputation only in !PvP case
18230 if(!PvP)
18232 RewardReputation(pVictim,1);
18233 GiveXP(xp, pVictim);
18235 if(Pet* pet = GetPet())
18236 pet->GivePetXP(xp);
18238 // normal creature (not pet/etc) can be only in !PvP case
18239 if(pVictim->GetTypeId()==TYPEID_UNIT)
18240 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
18243 return xp || honored_kill;
18246 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
18248 if(pRewardSource->GetDistance(this) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
18249 return true;
18251 if(isAlive())
18252 return false;
18254 Corpse* corpse = GetCorpse();
18255 if(!corpse)
18256 return false;
18258 return pRewardSource->GetDistance(corpse) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE);
18261 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
18263 Item* item = GetWeaponForAttack(attType,true);
18265 // unarmed only with base attack
18266 if(attType != BASE_ATTACK && !item)
18267 return 0;
18269 // weapon skill or (unarmed for base attack)
18270 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
18271 return GetBaseSkillValue(skill);
18274 void Player::ResurectUsingRequestData()
18276 ResurrectPlayer(0.0f,false);
18278 if(GetMaxHealth() > m_resurrectHealth)
18279 SetHealth( m_resurrectHealth );
18280 else
18281 SetHealth( GetMaxHealth() );
18283 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
18284 SetPower(POWER_MANA, m_resurrectMana );
18285 else
18286 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
18288 SetPower(POWER_RAGE, 0 );
18290 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
18292 SpawnCorpseBones();
18294 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
18297 void Player::SetClientControl(Unit* target, uint8 allowMove)
18299 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
18300 data.append(target->GetPackGUID());
18301 data << uint8(allowMove);
18302 GetSession()->SendPacket(&data);
18305 void Player::UpdateZoneDependentAuras( uint32 newZone )
18307 // remove new continent flight forms
18308 if( !isGameMaster() &&
18309 GetVirtualMapForMapAndZone(GetMapId(),newZone) != 530)
18311 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
18312 RemoveSpellsCausingAura(SPELL_AURA_FLY);
18315 // Some spells applied at enter into zone (with subzones)
18316 // Human Illusion
18317 // NOTE: these are removed by RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
18318 if ( newZone == 2367 ) // Old Hillsbrad Foothills
18320 uint32 spellid = 0;
18321 // all horde races
18322 if( GetTeam() == HORDE )
18323 spellid = getGender() == GENDER_FEMALE ? 35481 : 35480;
18324 // and some alliance races
18325 else if( getRace() == RACE_NIGHTELF || getRace() == RACE_DRAENEI )
18326 spellid = getGender() == GENDER_FEMALE ? 35483 : 35482;
18328 if(spellid && !HasAura(spellid,0) )
18329 CastSpell(this,spellid,true);
18333 void Player::UpdateAreaDependentAuras( uint32 newArea )
18335 // remove auras from spells with area limitations
18336 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
18338 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18339 if(!IsSpellAllowedInLocation(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea))
18340 RemoveAura(iter);
18341 else
18342 ++iter;
18345 // unmount if enter in this subzone
18346 if( newArea == 35)
18347 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
18348 // Dragonmaw Illusion
18349 else if( newArea == 3759 || newArea == 3966 || newArea == 3939 )
18351 if( GetDummyAura(40214) )
18353 if( !HasAura(40216,0) )
18354 CastSpell(this,40216,true);
18355 if( !HasAura(42016,0) )
18356 CastSpell(this,42016,true);
18361 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
18363 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18364 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18366 return copseReclaimDelay[0];
18369 time_t now = time(NULL);
18370 // 0..2 full period
18371 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
18372 return copseReclaimDelay[count];
18375 void Player::UpdateCorpseReclaimDelay()
18377 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
18379 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18380 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18381 return;
18383 time_t now = time(NULL);
18384 if(now < m_deathExpireTime)
18386 // full and partly periods 1..3
18387 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
18388 if(count < MAX_DEATH_COUNT)
18389 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
18390 else
18391 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
18393 else
18394 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
18397 void Player::SendCorpseReclaimDelay(bool load)
18399 Corpse* corpse = GetCorpse();
18400 if(!corpse)
18401 return;
18403 uint32 delay;
18404 if(load)
18406 if(corpse->GetGhostTime() > m_deathExpireTime)
18407 return;
18409 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
18411 uint32 count;
18412 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18413 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18415 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
18416 if(count>=MAX_DEATH_COUNT)
18417 count = MAX_DEATH_COUNT-1;
18419 else
18420 count=0;
18422 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
18424 time_t now = time(NULL);
18425 if(now >= expected_time)
18426 return;
18428 delay = expected_time-now;
18430 else
18431 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
18433 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
18434 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
18435 data << uint32(delay*1000);
18436 GetSession()->SendPacket( &data );
18439 Player* Player::GetNextRandomRaidMember(float radius)
18441 Group *pGroup = GetGroup();
18442 if(!pGroup)
18443 return NULL;
18445 std::vector<Player*> nearMembers;
18446 nearMembers.reserve(pGroup->GetMembersCount());
18448 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18450 Player* Target = itr->getSource();
18452 // IsHostileTo check duel and controlled by enemy
18453 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
18454 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
18455 nearMembers.push_back(Target);
18458 if (nearMembers.empty())
18459 return NULL;
18461 uint32 randTarget = urand(0,nearMembers.size()-1);
18462 return nearMembers[randTarget];
18465 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
18467 float water_z = m->GetWaterLevel(x,y);
18468 float height_z = m->GetHeight(x,y,z, false); // use .map base surface height
18469 uint8 flag1 = m->GetTerrainType(x,y);
18471 //!Underwater check, not in water if underground or above water level
18472 if (height_z <= INVALID_HEIGHT || z < (height_z-2) || z > (water_z - 2) )
18473 m_isunderwater &= 0x7A;
18474 else if ((z < (water_z - 2)) && (flag1 & 0x01))
18475 m_isunderwater |= 0x01;
18477 //!in lava check, anywhere under lava level
18478 if ((height_z <= INVALID_HEIGHT || z < (height_z - 0)) && (flag1 == 0x00) && IsInWater())
18479 m_isunderwater |= 0x80;
18482 void Player::SetCanParry( bool value )
18484 if(m_canParry==value)
18485 return;
18487 m_canParry = value;
18488 UpdateParryPercentage();
18491 void Player::SetCanBlock( bool value )
18493 if(m_canBlock==value)
18494 return;
18496 m_canBlock = value;
18497 UpdateBlockPercentage();
18500 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
18502 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
18503 if(itr->pos == pos)
18504 return true;
18506 return false;
18509 bool Player::isAllowUseBattleGroundObject()
18511 return ( //InBattleGround() && // in battleground - not need, check in other cases
18512 !IsMounted() && // not mounted
18513 !HasStealthAura() && // not stealthed
18514 !HasInvisibilityAura() && // not invisible
18515 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
18516 isAlive() // live player
18520 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
18522 uint32 level = getLevel();
18524 if(level > sGtBarberShopCostBaseStore.GetNumRows())
18525 level = GT_MAX_LEVEL; // max level in this dbc
18527 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
18528 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
18529 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
18531 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
18532 return 0;
18534 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
18536 if(!bsc) // shouldn't happen
18537 return 0xFFFFFFFF;
18539 float cost = 0;
18541 if(hairstyle != newhairstyle)
18542 cost += bsc->cost; // full price
18544 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
18545 cost += bsc->cost * 0.5f; // +1/2 of price
18547 if(facialhair != newfacialhair)
18548 cost += bsc->cost * 0.75f; // +3/4 of price
18550 return uint32(cost);
18553 void Player::InitGlyphsForLevel()
18555 uint32 level = getLevel();
18556 uint32 value = 0;
18558 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
18559 if(level >= 15)
18560 value |= (0x01 | 0x02);
18561 if(level >= 30)
18562 value |= 0x04;
18563 if(level >= 50)
18564 value |= 0x08;
18565 if(level >= 70)
18566 value |= 0x10;
18567 if(level >= 80)
18568 value |= 0x20;
18570 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);