Character re-customization fix
[getmangos.git] / src / game / Player.cpp
blobe784962463e42f708efb34f01d6f34f9ede9e371
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( const 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_mover = NULL;
428 m_miniPet = 0;
429 m_bgAfkReportedTimer = 0;
430 m_contestedPvPTimer = 0;
432 m_declinedname = NULL;
433 m_runes = NULL;
436 Player::~Player ()
438 CleanupsBeforeDelete();
440 // it must be unloaded already in PlayerLogout and accessed only for loggined player
441 //m_social = NULL;
443 // Note: buy back item already deleted from DB when player was saved
444 for(int i = 0; i < PLAYER_SLOTS_COUNT; ++i)
446 if(m_items[i])
447 delete m_items[i];
449 CleanupChannels();
451 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
452 delete itr->second;
454 //all mailed items should be deleted, also all mail should be deallocated
455 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
456 delete *itr;
458 for (ItemMap::iterator iter = mMitems.begin(); iter != mMitems.end(); ++iter)
459 delete iter->second; //if item is duplicated... then server may crash ... but that item should be deallocated
461 delete PlayerTalkClass;
463 if (m_transport)
465 m_transport->RemovePassenger(this);
468 for(size_t x = 0; x < ItemSetEff.size(); x++)
469 if(ItemSetEff[x])
470 delete ItemSetEff[x];
472 // clean up player-instance binds, may unload some instance saves
473 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
474 for(BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
475 itr->second.save->RemovePlayer(this);
477 delete m_declinedname;
478 delete m_runes;
481 void Player::CleanupsBeforeDelete()
483 if(m_uint32Values) // only for fully created Object
485 TradeCancel(false);
486 DuelComplete(DUEL_INTERUPTED);
488 Unit::CleanupsBeforeDelete();
491 bool Player::Create( uint32 guidlow, const std::string& name, uint8 race, uint8 class_, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair, uint8 outfitId )
493 //FIXME: outfitId not used in player creating
495 Object::_Create(guidlow, 0, HIGHGUID_PLAYER);
497 m_name = name;
499 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
500 if(!info)
502 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
503 return false;
506 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
507 m_items[i] = NULL;
509 m_race = race;
510 m_class = class_;
512 SetMapId(info->mapId);
513 Relocate(info->positionX,info->positionY,info->positionZ);
515 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(class_);
516 if(!cEntry)
518 sLog.outError("Class %u not found in DBC (Wrong DBC files?)",class_);
519 return false;
522 uint8 powertype = cEntry->powerType;
524 //uint32 unitfield;
526 /*switch(powertype)
528 case POWER_ENERGY:
529 case POWER_MANA:
530 unitfield = 0x00000000;
531 break;
532 case POWER_RAGE:
533 unitfield = 0x00110000;
534 break;
535 case POWER_RUNIC_POWER:
536 unitfield = 0x0000EE00; //TODO: find correct unitfield here
537 break;
538 default:
539 sLog.outError("Invalid default powertype %u for player (class %u)",powertype,class_);
540 return false;
543 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, DEFAULT_WORLD_OBJECT_SIZE);
544 SetFloatValue(UNIT_FIELD_COMBATREACH, 1.5f);
546 switch(gender)
548 case GENDER_FEMALE:
549 SetDisplayId(info->displayId_f );
550 SetNativeDisplayId(info->displayId_f );
551 break;
552 case GENDER_MALE:
553 SetDisplayId(info->displayId_m );
554 SetNativeDisplayId(info->displayId_m );
555 break;
556 default:
557 sLog.outError("Invalid gender %u for player",gender);
558 return false;
559 break;
562 setFactionForRace(m_race);
564 uint32 RaceClassGender = ( race ) | ( class_ << 8 ) | ( gender << 16 );
566 SetUInt32Value(UNIT_FIELD_BYTES_0, ( RaceClassGender | ( powertype << 24 ) ) );
567 //SetUInt32Value(UNIT_FIELD_BYTES_1, unitfield);
568 SetByteFlag(UNIT_FIELD_BYTES_2, 1, UNIT_BYTE2_FLAG_PVP );
569 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE );
570 SetFlag(UNIT_FIELD_FLAGS_2, UNIT_FLAG2_REGENERATE_POWER);
571 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f); // fix cast time showed in spell tooltip on client
572 SetFloatValue(UNIT_FIELD_HOVERHEIGHT, 1.0f); // default for players in 3.0.3
574 // -1 is default value
575 SetUInt32Value(PLAYER_FIELD_WATCHED_FACTION_INDEX, uint32(-1));
577 SetUInt32Value(PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
578 SetUInt32Value(PLAYER_BYTES_2, (facialHair | (0x00 << 8) | (0x00 << 16) | (0x02 << 24)));
579 SetByteValue(PLAYER_BYTES_3, 0, gender);
581 SetUInt32Value( PLAYER_GUILDID, 0 );
582 SetUInt32Value( PLAYER_GUILDRANK, 0 );
583 SetUInt32Value( PLAYER_GUILD_TIMESTAMP, 0 );
585 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES, 0 ); // 0=disabled
586 SetUInt64Value( PLAYER__FIELD_KNOWN_TITLES1, 0 ); // 0=disabled
587 SetUInt32Value( PLAYER_CHOSEN_TITLE, 0 );
588 SetUInt32Value( PLAYER_FIELD_KILLS, 0 );
589 SetUInt32Value( PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 0 );
590 SetUInt32Value( PLAYER_FIELD_TODAY_CONTRIBUTION, 0 );
591 SetUInt32Value( PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0 );
593 for(uint32 i = 0; i < sGlyphSlotStore.GetNumRows(); ++i)
595 GlyphSlotEntry const * gs = sGlyphSlotStore.LookupEntry(i);
596 if(gs && gs->Order)
597 SetGlyphSlot(gs->Order - 1, gs->Id);
600 // set starting level
601 if (GetSession()->GetSecurity() >= SEC_MODERATOR)
602 SetUInt32Value(UNIT_FIELD_LEVEL, sWorld.getConfig(CONFIG_START_GM_LEVEL));
603 else
605 if(getClass() == CLASS_DEATH_KNIGHT)
606 SetUInt32Value(UNIT_FIELD_LEVEL, 55);
607 else
608 SetUInt32Value(UNIT_FIELD_LEVEL, sWorld.getConfig(CONFIG_START_PLAYER_LEVEL));
611 InitRunes();
613 SetUInt32Value (PLAYER_FIELD_COINAGE, sWorld.getConfig(CONFIG_START_PLAYER_MONEY));
614 SetUInt32Value (PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_START_HONOR_POINTS));
615 SetUInt32Value (PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_START_ARENA_POINTS));
617 // Played time
618 m_Last_tick = time(NULL);
619 m_Played_time[0] = 0;
620 m_Played_time[1] = 0;
622 // base stats and related field values
623 InitStatsForLevel();
624 InitTaxiNodesForLevel();
625 InitGlyphsForLevel();
626 InitTalentForLevel();
627 InitPrimaryProffesions(); // to max set before any spell added
629 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
630 UpdateMaxHealth(); // Update max Health (for add bonus from stamina)
631 SetHealth(GetMaxHealth());
632 if (getPowerType()==POWER_MANA)
634 UpdateMaxPower(POWER_MANA); // Update max Mana (for add bonus from intellect)
635 SetPower(POWER_MANA,GetMaxPower(POWER_MANA));
638 if(getPowerType() == POWER_RUNIC_POWER)
640 SetPower(POWER_RUNE, 8);
641 SetMaxPower(POWER_RUNE, 8);
642 SetPower(POWER_RUNIC_POWER, 0);
643 SetMaxPower(POWER_RUNIC_POWER, 1000);
646 // original spells
647 learnDefaultSpells(true);
649 // original action bar
650 std::list<uint16>::const_iterator action_itr[4];
651 for(int i=0; i<4; i++)
652 action_itr[i] = info->action[i].begin();
654 for (; action_itr[0]!=info->action[0].end() && action_itr[1]!=info->action[1].end();)
656 uint16 taction[4];
657 for(int i=0; i<4 ;i++)
658 taction[i] = (*action_itr[i]);
660 addActionButton((uint8)taction[0], taction[1], (uint8)taction[2], (uint8)taction[3]);
662 for(int i=0; i<4 ;i++)
663 ++action_itr[i];
666 // original items
667 CharStartOutfitEntry const* oEntry = NULL;
668 for (uint32 i = 1; i < sCharStartOutfitStore.GetNumRows(); ++i)
670 if(CharStartOutfitEntry const* entry = sCharStartOutfitStore.LookupEntry(i))
672 if(entry->RaceClassGender == RaceClassGender)
674 oEntry = entry;
675 break;
680 if(oEntry)
682 for(int j = 0; j < MAX_OUTFIT_ITEMS; ++j)
684 if(oEntry->ItemId[j] <= 0)
685 continue;
687 uint32 item_id = oEntry->ItemId[j];
689 ItemPrototype const* iProto = objmgr.GetItemPrototype(item_id);
690 if(!iProto)
692 sLog.outErrorDb("Initial item id %u (race %u class %u) from CharStartOutfit.dbc not listed in `item_template`, ignoring.",item_id,getRace(),getClass());
693 continue;
696 uint32 count = iProto->Stackable; // max stack by default (mostly 1)
697 if(iProto->Class==ITEM_CLASS_CONSUMABLE && iProto->SubClass==ITEM_SUBCLASS_FOOD)
699 switch(iProto->Spells[0].SpellCategory)
701 case 11: // food
702 if(iProto->Stackable > 4)
703 count = 4;
704 break;
705 case 59: // drink
706 if(iProto->Stackable > 2)
707 count = 2;
708 break;
712 StoreNewItemInBestSlot(item_id, count);
716 for (PlayerCreateInfoItems::const_iterator item_id_itr = info->item.begin(); item_id_itr!=info->item.end(); ++item_id_itr++)
717 StoreNewItemInBestSlot(item_id_itr->item_id, item_id_itr->item_amount);
719 // bags and main-hand weapon must equipped at this moment
720 // now second pass for not equipped (offhand weapon/shield if it attempt equipped before main-hand weapon)
721 // or ammo not equipped in special bag
722 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
724 if(Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
726 uint16 eDest;
727 // equip offhand weapon/shield if it attempt equipped before main-hand weapon
728 uint8 msg = CanEquipItem( NULL_SLOT, eDest, pItem, false );
729 if( msg == EQUIP_ERR_OK )
731 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
732 EquipItem( eDest, pItem, true);
734 // move other items to more appropriate slots (ammo not equipped in special bag)
735 else
737 ItemPosCountVec sDest;
738 msg = CanStoreItem( NULL_BAG, NULL_SLOT, sDest, pItem, false );
739 if( msg == EQUIP_ERR_OK )
741 RemoveItem(INVENTORY_SLOT_BAG_0, i,true);
742 pItem = StoreItem( sDest, pItem, true);
745 // if this is ammo then use it
746 uint8 msg = CanUseAmmo( pItem->GetProto()->ItemId );
747 if( msg == EQUIP_ERR_OK )
748 SetAmmo( pItem->GetProto()->ItemId );
752 // all item positions resolved
754 return true;
757 bool Player::StoreNewItemInBestSlot(uint32 titem_id, uint32 titem_amount)
759 sLog.outDebug("STORAGE: Creating initial item, itemId = %u, count = %u",titem_id, titem_amount);
761 // attempt equip
762 uint16 eDest;
763 uint8 msg = CanEquipNewItem( NULL_SLOT, eDest, titem_id, titem_amount, false );
764 if( msg == EQUIP_ERR_OK )
766 EquipNewItem( eDest, titem_id, titem_amount, true);
767 AutoUnequipOffhandIfNeed();
768 return true; // equipped
771 // attempt store
772 ItemPosCountVec sDest;
773 // store in main bag to simplify second pass (special bags can be not equipped yet at this moment)
774 msg = CanStoreNewItem( INVENTORY_SLOT_BAG_0, NULL_SLOT, sDest, titem_id, titem_amount );
775 if( msg == EQUIP_ERR_OK )
777 StoreNewItem( sDest, titem_id, true, Item::GenerateItemRandomPropertyId(titem_id) );
778 return true; // stored
781 // item can't be added
782 sLog.outError("STORAGE: Can't equip or store initial item %u for race %u class %u , error msg = %u",titem_id,getRace(),getClass(),msg);
783 return false;
786 void Player::StartMirrorTimer(MirrorTimerType Type, uint32 MaxValue)
788 uint32 BreathRegen = (uint32)-1;
790 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
791 data << (uint32)Type;
792 data << MaxValue;
793 data << MaxValue;
794 data << BreathRegen;
795 data << (uint8)0;
796 data << (uint32)0; // spell id
797 GetSession()->SendPacket(&data);
800 void Player::ModifyMirrorTimer(MirrorTimerType Type, uint32 MaxValue, uint32 CurrentValue, uint32 Regen)
802 if(Type==BREATH_TIMER)
803 m_breathTimer = ((MaxValue + 1000) - CurrentValue) / Regen;
805 WorldPacket data(SMSG_START_MIRROR_TIMER, (21));
806 data << (uint32)Type;
807 data << CurrentValue;
808 data << MaxValue;
809 data << Regen;
810 data << (uint8)0;
811 data << (uint32)0; // spell id
812 GetSession()->SendPacket( &data );
815 void Player::StopMirrorTimer(MirrorTimerType Type)
817 if(Type==BREATH_TIMER)
818 m_breathTimer = 0;
820 WorldPacket data(SMSG_STOP_MIRROR_TIMER, 4);
821 data << (uint32)Type;
822 GetSession()->SendPacket( &data );
825 void Player::EnvironmentalDamage(uint64 guid, EnviromentalDamage type, uint32 damage)
827 WorldPacket data(SMSG_ENVIRONMENTALDAMAGELOG, (21));
828 data << (uint64)guid;
829 data << (uint8)(type!=DAMAGE_FALL_TO_VOID ? type : DAMAGE_FALL);
830 data << (uint32)damage;
831 data << (uint32)0;
832 data << (uint32)0;
833 SendMessageToSet(&data, true);
835 DealDamage(this, damage, NULL, SELF_DAMAGE, SPELL_SCHOOL_MASK_NORMAL, NULL, false);
837 if(type==DAMAGE_FALL && !isAlive()) // DealDamage not apply item durability loss at self damage
839 DEBUG_LOG("We are fall to death, loosing 10 percents durability");
840 DurabilityLossAll(0.10f,false);
841 // durability lost message
842 WorldPacket data(SMSG_DURABILITY_DAMAGE_DEATH, 0);
843 GetSession()->SendPacket(&data);
847 void Player::HandleDrowning()
849 if(!m_isunderwater)
850 return;
852 //if player is GM, have waterbreath, is dead or if breathing is disabled then return
853 if(waterbreath || isGameMaster() || !isAlive() || GetSession()->GetSecurity() >= sWorld.getConfig(CONFIG_DISABLE_BREATHING))
855 StopMirrorTimer(BREATH_TIMER);
856 m_isunderwater = 0;
857 return;
860 uint32 UnderWaterTime = 1*MINUTE*1000; // default length 1 min
862 AuraList const& mModWaterBreathing = GetAurasByType(SPELL_AURA_MOD_WATER_BREATHING);
863 for(AuraList::const_iterator i = mModWaterBreathing.begin(); i != mModWaterBreathing.end(); ++i)
864 UnderWaterTime = uint32(UnderWaterTime * (100.0f + (*i)->GetModifier()->m_amount) / 100.0f);
866 if ((m_isunderwater & 0x01) && !(m_isunderwater & 0x80) && isAlive())
868 //single trigger timer
869 if (!(m_isunderwater & 0x02))
871 m_isunderwater|= 0x02;
872 m_breathTimer = UnderWaterTime + 1000;
874 //single trigger "Breathbar"
875 if ( m_breathTimer <= UnderWaterTime && !(m_isunderwater & 0x04))
877 m_isunderwater|= 0x04;
878 StartMirrorTimer(BREATH_TIMER, UnderWaterTime);
880 //continuous trigger drowning "Damage"
881 if ((m_breathTimer == 0) && (m_isunderwater & 0x01))
883 //TODO: Check this formula
884 uint64 guid = GetGUID();
885 uint32 damage = GetMaxHealth() / 5 + urand(0, getLevel()-1);
887 EnvironmentalDamage(guid, DAMAGE_DROWNING,damage);
888 m_breathTimer = 2000;
891 //single trigger retract bar
892 else if (!(m_isunderwater & 0x01) && !(m_isunderwater & 0x08) && (m_isunderwater & 0x02) && (m_breathTimer > 0) && isAlive())
894 m_isunderwater = 0x08;
896 uint32 BreathRegen = 10;
897 ModifyMirrorTimer(BREATH_TIMER, UnderWaterTime, m_breathTimer,BreathRegen);
898 m_isunderwater = 0x10;
900 //remove bar
901 else if ((m_breathTimer < 50) && !(m_isunderwater & 0x01) && (m_isunderwater == 0x10))
903 StopMirrorTimer(BREATH_TIMER);
904 m_isunderwater = 0;
908 void Player::HandleLava()
910 if ((m_isunderwater & 0x80) && isAlive())
912 // Single trigger Set BreathTimer
913 if (!(m_isunderwater & 0x80))
915 m_isunderwater|= 0x04;
916 m_breathTimer = 1000;
919 // Reset BreathTimer and still in the lava
920 if (!m_breathTimer)
922 uint64 guid = GetGUID();
923 uint32 damage = urand(600, 700); // TODO: Get more detailed information about lava damage
925 // if not gamemaster then deal damage
926 if ( !isGameMaster() )
927 EnvironmentalDamage(guid, DAMAGE_LAVA, damage);
929 m_breathTimer = 1000;
932 else if (m_deathState == DEAD) // Disable breath timer and reset underwater flags
934 m_breathTimer = 0;
935 m_isunderwater = 0;
939 ///The player sobers by 256 every 10 seconds
940 void Player::HandleSobering()
942 m_drunkTimer = 0;
944 uint32 drunk = (m_drunk <= 256) ? 0 : (m_drunk - 256);
945 SetDrunkValue(drunk);
948 DrunkenState Player::GetDrunkenstateByValue(uint16 value)
950 if(value >= 23000)
951 return DRUNKEN_SMASHED;
952 if(value >= 12800)
953 return DRUNKEN_DRUNK;
954 if(value & 0xFFFE)
955 return DRUNKEN_TIPSY;
956 return DRUNKEN_SOBER;
959 void Player::SetDrunkValue(uint16 newDrunkenValue, uint32 itemId)
961 uint32 oldDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
963 m_drunk = newDrunkenValue;
964 SetUInt32Value(PLAYER_BYTES_3,(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFF0001) | (m_drunk & 0xFFFE));
966 uint32 newDrunkenState = Player::GetDrunkenstateByValue(m_drunk);
968 // special drunk invisibility detection
969 if(newDrunkenState >= DRUNKEN_DRUNK)
970 m_detectInvisibilityMask |= (1<<6);
971 else
972 m_detectInvisibilityMask &= ~(1<<6);
974 if(newDrunkenState == oldDrunkenState)
975 return;
977 WorldPacket data(SMSG_CROSSED_INEBRIATION_THRESHOLD, (8+4+4));
978 data << uint64(GetGUID());
979 data << uint32(newDrunkenState);
980 data << uint32(itemId);
982 SendMessageToSet(&data, true);
985 void Player::Update( uint32 p_time )
987 if(!IsInWorld())
988 return;
990 // undelivered mail
991 if(m_nextMailDelivereTime && m_nextMailDelivereTime <= time(NULL))
993 SendNewMail();
994 ++unReadMails;
996 // It will be recalculate at mailbox open (for unReadMails important non-0 until mailbox open, it also will be recalculated)
997 m_nextMailDelivereTime = 0;
1000 Unit::Update( p_time );
1002 // update player only attacks
1003 if(uint32 ranged_att = getAttackTimer(RANGED_ATTACK))
1005 setAttackTimer(RANGED_ATTACK, (p_time >= ranged_att ? 0 : ranged_att - p_time) );
1008 if(uint32 off_att = getAttackTimer(OFF_ATTACK))
1010 setAttackTimer(OFF_ATTACK, (p_time >= off_att ? 0 : off_att - p_time) );
1013 time_t now = time (NULL);
1015 UpdatePvPFlag(now);
1017 UpdateContestedPvP(p_time);
1019 UpdateDuelFlag(now);
1021 CheckDuelDistance(now);
1023 UpdateAfkReport(now);
1025 CheckExploreSystem();
1027 // Update items that have just a limited lifetime
1028 if (now>m_Last_tick)
1029 UpdateItemDuration(uint32(now- m_Last_tick));
1031 if (!m_timedquests.empty())
1033 std::set<uint32>::iterator iter = m_timedquests.begin();
1034 while (iter != m_timedquests.end())
1036 QuestStatusData& q_status = mQuestStatus[*iter];
1037 if( q_status.m_timer <= p_time )
1039 uint32 quest_id = *iter;
1040 ++iter; // current iter will be removed in FailTimedQuest
1041 FailTimedQuest( quest_id );
1043 else
1045 q_status.m_timer -= p_time;
1046 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
1047 ++iter;
1052 if (hasUnitState(UNIT_STAT_MELEE_ATTACKING))
1054 Unit *pVictim = getVictim();
1055 if( !IsNonMeleeSpellCasted(false) && pVictim)
1057 // default combat reach 10
1058 // TODO add weapon,skill check
1060 float pldistance = ATTACK_DISTANCE;
1062 if (isAttackReady(BASE_ATTACK))
1064 if(!IsWithinDistInMap(pVictim, pldistance))
1066 setAttackTimer(BASE_ATTACK,100);
1067 if(m_swingErrorMsg != 1) // send single time (client auto repeat)
1069 SendAttackSwingNotInRange();
1070 m_swingErrorMsg = 1;
1073 //120 degrees of radiant range
1074 else if( !HasInArc( 2*M_PI/3, pVictim ))
1076 setAttackTimer(BASE_ATTACK,100);
1077 if(m_swingErrorMsg != 2) // send single time (client auto repeat)
1079 SendAttackSwingBadFacingAttack();
1080 m_swingErrorMsg = 2;
1083 else
1085 m_swingErrorMsg = 0; // reset swing error state
1087 // prevent base and off attack in same time, delay attack at 0.2 sec
1088 if(haveOffhandWeapon())
1090 uint32 off_att = getAttackTimer(OFF_ATTACK);
1091 if(off_att < ATTACK_DISPLAY_DELAY)
1092 setAttackTimer(OFF_ATTACK,ATTACK_DISPLAY_DELAY);
1094 AttackerStateUpdate(pVictim, BASE_ATTACK);
1095 resetAttackTimer(BASE_ATTACK);
1099 if ( haveOffhandWeapon() && isAttackReady(OFF_ATTACK))
1101 if(!IsWithinDistInMap(pVictim, pldistance))
1103 setAttackTimer(OFF_ATTACK,100);
1105 else if( !HasInArc( 2*M_PI/3, pVictim ))
1107 setAttackTimer(OFF_ATTACK,100);
1109 else
1111 // prevent base and off attack in same time, delay attack at 0.2 sec
1112 uint32 base_att = getAttackTimer(BASE_ATTACK);
1113 if(base_att < ATTACK_DISPLAY_DELAY)
1114 setAttackTimer(BASE_ATTACK,ATTACK_DISPLAY_DELAY);
1115 // do attack
1116 AttackerStateUpdate(pVictim, OFF_ATTACK);
1117 resetAttackTimer(OFF_ATTACK);
1121 Unit *owner = pVictim->GetOwner();
1122 Unit *u = owner ? owner : pVictim;
1123 if(u->IsPvP() && (!duel || duel->opponent != u))
1125 UpdatePvP(true);
1126 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_ENTER_PVP_COMBAT);
1131 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING))
1133 if(roll_chance_i(3) && GetTimeInnEnter() > 0) //freeze update
1135 int time_inn = time(NULL)-GetTimeInnEnter();
1136 if (time_inn >= 10) //freeze update
1138 float bubble = 0.125*sWorld.getRate(RATE_REST_INGAME);
1139 //speed collect rest bonus (section/in hour)
1140 SetRestBonus( GetRestBonus()+ time_inn*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble );
1141 UpdateInnerTime(time(NULL));
1146 if(m_regenTimer > 0)
1148 if(p_time >= m_regenTimer)
1149 m_regenTimer = 0;
1150 else
1151 m_regenTimer -= p_time;
1154 if (m_weaponChangeTimer > 0)
1156 if(p_time >= m_weaponChangeTimer)
1157 m_weaponChangeTimer = 0;
1158 else
1159 m_weaponChangeTimer -= p_time;
1162 if (m_zoneUpdateTimer > 0)
1164 if(p_time >= m_zoneUpdateTimer)
1166 uint32 newzone = GetZoneId();
1167 if( m_zoneUpdateId != newzone )
1168 UpdateZone(newzone); // also update area
1169 else
1171 // use area updates as well
1172 // needed for free far all arenas for example
1173 uint32 newarea = GetAreaId();
1174 if( m_areaUpdateId != newarea )
1175 UpdateArea(newarea);
1177 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
1180 else
1181 m_zoneUpdateTimer -= p_time;
1184 if (isAlive())
1186 RegenerateAll();
1189 if (m_deathState == JUST_DIED)
1191 KillPlayer();
1194 if(m_nextSave > 0)
1196 if(p_time >= m_nextSave)
1198 // m_nextSave reseted in SaveToDB call
1199 SaveToDB();
1200 sLog.outDetail("Player '%s' (GUID: %u) saved", GetName(), GetGUIDLow());
1202 else
1204 m_nextSave -= p_time;
1208 //Breathtimer
1209 if(m_breathTimer > 0)
1211 if(p_time >= m_breathTimer)
1212 m_breathTimer = 0;
1213 else
1214 m_breathTimer -= p_time;
1218 //Handle Water/drowning
1219 HandleDrowning();
1221 //Handle lava
1222 HandleLava();
1224 //Handle detect stealth players
1225 if (m_DetectInvTimer > 0)
1227 if (p_time >= m_DetectInvTimer)
1229 m_DetectInvTimer = 3000;
1230 HandleStealthedUnitsDetection();
1232 else
1233 m_DetectInvTimer -= p_time;
1236 // Played time
1237 if (now > m_Last_tick)
1239 uint32 elapsed = uint32(now - m_Last_tick);
1240 m_Played_time[0] += elapsed; // Total played time
1241 m_Played_time[1] += elapsed; // Level played time
1242 m_Last_tick = now;
1245 if (m_drunk)
1247 m_drunkTimer += p_time;
1249 if (m_drunkTimer > 10000)
1250 HandleSobering();
1253 // not auto-free ghost from body in instances
1254 if(m_deathTimer > 0 && !GetBaseMap()->Instanceable())
1256 if(p_time >= m_deathTimer)
1258 m_deathTimer = 0;
1259 BuildPlayerRepop();
1260 RepopAtGraveyard();
1262 else
1263 m_deathTimer -= p_time;
1266 UpdateEnchantTime(p_time);
1267 UpdateHomebindTime(p_time);
1269 // group update
1270 SendUpdateToOutOfRangeGroupMembers();
1272 Pet* pet = GetPet();
1273 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE) && (GetCharmGUID() && (pet->GetGUID() != GetCharmGUID())))
1275 RemovePet(pet, PET_SAVE_NOT_IN_SLOT, true);
1276 return;
1280 void Player::setDeathState(DeathState s)
1282 uint32 ressSpellId = 0;
1284 bool cur = isAlive();
1286 if(s == JUST_DIED && cur)
1288 // drunken state is cleared on death
1289 SetDrunkValue(0);
1290 // lost combo points at any target (targeted combo points clear in Unit::setDeathState)
1291 ClearComboPoints();
1293 clearResurrectRequestData();
1295 // remove form before other mods to prevent incorrect stats calculation
1296 RemoveAurasDueToSpell(m_ShapeShiftFormSpellId);
1298 //FIXME: is pet dismissed at dying or releasing spirit? if second, add setDeathState(DEAD) to HandleRepopRequestOpcode and define pet unsummon here with (s == DEAD)
1299 RemovePet(NULL, PET_SAVE_NOT_IN_SLOT, true);
1301 // remove uncontrolled pets
1302 RemoveMiniPet();
1303 RemoveGuardians();
1305 // save value before aura remove in Unit::setDeathState
1306 ressSpellId = GetUInt32Value(PLAYER_SELF_RES_SPELL);
1308 // passive spell
1309 if(!ressSpellId)
1310 ressSpellId = GetResurrectionSpellId();
1311 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP, 1);
1313 Unit::setDeathState(s);
1315 // restore resurrection spell id for player after aura remove
1316 if(s == JUST_DIED && cur && ressSpellId)
1317 SetUInt32Value(PLAYER_SELF_RES_SPELL, ressSpellId);
1319 if(isAlive() && !cur)
1321 //clear aura case after resurrection by another way (spells will be applied before next death)
1322 SetUInt32Value(PLAYER_SELF_RES_SPELL, 0);
1324 // restore default warrior stance
1325 if(getClass()== CLASS_WARRIOR)
1326 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
1330 void Player::BuildEnumData( QueryResult * result, WorldPacket * p_data )
1332 Field *fields = result->Fetch();
1334 *p_data << uint64(GetGUID());
1335 *p_data << m_name;
1337 *p_data << uint8(getRace());
1338 uint8 pClass = getClass();
1339 *p_data << uint8(pClass);
1340 *p_data << uint8(getGender());
1342 uint32 bytes = GetUInt32Value(PLAYER_BYTES);
1343 *p_data << uint8(bytes);
1344 *p_data << uint8(bytes >> 8);
1345 *p_data << uint8(bytes >> 16);
1346 *p_data << uint8(bytes >> 24);
1348 bytes = GetUInt32Value(PLAYER_BYTES_2);
1349 *p_data << uint8(bytes);
1351 *p_data << uint8(getLevel()); // player level
1352 // do not use GetMap! it will spawn a new instance since the bound instances are not loaded
1353 uint32 zoneId = MapManager::Instance().GetZoneId(GetMapId(), GetPositionX(),GetPositionY());
1354 sLog.outDebug("Player::BuildEnumData: m:%u, x:%f, y:%f, z:%f zone:%u", GetMapId(), GetPositionX(), GetPositionY(), GetPositionZ(), zoneId);
1355 *p_data << uint32(zoneId);
1356 *p_data << uint32(GetMapId());
1358 *p_data << GetPositionX();
1359 *p_data << GetPositionY();
1360 *p_data << GetPositionZ();
1362 // guild id
1363 *p_data << (result ? fields[13].GetUInt32() : 0);
1365 uint32 char_flags = 0;
1366 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
1367 char_flags |= CHARACTER_FLAG_HIDE_HELM;
1368 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
1369 char_flags |= CHARACTER_FLAG_HIDE_CLOAK;
1370 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST))
1371 char_flags |= CHARACTER_FLAG_GHOST;
1372 if(HasAtLoginFlag(AT_LOGIN_RENAME))
1373 char_flags |= CHARACTER_FLAG_RENAME;
1374 if(sWorld.getConfig(CONFIG_DECLINED_NAMES_USED) && (fields[14].GetCppString() != ""))
1375 char_flags |= CHARACTER_FLAG_DECLINED;
1377 *p_data << uint32(char_flags); // character flags
1378 // character customize (flags?)
1379 *p_data << uint32(HasAtLoginFlag(AT_LOGIN_CUSTOMIZE) ? 1 : 0);
1380 *p_data << uint8(1); // unknown
1382 // Pets info
1384 uint32 petDisplayId = 0;
1385 uint32 petLevel = 0;
1386 uint32 petFamily = 0;
1388 // show pet at selection character in character list only for non-ghost character
1389 if(result && isAlive() && (pClass == CLASS_WARLOCK || pClass == CLASS_HUNTER))
1391 uint32 entry = fields[10].GetUInt32();
1392 CreatureInfo const* cInfo = sCreatureStorage.LookupEntry<CreatureInfo>(entry);
1393 if(cInfo)
1395 petDisplayId = fields[11].GetUInt32();
1396 petLevel = fields[12].GetUInt32();
1397 petFamily = cInfo->family;
1401 *p_data << uint32(petDisplayId);
1402 *p_data << uint32(petLevel);
1403 *p_data << uint32(petFamily);
1406 for (uint8 slot = 0; slot < EQUIPMENT_SLOT_END; slot++)
1408 uint32 visualbase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
1409 uint32 item_id = GetUInt32Value(visualbase);
1410 const ItemPrototype * proto = objmgr.GetItemPrototype(item_id);
1411 SpellItemEnchantmentEntry const *enchant = NULL;
1413 for(uint8 enchantSlot = PERM_ENCHANTMENT_SLOT; enchantSlot<=TEMP_ENCHANTMENT_SLOT; enchantSlot++)
1415 uint32 enchantId = GetUInt32Value(visualbase+1+enchantSlot);
1416 if(enchant = sSpellItemEnchantmentStore.LookupEntry(enchantId))
1417 break;
1420 if (proto != NULL)
1422 *p_data << uint32(proto->DisplayInfoID);
1423 *p_data << uint8(proto->InventoryType);
1424 *p_data << uint32(enchant ? enchant->aura_id : 0);
1426 else
1428 *p_data << uint32(0);
1429 *p_data << uint8(0);
1430 *p_data << uint32(0); // enchant?
1433 *p_data << uint32(0); // first bag display id
1434 *p_data << uint8(0); // first bag inventory type
1435 *p_data << uint32(0); // enchant?
1438 bool Player::ToggleAFK()
1440 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1442 bool state = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK);
1444 // afk player not allowed in battleground
1445 if(state && InBattleGround())
1446 LeaveBattleground();
1448 return state;
1451 bool Player::ToggleDND()
1453 ToggleFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1455 return HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_DND);
1458 uint8 Player::chatTag() const
1460 // it's bitmask
1461 // 0x8 - ??
1462 // 0x4 - gm
1463 // 0x2 - dnd
1464 // 0x1 - afk
1465 if(isGMChat())
1466 return 4;
1467 else if(isDND())
1468 return 3;
1469 if(isAFK())
1470 return 1;
1471 else
1472 return 0;
1475 bool Player::TeleportTo(uint32 mapid, float x, float y, float z, float orientation, uint32 options)
1477 if(!MapManager::IsValidMapCoord(mapid, x, y, z, orientation))
1479 sLog.outError("TeleportTo: invalid map %d or absent instance template.", mapid);
1480 return false;
1483 // preparing unsummon pet if lost (we must get pet before teleportation or will not find it later)
1484 Pet* pet = GetPet();
1486 MapEntry const* mEntry = sMapStore.LookupEntry(mapid);
1488 // don't let enter battlegrounds without assigned battleground id (for example through areatrigger)...
1489 if(!InBattleGround() && mEntry->IsBattleGround() && !GetSession()->GetSecurity())
1490 return false;
1492 // client without expansion support
1493 if(GetSession()->Expansion() < mEntry->Expansion())
1495 sLog.outDebug("Player %s using client without required expansion tried teleport to non accessible map %u", GetName(), mapid);
1497 if(GetTransport())
1498 RepopAtGraveyard(); // teleport to near graveyard if on transport, looks blizz like :)
1500 SendTransferAborted(mapid, TRANSFER_ABORT_INSUF_EXPAN_LVL, mEntry->Expansion());
1502 return false; // normal client can't teleport to this map...
1504 else
1506 sLog.outDebug("Player %s will teleported to map %u", GetName(), mapid);
1509 // if we were on a transport, leave
1510 if (!(options & TELE_TO_NOT_LEAVE_TRANSPORT) && m_transport)
1512 m_transport->RemovePassenger(this);
1513 m_transport = NULL;
1514 m_movementInfo.t_x = 0.0f;
1515 m_movementInfo.t_y = 0.0f;
1516 m_movementInfo.t_z = 0.0f;
1517 m_movementInfo.t_o = 0.0f;
1518 m_movementInfo.t_time = 0;
1521 SetSemaphoreTeleport(true);
1523 // The player was ported to another map and looses the duel immediately.
1524 // We have to perform this check before the teleport, otherwise the
1525 // ObjectAccessor won't find the flag.
1526 if (duel && GetMapId()!=mapid)
1528 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
1529 if (obj)
1530 DuelComplete(DUEL_FLED);
1533 // reset movement flags at teleport, because player will continue move with these flags after teleport
1534 SetUnitMovementFlags(0);
1536 if ((GetMapId() == mapid) && (!m_transport))
1538 // prepare zone change detect
1539 uint32 old_zone = GetZoneId();
1541 // near teleport
1542 if(!GetSession()->PlayerLogout())
1544 WorldPacket data;
1545 BuildTeleportAckMsg(&data, x, y, z, orientation);
1546 GetSession()->SendPacket(&data);
1547 SetPosition( x, y, z, orientation, true);
1549 else
1550 // this will be used instead of the current location in SaveToDB
1551 m_teleport_dest = WorldLocation(mapid, x, y, z, orientation);
1552 SetFallInformation(0, z);
1554 //BuildHeartBeatMsg(&data);
1555 //SendMessageToSet(&data, true);
1556 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1558 //same map, only remove pet if out of range
1559 if(pet && !IsWithinDistInMap(pet, OWNER_MAX_DISTANCE))
1561 if(pet->isControlled() && !pet->isTemporarySummoned() )
1562 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1563 else
1564 m_temporaryUnsummonedPetNumber = 0;
1566 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1570 if(!(options & TELE_TO_NOT_LEAVE_COMBAT))
1571 CombatStop();
1573 if (!(options & TELE_TO_NOT_UNSUMMON_PET))
1575 // resummon pet
1576 if(pet && m_temporaryUnsummonedPetNumber)
1578 Pet* NewPet = new Pet;
1579 if(!NewPet->LoadPetFromDB(this, 0, m_temporaryUnsummonedPetNumber, true))
1580 delete NewPet;
1582 m_temporaryUnsummonedPetNumber = 0;
1586 if(!GetSession()->PlayerLogout())
1588 // don't reset teleport semaphore while logging out, otherwise m_teleport_dest won't be used in Player::SaveToDB
1589 SetSemaphoreTeleport(false);
1591 UpdateZone(GetZoneId());
1594 // new zone
1595 if(old_zone != GetZoneId())
1597 // honorless target
1598 if(pvpInfo.inHostileArea)
1599 CastSpell(this, 2479, true);
1602 else
1604 // far teleport to another map
1605 Map* oldmap = IsInWorld() ? GetMap() : NULL;
1606 // check if we can enter before stopping combat / removing pet / totems / interrupting spells
1608 // Check enter rights before map getting to avoid creating instance copy for player
1609 // this check not dependent from map instance copy and same for all instance copies of selected map
1610 if (!MapManager::Instance().CanPlayerEnter(mapid, this))
1612 SetSemaphoreTeleport(false);
1613 return false;
1616 // If the map is not created, assume it is possible to enter it.
1617 // It will be created in the WorldPortAck.
1618 Map *map = MapManager::Instance().FindMap(mapid);
1619 if (!map || map->CanEnter(this))
1621 SetSelection(0);
1623 CombatStop();
1625 ResetContestedPvP();
1627 // remove player from battleground on far teleport (when changing maps)
1628 if(BattleGround const* bg = GetBattleGround())
1630 // Note: at battleground join battleground id set before teleport
1631 // and we already will found "current" battleground
1632 // just need check that this is targeted map or leave
1633 if(bg->GetMapId() != mapid)
1634 LeaveBattleground(false); // don't teleport to entry point
1637 // remove pet on map change
1638 if (pet)
1640 //leaving map -> delete pet right away (doing this later will cause problems)
1641 if(pet->isControlled() && !pet->isTemporarySummoned())
1642 m_temporaryUnsummonedPetNumber = pet->GetCharmInfo()->GetPetNumber();
1643 else
1644 m_temporaryUnsummonedPetNumber = 0;
1646 RemovePet(pet, PET_SAVE_NOT_IN_SLOT);
1649 // remove all dyn objects
1650 RemoveAllDynObjects();
1652 // stop spellcasting
1653 // not attempt interrupt teleportation spell at caster teleport
1654 if(!(options & TELE_TO_SPELL))
1655 if(IsNonMeleeSpellCasted(true))
1656 InterruptNonMeleeSpells(true);
1658 if(!GetSession()->PlayerLogout())
1660 // send transfer packets
1661 WorldPacket data(SMSG_TRANSFER_PENDING, (4+4+4));
1662 data << uint32(mapid);
1663 if (m_transport)
1665 data << m_transport->GetEntry() << GetMapId();
1667 GetSession()->SendPacket(&data);
1669 data.Initialize(SMSG_NEW_WORLD, (20));
1670 if (m_transport)
1672 data << (uint32)mapid << m_movementInfo.t_x << m_movementInfo.t_y << m_movementInfo.t_z << m_movementInfo.t_o;
1674 else
1676 data << (uint32)mapid << (float)x << (float)y << (float)z << (float)orientation;
1678 GetSession()->SendPacket( &data );
1679 SendSavedInstances();
1681 // remove from old map now
1682 if(oldmap) oldmap->Remove(this, false);
1685 // new final coordinates
1686 float final_x = x;
1687 float final_y = y;
1688 float final_z = z;
1689 float final_o = orientation;
1691 if(m_transport)
1693 final_x += m_movementInfo.t_x;
1694 final_y += m_movementInfo.t_y;
1695 final_z += m_movementInfo.t_z;
1696 final_o += m_movementInfo.t_o;
1699 m_teleport_dest = WorldLocation(mapid, final_x, final_y, final_z, final_o);
1700 SetFallInformation(0, final_z);
1701 // if the player is saved before worldportack (at logout for example)
1702 // this will be used instead of the current location in SaveToDB
1704 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
1706 // move packet sent by client always after far teleport
1707 // SetPosition(final_x, final_y, final_z, final_o, true);
1708 SetDontMove(true);
1710 // code for finish transfer to new map called in WorldSession::HandleMoveWorldportAckOpcode at client packet
1712 else
1713 return false;
1715 return true;
1718 void Player::AddToWorld()
1720 ///- Do not add/remove the player from the object storage
1721 ///- It will crash when updating the ObjectAccessor
1722 ///- The player should only be added when logging in
1723 Unit::AddToWorld();
1725 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1727 if(m_items[i])
1728 m_items[i]->AddToWorld();
1732 void Player::RemoveFromWorld()
1734 // cleanup
1735 if(IsInWorld())
1737 ///- Release charmed creatures, unsummon totems and remove pets/guardians
1738 Uncharm();
1739 UnsummonAllTotems();
1740 RemoveMiniPet();
1741 RemoveGuardians();
1744 for(int i = PLAYER_SLOT_START; i < PLAYER_SLOT_END; i++)
1746 if(m_items[i])
1747 m_items[i]->RemoveFromWorld();
1750 ///- Do not add/remove the player from the object storage
1751 ///- It will crash when updating the ObjectAccessor
1752 ///- The player should only be removed when logging out
1753 Unit::RemoveFromWorld();
1756 void Player::RewardRage( uint32 damage, uint32 weaponSpeedHitFactor, bool attacker )
1758 float addRage;
1760 float rageconversion = ((0.0091107836 * getLevel()*getLevel())+3.225598133*getLevel())+4.2652911;
1762 if(attacker)
1764 addRage = ((damage/rageconversion*7.5 + weaponSpeedHitFactor)/2);
1766 // talent who gave more rage on attack
1767 addRage *= 1.0f + GetTotalAuraModifier(SPELL_AURA_MOD_RAGE_FROM_DAMAGE_DEALT) / 100.0f;
1769 else
1771 addRage = damage/rageconversion*2.5;
1773 // Berserker Rage effect
1774 if(HasAura(18499,0))
1775 addRage *= 1.3;
1778 addRage *= sWorld.getRate(RATE_POWER_RAGE_INCOME);
1780 ModifyPower(POWER_RAGE, uint32(addRage*10));
1783 void Player::RegenerateAll()
1785 if (m_regenTimer != 0)
1786 return;
1787 uint32 regenDelay = 2000;
1789 // Not in combat or they have regeneration
1790 if( !isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) ||
1791 HasAuraType(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT) || IsPolymorphed() )
1793 RegenerateHealth();
1794 if (!isInCombat() && !HasAuraType(SPELL_AURA_INTERRUPT_REGEN))
1796 Regenerate(POWER_RAGE);
1797 if(getClass() == CLASS_DEATH_KNIGHT)
1798 Regenerate(POWER_RUNIC_POWER);
1802 Regenerate( POWER_ENERGY );
1804 Regenerate( POWER_MANA );
1806 if(getClass() == CLASS_DEATH_KNIGHT)
1807 Regenerate( POWER_RUNE );
1809 m_regenTimer = regenDelay;
1812 void Player::Regenerate(Powers power)
1814 uint32 curValue = GetPower(power);
1815 uint32 maxValue = GetMaxPower(power);
1817 float addvalue = 0.0f;
1819 switch (power)
1821 case POWER_MANA:
1823 bool recentCast = IsUnderLastManaUseEffect();
1824 float ManaIncreaseRate = sWorld.getRate(RATE_POWER_MANA);
1825 if (recentCast)
1827 // Mangos Updates Mana in intervals of 2s, which is correct
1828 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_INTERRUPTED_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1830 else
1832 addvalue = GetFloatValue(UNIT_FIELD_POWER_REGEN_FLAT_MODIFIER) * ManaIncreaseRate * 2.00f;
1834 } break;
1835 case POWER_RAGE: // Regenerate rage
1837 float RageDecreaseRate = sWorld.getRate(RATE_POWER_RAGE_LOSS);
1838 addvalue = 30 * RageDecreaseRate; // 3 rage by tick
1839 } break;
1840 case POWER_ENERGY: // Regenerate energy (rogue)
1841 addvalue = 20;
1842 break;
1843 case POWER_RUNIC_POWER:
1845 float RunicPowerDecreaseRate = sWorld.getRate(RATE_POWER_RUNICPOWER_LOSS);
1846 addvalue = 30 * RunicPowerDecreaseRate; // 3 RunicPower by tick
1847 } break;
1848 case POWER_RUNE:
1850 for(uint32 i = 0; i < MAX_RUNES; ++i)
1851 if(uint8 cd = GetRuneCooldown(i)) // if we have cooldown, reduce it...
1852 SetRuneCooldown(i, cd - 1); // ... by 2 sec (because update is every 2 sec)
1853 } break;
1854 case POWER_FOCUS:
1855 case POWER_HAPPINESS:
1856 break;
1859 // Mana regen calculated in Player::UpdateManaRegen()
1860 // Exist only for POWER_MANA, POWER_ENERGY, POWER_FOCUS auras
1861 if(power != POWER_MANA)
1863 AuraList const& ModPowerRegenPCTAuras = GetAurasByType(SPELL_AURA_MOD_POWER_REGEN_PERCENT);
1864 for(AuraList::const_iterator i = ModPowerRegenPCTAuras.begin(); i != ModPowerRegenPCTAuras.end(); ++i)
1865 if ((*i)->GetModifier()->m_miscvalue == power)
1866 addvalue *= ((*i)->GetModifier()->m_amount + 100) / 100.0f;
1869 if (power != POWER_RAGE && power != POWER_RUNIC_POWER)
1871 curValue += uint32(addvalue);
1872 if (curValue > maxValue)
1873 curValue = maxValue;
1875 else
1877 if(curValue <= uint32(addvalue))
1878 curValue = 0;
1879 else
1880 curValue -= uint32(addvalue);
1882 SetPower(power, curValue);
1885 void Player::RegenerateHealth()
1887 uint32 curValue = GetHealth();
1888 uint32 maxValue = GetMaxHealth();
1890 if (curValue >= maxValue) return;
1892 float HealthIncreaseRate = sWorld.getRate(RATE_HEALTH);
1894 float addvalue = 0.0f;
1896 // polymorphed case
1897 if ( IsPolymorphed() )
1898 addvalue = GetMaxHealth()/3;
1899 // normal regen case (maybe partly in combat case)
1900 else if (!isInCombat() || HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT) )
1902 addvalue = OCTRegenHPPerSpirit()* HealthIncreaseRate;
1903 if (!isInCombat())
1905 AuraList const& mModHealthRegenPct = GetAurasByType(SPELL_AURA_MOD_HEALTH_REGEN_PERCENT);
1906 for(AuraList::const_iterator i = mModHealthRegenPct.begin(); i != mModHealthRegenPct.end(); ++i)
1907 addvalue *= (100.0f + (*i)->GetModifier()->m_amount) / 100.0f;
1909 else if(HasAuraType(SPELL_AURA_MOD_REGEN_DURING_COMBAT))
1910 addvalue *= GetTotalAuraModifier(SPELL_AURA_MOD_REGEN_DURING_COMBAT) / 100.0f;
1912 if(!IsStandState())
1913 addvalue *= 1.5;
1916 // always regeneration bonus (including combat)
1917 addvalue += GetTotalAuraModifier(SPELL_AURA_MOD_HEALTH_REGEN_IN_COMBAT);
1919 if(addvalue < 0)
1920 addvalue = 0;
1922 ModifyHealth(int32(addvalue));
1925 bool Player::CanInteractWithNPCs(bool alive) const
1927 if(alive && !isAlive())
1928 return false;
1929 if(isInFlight())
1930 return false;
1932 return true;
1935 bool Player::IsUnderWater() const
1937 return IsInWater() &&
1938 GetPositionZ() < (MapManager::Instance().GetBaseMap(GetMapId())->GetWaterLevel(GetPositionX(),GetPositionY())-2);
1941 void Player::SetInWater(bool apply)
1943 if(m_isInWater==apply)
1944 return;
1946 //define player in water by opcodes
1947 //move player's guid into HateOfflineList of those mobs
1948 //which can't swim and move guid back into ThreatList when
1949 //on surface.
1950 //TODO: exist also swimming mobs, and function must be symmetric to enter/leave water
1951 m_isInWater = apply;
1953 // remove auras that need water/land
1954 RemoveAurasWithInterruptFlags(apply ? AURA_INTERRUPT_FLAG_NOT_ABOVEWATER : AURA_INTERRUPT_FLAG_NOT_UNDERWATER);
1956 getHostilRefManager().updateThreatTables();
1959 void Player::SetGameMaster(bool on)
1961 if(on)
1963 m_ExtraFlags |= PLAYER_EXTRA_GM_ON;
1964 setFaction(35);
1965 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
1967 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
1968 ResetContestedPvP();
1970 getHostilRefManager().setOnlineOfflineState(false);
1971 CombatStop();
1973 else
1975 m_ExtraFlags &= ~ PLAYER_EXTRA_GM_ON;
1976 setFactionForRace(getRace());
1977 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM);
1979 // restore FFA PvP Server state
1980 if(sWorld.IsFFAPvPRealm())
1981 SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
1983 // restore FFA PvP area state, remove not allowed for GM mounts
1984 UpdateArea(m_areaUpdateId);
1986 getHostilRefManager().setOnlineOfflineState(true);
1989 ObjectAccessor::UpdateVisibilityForPlayer(this);
1992 void Player::SetGMVisible(bool on)
1994 if(on)
1996 m_ExtraFlags &= ~PLAYER_EXTRA_GM_INVISIBLE; //remove flag
1998 // Reapply stealth/invisibility if active or show if not any
1999 if(HasAuraType(SPELL_AURA_MOD_STEALTH))
2000 SetVisibility(VISIBILITY_GROUP_STEALTH);
2001 else if(HasAuraType(SPELL_AURA_MOD_INVISIBILITY))
2002 SetVisibility(VISIBILITY_GROUP_INVISIBILITY);
2003 else
2004 SetVisibility(VISIBILITY_ON);
2006 else
2008 m_ExtraFlags |= PLAYER_EXTRA_GM_INVISIBLE; //add flag
2010 SetAcceptWhispers(false);
2011 SetGameMaster(true);
2013 SetVisibility(VISIBILITY_OFF);
2017 bool Player::IsGroupVisibleFor(Player* p) const
2019 switch(sWorld.getConfig(CONFIG_GROUP_VISIBILITY))
2021 default: return IsInSameGroupWith(p);
2022 case 1: return IsInSameRaidWith(p);
2023 case 2: return GetTeam()==p->GetTeam();
2027 bool Player::IsInSameGroupWith(Player const* p) const
2029 return p==this || GetGroup() != NULL &&
2030 GetGroup() == p->GetGroup() &&
2031 GetGroup()->SameSubGroup((Player*)this, (Player*)p);
2034 ///- If the player is invited, remove him. If the group if then only 1 person, disband the group.
2035 /// \todo Shouldn't we also check if there is no other invitees before disbanding the group?
2036 void Player::UninviteFromGroup()
2038 Group* group = GetGroupInvite();
2039 if(!group)
2040 return;
2042 group->RemoveInvite(this);
2044 if(group->GetMembersCount() <= 1) // group has just 1 member => disband
2046 if(group->IsCreated())
2048 group->Disband(true);
2049 objmgr.RemoveGroup(group);
2051 else
2052 group->RemoveAllInvites();
2054 delete group;
2058 void Player::RemoveFromGroup(Group* group, uint64 guid)
2060 if(group)
2062 if (group->RemoveMember(guid, 0) <= 1)
2064 // group->Disband(); already disbanded in RemoveMember
2065 objmgr.RemoveGroup(group);
2066 delete group;
2067 // removemember sets the player's group pointer to NULL
2072 void Player::SendLogXPGain(uint32 GivenXP, Unit* victim, uint32 RestXP)
2074 WorldPacket data(SMSG_LOG_XPGAIN, 21);
2075 data << uint64(victim ? victim->GetGUID() : 0); // guid
2076 data << uint32(GivenXP+RestXP); // given experience
2077 data << uint8(victim ? 0 : 1); // 00-kill_xp type, 01-non_kill_xp type
2078 if(victim)
2080 data << uint32(GivenXP); // experience without rested bonus
2081 data << float(1); // 1 - none 0 - 100% group bonus output
2083 data << uint8(0); // new 2.4.0
2084 GetSession()->SendPacket(&data);
2087 void Player::GiveXP(uint32 xp, Unit* victim)
2089 if ( xp < 1 )
2090 return;
2092 if(!isAlive())
2093 return;
2095 uint32 level = getLevel();
2097 // XP to money conversion processed in Player::RewardQuest
2098 if(level >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
2099 return;
2101 // handle SPELL_AURA_MOD_XP_PCT auras
2102 Unit::AuraList const& ModXPPctAuras = GetAurasByType(SPELL_AURA_MOD_XP_PCT);
2103 for(Unit::AuraList::const_iterator i = ModXPPctAuras.begin();i != ModXPPctAuras.end(); ++i)
2104 xp = uint32(xp*(1.0f + (*i)->GetModifier()->m_amount / 100.0f));
2106 // XP resting bonus for kill
2107 uint32 rested_bonus_xp = victim ? GetXPRestBonus(xp) : 0;
2109 SendLogXPGain(xp,victim,rested_bonus_xp);
2111 uint32 curXP = GetUInt32Value(PLAYER_XP);
2112 uint32 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2113 uint32 newXP = curXP + xp + rested_bonus_xp;
2115 while( newXP >= nextLvlXP && level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2117 newXP -= nextLvlXP;
2119 if ( level < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
2120 GiveLevel(level + 1);
2122 level = getLevel();
2123 nextLvlXP = GetUInt32Value(PLAYER_NEXT_LEVEL_XP);
2126 SetUInt32Value(PLAYER_XP, newXP);
2129 // Update player to next level
2130 // Current player experience not update (must be update by caller)
2131 void Player::GiveLevel(uint32 level)
2133 if ( level == getLevel() )
2134 return;
2136 PlayerLevelInfo info;
2137 objmgr.GetPlayerLevelInfo(getRace(),getClass(),level,&info);
2139 PlayerClassLevelInfo classInfo;
2140 objmgr.GetPlayerClassLevelInfo(getClass(),level,&classInfo);
2142 // send levelup info to client
2143 WorldPacket data(SMSG_LEVELUP_INFO, (4+4+MAX_POWERS*4+MAX_STATS*4));
2144 data << uint32(level);
2145 data << uint32(int32(classInfo.basehealth) - int32(GetCreateHealth()));
2146 // for(int i = 0; i < MAX_POWERS; ++i) // Powers loop (0-6)
2147 data << uint32(int32(classInfo.basemana) - int32(GetCreateMana()));
2148 data << uint32(0);
2149 data << uint32(0);
2150 data << uint32(0);
2151 data << uint32(0);
2152 data << uint32(0);
2153 data << uint32(0);
2154 // end for
2155 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i) // Stats loop (0-4)
2156 data << uint32(int32(info.stats[i]) - GetCreateStat(Stats(i)));
2158 GetSession()->SendPacket(&data);
2160 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, MaNGOS::XP::xp_to_level(level));
2162 //update level, max level of skills
2163 if(getLevel()!= level)
2164 m_Played_time[1] = 0; // Level Played Time reset
2165 SetLevel(level);
2166 UpdateSkillsForLevel ();
2168 // save base values (bonuses already included in stored stats
2169 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2170 SetCreateStat(Stats(i), info.stats[i]);
2172 SetCreateHealth(classInfo.basehealth);
2173 SetCreateMana(classInfo.basemana);
2175 InitTalentForLevel();
2176 InitTaxiNodesForLevel();
2177 InitGlyphsForLevel();
2179 UpdateAllStats();
2181 // set current level health and mana/energy to maximum after applying all mods.
2182 SetHealth(GetMaxHealth());
2183 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2184 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2185 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2186 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2187 SetPower(POWER_FOCUS, 0);
2188 SetPower(POWER_HAPPINESS, 0);
2190 // give level to summoned pet
2191 Pet* pet = GetPet();
2192 if(pet && pet->getPetType()==SUMMON_PET)
2193 pet->GivePetLevel(level);
2194 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL);
2197 void Player::InitTalentForLevel()
2199 uint32 level = getLevel();
2200 // talents base at level diff ( talents = level - 9 but some can be used already)
2201 if(level < 10)
2203 // Remove all talent points
2204 if(m_usedTalentCount > 0) // Free any used talents
2206 resetTalents(true);
2207 SetFreeTalentPoints(0);
2210 else
2212 uint32 talentPointsForLevel = uint32((level-9)*sWorld.getRate(RATE_TALENT));
2213 // if used more that have then reset
2214 if(m_usedTalentCount > talentPointsForLevel)
2216 if (GetSession()->GetSecurity() < SEC_ADMINISTRATOR)
2217 resetTalents(true);
2218 else
2219 SetFreeTalentPoints(0);
2221 // else update amount of free points
2222 else
2223 SetFreeTalentPoints(talentPointsForLevel-m_usedTalentCount);
2227 void Player::InitStatsForLevel(bool reapplyMods)
2229 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2230 _RemoveAllStatBonuses();
2232 PlayerClassLevelInfo classInfo;
2233 objmgr.GetPlayerClassLevelInfo(getClass(),getLevel(),&classInfo);
2235 PlayerLevelInfo info;
2236 objmgr.GetPlayerLevelInfo(getRace(),getClass(),getLevel(),&info);
2238 SetUInt32Value(PLAYER_FIELD_MAX_LEVEL, sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) );
2239 SetUInt32Value(PLAYER_NEXT_LEVEL_XP, MaNGOS::XP::xp_to_level(getLevel()));
2241 UpdateSkillsForLevel ();
2243 // set default cast time multiplier
2244 SetFloatValue(UNIT_MOD_CAST_SPEED, 1.0f);
2246 // reset size before reapply auras
2247 SetFloatValue(OBJECT_FIELD_SCALE_X,1.0f);
2249 // save base values (bonuses already included in stored stats
2250 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2251 SetCreateStat(Stats(i), info.stats[i]);
2253 for(int i = STAT_STRENGTH; i < MAX_STATS; ++i)
2254 SetStat(Stats(i), info.stats[i]);
2256 SetCreateHealth(classInfo.basehealth);
2258 //set create powers
2259 SetCreateMana(classInfo.basemana);
2261 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2263 InitStatBuffMods();
2265 //reset rating fields values
2266 for(uint16 index = PLAYER_FIELD_COMBAT_RATING_1; index < PLAYER_FIELD_COMBAT_RATING_1 + MAX_COMBAT_RATING; ++index)
2267 SetUInt32Value(index, 0);
2269 SetUInt32Value(PLAYER_FIELD_MOD_HEALING_DONE_POS,0);
2270 for (int i = 0; i < 7; i++)
2272 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_NEG+i, 0);
2273 SetUInt32Value(PLAYER_FIELD_MOD_DAMAGE_DONE_POS+i, 0);
2274 SetFloatValue(PLAYER_FIELD_MOD_DAMAGE_DONE_PCT+i, 1.00f);
2277 //reset attack power, damage and attack speed fields
2278 SetFloatValue(UNIT_FIELD_BASEATTACKTIME, 2000.0f );
2279 SetFloatValue(UNIT_FIELD_BASEATTACKTIME + 1, 2000.0f ); // offhand attack time
2280 SetFloatValue(UNIT_FIELD_RANGEDATTACKTIME, 2000.0f );
2282 SetFloatValue(UNIT_FIELD_MINDAMAGE, 0.0f );
2283 SetFloatValue(UNIT_FIELD_MAXDAMAGE, 0.0f );
2284 SetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE, 0.0f );
2285 SetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE, 0.0f );
2286 SetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE, 0.0f );
2287 SetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE, 0.0f );
2289 SetUInt32Value(UNIT_FIELD_ATTACK_POWER, 0 );
2290 SetUInt32Value(UNIT_FIELD_ATTACK_POWER_MODS, 0 );
2291 SetFloatValue(UNIT_FIELD_ATTACK_POWER_MULTIPLIER,0.0f);
2292 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER, 0 );
2293 SetUInt32Value(UNIT_FIELD_RANGED_ATTACK_POWER_MODS,0 );
2294 SetFloatValue(UNIT_FIELD_RANGED_ATTACK_POWER_MULTIPLIER,0.0f);
2296 // Base crit values (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2297 SetFloatValue(PLAYER_CRIT_PERCENTAGE,0.0f);
2298 SetFloatValue(PLAYER_OFFHAND_CRIT_PERCENTAGE,0.0f);
2299 SetFloatValue(PLAYER_RANGED_CRIT_PERCENTAGE,0.0f);
2301 // Init spell schools (will be recalculated in UpdateAllStats() at loading and in _ApplyAllStatBonuses() at reset
2302 for (uint8 i = 0; i < 7; ++i)
2303 SetFloatValue(PLAYER_SPELL_CRIT_PERCENTAGE1+i, 0.0f);
2305 SetFloatValue(PLAYER_PARRY_PERCENTAGE, 0.0f);
2306 SetFloatValue(PLAYER_BLOCK_PERCENTAGE, 0.0f);
2307 SetUInt32Value(PLAYER_SHIELD_BLOCK, 0);
2309 // Dodge percentage
2310 SetFloatValue(PLAYER_DODGE_PERCENTAGE, 0.0f);
2312 // set armor (resistance 0) to original value (create_agility*2)
2313 SetArmor(int32(m_createStats[STAT_AGILITY]*2));
2314 SetResistanceBuffMods(SpellSchools(0), true, 0.0f);
2315 SetResistanceBuffMods(SpellSchools(0), false, 0.0f);
2316 // set other resistance to original value (0)
2317 for (int i = 1; i < MAX_SPELL_SCHOOL; i++)
2319 SetResistance(SpellSchools(i), 0);
2320 SetResistanceBuffMods(SpellSchools(i), true, 0.0f);
2321 SetResistanceBuffMods(SpellSchools(i), false, 0.0f);
2324 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_RESISTANCE,0);
2325 SetUInt32Value(PLAYER_FIELD_MOD_TARGET_PHYSICAL_RESISTANCE,0);
2326 for(int i = 0; i < MAX_SPELL_SCHOOL; ++i)
2328 SetFloatValue(UNIT_FIELD_POWER_COST_MODIFIER+i,0.0f);
2329 SetFloatValue(UNIT_FIELD_POWER_COST_MULTIPLIER+i,0.0f);
2331 // Init data for form but skip reapply item mods for form
2332 InitDataForForm(reapplyMods);
2334 // save new stats
2335 for (int i = POWER_MANA; i < MAX_POWERS; i++)
2336 SetMaxPower(Powers(i), uint32(GetCreatePowers(Powers(i))));
2338 SetMaxHealth(classInfo.basehealth); // stamina bonus will applied later
2340 // cleanup mounted state (it will set correctly at aura loading if player saved at mount.
2341 SetUInt32Value(UNIT_FIELD_MOUNTDISPLAYID, 0);
2343 // cleanup unit flags (will be re-applied if need at aura load).
2344 RemoveFlag( UNIT_FIELD_FLAGS,
2345 UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_DISABLE_MOVE | UNIT_FLAG_NOT_ATTACKABLE_1 |
2346 UNIT_FLAG_PET_IN_COMBAT | UNIT_FLAG_SILENCED | UNIT_FLAG_PACIFIED |
2347 UNIT_FLAG_STUNNED | UNIT_FLAG_IN_COMBAT | UNIT_FLAG_DISARMED |
2348 UNIT_FLAG_CONFUSED | UNIT_FLAG_FLEEING | UNIT_FLAG_NOT_SELECTABLE |
2349 UNIT_FLAG_SKINNABLE | UNIT_FLAG_MOUNT | UNIT_FLAG_TAXI_FLIGHT );
2350 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PVP_ATTACKABLE ); // must be set
2352 // cleanup player flags (will be re-applied if need at aura load), to avoid have ghost flag without ghost aura, for example.
2353 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_AFK | PLAYER_FLAGS_DND | PLAYER_FLAGS_GM | PLAYER_FLAGS_GHOST | PLAYER_FLAGS_FFA_PVP);
2355 SetByteValue(UNIT_FIELD_BYTES_1, 2, 0x00); // one form stealth modified bytes
2357 // restore if need some important flags
2358 SetUInt32Value(PLAYER_FIELD_BYTES2, 0 ); // flags empty by default
2360 if(reapplyMods) //reapply stats values only on .reset stats (level) command
2361 _ApplyAllStatBonuses();
2363 // set current level health and mana/energy to maximum after applying all mods.
2364 SetHealth(GetMaxHealth());
2365 SetPower(POWER_MANA, GetMaxPower(POWER_MANA));
2366 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY));
2367 if(GetPower(POWER_RAGE) > GetMaxPower(POWER_RAGE))
2368 SetPower(POWER_RAGE, GetMaxPower(POWER_RAGE));
2369 SetPower(POWER_FOCUS, 0);
2370 SetPower(POWER_HAPPINESS, 0);
2371 SetPower(POWER_RUNIC_POWER, 0);
2374 void Player::SendInitialSpells()
2376 uint16 spellCount = 0;
2378 WorldPacket data(SMSG_INITIAL_SPELLS, (1+2+4*m_spells.size()+2+m_spellCooldowns.size()*(2+2+2+4+4)));
2379 data << uint8(0);
2381 size_t countPos = data.wpos();
2382 data << uint16(spellCount); // spell count placeholder
2384 for (PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2386 if(itr->second->state == PLAYERSPELL_REMOVED)
2387 continue;
2389 if(!itr->second->active || itr->second->disabled)
2390 continue;
2392 data << uint16(itr->first);
2393 data << uint16(0); // it's not slot id
2395 spellCount +=1;
2398 data.put<uint16>(countPos,spellCount); // write real count value
2400 uint16 spellCooldowns = m_spellCooldowns.size();
2401 data << uint16(spellCooldowns);
2402 for(SpellCooldowns::const_iterator itr=m_spellCooldowns.begin(); itr!=m_spellCooldowns.end(); ++itr)
2404 SpellEntry const *sEntry = sSpellStore.LookupEntry(itr->first);
2405 if(!sEntry)
2406 continue;
2408 data << uint16(itr->first);
2410 time_t cooldown = 0;
2411 time_t curTime = time(NULL);
2412 if(itr->second.end > curTime)
2413 cooldown = (itr->second.end-curTime)*1000;
2415 data << uint16(itr->second.itemid); // cast item id
2416 data << uint16(sEntry->Category); // spell category
2417 if(sEntry->Category) // may be wrong, but anyway better than nothing...
2419 data << uint32(0); // cooldown
2420 data << uint32(cooldown); // category cooldown
2422 else
2424 data << uint32(cooldown); // cooldown
2425 data << uint32(0); // category cooldown
2429 GetSession()->SendPacket(&data);
2431 sLog.outDetail( "CHARACTER: Sent Initial Spells" );
2434 void Player::RemoveMail(uint32 id)
2436 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end();++itr)
2438 if ((*itr)->messageID == id)
2440 //do not delete item, because Player::removeMail() is called when returning mail to sender.
2441 m_mail.erase(itr);
2442 return;
2447 void Player::SendMailResult(uint32 mailId, uint32 mailAction, uint32 mailError, uint32 equipError, uint32 item_guid, uint32 item_count)
2449 WorldPacket data(SMSG_SEND_MAIL_RESULT, (4+4+4+(mailError == MAIL_ERR_BAG_FULL?4:(mailAction == MAIL_ITEM_TAKEN?4+4:0))));
2450 data << (uint32) mailId;
2451 data << (uint32) mailAction;
2452 data << (uint32) mailError;
2453 if ( mailError == MAIL_ERR_BAG_FULL )
2454 data << (uint32) equipError;
2455 else if( mailAction == MAIL_ITEM_TAKEN )
2457 data << (uint32) item_guid; // item guid low?
2458 data << (uint32) item_count; // item count?
2460 GetSession()->SendPacket(&data);
2463 void Player::SendNewMail()
2465 // deliver undelivered mail
2466 WorldPacket data(SMSG_RECEIVED_MAIL, 4);
2467 data << (uint32) 0;
2468 GetSession()->SendPacket(&data);
2471 void Player::UpdateNextMailTimeAndUnreads()
2473 // calculate next delivery time (min. from non-delivered mails
2474 // and recalculate unReadMail
2475 time_t cTime = time(NULL);
2476 m_nextMailDelivereTime = 0;
2477 unReadMails = 0;
2478 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
2480 if((*itr)->deliver_time > cTime)
2482 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > (*itr)->deliver_time)
2483 m_nextMailDelivereTime = (*itr)->deliver_time;
2485 else if(((*itr)->checked & MAIL_CHECK_MASK_READ) == 0)
2486 ++unReadMails;
2490 void Player::AddNewMailDeliverTime(time_t deliver_time)
2492 if(deliver_time <= time(NULL)) // ready now
2494 ++unReadMails;
2495 SendNewMail();
2497 else // not ready and no have ready mails
2499 if(!m_nextMailDelivereTime || m_nextMailDelivereTime > deliver_time)
2500 m_nextMailDelivereTime = deliver_time;
2504 bool Player::addSpell(uint32 spell_id, bool active, bool learning, bool loading, uint16 slot_id, bool disabled)
2506 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
2507 if (!spellInfo)
2509 // do character spell book cleanup (all characters)
2510 if(loading && !learning) // spell load case
2512 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request, deleting for all characters in `character_spell`.",spell_id);
2513 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2515 else
2516 sLog.outError("Player::addSpell: Non-existed in SpellStore spell #%u request.",spell_id);
2518 return false;
2521 if(!SpellMgr::IsSpellValid(spellInfo,this,false))
2523 // do character spell book cleanup (all characters)
2524 if(loading && !learning) // spell load case
2526 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed, deleting for all characters in `character_spell`.",spell_id);
2527 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE spell = '%u'",spell_id);
2529 else
2530 sLog.outError("Player::addSpell: Broken spell #%u learning not allowed.",spell_id);
2532 return false;
2535 PlayerSpellState state = learning ? PLAYERSPELL_NEW : PLAYERSPELL_UNCHANGED;
2537 bool disabled_case = false;
2538 bool superceded_old = false;
2540 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2541 if (itr != m_spells.end())
2543 // update active state for known spell
2544 if(itr->second->active != active && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled)
2546 itr->second->active = active;
2548 // loading && !learning == explicitly load from DB and then exist in it already and set correctly
2549 if(loading && !learning)
2550 itr->second->state = PLAYERSPELL_UNCHANGED;
2551 else if(itr->second->state != PLAYERSPELL_NEW)
2552 itr->second->state = PLAYERSPELL_CHANGED;
2554 if(!active)
2556 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2557 data << uint16(spell_id);
2558 GetSession()->SendPacket(&data);
2560 return active; // learn (show in spell book if active now)
2563 if(itr->second->disabled != disabled && itr->second->state != PLAYERSPELL_REMOVED)
2565 if(itr->second->state != PLAYERSPELL_NEW)
2566 itr->second->state = PLAYERSPELL_CHANGED;
2567 itr->second->disabled = disabled;
2569 if(disabled)
2570 return false;
2572 disabled_case = true;
2574 else switch(itr->second->state)
2576 case PLAYERSPELL_UNCHANGED: // known saved spell
2577 return false;
2578 case PLAYERSPELL_REMOVED: // re-learning removed not saved spell
2580 delete itr->second;
2581 m_spells.erase(itr);
2582 state = PLAYERSPELL_CHANGED;
2583 break; // need re-add
2585 default: // known not saved yet spell (new or modified)
2587 // can be in case spell loading but learned at some previous spell loading
2588 if(loading && !learning)
2589 itr->second->state = PLAYERSPELL_UNCHANGED;
2591 return false;
2596 if(!disabled_case) // skip new spell adding if spell already known (disabled spells case)
2598 // talent: unlearn all other talent ranks (high and low)
2599 if(TalentSpellPos const* talentPos = GetTalentSpellPos(spell_id))
2601 if(TalentEntry const *talentInfo = sTalentStore.LookupEntry( talentPos->talent_id ))
2603 for(int i=0; i <5; ++i)
2605 // skip learning spell and no rank spell case
2606 uint32 rankSpellId = talentInfo->RankID[i];
2607 if(!rankSpellId || rankSpellId==spell_id)
2608 continue;
2610 // skip unknown ranks
2611 if(!HasSpell(rankSpellId))
2612 continue;
2614 removeSpell(rankSpellId);
2618 // non talent spell: learn low ranks (recursive call)
2619 else if(uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id))
2621 if(loading) // at spells loading, no output, but allow save
2622 addSpell(prev_spell,active,true,loading,SPELL_WITHOUT_SLOT_ID,disabled);
2623 else // at normal learning
2624 learnSpell(prev_spell);
2627 PlayerSpell *newspell = new PlayerSpell;
2628 newspell->active = active;
2629 newspell->state = state;
2630 newspell->disabled = disabled;
2632 // replace spells in action bars and spellbook to bigger rank if only one spell rank must be accessible
2633 if(newspell->active && !newspell->disabled && !SpellMgr::canStackSpellRanks(spellInfo) && spellmgr.GetSpellRank(spellInfo->Id) != 0)
2635 for( PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr )
2637 if(itr->second->state == PLAYERSPELL_REMOVED) continue;
2638 SpellEntry const *i_spellInfo = sSpellStore.LookupEntry(itr->first);
2639 if(!i_spellInfo) continue;
2641 if( spellmgr.IsRankSpellDueToSpell(spellInfo,itr->first) )
2643 if(itr->second->active)
2645 if(spellmgr.IsHighRankOfSpell(spell_id,itr->first))
2647 if(!loading) // not send spell (re-/over-)learn packets at loading
2649 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2650 data << uint16(itr->first);
2651 data << uint16(spell_id);
2652 GetSession()->SendPacket( &data );
2655 // mark old spell as disable (SMSG_SUPERCEDED_SPELL replace it in client by new)
2656 itr->second->active = false;
2657 itr->second->state = PLAYERSPELL_CHANGED;
2658 superceded_old = true; // new spell replace old in action bars and spell book.
2660 else if(spellmgr.IsHighRankOfSpell(itr->first,spell_id))
2662 if(!loading) // not send spell (re-/over-)learn packets at loading
2664 WorldPacket data(SMSG_SUPERCEDED_SPELL, (4));
2665 data << uint16(spell_id);
2666 data << uint16(itr->first);
2667 GetSession()->SendPacket( &data );
2670 // mark new spell as disable (not learned yet for client and will not learned)
2671 newspell->active = false;
2672 if(newspell->state != PLAYERSPELL_NEW)
2673 newspell->state = PLAYERSPELL_CHANGED;
2680 uint16 tmpslot=slot_id;
2682 if (tmpslot == SPELL_WITHOUT_SLOT_ID)
2684 uint16 maxid = 0;
2685 PlayerSpellMap::iterator itr;
2686 for (itr = m_spells.begin(); itr != m_spells.end(); ++itr)
2688 if(itr->second->state == PLAYERSPELL_REMOVED)
2689 continue;
2690 if (itr->second->slotId > maxid)
2691 maxid = itr->second->slotId;
2693 tmpslot = maxid + 1;
2696 newspell->slotId = tmpslot;
2697 m_spells[spell_id] = newspell;
2699 // return false if spell disabled
2700 if (newspell->disabled)
2701 return false;
2704 uint32 talentCost = GetTalentSpellCost(spell_id);
2706 // cast talents with SPELL_EFFECT_LEARN_SPELL (other dependent spells will learned later as not auto-learned)
2707 // note: all spells with SPELL_EFFECT_LEARN_SPELL isn't passive
2708 if( talentCost > 0 && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_LEARN_SPELL) )
2710 // ignore stance requirement for talent learn spell (stance set for spell only for client spell description show)
2711 CastSpell(this, spell_id, true);
2713 // also cast passive spells (including all talents without SPELL_EFFECT_LEARN_SPELL) with additional checks
2714 else if (IsPassiveSpell(spell_id))
2716 // if spell doesn't require a stance or the player is in the required stance
2717 if( ( !spellInfo->Stances &&
2718 spell_id != 5420 && spell_id != 5419 && spell_id != 7376 &&
2719 spell_id != 7381 && spell_id != 21156 && spell_id != 21009 &&
2720 spell_id != 21178 && spell_id != 33948 && spell_id != 40121 ) ||
2721 m_form != 0 && (spellInfo->Stances & (1<<(m_form-1))) ||
2722 (spell_id == 5420 && m_form == FORM_TREE) ||
2723 (spell_id == 5419 && m_form == FORM_TRAVEL) ||
2724 (spell_id == 7376 && m_form == FORM_DEFENSIVESTANCE) ||
2725 (spell_id == 7381 && m_form == FORM_BERSERKERSTANCE) ||
2726 (spell_id == 21156 && m_form == FORM_BATTLESTANCE)||
2727 (spell_id == 21178 && (m_form == FORM_BEAR || m_form == FORM_DIREBEAR) ) ||
2728 (spell_id == 33948 && m_form == FORM_FLIGHT) ||
2729 (spell_id == 40121 && m_form == FORM_FLIGHT_EPIC) )
2730 //Check CasterAuraStates
2731 if (!spellInfo->CasterAuraState || HasAuraState(AuraState(spellInfo->CasterAuraState)))
2732 CastSpell(this, spell_id, true);
2734 else if( IsSpellHaveEffect(spellInfo,SPELL_EFFECT_SKILL_STEP) )
2736 CastSpell(this, spell_id, true);
2737 return false;
2740 // update used talent points count
2741 m_usedTalentCount += talentCost;
2743 // update free primary prof.points (if any, can be none in case GM .learn prof. learning)
2744 if(uint32 freeProfs = GetFreePrimaryProffesionPoints())
2746 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2747 SetFreePrimaryProffesions(freeProfs-1);
2750 // add dependent skills
2751 uint16 maxskill = GetMaxSkillValueForLevel();
2753 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2755 if(spellLearnSkill)
2757 uint32 skill_value = GetPureSkillValue(spellLearnSkill->skill);
2758 uint32 skill_max_value = GetPureMaxSkillValue(spellLearnSkill->skill);
2760 if(skill_value < spellLearnSkill->value)
2761 skill_value = spellLearnSkill->value;
2763 uint32 new_skill_max_value = spellLearnSkill->maxvalue == 0 ? maxskill : spellLearnSkill->maxvalue;
2765 if(skill_max_value < new_skill_max_value)
2766 skill_max_value = new_skill_max_value;
2768 SetSkill(spellLearnSkill->skill,skill_value,skill_max_value);
2770 else
2772 // not ranked skills
2773 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2774 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2776 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2778 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2779 if(!pSkill)
2780 continue;
2782 if(HasSkill(pSkill->id))
2783 continue;
2785 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2786 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2787 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
2789 switch(GetSkillRangeType(pSkill,_spell_idx->second->racemask!=0))
2791 case SKILL_RANGE_LANGUAGE:
2792 SetSkill(pSkill->id, 300, 300 );
2793 break;
2794 case SKILL_RANGE_LEVEL:
2795 SetSkill(pSkill->id, 1, GetMaxSkillValueForLevel() );
2796 break;
2797 case SKILL_RANGE_MONO:
2798 SetSkill(pSkill->id, 1, 1 );
2799 break;
2800 default:
2801 break;
2807 // learn dependent spells
2808 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2809 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2811 for(SpellLearnSpellMap::const_iterator itr = spell_begin; itr != spell_end; ++itr)
2813 if(!itr->second.autoLearned)
2815 if(loading) // at spells loading, no output, but allow save
2816 addSpell(itr->second.spell,true,true,loading);
2817 else // at normal learning
2818 learnSpell(itr->second.spell);
2822 if(!loading)
2824 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL);
2825 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS);
2828 // return true (for send learn packet) only if spell active (in case ranked spells) and not replace old spell
2829 return active && !disabled && !superceded_old;
2832 void Player::learnSpell(uint32 spell_id)
2834 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2836 bool disabled = (itr != m_spells.end()) ? itr->second->disabled : false;
2837 bool active = disabled ? itr->second->active : true;
2839 bool learning = addSpell(spell_id,active);
2841 // learn all disabled higher ranks (recursive)
2842 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2843 for(SpellChainMapNext::const_iterator i = nextMap.lower_bound(spell_id); i != nextMap.upper_bound(spell_id); ++i)
2845 PlayerSpellMap::iterator iter = m_spells.find(i->second);
2846 if (disabled && iter != m_spells.end() && iter->second->disabled)
2847 learnSpell(i->second);
2850 // prevent duplicated entires in spell book
2851 if(!learning)
2852 return;
2854 WorldPacket data(SMSG_LEARNED_SPELL, 4);
2855 data << uint32(spell_id);
2856 GetSession()->SendPacket(&data);
2859 void Player::removeSpell(uint32 spell_id, bool disabled)
2861 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
2862 if (itr == m_spells.end())
2863 return;
2865 if(itr->second->state == PLAYERSPELL_REMOVED || disabled && itr->second->disabled)
2866 return;
2868 // unlearn non talent higher ranks (recursive)
2869 SpellChainMapNext const& nextMap = spellmgr.GetSpellChainNext();
2870 for(SpellChainMapNext::const_iterator itr2 = nextMap.lower_bound(spell_id); itr2 != nextMap.upper_bound(spell_id); ++itr2)
2871 if(HasSpell(itr2->second) && !GetTalentSpellPos(itr2->second))
2872 removeSpell(itr2->second,disabled);
2874 // removing
2875 WorldPacket data(SMSG_REMOVED_SPELL, 4);
2876 data << uint16(spell_id);
2877 GetSession()->SendPacket(&data);
2879 if (disabled)
2881 itr->second->disabled = disabled;
2882 if(itr->second->state != PLAYERSPELL_NEW)
2883 itr->second->state = PLAYERSPELL_CHANGED;
2885 else
2887 if(itr->second->state == PLAYERSPELL_NEW)
2889 delete itr->second;
2890 m_spells.erase(itr);
2892 else
2893 itr->second->state = PLAYERSPELL_REMOVED;
2896 RemoveAurasDueToSpell(spell_id);
2898 // remove pet auras
2899 if(PetAura const* petSpell = spellmgr.GetPetAura(spell_id))
2900 RemovePetAura(petSpell);
2902 // free talent points
2903 uint32 talentCosts = GetTalentSpellCost(spell_id);
2904 if(talentCosts > 0)
2906 if(talentCosts < m_usedTalentCount)
2907 m_usedTalentCount -= talentCosts;
2908 else
2909 m_usedTalentCount = 0;
2912 // update free primary prof.points (if not overflow setting, can be in case GM use before .learn prof. learning)
2913 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell_id))
2915 uint32 freeProfs = GetFreePrimaryProffesionPoints()+1;
2916 if(freeProfs <= sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL))
2917 SetFreePrimaryProffesions(freeProfs);
2920 // remove dependent skill
2921 SpellLearnSkillNode const* spellLearnSkill = spellmgr.GetSpellLearnSkill(spell_id);
2922 if(spellLearnSkill)
2924 uint32 prev_spell = spellmgr.GetPrevSpellInChain(spell_id);
2925 if(!prev_spell) // first rank, remove skill
2926 SetSkill(spellLearnSkill->skill,0,0);
2927 else
2929 // search prev. skill setting by spell ranks chain
2930 SpellLearnSkillNode const* prevSkill = spellmgr.GetSpellLearnSkill(prev_spell);
2931 while(!prevSkill && prev_spell)
2933 prev_spell = spellmgr.GetPrevSpellInChain(prev_spell);
2934 prevSkill = spellmgr.GetSpellLearnSkill(spellmgr.GetFirstSpellInChain(prev_spell));
2937 if(!prevSkill) // not found prev skill setting, remove skill
2938 SetSkill(spellLearnSkill->skill,0,0);
2939 else // set to prev. skill setting values
2941 uint32 skill_value = GetPureSkillValue(prevSkill->skill);
2942 uint32 skill_max_value = GetPureMaxSkillValue(prevSkill->skill);
2944 if(skill_value > prevSkill->value)
2945 skill_value = prevSkill->value;
2947 uint32 new_skill_max_value = prevSkill->maxvalue == 0 ? GetMaxSkillValueForLevel() : prevSkill->maxvalue;
2949 if(skill_max_value > new_skill_max_value)
2950 skill_max_value = new_skill_max_value;
2952 SetSkill(prevSkill->skill,skill_value,skill_max_value);
2957 else
2959 // not ranked skills
2960 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
2961 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
2963 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
2965 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(_spell_idx->second->skillId);
2966 if(!pSkill)
2967 continue;
2969 if(_spell_idx->second->learnOnGetSkill == ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL ||
2970 // lockpicking special case, not have ABILITY_LEARNED_ON_GET_RACE_OR_CLASS_SKILL
2971 pSkill->id==SKILL_LOCKPICKING && _spell_idx->second->max_value==0 )
2973 // not reset skills for professions and racial abilities
2974 if( (pSkill->categoryId==SKILL_CATEGORY_SECONDARY || pSkill->categoryId==SKILL_CATEGORY_PROFESSION) &&
2975 (IsProfessionSkill(pSkill->id) || _spell_idx->second->racemask!=0) )
2976 continue;
2978 SetSkill(pSkill->id, 0, 0 );
2983 // remove dependent spells
2984 SpellLearnSpellMap::const_iterator spell_begin = spellmgr.GetBeginSpellLearnSpell(spell_id);
2985 SpellLearnSpellMap::const_iterator spell_end = spellmgr.GetEndSpellLearnSpell(spell_id);
2987 for(SpellLearnSpellMap::const_iterator itr2 = spell_begin; itr2 != spell_end; ++itr2)
2988 removeSpell(itr2->second.spell, disabled);
2991 void Player::RemoveArenaSpellCooldowns()
2993 // remove cooldowns on spells that has < 15 min CD
2994 SpellCooldowns::iterator itr, next;
2995 // iterate spell cooldowns
2996 for(itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); itr = next)
2998 next = itr;
2999 ++next;
3000 SpellEntry const * entry = sSpellStore.LookupEntry(itr->first);
3001 // check if spellentry is present and if the cooldown is less than 15 mins
3002 if( entry &&
3003 entry->RecoveryTime <= 15 * MINUTE * 1000 &&
3004 entry->CategoryRecoveryTime <= 15 * MINUTE * 1000 )
3006 // notify player
3007 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3008 data << uint32(itr->first);
3009 data << GetGUID();
3010 GetSession()->SendPacket(&data);
3011 // remove cooldown
3012 m_spellCooldowns.erase(itr);
3017 void Player::RemoveAllSpellCooldown()
3019 if(!m_spellCooldowns.empty())
3021 for(SpellCooldowns::const_iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end(); ++itr)
3023 WorldPacket data(SMSG_CLEAR_COOLDOWN, (4+8));
3024 data << uint32(itr->first);
3025 data << uint64(GetGUID());
3026 GetSession()->SendPacket(&data);
3028 m_spellCooldowns.clear();
3032 void Player::_LoadSpellCooldowns(QueryResult *result)
3034 m_spellCooldowns.clear();
3036 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,item,time FROM character_spell_cooldown WHERE guid = '%u'",GetGUIDLow());
3038 if(result)
3040 time_t curTime = time(NULL);
3044 Field *fields = result->Fetch();
3046 uint32 spell_id = fields[0].GetUInt32();
3047 uint32 item_id = fields[1].GetUInt32();
3048 time_t db_time = (time_t)fields[2].GetUInt64();
3050 if(!sSpellStore.LookupEntry(spell_id))
3052 sLog.outError("Player %u have unknown spell %u in `character_spell_cooldown`, skipping.",GetGUIDLow(),spell_id);
3053 continue;
3056 // skip outdated cooldown
3057 if(db_time <= curTime)
3058 continue;
3060 AddSpellCooldown(spell_id, item_id, db_time);
3062 sLog.outDebug("Player (GUID: %u) spell %u, item %u cooldown loaded (%u secs).", GetGUIDLow(), spell_id, item_id, uint32(db_time-curTime));
3064 while( result->NextRow() );
3066 delete result;
3070 void Player::_SaveSpellCooldowns()
3072 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'", GetGUIDLow());
3074 time_t curTime = time(NULL);
3076 // remove outdated and save active
3077 for(SpellCooldowns::iterator itr = m_spellCooldowns.begin();itr != m_spellCooldowns.end();)
3079 if(itr->second.end <= curTime)
3080 m_spellCooldowns.erase(itr++);
3081 else
3083 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));
3084 ++itr;
3089 uint32 Player::resetTalentsCost() const
3091 // The first time reset costs 1 gold
3092 if(m_resetTalentsCost < 1*GOLD)
3093 return 1*GOLD;
3094 // then 5 gold
3095 else if(m_resetTalentsCost < 5*GOLD)
3096 return 5*GOLD;
3097 // After that it increases in increments of 5 gold
3098 else if(m_resetTalentsCost < 10*GOLD)
3099 return 10*GOLD;
3100 else
3102 uint32 months = (sWorld.GetGameTime() - m_resetTalentsTime)/MONTH;
3103 if(months > 0)
3105 // This cost will be reduced by a rate of 5 gold per month
3106 int32 new_cost = int32(m_resetTalentsCost) - 5*GOLD*months;
3107 // to a minimum of 10 gold.
3108 return (new_cost < 10*GOLD ? 10*GOLD : new_cost);
3110 else
3112 // After that it increases in increments of 5 gold
3113 int32 new_cost = m_resetTalentsCost + 5*GOLD;
3114 // until it hits a cap of 50 gold.
3115 if(new_cost > 50*GOLD)
3116 new_cost = 50*GOLD;
3117 return new_cost;
3122 bool Player::resetTalents(bool no_cost)
3124 // not need after this call
3125 if(HasAtLoginFlag(AT_LOGIN_RESET_TALENTS))
3127 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_TALENTS;
3128 CharacterDatabase.PExecute("UPDATE characters set at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_TALENTS), GetGUIDLow());
3131 uint32 level = getLevel();
3132 uint32 talentPointsForLevel = level < 10 ? 0 : uint32((level-9)*sWorld.getRate(RATE_TALENT));
3134 if (m_usedTalentCount == 0)
3136 SetFreeTalentPoints(talentPointsForLevel);
3137 return false;
3140 uint32 cost = 0;
3142 if(!no_cost)
3144 cost = resetTalentsCost();
3146 if (GetMoney() < cost)
3148 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, 0, 0, 0);
3149 return false;
3153 for (unsigned int i = 0; i < sTalentStore.GetNumRows(); i++)
3155 TalentEntry const *talentInfo = sTalentStore.LookupEntry(i);
3157 if (!talentInfo) continue;
3159 TalentTabEntry const *talentTabInfo = sTalentTabStore.LookupEntry( talentInfo->TalentTab );
3161 if(!talentTabInfo)
3162 continue;
3164 // unlearn only talents for character class
3165 // some spell learned by one class as normal spells or know at creation but another class learn it as talent,
3166 // to prevent unexpected lost normal learned spell skip another class talents
3167 if( (getClassMask() & talentTabInfo->ClassMask) == 0 )
3168 continue;
3170 for (int j = 0; j < 5; j++)
3172 for(PlayerSpellMap::iterator itr = GetSpellMap().begin(); itr != GetSpellMap().end();)
3174 if(itr->second->state == PLAYERSPELL_REMOVED || itr->second->disabled)
3176 ++itr;
3177 continue;
3180 // remove learned spells (all ranks)
3181 uint32 itrFirstId = spellmgr.GetFirstSpellInChain(itr->first);
3183 // unlearn if first rank is talent or learned by talent
3184 if (itrFirstId == talentInfo->RankID[j] || spellmgr.IsSpellLearnToSpell(talentInfo->RankID[j],itrFirstId))
3186 removeSpell(itr->first,!IsPassiveSpell(itr->first));
3187 itr = GetSpellMap().begin();
3188 continue;
3190 else
3191 ++itr;
3196 SetFreeTalentPoints(talentPointsForLevel);
3198 if(!no_cost)
3200 ModifyMoney(-(int32)cost);
3202 m_resetTalentsCost = cost;
3203 m_resetTalentsTime = time(NULL);
3206 //FIXME: remove pet before or after unlearn spells? for now after unlearn to allow removing of talent related, pet affecting auras
3207 RemovePet(NULL,PET_SAVE_NOT_IN_SLOT, true);
3209 return true;
3212 bool Player::_removeSpell(uint16 spell_id)
3214 PlayerSpellMap::iterator itr = m_spells.find(spell_id);
3215 if (itr != m_spells.end())
3217 delete itr->second;
3218 m_spells.erase(itr);
3219 return true;
3221 return false;
3224 Mail* Player::GetMail(uint32 id)
3226 for(PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
3228 if ((*itr)->messageID == id)
3230 return (*itr);
3233 return NULL;
3236 void Player::_SetCreateBits(UpdateMask *updateMask, Player *target) const
3238 if(target == this)
3240 Object::_SetCreateBits(updateMask, target);
3242 else
3244 for(uint16 index = 0; index < m_valuesCount; index++)
3246 if(GetUInt32Value(index) != 0 && updateVisualBits.GetBit(index))
3247 updateMask->SetBit(index);
3252 void Player::_SetUpdateBits(UpdateMask *updateMask, Player *target) const
3254 if(target == this)
3256 Object::_SetUpdateBits(updateMask, target);
3258 else
3260 Object::_SetUpdateBits(updateMask, target);
3261 *updateMask &= updateVisualBits;
3265 void Player::InitVisibleBits()
3267 updateVisualBits.SetCount(PLAYER_END);
3269 updateVisualBits.SetBit(OBJECT_FIELD_GUID);
3270 updateVisualBits.SetBit(OBJECT_FIELD_TYPE);
3271 updateVisualBits.SetBit(OBJECT_FIELD_ENTRY);
3272 updateVisualBits.SetBit(OBJECT_FIELD_SCALE_X);
3273 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 0);
3274 updateVisualBits.SetBit(UNIT_FIELD_CHARM + 1);
3275 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 0);
3276 updateVisualBits.SetBit(UNIT_FIELD_SUMMON + 1);
3277 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 0);
3278 updateVisualBits.SetBit(UNIT_FIELD_CHARMEDBY + 1);
3279 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 0);
3280 updateVisualBits.SetBit(UNIT_FIELD_TARGET + 1);
3281 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 0);
3282 updateVisualBits.SetBit(UNIT_FIELD_CHANNEL_OBJECT + 1);
3283 updateVisualBits.SetBit(UNIT_FIELD_BYTES_0);
3284 updateVisualBits.SetBit(UNIT_FIELD_HEALTH);
3285 updateVisualBits.SetBit(UNIT_FIELD_POWER1);
3286 updateVisualBits.SetBit(UNIT_FIELD_POWER2);
3287 updateVisualBits.SetBit(UNIT_FIELD_POWER3);
3288 updateVisualBits.SetBit(UNIT_FIELD_POWER4);
3289 updateVisualBits.SetBit(UNIT_FIELD_POWER5);
3290 updateVisualBits.SetBit(UNIT_FIELD_POWER6);
3291 updateVisualBits.SetBit(UNIT_FIELD_POWER7);
3292 updateVisualBits.SetBit(UNIT_FIELD_MAXHEALTH);
3293 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER1);
3294 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER2);
3295 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER3);
3296 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER4);
3297 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER5);
3298 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER6);
3299 updateVisualBits.SetBit(UNIT_FIELD_MAXPOWER7);
3300 updateVisualBits.SetBit(UNIT_FIELD_LEVEL);
3301 updateVisualBits.SetBit(UNIT_FIELD_FACTIONTEMPLATE);
3302 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 0);
3303 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 1);
3304 updateVisualBits.SetBit(UNIT_VIRTUAL_ITEM_SLOT_ID + 2);
3305 updateVisualBits.SetBit(UNIT_FIELD_FLAGS);
3306 updateVisualBits.SetBit(UNIT_FIELD_FLAGS_2);
3307 updateVisualBits.SetBit(UNIT_FIELD_AURASTATE);
3308 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 0);
3309 updateVisualBits.SetBit(UNIT_FIELD_BASEATTACKTIME + 1);
3310 updateVisualBits.SetBit(UNIT_FIELD_BOUNDINGRADIUS);
3311 updateVisualBits.SetBit(UNIT_FIELD_COMBATREACH);
3312 updateVisualBits.SetBit(UNIT_FIELD_DISPLAYID);
3313 updateVisualBits.SetBit(UNIT_FIELD_NATIVEDISPLAYID);
3314 updateVisualBits.SetBit(UNIT_FIELD_MOUNTDISPLAYID);
3315 updateVisualBits.SetBit(UNIT_FIELD_BYTES_1);
3316 updateVisualBits.SetBit(UNIT_FIELD_PETNUMBER);
3317 updateVisualBits.SetBit(UNIT_FIELD_PET_NAME_TIMESTAMP);
3318 updateVisualBits.SetBit(UNIT_DYNAMIC_FLAGS);
3319 updateVisualBits.SetBit(UNIT_CHANNEL_SPELL);
3320 updateVisualBits.SetBit(UNIT_MOD_CAST_SPEED);
3321 updateVisualBits.SetBit(UNIT_FIELD_BASE_MANA);
3322 updateVisualBits.SetBit(UNIT_FIELD_BYTES_2);
3323 updateVisualBits.SetBit(UNIT_FIELD_HOVERHEIGHT);
3325 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 0);
3326 updateVisualBits.SetBit(PLAYER_DUEL_ARBITER + 1);
3327 updateVisualBits.SetBit(PLAYER_FLAGS);
3328 updateVisualBits.SetBit(PLAYER_GUILDID);
3329 updateVisualBits.SetBit(PLAYER_GUILDRANK);
3330 updateVisualBits.SetBit(PLAYER_BYTES);
3331 updateVisualBits.SetBit(PLAYER_BYTES_2);
3332 updateVisualBits.SetBit(PLAYER_BYTES_3);
3333 updateVisualBits.SetBit(PLAYER_DUEL_TEAM);
3334 updateVisualBits.SetBit(PLAYER_GUILD_TIMESTAMP);
3336 // PLAYER_QUEST_LOG_x also visible bit on official (but only on party/raid)...
3337 for(uint16 i = PLAYER_QUEST_LOG_1_1; i < PLAYER_QUEST_LOG_25_2; i += 4)
3338 updateVisualBits.SetBit(i);
3340 // Players visible items are not inventory stuff
3341 for(uint16 i = 0; i < EQUIPMENT_SLOT_END; ++i)
3343 uint32 offset = i * MAX_VISIBLE_ITEM_OFFSET;
3345 // item creator
3346 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 0 + offset);
3347 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_CREATOR + 1 + offset);
3349 // item entry
3350 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 0 + offset);
3352 // item enchantments
3353 for(uint8 j = 0; j < MAX_ENCHANTMENT_SLOT; ++j)
3354 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_0 + 1 + j + offset);
3356 // random properties
3357 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PROPERTIES + offset);
3358 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_SEED + offset);
3359 updateVisualBits.SetBit(PLAYER_VISIBLE_ITEM_1_PAD + offset);
3362 updateVisualBits.SetBit(PLAYER_CHOSEN_TITLE);
3365 void Player::BuildCreateUpdateBlockForPlayer( UpdateData *data, Player *target ) const
3367 for(int i = 0; i < EQUIPMENT_SLOT_END; i++)
3369 if(m_items[i] == NULL)
3370 continue;
3372 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3375 if(target == this)
3377 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3379 if(m_items[i] == NULL)
3380 continue;
3382 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3384 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
3386 if(m_items[i] == NULL)
3387 continue;
3389 m_items[i]->BuildCreateUpdateBlockForPlayer( data, target );
3393 Unit::BuildCreateUpdateBlockForPlayer( data, target );
3396 void Player::DestroyForPlayer( Player *target ) const
3398 Unit::DestroyForPlayer( target );
3400 for(int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
3402 if(m_items[i] == NULL)
3403 continue;
3405 m_items[i]->DestroyForPlayer( target );
3408 if(target == this)
3410 for(int i = INVENTORY_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
3412 if(m_items[i] == NULL)
3413 continue;
3415 m_items[i]->DestroyForPlayer( target );
3417 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
3419 if(m_items[i] == NULL)
3420 continue;
3422 m_items[i]->DestroyForPlayer( target );
3427 bool Player::HasSpell(uint32 spell) const
3429 PlayerSpellMap::const_iterator itr = m_spells.find((uint16)spell);
3430 return (itr != m_spells.end() && itr->second->state != PLAYERSPELL_REMOVED && !itr->second->disabled);
3433 TrainerSpellState Player::GetTrainerSpellState(TrainerSpell const* trainer_spell) const
3435 if (!trainer_spell)
3436 return TRAINER_SPELL_RED;
3438 if (!trainer_spell->spell)
3439 return TRAINER_SPELL_RED;
3441 // known spell
3442 if(HasSpell(trainer_spell->spell))
3443 return TRAINER_SPELL_GRAY;
3445 // check race/class requirement
3446 if(!IsSpellFitByClassAndRace(trainer_spell->spell))
3447 return TRAINER_SPELL_RED;
3449 // check level requirement
3450 if(getLevel() < trainer_spell->reqlevel)
3451 return TRAINER_SPELL_RED;
3453 if(SpellChainNode const* spell_chain = spellmgr.GetSpellChainNode(trainer_spell->spell))
3455 // check prev.rank requirement
3456 if(spell_chain->prev && !HasSpell(spell_chain->prev))
3457 return TRAINER_SPELL_RED;
3459 // check additional spell requirement
3460 if(spell_chain->req && !HasSpell(spell_chain->req))
3461 return TRAINER_SPELL_RED;
3464 // check skill requirement
3465 if(trainer_spell->reqskill && GetBaseSkillValue(trainer_spell->reqskill) < trainer_spell->reqskillvalue)
3466 return TRAINER_SPELL_RED;
3468 // exist, already checked at loading
3469 SpellEntry const* spell = sSpellStore.LookupEntry(trainer_spell->spell);
3471 // secondary prof. or not prof. spell
3472 uint32 skill = spell->EffectMiscValue[1];
3474 if(spell->Effect[1] != SPELL_EFFECT_SKILL || !IsPrimaryProfessionSkill(skill))
3475 return TRAINER_SPELL_GREEN;
3477 // check primary prof. limit
3478 if(spellmgr.IsPrimaryProfessionFirstRankSpell(spell->Id) && GetFreePrimaryProffesionPoints() == 0)
3479 return TRAINER_SPELL_RED;
3481 return TRAINER_SPELL_GREEN;
3484 void Player::DeleteFromDB(uint64 playerguid, uint32 accountId, bool updateRealmChars)
3486 uint32 guid = GUID_LOPART(playerguid);
3488 // convert corpse to bones if exist (to prevent exiting Corpse in World without DB entry)
3489 // bones will be deleted by corpse/bones deleting thread shortly
3490 ObjectAccessor::Instance().ConvertCorpseForPlayer(playerguid);
3492 // remove from guild
3493 uint32 guildId = GetGuildIdFromDB(playerguid);
3494 if(guildId != 0)
3496 Guild* guild = objmgr.GetGuildById(guildId);
3497 if(guild)
3498 guild->DelMember(guid);
3501 // the player was uninvited already on logout so just remove from group
3502 QueryResult *resultGroup = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", guid);
3503 if(resultGroup)
3505 uint64 leaderGuid = MAKE_NEW_GUID((*resultGroup)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
3506 delete resultGroup;
3507 Group* group = objmgr.GetGroupByLeader(leaderGuid);
3508 if(group)
3510 RemoveFromGroup(group, playerguid);
3514 // remove signs from petitions (also remove petitions if owner);
3515 RemovePetitionsAndSigns(playerguid, 10);
3517 // return back all mails with COD and Item 0 1 2 3 4 5 6
3518 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);
3519 if(resultMail)
3523 Field *fields = resultMail->Fetch();
3525 uint32 mail_id = fields[0].GetUInt32();
3526 uint16 mailTemplateId= fields[1].GetUInt16();
3527 uint32 sender = fields[2].GetUInt32();
3528 std::string subject = fields[3].GetCppString();
3529 uint32 itemTextId = fields[4].GetUInt32();
3530 uint32 money = fields[5].GetUInt32();
3531 bool has_items = fields[6].GetBool();
3533 //we can return mail now
3534 //so firstly delete the old one
3535 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", mail_id);
3537 MailItemsInfo mi;
3538 if(has_items)
3540 QueryResult *resultItems = CharacterDatabase.PQuery("SELECT item_guid,item_template FROM mail_items WHERE mail_id='%u'", mail_id);
3541 if(resultItems)
3545 Field *fields2 = resultItems->Fetch();
3547 uint32 item_guidlow = fields2[0].GetUInt32();
3548 uint32 item_template = fields2[1].GetUInt32();
3550 ItemPrototype const* itemProto = objmgr.GetItemPrototype(item_template);
3551 if(!itemProto)
3553 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guidlow);
3554 continue;
3557 Item *pItem = NewItemOrBag(itemProto);
3558 if(!pItem->LoadFromDB(item_guidlow, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER)))
3560 pItem->FSetState(ITEM_REMOVED);
3561 pItem->SaveToDB(); // it also deletes item object !
3562 continue;
3565 mi.AddItem(item_guidlow, item_template, pItem);
3567 while (resultItems->NextRow());
3569 delete resultItems;
3573 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", mail_id);
3575 uint32 pl_account = objmgr.GetPlayerAccountIdByGUID(MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
3577 WorldSession::SendReturnToSender(MAIL_NORMAL, pl_account, guid, sender, subject, itemTextId, &mi, money, mailTemplateId);
3579 while (resultMail->NextRow());
3581 delete resultMail;
3584 // unsummon and delete for pets in world is not required: player deleted from CLI or character list with not loaded pet.
3585 // Get guids of character's pets, will deleted in transaction
3586 QueryResult *resultPets = CharacterDatabase.PQuery("SELECT id FROM character_pet WHERE owner = '%u'",guid);
3588 // NOW we can finally clear other DB data related to character
3589 CharacterDatabase.BeginTransaction();
3590 if (resultPets)
3594 Field *fields3 = resultPets->Fetch();
3595 uint32 petguidlow = fields3[0].GetUInt32();
3596 Pet::DeleteFromDB(petguidlow);
3597 } while (resultPets->NextRow());
3598 delete resultPets;
3601 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",guid);
3602 CharacterDatabase.PExecute("DELETE FROM character_declinedname WHERE guid = '%u'",guid);
3603 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u'",guid);
3604 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",guid);
3605 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE guid = '%u'",guid);
3606 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'",guid);
3607 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u'",guid);
3608 CharacterDatabase.PExecute("DELETE FROM group_instance WHERE leaderGuid = '%u'",guid);
3609 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE guid = '%u'",guid);
3610 CharacterDatabase.PExecute("DELETE FROM character_queststatus WHERE guid = '%u'",guid);
3611 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u'",guid);
3612 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u'",guid);
3613 CharacterDatabase.PExecute("DELETE FROM character_spell_cooldown WHERE guid = '%u'",guid);
3614 CharacterDatabase.PExecute("DELETE FROM character_ticket WHERE guid = '%u'",guid);
3615 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE owner_guid = '%u'",guid);
3616 CharacterDatabase.PExecute("DELETE FROM character_social WHERE guid = '%u' OR friend='%u'",guid,guid);
3617 CharacterDatabase.PExecute("DELETE FROM mail WHERE receiver = '%u'",guid);
3618 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE receiver = '%u'",guid);
3619 CharacterDatabase.PExecute("DELETE FROM character_pet WHERE owner = '%u'",guid);
3620 CharacterDatabase.PExecute("DELETE FROM character_pet_declinedname WHERE owner = '%u'",guid);
3621 CharacterDatabase.PExecute("DELETE FROM character_achievement WHERE guid = '%u'",guid);
3622 CharacterDatabase.PExecute("DELETE FROM character_achievement_progress WHERE guid = '%u'",guid);
3623 CharacterDatabase.CommitTransaction();
3625 //loginDatabase.PExecute("UPDATE realmcharacters SET numchars = numchars - 1 WHERE acctid = %d AND realmid = %d", accountId, realmID);
3626 if(updateRealmChars) sWorld.UpdateRealmCharCount(accountId);
3629 void Player::SetMovement(PlayerMovementType pType)
3631 WorldPacket data;
3632 switch(pType)
3634 case MOVE_ROOT: data.Initialize(SMSG_FORCE_MOVE_ROOT, GetPackGUID().size()+4); break;
3635 case MOVE_UNROOT: data.Initialize(SMSG_FORCE_MOVE_UNROOT, GetPackGUID().size()+4); break;
3636 case MOVE_WATER_WALK: data.Initialize(SMSG_MOVE_WATER_WALK, GetPackGUID().size()+4); break;
3637 case MOVE_LAND_WALK: data.Initialize(SMSG_MOVE_LAND_WALK, GetPackGUID().size()+4); break;
3638 default:
3639 sLog.outError("Player::SetMovement: Unsupported move type (%d), data not sent to client.",pType);
3640 return;
3642 data.append(GetPackGUID());
3643 data << uint32(0);
3644 GetSession()->SendPacket( &data );
3647 /* Preconditions:
3648 - a resurrectable corpse must not be loaded for the player (only bones)
3649 - the player must be in world
3651 void Player::BuildPlayerRepop()
3653 WorldPacket data(SMSG_PRE_RESURRECT, GetPackGUID().size());
3654 data.append(GetPackGUID());
3655 GetSession()->SendPacket(&data);
3657 if(getRace() == RACE_NIGHTELF)
3658 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)
3659 CastSpell(this, 8326, true); // auras SPELL_AURA_GHOST, SPELL_AURA_INCREASE_SPEED(why?), SPELL_AURA_INCREASE_SWIM_SPEED(why?)
3661 // there must be SMSG.FORCE_RUN_SPEED_CHANGE, SMSG.FORCE_SWIM_SPEED_CHANGE, SMSG.MOVE_WATER_WALK
3662 // there must be SMSG.STOP_MIRROR_TIMER
3663 // there we must send 888 opcode
3665 // the player cannot have a corpse already, only bones which are not returned by GetCorpse
3666 if(GetCorpse())
3668 sLog.outError("BuildPlayerRepop: player %s(%d) already has a corpse", GetName(), GetGUIDLow());
3669 assert(false);
3672 // create a corpse and place it at the player's location
3673 CreateCorpse();
3674 Corpse *corpse = GetCorpse();
3675 if(!corpse)
3677 sLog.outError("Error creating corpse for Player %s [%u]", GetName(), GetGUIDLow());
3678 return;
3680 GetMap()->Add(corpse);
3682 // convert player body to ghost
3683 SetHealth( 1 );
3685 SetMovement(MOVE_WATER_WALK);
3686 if(!GetSession()->isLogingOut())
3687 SetMovement(MOVE_UNROOT);
3689 // BG - remove insignia related
3690 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SKINNABLE);
3692 SendCorpseReclaimDelay();
3694 // to prevent cheating
3695 corpse->ResetGhostTime();
3697 StopMirrorTimers(); //disable timers(bars)
3699 SetFloatValue(UNIT_FIELD_BOUNDINGRADIUS, (float)1.0); //see radius of death player?
3701 SetByteValue(UNIT_FIELD_BYTES_1, 3, PLAYER_STATE_FLAG_ALWAYS_STAND);
3704 void Player::SendDelayResponse(const uint32 ml_seconds)
3706 //FIXME: is this delay time arg really need? 50msec by default in code
3707 WorldPacket data( SMSG_QUERY_TIME_RESPONSE, 4+4 );
3708 data << (uint32)time(NULL);
3709 data << (uint32)0;
3710 GetSession()->SendPacket( &data );
3713 void Player::ResurrectPlayer(float restore_percent, bool applySickness)
3715 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // remove spirit healer position
3716 data << uint32(-1);
3717 data << float(0);
3718 data << float(0);
3719 data << float(0);
3720 GetSession()->SendPacket(&data);
3722 // speed change, land walk
3724 // remove death flag + set aura
3725 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0x00);
3726 if(getRace() == RACE_NIGHTELF)
3727 RemoveAurasDueToSpell(20584); // speed bonuses
3728 RemoveAurasDueToSpell(8326); // SPELL_AURA_GHOST
3730 setDeathState(ALIVE);
3732 SetMovement(MOVE_LAND_WALK);
3733 SetMovement(MOVE_UNROOT);
3735 m_deathTimer = 0;
3737 // set health/powers (0- will be set in caller)
3738 if(restore_percent>0.0f)
3740 SetHealth(uint32(GetMaxHealth()*restore_percent));
3741 SetPower(POWER_MANA, uint32(GetMaxPower(POWER_MANA)*restore_percent));
3742 SetPower(POWER_RAGE, 0);
3743 SetPower(POWER_ENERGY, uint32(GetMaxPower(POWER_ENERGY)*restore_percent));
3746 // update visibility
3747 ObjectAccessor::UpdateVisibilityForPlayer(this);
3749 // some items limited to specific map
3750 DestroyZoneLimitedItem( true, GetZoneId());
3752 if(!applySickness)
3753 return;
3755 //Characters from level 1-10 are not affected by resurrection sickness.
3756 //Characters from level 11-19 will suffer from one minute of sickness
3757 //for each level they are above 10.
3758 //Characters level 20 and up suffer from ten minutes of sickness.
3759 int32 startLevel = sWorld.getConfig(CONFIG_DEATH_SICKNESS_LEVEL);
3761 if(int32(getLevel()) >= startLevel)
3763 // set resurrection sickness
3764 CastSpell(this,SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,true);
3766 // not full duration
3767 if(int32(getLevel()) < startLevel+9)
3769 int32 delta = (int32(getLevel()) - startLevel + 1)*MINUTE;
3771 for(int i =0; i < 3; ++i)
3773 if(Aura* Aur = GetAura(SPELL_ID_PASSIVE_RESURRECTION_SICKNESS,i))
3775 Aur->SetAuraDuration(delta*1000);
3776 Aur->SendAuraUpdate(false);
3783 void Player::KillPlayer()
3785 SetMovement(MOVE_ROOT);
3787 StopMirrorTimers(); //disable timers(bars)
3789 setDeathState(CORPSE);
3790 //SetFlag( UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_IN_PVP );
3792 SetFlag(UNIT_DYNAMIC_FLAGS, 0x00);
3793 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, !sMapStore.LookupEntry(GetMapId())->Instanceable());
3795 // 6 minutes until repop at graveyard
3796 m_deathTimer = 6*MINUTE*1000;
3798 UpdateCorpseReclaimDelay(); // dependent at use SetDeathPvP() call before kill
3800 // don't create corpse at this moment, player might be falling
3802 // update visibility
3803 ObjectAccessor::UpdateObjectVisibility(this);
3806 void Player::CreateCorpse()
3808 // prevent existence 2 corpse for player
3809 SpawnCorpseBones();
3811 uint32 _uf, _pb, _pb2, _cfb1, _cfb2;
3813 Corpse *corpse = new Corpse( (m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH) ? CORPSE_RESURRECTABLE_PVP : CORPSE_RESURRECTABLE_PVE );
3814 SetPvPDeath(false);
3816 if(!corpse->Create(objmgr.GenerateLowGuid(HIGHGUID_CORPSE), this, GetMapId(), GetPositionX(),
3817 GetPositionY(), GetPositionZ(), GetOrientation()))
3819 delete corpse;
3820 return;
3823 _uf = GetUInt32Value(UNIT_FIELD_BYTES_0);
3824 _pb = GetUInt32Value(PLAYER_BYTES);
3825 _pb2 = GetUInt32Value(PLAYER_BYTES_2);
3827 uint8 race = (uint8)(_uf);
3828 uint8 skin = (uint8)(_pb);
3829 uint8 face = (uint8)(_pb >> 8);
3830 uint8 hairstyle = (uint8)(_pb >> 16);
3831 uint8 haircolor = (uint8)(_pb >> 24);
3832 uint8 facialhair = (uint8)(_pb2);
3834 _cfb1 = ((0x00) | (race << 8) | (getGender() << 16) | (skin << 24));
3835 _cfb2 = ((face) | (hairstyle << 8) | (haircolor << 16) | (facialhair << 24));
3837 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_1, _cfb1 );
3838 corpse->SetUInt32Value( CORPSE_FIELD_BYTES_2, _cfb2 );
3840 uint32 flags = CORPSE_FLAG_UNK2;
3841 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_HELM))
3842 flags |= CORPSE_FLAG_HIDE_HELM;
3843 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_HIDE_CLOAK))
3844 flags |= CORPSE_FLAG_HIDE_CLOAK;
3845 if(InBattleGround())
3846 flags |= CORPSE_FLAG_LOOTABLE; // to be able to remove insignia
3847 corpse->SetUInt32Value( CORPSE_FIELD_FLAGS, flags );
3849 corpse->SetUInt32Value( CORPSE_FIELD_DISPLAY_ID, GetNativeDisplayId() );
3851 corpse->SetUInt32Value( CORPSE_FIELD_GUILD, GetGuildId() );
3853 uint32 iDisplayID;
3854 uint16 iIventoryType;
3855 uint32 _cfi;
3856 for (int i = 0; i < EQUIPMENT_SLOT_END; i++)
3858 if(m_items[i])
3860 iDisplayID = m_items[i]->GetProto()->DisplayInfoID;
3861 iIventoryType = (uint16)m_items[i]->GetProto()->InventoryType;
3863 _cfi = (uint16(iDisplayID)) | (iIventoryType)<< 24;
3864 corpse->SetUInt32Value(CORPSE_FIELD_ITEM + i,_cfi);
3868 // we don't SaveToDB for players in battlegrounds so don't do it for corpses either
3869 const MapEntry *entry = sMapStore.LookupEntry(corpse->GetMapId());
3870 assert(entry);
3871 if(entry->map_type != MAP_BATTLEGROUND)
3872 corpse->SaveToDB();
3874 // register for player, but not show
3875 ObjectAccessor::Instance().AddCorpse(corpse);
3878 void Player::SpawnCorpseBones()
3880 if(ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID()))
3881 SaveToDB(); // prevent loading as ghost without corpse
3884 Corpse* Player::GetCorpse() const
3886 return ObjectAccessor::Instance().GetCorpseForPlayerGUID(GetGUID());
3889 void Player::DurabilityLossAll(double percent, bool inventory)
3891 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
3892 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3893 DurabilityLoss(pItem,percent);
3895 if(inventory)
3897 // bags not have durability
3898 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3900 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
3901 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3902 DurabilityLoss(pItem,percent);
3904 // keys not have durability
3905 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3907 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3908 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3909 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
3910 if(Item* pItem = GetItemByPos( i, j ))
3911 DurabilityLoss(pItem,percent);
3915 void Player::DurabilityLoss(Item* item, double percent)
3917 if(!item )
3918 return;
3920 uint32 pMaxDurability = item ->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3922 if(!pMaxDurability)
3923 return;
3925 uint32 pDurabilityLoss = uint32(pMaxDurability*percent);
3927 if(pDurabilityLoss < 1 )
3928 pDurabilityLoss = 1;
3930 DurabilityPointsLoss(item,pDurabilityLoss);
3933 void Player::DurabilityPointsLossAll(int32 points, bool inventory)
3935 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
3936 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3937 DurabilityPointsLoss(pItem,points);
3939 if(inventory)
3941 // bags not have durability
3942 // for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3944 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
3945 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3946 DurabilityPointsLoss(pItem,points);
3948 // keys not have durability
3949 //for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
3951 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
3952 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
3953 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
3954 if(Item* pItem = GetItemByPos( i, j ))
3955 DurabilityPointsLoss(pItem,points);
3959 void Player::DurabilityPointsLoss(Item* item, int32 points)
3961 int32 pMaxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
3962 int32 pOldDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
3963 int32 pNewDurability = pOldDurability - points;
3965 if (pNewDurability < 0)
3966 pNewDurability = 0;
3967 else if (pNewDurability > pMaxDurability)
3968 pNewDurability = pMaxDurability;
3970 if (pOldDurability != pNewDurability)
3972 // modify item stats _before_ Durability set to 0 to pass _ApplyItemMods internal check
3973 if ( pNewDurability == 0 && pOldDurability > 0 && item->IsEquipped())
3974 _ApplyItemMods(item,item->GetSlot(), false);
3976 item->SetUInt32Value(ITEM_FIELD_DURABILITY, pNewDurability);
3978 // modify item stats _after_ restore durability to pass _ApplyItemMods internal check
3979 if ( pNewDurability > 0 && pOldDurability == 0 && item->IsEquipped())
3980 _ApplyItemMods(item,item->GetSlot(), true);
3982 item->SetState(ITEM_CHANGED, this);
3986 void Player::DurabilityPointLossForEquipSlot(EquipmentSlots slot)
3988 if(Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot ))
3989 DurabilityPointsLoss(pItem,1);
3992 uint32 Player::DurabilityRepairAll(bool cost, float discountMod, bool guildBank)
3994 uint32 TotalCost = 0;
3995 // equipped, backpack, bags itself
3996 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
3997 TotalCost += DurabilityRepair(( (INVENTORY_SLOT_BAG_0 << 8) | i ),cost,discountMod, guildBank);
3999 // bank, buyback and keys not repaired
4001 // items in inventory bags
4002 for(int j = INVENTORY_SLOT_BAG_START; j < INVENTORY_SLOT_BAG_END; j++)
4003 for(int i = 0; i < MAX_BAG_SIZE; i++)
4004 TotalCost += DurabilityRepair(( (j << 8) | i ),cost,discountMod, guildBank);
4005 return TotalCost;
4008 uint32 Player::DurabilityRepair(uint16 pos, bool cost, float discountMod, bool guildBank)
4010 Item* item = GetItemByPos(pos);
4012 uint32 TotalCost = 0;
4013 if(!item)
4014 return TotalCost;
4016 uint32 maxDurability = item->GetUInt32Value(ITEM_FIELD_MAXDURABILITY);
4017 if(!maxDurability)
4018 return TotalCost;
4020 uint32 curDurability = item->GetUInt32Value(ITEM_FIELD_DURABILITY);
4022 if(cost)
4024 uint32 LostDurability = maxDurability - curDurability;
4025 if(LostDurability>0)
4027 ItemPrototype const *ditemProto = item->GetProto();
4029 DurabilityCostsEntry const *dcost = sDurabilityCostsStore.LookupEntry(ditemProto->ItemLevel);
4030 if(!dcost)
4032 sLog.outError("ERROR: RepairDurability: Wrong item lvl %u", ditemProto->ItemLevel);
4033 return TotalCost;
4036 uint32 dQualitymodEntryId = (ditemProto->Quality+1)*2;
4037 DurabilityQualityEntry const *dQualitymodEntry = sDurabilityQualityStore.LookupEntry(dQualitymodEntryId);
4038 if(!dQualitymodEntry)
4040 sLog.outError("ERROR: RepairDurability: Wrong dQualityModEntry %u", dQualitymodEntryId);
4041 return TotalCost;
4044 uint32 dmultiplier = dcost->multiplier[ItemSubClassToDurabilityMultiplierId(ditemProto->Class,ditemProto->SubClass)];
4045 uint32 costs = uint32(LostDurability*dmultiplier*double(dQualitymodEntry->quality_mod));
4047 costs = uint32(costs * discountMod);
4049 if (costs==0) //fix for ITEM_QUALITY_ARTIFACT
4050 costs = 1;
4052 if (guildBank)
4054 if (GetGuildId()==0)
4056 DEBUG_LOG("You are not member of a guild");
4057 return TotalCost;
4060 Guild *pGuild = objmgr.GetGuildById(GetGuildId());
4061 if (!pGuild)
4062 return TotalCost;
4064 if (!pGuild->HasRankRight(GetRank(), GR_RIGHT_WITHDRAW_REPAIR))
4066 DEBUG_LOG("You do not have rights to withdraw for repairs");
4067 return TotalCost;
4070 if (pGuild->GetMemberMoneyWithdrawRem(GetGUIDLow()) < costs)
4072 DEBUG_LOG("You do not have enough money withdraw amount remaining");
4073 return TotalCost;
4076 if (pGuild->GetGuildBankMoney() < costs)
4078 DEBUG_LOG("There is not enough money in bank");
4079 return TotalCost;
4082 pGuild->MemberMoneyWithdraw(costs, GetGUIDLow());
4083 TotalCost = costs;
4085 else if (GetMoney() < costs)
4087 DEBUG_LOG("You do not have enough money");
4088 return TotalCost;
4090 else
4091 ModifyMoney( -int32(costs) );
4095 item->SetUInt32Value(ITEM_FIELD_DURABILITY, maxDurability);
4096 item->SetState(ITEM_CHANGED, this);
4098 // reapply mods for total broken and repaired item if equipped
4099 if(IsEquipmentPos(pos) && !curDurability)
4100 _ApplyItemMods(item,pos & 255, true);
4101 return TotalCost;
4104 void Player::RepopAtGraveyard()
4106 // note: this can be called also when the player is alive
4107 // for example from WorldSession::HandleMovementOpcodes
4109 AreaTableEntry const *zone = GetAreaEntryByAreaID(GetAreaId());
4111 // Such zones are considered unreachable as a ghost and the player must be automatically revived
4112 if(!isAlive() && zone && zone->flags & AREA_FLAG_NEED_FLY || GetTransport())
4114 ResurrectPlayer(0.5f);
4115 SpawnCorpseBones();
4118 WorldSafeLocsEntry const *ClosestGrave = NULL;
4120 // Special handle for battleground maps
4121 BattleGround *bg = sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
4123 if(bg && (bg->GetTypeID() == BATTLEGROUND_AB || bg->GetTypeID() == BATTLEGROUND_EY))
4124 ClosestGrave = bg->GetClosestGraveYard(GetPositionX(), GetPositionY(), GetPositionZ(), GetTeam());
4125 else
4126 ClosestGrave = objmgr.GetClosestGraveYard( GetPositionX(), GetPositionY(), GetPositionZ(), GetMapId(), GetTeam() );
4128 // stop countdown until repop
4129 m_deathTimer = 0;
4131 // if no grave found, stay at the current location
4132 // and don't show spirit healer location
4133 if(ClosestGrave)
4135 TeleportTo(ClosestGrave->map_id, ClosestGrave->x, ClosestGrave->y, ClosestGrave->z, GetOrientation());
4136 if(isDead()) // not send if alive, because it used in TeleportTo()
4138 WorldPacket data(SMSG_DEATH_RELEASE_LOC, 4*4); // show spirit healer position on minimap
4139 data << ClosestGrave->map_id;
4140 data << ClosestGrave->x;
4141 data << ClosestGrave->y;
4142 data << ClosestGrave->z;
4143 GetSession()->SendPacket(&data);
4148 void Player::JoinedChannel(Channel *c)
4150 m_channels.push_back(c);
4153 void Player::LeftChannel(Channel *c)
4155 m_channels.remove(c);
4158 void Player::CleanupChannels()
4160 while(!m_channels.empty())
4162 Channel* ch = *m_channels.begin();
4163 m_channels.erase(m_channels.begin()); // remove from player's channel list
4164 ch->Leave(GetGUID(), false); // not send to client, not remove from player's channel list
4165 if (ChannelMgr* cMgr = channelMgr(GetTeam()))
4166 cMgr->LeftChannel(ch->GetName()); // deleted channel if empty
4169 sLog.outDebug("Player: channels cleaned up!");
4172 void Player::UpdateLocalChannels(uint32 newZone )
4174 if(m_channels.empty())
4175 return;
4177 AreaTableEntry const* current_zone = GetAreaEntryByAreaID(newZone);
4178 if(!current_zone)
4179 return;
4181 ChannelMgr* cMgr = channelMgr(GetTeam());
4182 if(!cMgr)
4183 return;
4185 std::string current_zone_name = current_zone->area_name[GetSession()->GetSessionDbcLocale()];
4187 for(JoinedChannelsList::iterator i = m_channels.begin(), next; i != m_channels.end(); i = next)
4189 next = i; ++next;
4191 // skip non built-in channels
4192 if(!(*i)->IsConstant())
4193 continue;
4195 ChatChannelsEntry const* ch = GetChannelEntryFor((*i)->GetChannelId());
4196 if(!ch)
4197 continue;
4199 if((ch->flags & 4) == 4) // global channel without zone name in pattern
4200 continue;
4202 // new channel
4203 char new_channel_name_buf[100];
4204 snprintf(new_channel_name_buf,100,ch->pattern[m_session->GetSessionDbcLocale()],current_zone_name.c_str());
4205 Channel* new_channel = cMgr->GetJoinChannel(new_channel_name_buf,ch->ChannelID);
4207 if((*i)!=new_channel)
4209 new_channel->Join(GetGUID(),""); // will output Changed Channel: N. Name
4211 // leave old channel
4212 (*i)->Leave(GetGUID(),false); // not send leave channel, it already replaced at client
4213 std::string name = (*i)->GetName(); // store name, (*i)erase in LeftChannel
4214 LeftChannel(*i); // remove from player's channel list
4215 cMgr->LeftChannel(name); // delete if empty
4218 sLog.outDebug("Player: channels cleaned up!");
4221 void Player::LeaveLFGChannel()
4223 for(JoinedChannelsList::iterator i = m_channels.begin(); i != m_channels.end(); ++i )
4225 if((*i)->IsLFG())
4227 (*i)->Leave(GetGUID());
4228 break;
4233 void Player::UpdateDefense()
4235 uint32 defense_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_DEFENSE);
4237 if(UpdateSkill(SKILL_DEFENSE,defense_skill_gain))
4239 // update dependent from defense skill part
4240 UpdateDefenseBonusesMod();
4244 void Player::HandleBaseModValue(BaseModGroup modGroup, BaseModType modType, float amount, bool apply)
4246 if(modGroup >= BASEMOD_END || modType >= MOD_END)
4248 sLog.outError("ERROR in HandleBaseModValue(): non existed BaseModGroup of wrong BaseModType!");
4249 return;
4252 float val = 1.0f;
4254 switch(modType)
4256 case FLAT_MOD:
4257 m_auraBaseMod[modGroup][modType] += apply ? amount : -amount;
4258 break;
4259 case PCT_MOD:
4260 if(amount <= -100.0f)
4261 amount = -200.0f;
4263 val = (100.0f + amount) / 100.0f;
4264 m_auraBaseMod[modGroup][modType] *= apply ? val : (1.0f/val);
4265 break;
4268 if(!CanModifyStats())
4269 return;
4271 switch(modGroup)
4273 case CRIT_PERCENTAGE: UpdateCritPercentage(BASE_ATTACK); break;
4274 case RANGED_CRIT_PERCENTAGE: UpdateCritPercentage(RANGED_ATTACK); break;
4275 case OFFHAND_CRIT_PERCENTAGE: UpdateCritPercentage(OFF_ATTACK); break;
4276 case SHIELD_BLOCK_VALUE: UpdateShieldBlockValue(); break;
4277 default: break;
4281 float Player::GetBaseModValue(BaseModGroup modGroup, BaseModType modType) const
4283 if(modGroup >= BASEMOD_END || modType > MOD_END)
4285 sLog.outError("ERROR: trial to access non existed BaseModGroup or wrong BaseModType!");
4286 return 0.0f;
4289 if(modType == PCT_MOD && m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4290 return 0.0f;
4292 return m_auraBaseMod[modGroup][modType];
4295 float Player::GetTotalBaseModValue(BaseModGroup modGroup) const
4297 if(modGroup >= BASEMOD_END)
4299 sLog.outError("ERROR: wrong BaseModGroup in GetTotalBaseModValue()!");
4300 return 0.0f;
4303 if(m_auraBaseMod[modGroup][PCT_MOD] <= 0.0f)
4304 return 0.0f;
4306 return m_auraBaseMod[modGroup][FLAT_MOD] * m_auraBaseMod[modGroup][PCT_MOD];
4309 uint32 Player::GetShieldBlockValue() const
4311 BaseModGroup modGroup = SHIELD_BLOCK_VALUE;
4313 float value = GetTotalBaseModValue(modGroup) + GetStat(STAT_STRENGTH)/20 - 1;
4315 value = (value < 0) ? 0 : value;
4317 return uint32(value);
4320 float Player::GetMeleeCritFromAgility()
4322 uint32 level = getLevel();
4323 uint32 pclass = getClass();
4325 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4327 GtChanceToMeleeCritBaseEntry const *critBase = sGtChanceToMeleeCritBaseStore.LookupEntry(pclass-1);
4328 GtChanceToMeleeCritEntry const *critRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4329 if (critBase==NULL || critRatio==NULL)
4330 return 0.0f;
4332 float crit=critBase->base + GetStat(STAT_AGILITY)*critRatio->ratio;
4333 return crit*100.0f;
4336 float Player::GetDodgeFromAgility()
4338 // Table for base dodge values
4339 float dodge_base[MAX_CLASSES] = {
4340 0.0075f, // Warrior
4341 0.00652f, // Paladin
4342 -0.0545f, // Hunter
4343 -0.0059f, // Rogue
4344 0.03183f, // Priest
4345 0.0114f, // DK
4346 0.0167f, // Shaman
4347 0.034575f, // Mage
4348 0.02011f, // Warlock
4349 0.0f, // ??
4350 -0.0187f // Druid
4352 // Crit/agility to dodge/agility coefficient multipliers
4353 float crit_to_dodge[MAX_CLASSES] = {
4354 1.1f, // Warrior
4355 1.0f, // Paladin
4356 1.6f, // Hunter
4357 2.0f, // Rogue
4358 1.0f, // Priest
4359 1.0f, // DK?
4360 1.0f, // Shaman
4361 1.0f, // Mage
4362 1.0f, // Warlock
4363 0.0f, // ??
4364 1.7f // Druid
4367 uint32 level = getLevel();
4368 uint32 pclass = getClass();
4370 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4372 // Dodge per agility for most classes equal crit per agility (but for some classes need apply some multiplier)
4373 GtChanceToMeleeCritEntry const *dodgeRatio = sGtChanceToMeleeCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4374 if (dodgeRatio==NULL || pclass > MAX_CLASSES)
4375 return 0.0f;
4377 float dodge=dodge_base[pclass-1] + GetStat(STAT_AGILITY) * dodgeRatio->ratio * crit_to_dodge[pclass-1];
4378 return dodge*100.0f;
4381 float Player::GetSpellCritFromIntellect()
4383 uint32 level = getLevel();
4384 uint32 pclass = getClass();
4386 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4388 GtChanceToSpellCritBaseEntry const *critBase = sGtChanceToSpellCritBaseStore.LookupEntry(pclass-1);
4389 GtChanceToSpellCritEntry const *critRatio = sGtChanceToSpellCritStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4390 if (critBase==NULL || critRatio==NULL)
4391 return 0.0f;
4393 float crit=critBase->base + GetStat(STAT_INTELLECT)*critRatio->ratio;
4394 return crit*100.0f;
4397 float Player::GetRatingCoefficient(CombatRating cr) const
4399 uint32 level = getLevel();
4401 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4403 GtCombatRatingsEntry const *Rating = sGtCombatRatingsStore.LookupEntry(cr*GT_MAX_LEVEL+level-1);
4404 if (Rating == NULL)
4405 return 1.0f; // By default use minimum coefficient (not must be called)
4407 return Rating->ratio;
4410 float Player::GetRatingBonusValue(CombatRating cr) const
4412 return float(GetUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr)) / GetRatingCoefficient(cr);
4415 uint32 Player::GetMeleeCritDamageReduction(uint32 damage) const
4417 float melee = GetRatingBonusValue(CR_CRIT_TAKEN_MELEE)*2.0f;
4418 if (melee>25.0f) melee = 25.0f;
4419 return uint32 (melee * damage /100.0f);
4422 uint32 Player::GetRangedCritDamageReduction(uint32 damage) const
4424 float ranged = GetRatingBonusValue(CR_CRIT_TAKEN_RANGED)*2.0f;
4425 if (ranged>25.0f) ranged=25.0f;
4426 return uint32 (ranged * damage /100.0f);
4429 uint32 Player::GetSpellCritDamageReduction(uint32 damage) const
4431 float spell = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL)*2.0f;
4432 // In wow script resilience limited to 25%
4433 if (spell>25.0f)
4434 spell = 25.0f;
4435 return uint32 (spell * damage / 100.0f);
4438 uint32 Player::GetDotDamageReduction(uint32 damage) const
4440 float spellDot = GetRatingBonusValue(CR_CRIT_TAKEN_SPELL);
4441 // Dot resilience not limited (limit it by 100%)
4442 if (spellDot > 100.0f)
4443 spellDot = 100.0f;
4444 return uint32 (spellDot * damage / 100.0f);
4447 float Player::GetExpertiseDodgeOrParryReduction(WeaponAttackType attType) const
4449 switch (attType)
4451 case BASE_ATTACK:
4452 return GetUInt32Value(PLAYER_EXPERTISE) / 4.0f;
4453 case OFF_ATTACK:
4454 return GetUInt32Value(PLAYER_OFFHAND_EXPERTISE) / 4.0f;
4455 default:
4456 break;
4458 return 0.0f;
4461 float Player::OCTRegenHPPerSpirit()
4463 uint32 level = getLevel();
4464 uint32 pclass = getClass();
4466 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4468 GtOCTRegenHPEntry const *baseRatio = sGtOCTRegenHPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4469 GtRegenHPPerSptEntry const *moreRatio = sGtRegenHPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4470 if (baseRatio==NULL || moreRatio==NULL)
4471 return 0.0f;
4473 // Formula from PaperDollFrame script
4474 float spirit = GetStat(STAT_SPIRIT);
4475 float baseSpirit = spirit;
4476 if (baseSpirit>50) baseSpirit = 50;
4477 float moreSpirit = spirit - baseSpirit;
4478 float regen = baseSpirit * baseRatio->ratio + moreSpirit * moreRatio->ratio;
4479 return regen;
4482 float Player::OCTRegenMPPerSpirit()
4484 uint32 level = getLevel();
4485 uint32 pclass = getClass();
4487 if (level>GT_MAX_LEVEL) level = GT_MAX_LEVEL;
4489 // GtOCTRegenMPEntry const *baseRatio = sGtOCTRegenMPStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4490 GtRegenMPPerSptEntry const *moreRatio = sGtRegenMPPerSptStore.LookupEntry((pclass-1)*GT_MAX_LEVEL + level-1);
4491 if (moreRatio==NULL)
4492 return 0.0f;
4494 // Formula get from PaperDollFrame script
4495 float spirit = GetStat(STAT_SPIRIT);
4496 float regen = spirit * moreRatio->ratio;
4497 return regen;
4500 void Player::ApplyRatingMod(CombatRating cr, int32 value, bool apply)
4502 ApplyModUInt32Value(PLAYER_FIELD_COMBAT_RATING_1 + cr, value, apply);
4504 float RatingCoeffecient = GetRatingCoefficient(cr);
4505 float RatingChange = 0.0f;
4507 bool affectStats = CanModifyStats();
4509 switch (cr)
4511 case CR_WEAPON_SKILL: // Implemented in Unit::RollMeleeOutcomeAgainst
4512 case CR_DEFENSE_SKILL:
4513 UpdateDefenseBonusesMod();
4514 break;
4515 case CR_DODGE:
4516 UpdateDodgePercentage();
4517 break;
4518 case CR_PARRY:
4519 UpdateParryPercentage();
4520 break;
4521 case CR_BLOCK:
4522 UpdateBlockPercentage();
4523 break;
4524 case CR_HIT_MELEE:
4525 RatingChange = value / RatingCoeffecient;
4526 m_modMeleeHitChance += apply ? RatingChange : -RatingChange;
4527 break;
4528 case CR_HIT_RANGED:
4529 RatingChange = value / RatingCoeffecient;
4530 m_modRangedHitChance += apply ? RatingChange : -RatingChange;
4531 break;
4532 case CR_HIT_SPELL:
4533 RatingChange = value / RatingCoeffecient;
4534 m_modSpellHitChance += apply ? RatingChange : -RatingChange;
4535 break;
4536 case CR_CRIT_MELEE:
4537 if(affectStats)
4539 UpdateCritPercentage(BASE_ATTACK);
4540 UpdateCritPercentage(OFF_ATTACK);
4542 break;
4543 case CR_CRIT_RANGED:
4544 if(affectStats)
4545 UpdateCritPercentage(RANGED_ATTACK);
4546 break;
4547 case CR_CRIT_SPELL:
4548 if(affectStats)
4549 UpdateAllSpellCritChances();
4550 break;
4551 case CR_HIT_TAKEN_MELEE: // Implemented in Unit::MeleeMissChanceCalc
4552 case CR_HIT_TAKEN_RANGED:
4553 break;
4554 case CR_HIT_TAKEN_SPELL: // Implemented in Unit::MagicSpellHitResult
4555 break;
4556 case CR_CRIT_TAKEN_MELEE: // Implemented in Unit::RollMeleeOutcomeAgainst (only for chance to crit)
4557 case CR_CRIT_TAKEN_RANGED:
4558 break;
4559 case CR_CRIT_TAKEN_SPELL: // Implemented in Unit::SpellCriticalBonus (only for chance to crit)
4560 break;
4561 case CR_HASTE_MELEE:
4562 RatingChange = value / RatingCoeffecient;
4563 ApplyAttackTimePercentMod(BASE_ATTACK,RatingChange,apply);
4564 ApplyAttackTimePercentMod(OFF_ATTACK,RatingChange,apply);
4565 break;
4566 case CR_HASTE_RANGED:
4567 RatingChange = value / RatingCoeffecient;
4568 ApplyAttackTimePercentMod(RANGED_ATTACK, RatingChange, apply);
4569 break;
4570 case CR_HASTE_SPELL:
4571 RatingChange = value / RatingCoeffecient;
4572 ApplyCastTimePercentMod(RatingChange,apply);
4573 break;
4574 case CR_WEAPON_SKILL_MAINHAND: // Implemented in Unit::RollMeleeOutcomeAgainst
4575 case CR_WEAPON_SKILL_OFFHAND:
4576 case CR_WEAPON_SKILL_RANGED:
4577 break;
4578 case CR_EXPERTISE:
4579 if(affectStats)
4581 UpdateExpertise(BASE_ATTACK);
4582 UpdateExpertise(OFF_ATTACK);
4584 break;
4588 void Player::SetRegularAttackTime()
4590 for(int i = 0; i < MAX_ATTACK; ++i)
4592 Item *tmpitem = GetWeaponForAttack(WeaponAttackType(i));
4593 if(tmpitem && !tmpitem->IsBroken())
4595 ItemPrototype const *proto = tmpitem->GetProto();
4596 if(proto->Delay)
4597 SetAttackTime(WeaponAttackType(i), proto->Delay);
4598 else
4599 SetAttackTime(WeaponAttackType(i), BASE_ATTACK_TIME);
4604 //skill+step, checking for max value
4605 bool Player::UpdateSkill(uint32 skill_id, uint32 step)
4607 if(!skill_id)
4608 return false;
4610 uint16 i=0;
4611 for (; i < PLAYER_MAX_SKILLS; i++)
4612 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill_id)
4613 break;
4615 if(i>=PLAYER_MAX_SKILLS)
4616 return false;
4618 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4619 uint32 value = SKILL_VALUE(data);
4620 uint32 max = SKILL_MAX(data);
4622 if ((!max) || (!value) || (value >= max))
4623 return false;
4625 if (value*512 < max*urand(0,512))
4627 uint32 new_value = value+step;
4628 if(new_value > max)
4629 new_value = max;
4631 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,max));
4632 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4633 return true;
4636 return false;
4639 inline int SkillGainChance(uint32 SkillValue, uint32 GrayLevel, uint32 GreenLevel, uint32 YellowLevel)
4641 if ( SkillValue >= GrayLevel )
4642 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREY)*10;
4643 if ( SkillValue >= GreenLevel )
4644 return sWorld.getConfig(CONFIG_SKILL_CHANCE_GREEN)*10;
4645 if ( SkillValue >= YellowLevel )
4646 return sWorld.getConfig(CONFIG_SKILL_CHANCE_YELLOW)*10;
4647 return sWorld.getConfig(CONFIG_SKILL_CHANCE_ORANGE)*10;
4650 bool Player::UpdateCraftSkill(uint32 spellid)
4652 sLog.outDebug("UpdateCraftSkill spellid %d", spellid);
4654 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spellid);
4655 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spellid);
4657 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4659 if(_spell_idx->second->skillId)
4661 uint32 SkillValue = GetPureSkillValue(_spell_idx->second->skillId);
4663 // Alchemy Discoveries here
4664 SpellEntry const* spellEntry = sSpellStore.LookupEntry(spellid);
4665 if(spellEntry && spellEntry->Mechanic==MECHANIC_DISCOVERY)
4667 if(uint32 discoveredSpell = GetSkillDiscoverySpell(_spell_idx->second->skillId, spellid, this))
4668 learnSpell(discoveredSpell);
4671 uint32 craft_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_CRAFTING);
4673 return UpdateSkillPro(_spell_idx->second->skillId, SkillGainChance(SkillValue,
4674 _spell_idx->second->max_value,
4675 (_spell_idx->second->max_value + _spell_idx->second->min_value)/2,
4676 _spell_idx->second->min_value),
4677 craft_skill_gain);
4680 return false;
4683 bool Player::UpdateGatherSkill(uint32 SkillId, uint32 SkillValue, uint32 RedLevel, uint32 Multiplicator )
4685 sLog.outDebug("UpdateGatherSkill(SkillId %d SkillLevel %d RedLevel %d)", SkillId, SkillValue, RedLevel);
4687 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4689 // For skinning and Mining chance decrease with level. 1-74 - no decrease, 75-149 - 2 times, 225-299 - 8 times
4690 switch (SkillId)
4692 case SKILL_HERBALISM:
4693 case SKILL_LOCKPICKING:
4694 case SKILL_JEWELCRAFTING:
4695 case SKILL_INSCRIPTION:
4696 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4697 case SKILL_SKINNING:
4698 if( sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)==0)
4699 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4700 else
4701 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_SKINNING_STEPS)), gathering_skill_gain);
4702 case SKILL_MINING:
4703 if (sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)==0)
4704 return UpdateSkillPro(SkillId, SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator,gathering_skill_gain);
4705 else
4706 return UpdateSkillPro(SkillId, (SkillGainChance(SkillValue, RedLevel+100, RedLevel+50, RedLevel+25)*Multiplicator) >> (SkillValue/sWorld.getConfig(CONFIG_SKILL_CHANCE_MINING_STEPS)),gathering_skill_gain);
4708 return false;
4711 bool Player::UpdateFishingSkill()
4713 sLog.outDebug("UpdateFishingSkill");
4715 uint32 SkillValue = GetPureSkillValue(SKILL_FISHING);
4717 int32 chance = SkillValue < 75 ? 100 : 2500/(SkillValue-50);
4719 uint32 gathering_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_GATHERING);
4721 return UpdateSkillPro(SKILL_FISHING,chance*10,gathering_skill_gain);
4724 bool Player::UpdateSkillPro(uint16 SkillId, int32 Chance, uint32 step)
4726 sLog.outDebug("UpdateSkillPro(SkillId %d, Chance %3.1f%%)", SkillId, Chance/10.0);
4727 if ( !SkillId )
4728 return false;
4730 if(Chance <= 0) // speedup in 0 chance case
4732 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4733 return false;
4736 uint16 i=0;
4737 for (; i < PLAYER_MAX_SKILLS; i++)
4738 if ( SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_INDEX(i))) == SkillId ) break;
4739 if ( i >= PLAYER_MAX_SKILLS )
4740 return false;
4742 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4743 uint16 SkillValue = SKILL_VALUE(data);
4744 uint16 MaxValue = SKILL_MAX(data);
4746 if ( !MaxValue || !SkillValue || SkillValue >= MaxValue )
4747 return false;
4749 int32 Roll = irand(1,1000);
4751 if ( Roll <= Chance )
4753 uint32 new_value = SkillValue+step;
4754 if(new_value > MaxValue)
4755 new_value = MaxValue;
4757 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(new_value,MaxValue));
4758 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4759 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% taken", Chance/10.0);
4760 return true;
4763 sLog.outDebug("Player::UpdateSkillPro Chance=%3.1f%% missed", Chance/10.0);
4764 return false;
4767 void Player::UpdateWeaponSkill (WeaponAttackType attType)
4769 // no skill gain in pvp
4770 Unit *pVictim = getVictim();
4771 if(pVictim && pVictim->GetTypeId() == TYPEID_PLAYER)
4772 return;
4774 if(IsInFeralForm())
4775 return; // always maximized SKILL_FERAL_COMBAT in fact
4777 if(m_form == FORM_TREE)
4778 return; // use weapon but not skill up
4780 uint32 weapon_skill_gain = sWorld.getConfig(CONFIG_SKILL_GAIN_WEAPON);
4782 switch(attType)
4784 case BASE_ATTACK:
4786 Item *tmpitem = GetWeaponForAttack(attType,true);
4788 if (!tmpitem)
4789 UpdateSkill(SKILL_UNARMED,weapon_skill_gain);
4790 else if(tmpitem->GetProto()->SubClass != ITEM_SUBCLASS_WEAPON_FISHING_POLE)
4791 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4792 break;
4794 case OFF_ATTACK:
4795 case RANGED_ATTACK:
4797 Item *tmpitem = GetWeaponForAttack(attType,true);
4798 if (tmpitem)
4799 UpdateSkill(tmpitem->GetSkill(),weapon_skill_gain);
4800 break;
4803 UpdateAllCritPercentages();
4806 void Player::UpdateCombatSkills(Unit *pVictim, WeaponAttackType attType, MeleeHitOutcome outcome, bool defence)
4808 switch(outcome)
4810 case MELEE_HIT_CRIT:
4811 case MELEE_HIT_DODGE:
4812 case MELEE_HIT_PARRY:
4813 case MELEE_HIT_BLOCK:
4814 case MELEE_HIT_BLOCK_CRIT:
4815 return;
4817 default:
4818 break;
4821 uint32 plevel = getLevel(); // if defense than pVictim == attacker
4822 uint32 greylevel = MaNGOS::XP::GetGrayLevel(plevel);
4823 uint32 moblevel = pVictim->getLevelForTarget(this);
4824 if(moblevel < greylevel)
4825 return;
4827 if (moblevel > plevel + 5)
4828 moblevel = plevel + 5;
4830 uint32 lvldif = moblevel - greylevel;
4831 if(lvldif < 3)
4832 lvldif = 3;
4834 uint32 skilldif = 5 * plevel - (defence ? GetBaseDefenseSkillValue() : GetBaseWeaponSkillValue(attType));
4835 if(skilldif <= 0)
4836 return;
4838 float chance = float(3 * lvldif * skilldif) / plevel;
4839 if(!defence)
4841 if(getClass() == CLASS_WARRIOR || getClass() == CLASS_ROGUE)
4842 chance *= 0.1f * GetStat(STAT_INTELLECT);
4845 chance = chance < 1.0f ? 1.0f : chance; //minimum chance to increase skill is 1%
4847 if(roll_chance_f(chance))
4849 if(defence)
4850 UpdateDefense();
4851 else
4852 UpdateWeaponSkill(attType);
4854 else
4855 return;
4858 void Player::ModifySkillBonus(uint32 skillid,int32 val, bool talent)
4860 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4861 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skillid)
4863 uint32 bonus_val = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
4864 int16 temp_bonus = SKILL_TEMP_BONUS(bonus_val);
4865 int16 perm_bonus = SKILL_PERM_BONUS(bonus_val);
4867 if(talent) // permanent bonus stored in high part
4868 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus,perm_bonus+val));
4869 else // temporary/item bonus stored in low part
4870 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),MAKE_SKILL_BONUS(temp_bonus+val,perm_bonus));
4871 return;
4875 void Player::UpdateSkillsForLevel()
4877 uint16 maxconfskill = sWorld.GetConfigMaxSkillValue();
4878 uint32 maxSkill = GetMaxSkillValueForLevel();
4880 bool alwaysMaxSkill = sWorld.getConfig(CONFIG_ALWAYS_MAX_SKILL_FOR_LEVEL);
4882 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4883 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4885 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
4887 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(pskill);
4888 if(!pSkill)
4889 continue;
4891 if(GetSkillRangeType(pSkill,false) != SKILL_RANGE_LEVEL)
4892 continue;
4894 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4895 uint32 max = SKILL_MAX(data);
4896 uint32 val = SKILL_VALUE(data);
4898 /// update only level dependent max skill values
4899 if(max!=1)
4901 /// miximize skill always
4902 if(alwaysMaxSkill)
4903 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(maxSkill,maxSkill));
4904 /// update max skill value if current max skill not maximized
4905 else if(max != maxconfskill)
4906 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(val,maxSkill));
4911 void Player::UpdateSkillsToMaxSkillsForLevel()
4913 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
4914 if (GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4916 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
4917 if( IsProfessionSkill(pskill) || pskill == SKILL_RIDING )
4918 continue;
4919 uint32 data = GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i));
4921 uint32 max = SKILL_MAX(data);
4923 if(max > 1)
4924 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(max,max));
4926 if(pskill == SKILL_DEFENSE)
4927 UpdateDefenseBonusesMod();
4931 // This functions sets a skill line value (and adds if doesn't exist yet)
4932 // To "remove" a skill line, set it's values to zero
4933 void Player::SetSkill(uint32 id, uint16 currVal, uint16 maxVal)
4935 if(!id)
4936 return;
4938 uint16 i=0;
4939 for (; i < PLAYER_MAX_SKILLS; i++)
4940 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == id) break;
4942 if(i<PLAYER_MAX_SKILLS) //has skill
4944 if(currVal)
4946 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
4947 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4949 else //remove
4951 // clear skill fields
4952 SetUInt32Value(PLAYER_SKILL_INDEX(i),0);
4953 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),0);
4954 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
4956 // remove spells that depend on this skill when removing the skill
4957 for (PlayerSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
4959 ++next;
4960 if(itr->second->state == PLAYERSPELL_REMOVED)
4961 continue;
4963 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(itr->first);
4964 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(itr->first);
4966 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
4968 if (_spell_idx->second->skillId == id)
4970 // this may remove more than one spell (dependents)
4971 removeSpell(itr->first);
4972 next = m_spells.begin();
4973 break;
4979 else if(currVal) //add
4981 for (i=0; i < PLAYER_MAX_SKILLS; i++)
4982 if (!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
4984 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
4985 if(!pSkill)
4987 sLog.outError("Skill not found in SkillLineStore: skill #%u", id);
4988 return;
4990 // enable unlearn button for primary professions only
4991 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
4992 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
4993 else
4994 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
4995 SetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i),MAKE_SKILL_VALUE(currVal,maxVal));
4996 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL);
4998 // apply skill bonuses
4999 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
5001 // temporary bonuses
5002 AuraList const& mModSkill = GetAurasByType(SPELL_AURA_MOD_SKILL);
5003 for(AuraList::const_iterator i = mModSkill.begin(); i != mModSkill.end(); ++i)
5004 if ((*i)->GetModifier()->m_miscvalue == int32(id))
5005 (*i)->ApplyModifier(true);
5007 // permanent bonuses
5008 AuraList const& mModSkillTalent = GetAurasByType(SPELL_AURA_MOD_SKILL_TALENT);
5009 for(AuraList::const_iterator i = mModSkillTalent.begin(); i != mModSkillTalent.end(); ++i)
5010 if ((*i)->GetModifier()->m_miscvalue == int32(id))
5011 (*i)->ApplyModifier(true);
5013 // Learn all spells for skill
5014 learnSkillRewardedSpells(id);
5015 return;
5020 bool Player::HasSkill(uint32 skill) const
5022 if(!skill)return false;
5023 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5025 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5027 return true;
5030 return false;
5033 uint16 Player::GetSkillValue(uint32 skill) const
5035 if(!skill)
5036 return 0;
5038 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5040 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5042 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5044 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5045 result += SKILL_TEMP_BONUS(bonus);
5046 result += SKILL_PERM_BONUS(bonus);
5047 return result < 0 ? 0 : result;
5050 return 0;
5053 uint16 Player::GetMaxSkillValue(uint32 skill) const
5055 if(!skill)return 0;
5056 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5058 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5060 uint32 bonus = GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i));
5062 int32 result = int32(SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5063 result += SKILL_TEMP_BONUS(bonus);
5064 result += SKILL_PERM_BONUS(bonus);
5065 return result < 0 ? 0 : result;
5068 return 0;
5071 uint16 Player::GetPureMaxSkillValue(uint32 skill) const
5073 if(!skill)return 0;
5074 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5076 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5078 return SKILL_MAX(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5081 return 0;
5084 uint16 Player::GetBaseSkillValue(uint32 skill) const
5086 if(!skill)return 0;
5087 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5089 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5091 int32 result = int32(SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i))));
5092 result += SKILL_PERM_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5093 return result < 0 ? 0 : result;
5096 return 0;
5099 uint16 Player::GetPureSkillValue(uint32 skill) const
5101 if(!skill)return 0;
5102 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
5104 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5106 return SKILL_VALUE(GetUInt32Value(PLAYER_SKILL_VALUE_INDEX(i)));
5109 return 0;
5112 int16 Player::GetSkillTempBonusValue(uint32 skill) const
5114 if(!skill)
5115 return 0;
5117 for (int i = 0; i < PLAYER_MAX_SKILLS; i++)
5119 if ((GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF) == skill)
5121 return SKILL_TEMP_BONUS(GetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i)));
5125 return 0;
5128 void Player::SendInitialActionButtons()
5130 sLog.outDetail( "Initializing Action Buttons for '%u'", GetGUIDLow() );
5132 WorldPacket data(SMSG_ACTION_BUTTONS, (MAX_ACTION_BUTTONS*4));
5133 for(int button = 0; button < MAX_ACTION_BUTTONS; ++button)
5135 ActionButtonList::const_iterator itr = m_actionButtons.find(button);
5136 if(itr != m_actionButtons.end() && itr->second.uState != ACTIONBUTTON_DELETED)
5138 data << uint16(itr->second.action);
5139 data << uint8(itr->second.misc);
5140 data << uint8(itr->second.type);
5142 else
5144 data << uint32(0);
5148 GetSession()->SendPacket( &data );
5149 sLog.outDetail( "Action Buttons for '%u' Initialized", GetGUIDLow() );
5152 void Player::addActionButton(const uint8 button, const uint16 action, const uint8 type, const uint8 misc)
5154 if(button >= MAX_ACTION_BUTTONS)
5156 sLog.outError( "Action %u not added into button %u for player %s: button must be < 132", action, button, GetName() );
5157 return;
5160 // check cheating with adding non-known spells to action bar
5161 if(type==ACTION_BUTTON_SPELL)
5163 if(!sSpellStore.LookupEntry(action))
5165 sLog.outError( "Action %u not added into button %u for player %s: spell not exist", action, button, GetName() );
5166 return;
5169 if(!HasSpell(action))
5171 sLog.outError( "Action %u not added into button %u for player %s: player don't known this spell", action, button, GetName() );
5172 return;
5176 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5178 if (buttonItr==m_actionButtons.end())
5179 { // just add new button
5180 m_actionButtons[button] = ActionButton(action,type,misc);
5182 else
5183 { // change state of current button
5184 ActionButtonUpdateState uState = buttonItr->second.uState;
5185 buttonItr->second = ActionButton(action,type,misc);
5186 if (uState != ACTIONBUTTON_NEW) buttonItr->second.uState = ACTIONBUTTON_CHANGED;
5189 sLog.outDetail( "Player '%u' Added Action '%u' to Button '%u'", GetGUIDLow(), action, button );
5192 void Player::removeActionButton(uint8 button)
5194 ActionButtonList::iterator buttonItr = m_actionButtons.find(button);
5195 if (buttonItr==m_actionButtons.end())
5196 return;
5198 if(buttonItr->second.uState==ACTIONBUTTON_NEW)
5199 m_actionButtons.erase(buttonItr); // new and not saved
5200 else
5201 buttonItr->second.uState = ACTIONBUTTON_DELETED; // saved, will deleted at next save
5203 sLog.outDetail( "Action Button '%u' Removed from Player '%u'", button, GetGUIDLow() );
5206 void Player::SetDontMove(bool dontMove)
5208 m_dontMove = dontMove;
5211 bool Player::SetPosition(float x, float y, float z, float orientation, bool teleport)
5213 // prevent crash when a bad coord is sent by the client
5214 if(!MaNGOS::IsValidMapCoord(x,y,z,orientation))
5216 sLog.outDebug("Player::SetPosition(%f, %f, %f, %f, %d) .. bad coordinates for player %d!",x,y,z,orientation,teleport,GetGUIDLow());
5217 return false;
5220 Map *m = GetMap();
5222 const float old_x = GetPositionX();
5223 const float old_y = GetPositionY();
5224 const float old_z = GetPositionZ();
5225 const float old_r = GetOrientation();
5227 if( teleport || old_x != x || old_y != y || old_z != z || old_r != orientation )
5229 if (teleport || old_x != x || old_y != y || old_z != z)
5230 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_MOVE | AURA_INTERRUPT_FLAG_TURNING);
5231 else
5232 RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_TURNING);
5234 // move and update visible state if need
5235 m->PlayerRelocation(this, x, y, z, orientation);
5237 // reread after Map::Relocation
5238 m = GetMap();
5239 x = GetPositionX();
5240 y = GetPositionY();
5241 z = GetPositionZ();
5243 // group update
5244 if(GetGroup() && (old_x != x || old_y != y))
5245 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_POSITION);
5248 // code block for underwater state update
5249 UpdateUnderwaterState(m, x, y, z);
5251 CheckExploreSystem();
5253 return true;
5256 void Player::SaveRecallPosition()
5258 m_recallMap = GetMapId();
5259 m_recallX = GetPositionX();
5260 m_recallY = GetPositionY();
5261 m_recallZ = GetPositionZ();
5262 m_recallO = GetOrientation();
5265 void Player::SendMessageToSet(WorldPacket *data, bool self)
5267 GetMap()->MessageBroadcast(this, data, self);
5270 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self)
5272 GetMap()->MessageDistBroadcast(this, data, dist, self);
5275 void Player::SendMessageToSetInRange(WorldPacket *data, float dist, bool self, bool own_team_only)
5277 GetMap()->MessageDistBroadcast(this, data, dist, self,own_team_only);
5280 void Player::SendDirectMessage(WorldPacket *data)
5282 GetSession()->SendPacket(data);
5285 void Player::CheckExploreSystem()
5287 if (!isAlive())
5288 return;
5290 if (isInFlight())
5291 return;
5293 uint16 areaFlag=MapManager::Instance().GetBaseMap(GetMapId())->GetAreaFlag(GetPositionX(),GetPositionY());
5294 if(areaFlag==0xffff)
5295 return;
5296 int offset = areaFlag / 32;
5298 if(offset >= 128)
5300 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);
5301 return;
5304 uint32 val = (uint32)(1 << (areaFlag % 32));
5305 uint32 currFields = GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset);
5307 if( !(currFields & val) )
5309 SetUInt32Value(PLAYER_EXPLORED_ZONES_1 + offset, (uint32)(currFields | val));
5311 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA);
5313 AreaTableEntry const *p = GetAreaEntryByAreaFlagAndMap(areaFlag,GetMapId());
5314 if(!p)
5316 sLog.outError("PLAYER: Player %u discovered unknown area (x: %f y: %f map: %u", GetGUIDLow(), GetPositionX(),GetPositionY(),GetMapId());
5318 else if(p->area_level > 0)
5320 uint32 area = p->ID;
5321 if (getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
5323 SendExplorationExperience(area,0);
5325 else
5327 int32 diff = int32(getLevel()) - p->area_level;
5328 uint32 XP = 0;
5329 if (diff < -5)
5331 XP = uint32(objmgr.GetBaseXP(getLevel()+5)*sWorld.getRate(RATE_XP_EXPLORE));
5333 else if (diff > 5)
5335 int32 exploration_percent = (100-((diff-5)*5));
5336 if (exploration_percent > 100)
5337 exploration_percent = 100;
5338 else if (exploration_percent < 0)
5339 exploration_percent = 0;
5341 XP = uint32(objmgr.GetBaseXP(p->area_level)*exploration_percent/100*sWorld.getRate(RATE_XP_EXPLORE));
5343 else
5345 XP = uint32(objmgr.GetBaseXP(p->area_level)*sWorld.getRate(RATE_XP_EXPLORE));
5348 GiveXP( XP, NULL );
5349 SendExplorationExperience(area,XP);
5351 sLog.outDetail("PLAYER: Player %u discovered a new area: %u", GetGUIDLow(), area);
5356 uint32 Player::TeamForRace(uint8 race)
5358 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5359 if(!rEntry)
5361 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5362 return ALLIANCE;
5365 switch(rEntry->TeamID)
5367 case 7: return ALLIANCE;
5368 case 1: return HORDE;
5371 sLog.outError("Race %u have wrong team id in DBC: wrong DBC files?",uint32(race),rEntry->TeamID);
5372 return ALLIANCE;
5375 uint32 Player::getFactionForRace(uint8 race)
5377 ChrRacesEntry const* rEntry = sChrRacesStore.LookupEntry(race);
5378 if(!rEntry)
5380 sLog.outError("Race %u not found in DBC: wrong DBC files?",uint32(race));
5381 return 0;
5384 return rEntry->FactionID;
5387 void Player::setFactionForRace(uint8 race)
5389 m_team = TeamForRace(race);
5390 setFaction( getFactionForRace(race) );
5393 void Player::UpdateReputation() const
5395 sLog.outDetail( "WORLD: Player::UpdateReputation" );
5397 for(FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
5399 SendFactionState(&(itr->second));
5403 void Player::SendFactionState(FactionState const* faction) const
5405 if(faction->Flags & FACTION_FLAG_VISIBLE) //If faction is visible then update it
5407 WorldPacket data(SMSG_SET_FACTION_STANDING, (16)); // last check 2.4.0
5408 data << (float) 0; // unk 2.4.0
5409 data << (uint8) 0; // wotlk 8634
5410 data << (uint32) 1; // count
5411 // for
5412 data << (uint32) faction->ReputationListID;
5413 data << (uint32) faction->Standing;
5414 // end for
5415 GetSession()->SendPacket(&data);
5419 void Player::SendInitialReputations()
5421 WorldPacket data(SMSG_INITIALIZE_FACTIONS, (4+128*5));
5422 data << uint32 (0x00000080);
5424 RepListID a = 0;
5426 for (FactionStateList::const_iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
5428 // fill in absent fields
5429 for (; a != itr->first; a++)
5431 data << uint8 (0x00);
5432 data << uint32 (0x00000000);
5435 // fill in encountered data
5436 data << uint8 (itr->second.Flags);
5437 data << uint32 (itr->second.Standing);
5439 ++a;
5442 // fill in absent fields
5443 for (; a != 128; a++)
5445 data << uint8 (0x00);
5446 data << uint32 (0x00000000);
5449 GetSession()->SendPacket(&data);
5452 FactionState const* Player::GetFactionState( FactionEntry const* factionEntry) const
5454 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5455 if (itr != m_factions.end())
5456 return &itr->second;
5458 return NULL;
5461 void Player::SetFactionAtWar(FactionState* faction, bool atWar)
5463 // not allow declare war to own faction
5464 if(atWar && (faction->Flags & FACTION_FLAG_PEACE_FORCED) )
5465 return;
5467 // already set
5468 if(((faction->Flags & FACTION_FLAG_AT_WAR) != 0) == atWar)
5469 return;
5471 if( atWar )
5472 faction->Flags |= FACTION_FLAG_AT_WAR;
5473 else
5474 faction->Flags &= ~FACTION_FLAG_AT_WAR;
5476 faction->Changed = true;
5479 void Player::SetFactionInactive(FactionState* faction, bool inactive)
5481 // always invisible or hidden faction can't be inactive
5482 if(inactive && ((faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN)) || !(faction->Flags & FACTION_FLAG_VISIBLE) ) )
5483 return;
5485 // already set
5486 if(((faction->Flags & FACTION_FLAG_INACTIVE) != 0) == inactive)
5487 return;
5489 if(inactive)
5490 faction->Flags |= FACTION_FLAG_INACTIVE;
5491 else
5492 faction->Flags &= ~FACTION_FLAG_INACTIVE;
5494 faction->Changed = true;
5497 void Player::SetFactionVisibleForFactionTemplateId(uint32 FactionTemplateId)
5499 FactionTemplateEntry const*factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5501 if(!factionTemplateEntry)
5502 return;
5504 SetFactionVisibleForFactionId(factionTemplateEntry->faction);
5507 void Player::SetFactionVisibleForFactionId(uint32 FactionId)
5509 FactionEntry const *factionEntry = sFactionStore.LookupEntry(FactionId);
5510 if(!factionEntry)
5511 return;
5513 if(factionEntry->reputationListID < 0)
5514 return;
5516 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5517 if (itr == m_factions.end())
5518 return;
5520 SetFactionVisible(&itr->second);
5523 void Player::SetFactionVisible(FactionState* faction)
5525 // always invisible or hidden faction can't be make visible
5526 if(faction->Flags & (FACTION_FLAG_INVISIBLE_FORCED|FACTION_FLAG_HIDDEN))
5527 return;
5529 // already set
5530 if(faction->Flags & FACTION_FLAG_VISIBLE)
5531 return;
5533 faction->Flags |= FACTION_FLAG_VISIBLE;
5534 faction->Changed = true;
5536 if(!m_session->PlayerLoading())
5538 // make faction visible in reputation list at client
5539 WorldPacket data(SMSG_SET_FACTION_VISIBLE, 4);
5540 data << faction->ReputationListID;
5541 GetSession()->SendPacket(&data);
5545 void Player::SetInitialFactions()
5547 for(unsigned int i = 1; i < sFactionStore.GetNumRows(); i++)
5549 FactionEntry const *factionEntry = sFactionStore.LookupEntry(i);
5551 if( factionEntry && (factionEntry->reputationListID >= 0))
5553 FactionState newFaction;
5554 newFaction.ID = factionEntry->ID;
5555 newFaction.ReputationListID = factionEntry->reputationListID;
5556 newFaction.Standing = 0;
5557 newFaction.Flags = GetDefaultReputationFlags(factionEntry);
5558 newFaction.Changed = true;
5560 m_factions[newFaction.ReputationListID] = newFaction;
5565 uint32 Player::GetDefaultReputationFlags(const FactionEntry *factionEntry) const
5567 if (!factionEntry)
5568 return 0;
5570 uint32 raceMask = getRaceMask();
5571 uint32 classMask = getClassMask();
5572 for (int i=0; i < 4; i++)
5574 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5575 (factionEntry->BaseRepClassMask[i]==0 ||
5576 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5577 return factionEntry->ReputationFlags[i];
5579 return 0;
5582 int32 Player::GetBaseReputation(const FactionEntry *factionEntry) const
5584 if (!factionEntry)
5585 return 0;
5587 uint32 raceMask = getRaceMask();
5588 uint32 classMask = getClassMask();
5589 for (int i=0; i < 4; i++)
5591 if( (factionEntry->BaseRepRaceMask[i] & raceMask) &&
5592 (factionEntry->BaseRepClassMask[i]==0 ||
5593 (factionEntry->BaseRepClassMask[i] & classMask) ) )
5594 return factionEntry->BaseRepValue[i];
5597 // in faction.dbc exist factions with (RepListId >=0, listed in character reputation list) with all BaseRepRaceMask[i]==0
5598 return 0;
5601 int32 Player::GetReputation(uint32 faction_id) const
5603 FactionEntry const *factionEntry = sFactionStore.LookupEntry(faction_id);
5605 if (!factionEntry)
5607 sLog.outError("Player::GetReputation: Can't get reputation of %s for unknown faction (faction template id) #%u.",GetName(), faction_id);
5608 return 0;
5611 return GetReputation(factionEntry);
5614 int32 Player::GetReputation(const FactionEntry *factionEntry) const
5616 // Faction without recorded reputation. Just ignore.
5617 if(!factionEntry)
5618 return 0;
5620 FactionStateList::const_iterator itr = m_factions.find(factionEntry->reputationListID);
5621 if (itr != m_factions.end())
5622 return GetBaseReputation(factionEntry) + itr->second.Standing;
5624 return 0;
5627 ReputationRank Player::GetReputationRank(uint32 faction) const
5629 FactionEntry const*factionEntry = sFactionStore.LookupEntry(faction);
5630 if(!factionEntry)
5631 return MIN_REPUTATION_RANK;
5633 return GetReputationRank(factionEntry);
5636 ReputationRank Player::ReputationToRank(int32 standing) const
5638 int32 Limit = Reputation_Cap + 1;
5639 for (int i = MAX_REPUTATION_RANK-1; i >= MIN_REPUTATION_RANK; --i)
5641 Limit -= ReputationRank_Length[i];
5642 if (standing >= Limit )
5643 return ReputationRank(i);
5645 return MIN_REPUTATION_RANK;
5648 ReputationRank Player::GetReputationRank(const FactionEntry *factionEntry) const
5650 int32 Reputation = GetReputation(factionEntry);
5651 return ReputationToRank(Reputation);
5654 ReputationRank Player::GetBaseReputationRank(const FactionEntry *factionEntry) const
5656 int32 Reputation = GetBaseReputation(factionEntry);
5657 return ReputationToRank(Reputation);
5660 bool Player::ModifyFactionReputation(uint32 FactionTemplateId, int32 DeltaReputation)
5662 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5664 if(!factionTemplateEntry)
5666 sLog.outError("Player::ModifyFactionReputation: Can't update reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5667 return false;
5670 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5672 // Faction without recorded reputation. Just ignore.
5673 if(!factionEntry)
5674 return false;
5676 return ModifyFactionReputation(factionEntry, DeltaReputation);
5679 bool Player::ModifyFactionReputation(FactionEntry const* factionEntry, int32 standing)
5681 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5682 if (flist)
5684 bool res = false;
5685 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5687 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5688 if(factionEntryCalc)
5689 res = ModifyOneFactionReputation(factionEntryCalc, standing);
5691 return res;
5693 else
5694 return ModifyOneFactionReputation(factionEntry, standing);
5697 bool Player::ModifyOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5699 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5700 if (itr != m_factions.end())
5702 int32 BaseRep = GetBaseReputation(factionEntry);
5703 int32 new_rep = BaseRep + itr->second.Standing + standing;
5705 if (new_rep > Reputation_Cap)
5706 new_rep = Reputation_Cap;
5707 else
5708 if (new_rep < Reputation_Bottom)
5709 new_rep = Reputation_Bottom;
5711 if(ReputationToRank(new_rep) <= REP_HOSTILE)
5712 SetFactionAtWar(&itr->second,true);
5714 itr->second.Standing = new_rep - BaseRep;
5715 itr->second.Changed = true;
5717 SetFactionVisible(&itr->second);
5719 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
5721 if(uint32 questid = GetQuestSlotQuestId(i))
5723 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
5724 if( qInfo && qInfo->GetRepObjectiveFaction() == factionEntry->ID )
5726 QuestStatusData& q_status = mQuestStatus[questid];
5727 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
5729 if(GetReputation(factionEntry) >= qInfo->GetRepObjectiveValue())
5730 if ( CanCompleteQuest( questid ) )
5731 CompleteQuest( questid );
5733 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
5735 if(GetReputation(factionEntry) < qInfo->GetRepObjectiveValue())
5736 IncompleteQuest( questid );
5741 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION);
5742 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION);
5743 SendFactionState(&(itr->second));
5745 return true;
5747 return false;
5750 bool Player::SetFactionReputation(uint32 FactionTemplateId, int32 standing)
5752 FactionTemplateEntry const* factionTemplateEntry = sFactionTemplateStore.LookupEntry(FactionTemplateId);
5754 if(!factionTemplateEntry)
5756 sLog.outError("Player::SetFactionReputation: Can't set reputation of %s for unknown faction (faction template id) #%u.", GetName(), FactionTemplateId);
5757 return false;
5760 FactionEntry const *factionEntry = sFactionStore.LookupEntry(factionTemplateEntry->faction);
5762 // Faction without recorded reputation. Just ignore.
5763 if(!factionEntry)
5764 return false;
5766 return SetFactionReputation(factionEntry, standing);
5769 bool Player::SetFactionReputation(FactionEntry const* factionEntry, int32 standing)
5771 SimpleFactionsList const* flist = GetFactionTeamList(factionEntry->ID);
5772 if (flist)
5774 bool res = false;
5775 for (SimpleFactionsList::const_iterator itr = flist->begin();itr != flist->end();++itr)
5777 FactionEntry const *factionEntryCalc = sFactionStore.LookupEntry(*itr);
5778 if(factionEntryCalc)
5779 res = SetOneFactionReputation(factionEntryCalc, standing);
5781 return res;
5783 else
5784 return SetOneFactionReputation(factionEntry, standing);
5787 bool Player::SetOneFactionReputation(FactionEntry const* factionEntry, int32 standing)
5789 FactionStateList::iterator itr = m_factions.find(factionEntry->reputationListID);
5790 if (itr != m_factions.end())
5792 if (standing > Reputation_Cap)
5793 standing = Reputation_Cap;
5794 else
5795 if (standing < Reputation_Bottom)
5796 standing = Reputation_Bottom;
5798 int32 BaseRep = GetBaseReputation(factionEntry);
5799 itr->second.Standing = standing - BaseRep;
5800 itr->second.Changed = true;
5802 SetFactionVisible(&itr->second);
5804 if(ReputationToRank(standing) <= REP_HOSTILE)
5805 SetFactionAtWar(&itr->second,true);
5807 SendFactionState(&(itr->second));
5808 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION);
5809 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION);
5810 return true;
5812 return false;
5815 //Calculate total reputation percent player gain with quest/creature level
5816 int32 Player::CalculateReputationGain(uint32 creatureOrQuestLevel, int32 rep, bool for_quest)
5818 // for grey creature kill received 20%, in other case 100.
5819 int32 percent = (!for_quest && (creatureOrQuestLevel <= MaNGOS::XP::GetGrayLevel(getLevel()))) ? 20 : 100;
5821 int32 repMod = GetTotalAuraModifier(SPELL_AURA_MOD_REPUTATION_GAIN);
5823 percent += rep > 0 ? repMod : -repMod;
5825 if(percent <=0)
5826 return 0;
5828 return int32(sWorld.getRate(RATE_REPUTATION_GAIN)*rep*percent/100);
5831 //Calculates how many reputation points player gains in victim's enemy factions
5832 void Player::RewardReputation(Unit *pVictim, float rate)
5834 if(!pVictim || pVictim->GetTypeId() == TYPEID_PLAYER)
5835 return;
5837 ReputationOnKillEntry const* Rep = objmgr.GetReputationOnKilEntry(((Creature*)pVictim)->GetCreatureInfo()->Entry);
5839 if(!Rep)
5840 return;
5842 if(Rep->repfaction1 && (!Rep->team_dependent || GetTeam()==ALLIANCE))
5844 int32 donerep1 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue1,false);
5845 donerep1 = int32(donerep1*rate);
5846 FactionEntry const *factionEntry1 = sFactionStore.LookupEntry(Rep->repfaction1);
5847 uint32 current_reputation_rank1 = GetReputationRank(factionEntry1);
5848 if(factionEntry1 && current_reputation_rank1 <= Rep->reputation_max_cap1)
5849 ModifyFactionReputation(factionEntry1, donerep1);
5851 // Wiki: Team factions value divided by 2
5852 if(Rep->is_teamaward1)
5854 FactionEntry const *team1_factionEntry = sFactionStore.LookupEntry(factionEntry1->team);
5855 if(team1_factionEntry)
5856 ModifyFactionReputation(team1_factionEntry, donerep1 / 2);
5860 if(Rep->repfaction2 && (!Rep->team_dependent || GetTeam()==HORDE))
5862 int32 donerep2 = CalculateReputationGain(pVictim->getLevel(),Rep->repvalue2,false);
5863 donerep2 = int32(donerep2*rate);
5864 FactionEntry const *factionEntry2 = sFactionStore.LookupEntry(Rep->repfaction2);
5865 uint32 current_reputation_rank2 = GetReputationRank(factionEntry2);
5866 if(factionEntry2 && current_reputation_rank2 <= Rep->reputation_max_cap2)
5867 ModifyFactionReputation(factionEntry2, donerep2);
5869 // Wiki: Team factions value divided by 2
5870 if(Rep->is_teamaward2)
5872 FactionEntry const *team2_factionEntry = sFactionStore.LookupEntry(factionEntry2->team);
5873 if(team2_factionEntry)
5874 ModifyFactionReputation(team2_factionEntry, donerep2 / 2);
5879 //Calculate how many reputation points player gain with the quest
5880 void Player::RewardReputation(Quest const *pQuest)
5882 // quest reputation reward/loss
5883 for(int i = 0; i < QUEST_REPUTATIONS_COUNT; ++i)
5885 if(pQuest->RewRepFaction[i] && pQuest->RewRepValue[i] )
5887 int32 rep = CalculateReputationGain(pQuest->GetQuestLevel(),pQuest->RewRepValue[i],true);
5888 FactionEntry const* factionEntry = sFactionStore.LookupEntry(pQuest->RewRepFaction[i]);
5889 if(factionEntry)
5890 ModifyFactionReputation(factionEntry, rep);
5894 // TODO: implement reputation spillover
5897 void Player::UpdateArenaFields(void)
5899 /* arena calcs go here */
5902 void Player::UpdateHonorFields()
5904 /// called when rewarding honor and at each save
5905 uint64 now = time(NULL);
5906 uint64 today = uint64(time(NULL) / DAY) * DAY;
5908 if(m_lastHonorUpdateTime < today)
5910 uint64 yesterday = today - DAY;
5912 uint16 kills_today = PAIR32_LOPART(GetUInt32Value(PLAYER_FIELD_KILLS));
5914 // update yesterday's contribution
5915 if(m_lastHonorUpdateTime >= yesterday )
5917 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, GetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION));
5919 // this is the first update today, reset today's contribution
5920 SetUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, 0);
5921 SetUInt32Value(PLAYER_FIELD_KILLS, MAKE_PAIR32(0,kills_today));
5923 else
5925 // no honor/kills yesterday or today, reset
5926 SetUInt32Value(PLAYER_FIELD_YESTERDAY_CONTRIBUTION, 0);
5927 SetUInt32Value(PLAYER_FIELD_KILLS, 0);
5931 m_lastHonorUpdateTime = now;
5934 ///Calculate the amount of honor gained based on the victim
5935 ///and the size of the group for which the honor is divided
5936 ///An exact honor value can also be given (overriding the calcs)
5937 bool Player::RewardHonor(Unit *uVictim, uint32 groupsize, float honor)
5939 // do not reward honor in arenas, but enable onkill spellproc
5940 if(InArena())
5942 if(!uVictim || uVictim == this || uVictim->GetTypeId() != TYPEID_PLAYER)
5943 return false;
5945 if( GetBGTeam() == ((Player*)uVictim)->GetBGTeam() )
5946 return false;
5948 return true;
5951 // 'Inactive' this aura prevents the player from gaining honor points and battleground tokens
5952 if(GetDummyAura(SPELL_AURA_PLAYER_INACTIVE))
5953 return false;
5955 uint64 victim_guid = 0;
5956 uint32 victim_rank = 0;
5958 // need call before fields update to have chance move yesterday data to appropriate fields before today data change.
5959 UpdateHonorFields();
5961 if(honor <= 0)
5963 if(!uVictim || uVictim == this || uVictim->HasAuraType(SPELL_AURA_NO_PVP_CREDIT))
5964 return false;
5966 victim_guid = uVictim->GetGUID();
5968 if( uVictim->GetTypeId() == TYPEID_PLAYER )
5970 Player *pVictim = (Player *)uVictim;
5972 if( GetTeam() == pVictim->GetTeam() && !sWorld.IsFFAPvPRealm() )
5973 return false;
5975 float f = 1; //need for total kills (?? need more info)
5976 uint32 k_grey = 0;
5977 uint32 k_level = getLevel();
5978 uint32 v_level = pVictim->getLevel();
5981 // PLAYER_CHOSEN_TITLE VALUES DESCRIPTION
5982 // [0] Just name
5983 // [1..14] Alliance honor titles and player name
5984 // [15..28] Horde honor titles and player name
5985 // [29..38] Other title and player name
5986 // [39+] Nothing
5987 uint32 victim_title = pVictim->GetUInt32Value(PLAYER_CHOSEN_TITLE);
5988 // Get Killer titles, CharTitlesEntry::bit_index
5989 // Ranks:
5990 // title[1..14] -> rank[5..18]
5991 // title[15..28] -> rank[5..18]
5992 // title[other] -> 0
5993 if (victim_title == 0)
5994 victim_guid = 0; // Don't show HK: <rank> message, only log.
5995 else if (victim_title < 15)
5996 victim_rank = victim_title + 4;
5997 else if (victim_title < 29)
5998 victim_rank = victim_title - 14 + 4;
5999 else
6000 victim_guid = 0; // Don't show HK: <rank> message, only log.
6003 if(k_level <= 5)
6004 k_grey = 0;
6005 else if( k_level <= 39 )
6006 k_grey = k_level - 5 - k_level/10;
6007 else
6008 k_grey = k_level - 1 - k_level/5;
6010 if(v_level<=k_grey)
6011 return false;
6013 float diff_level = (k_level == k_grey) ? 1 : ((float(v_level) - float(k_grey)) / (float(k_level) - float(k_grey)));
6015 int32 v_rank =1; //need more info
6017 honor = ((f * diff_level * (190 + v_rank*10))/6);
6018 honor *= ((float)k_level) / 70.0f; //factor of dependence on levels of the killer
6020 // count the number of playerkills in one day
6021 ApplyModUInt32Value(PLAYER_FIELD_KILLS, 1, true);
6022 // and those in a lifetime
6023 ApplyModUInt32Value(PLAYER_FIELD_LIFETIME_HONORBALE_KILLS, 1, true);
6025 else
6027 Creature *cVictim = (Creature *)uVictim;
6029 if (!cVictim->isRacialLeader())
6030 return false;
6032 honor = 100; // ??? need more info
6033 victim_rank = 19; // HK: Leader
6037 if (uVictim != NULL)
6039 honor *= sWorld.getRate(RATE_HONOR);
6041 if(groupsize > 1)
6042 honor /= groupsize;
6044 honor *= (((float)urand(8,12))/10); // approx honor: 80% - 120% of real honor
6047 // honor - for show honor points in log
6048 // victim_guid - for show victim name in log
6049 // victim_rank [1..4] HK: <dishonored rank>
6050 // victim_rank [5..19] HK: <alliance\horde rank>
6051 // victim_rank [0,20+] HK: <>
6052 WorldPacket data(SMSG_PVP_CREDIT,4+8+4);
6053 data << (uint32) honor;
6054 data << (uint64) victim_guid;
6055 data << (uint32) victim_rank;
6057 GetSession()->SendPacket(&data);
6059 // add honor points
6060 ModifyHonorPoints(int32(honor));
6062 ApplyModUInt32Value(PLAYER_FIELD_TODAY_CONTRIBUTION, uint32(honor), true);
6063 return true;
6066 void Player::ModifyHonorPoints( int32 value )
6068 if(value < 0)
6070 if (GetHonorPoints() > sWorld.getConfig(CONFIG_MAX_HONOR_POINTS))
6071 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) + value);
6072 else
6073 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() > uint32(-value) ? GetHonorPoints() + value : 0);
6075 else
6076 SetUInt32Value(PLAYER_FIELD_HONOR_CURRENCY, GetHonorPoints() < sWorld.getConfig(CONFIG_MAX_HONOR_POINTS) - value ? GetHonorPoints() + value : sWorld.getConfig(CONFIG_MAX_HONOR_POINTS));
6079 void Player::ModifyArenaPoints( int32 value )
6081 if(value < 0)
6083 if (GetArenaPoints() > sWorld.getConfig(CONFIG_MAX_ARENA_POINTS))
6084 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) + value);
6085 else
6086 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() > uint32(-value) ? GetArenaPoints() + value : 0);
6088 else
6089 SetUInt32Value(PLAYER_FIELD_ARENA_CURRENCY, GetArenaPoints() < sWorld.getConfig(CONFIG_MAX_ARENA_POINTS) - value ? GetArenaPoints() + value : sWorld.getConfig(CONFIG_MAX_ARENA_POINTS));
6092 uint32 Player::GetGuildIdFromDB(uint64 guid)
6094 std::ostringstream ss;
6095 ss<<"SELECT guildid FROM guild_member WHERE guid='"<<guid<<"'";
6096 QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
6097 if( result )
6099 uint32 v = result->Fetch()[0].GetUInt32();
6100 delete result;
6101 return v;
6103 else
6104 return 0;
6107 uint32 Player::GetRankFromDB(uint64 guid)
6109 std::ostringstream ss;
6110 ss<<"SELECT rank FROM guild_member WHERE guid='"<<guid<<"'";
6111 QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
6112 if( result )
6114 uint32 v = result->Fetch()[0].GetUInt32();
6115 delete result;
6116 return v;
6118 else
6119 return 0;
6122 uint32 Player::GetArenaTeamIdFromDB(uint64 guid, uint8 type)
6124 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);
6125 if(!result)
6126 return 0;
6128 uint32 id = (*result)[0].GetUInt32();
6129 delete result;
6130 return id;
6133 uint32 Player::GetZoneIdFromDB(uint64 guid)
6135 std::ostringstream ss;
6137 ss<<"SELECT zone FROM characters WHERE guid='"<<GUID_LOPART(guid)<<"'";
6138 QueryResult *result = CharacterDatabase.Query( ss.str().c_str() );
6139 if (!result)
6140 return 0;
6141 Field* fields = result->Fetch();
6142 uint32 zone = fields[0].GetUInt32();
6143 delete result;
6145 if (!zone)
6147 // stored zone is zero, use generic and slow zone detection
6148 ss.str("");
6149 ss<<"SELECT map,position_x,position_y FROM characters WHERE guid='"<<GUID_LOPART(guid)<<"'";
6150 result = CharacterDatabase.Query(ss.str().c_str());
6151 if( !result )
6152 return 0;
6153 fields = result->Fetch();
6154 uint32 map = fields[0].GetUInt32();
6155 float posx = fields[1].GetFloat();
6156 float posy = fields[2].GetFloat();
6157 delete result;
6159 zone = MapManager::Instance().GetZoneId(map,posx,posy);
6161 ss.str("");
6162 ss << "UPDATE characters SET zone='"<<zone<<"' WHERE guid='"<<GUID_LOPART(guid)<<"'";
6163 CharacterDatabase.Execute(ss.str().c_str());
6166 return zone;
6169 void Player::UpdateArea(uint32 newArea)
6171 // FFA_PVP flags are area and not zone id dependent
6172 // so apply them accordingly
6173 m_areaUpdateId = newArea;
6175 AreaTableEntry const* area = GetAreaEntryByAreaID(newArea);
6177 if(area && (area->flags & AREA_FLAG_ARENA))
6179 if(!isGameMaster())
6180 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
6182 else
6184 // remove ffa flag only if not ffapvp realm
6185 // removal in sanctuaries and capitals is handled in zone update
6186 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP) && !sWorld.IsFFAPvPRealm())
6187 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_FFA_PVP);
6190 UpdateAreaDependentAuras(newArea);
6193 void Player::UpdateZone(uint32 newZone)
6195 m_zoneUpdateId = newZone;
6196 m_zoneUpdateTimer = ZONE_UPDATE_INTERVAL;
6198 // zone changed, so area changed as well, update it
6199 UpdateArea(GetAreaId());
6201 AreaTableEntry const* zone = GetAreaEntryByAreaID(newZone);
6202 if(!zone)
6203 return;
6205 if (sWorld.getConfig(CONFIG_WEATHER))
6207 Weather *wth = sWorld.FindWeather(zone->ID);
6208 if(wth)
6210 wth->SendWeatherUpdateToPlayer(this);
6212 else
6214 if(!sWorld.AddWeather(zone->ID))
6216 // send fine weather packet to remove old zone's weather
6217 Weather::SendFineWeatherUpdateToPlayer(this);
6222 pvpInfo.inHostileArea =
6223 GetTeam() == ALLIANCE && zone->team == AREATEAM_HORDE ||
6224 GetTeam() == HORDE && zone->team == AREATEAM_ALLY ||
6225 sWorld.IsPvPRealm() && zone->team == AREATEAM_NONE ||
6226 InBattleGround(); // overwrite for battlegrounds, maybe batter some zone flags but current known not 100% fit to this
6228 if(pvpInfo.inHostileArea) // in hostile area
6230 if(!IsPvP() || pvpInfo.endTimer != 0)
6231 UpdatePvP(true, true);
6233 else // in friendly area
6235 if(IsPvP() && !HasFlag(PLAYER_FLAGS,PLAYER_FLAGS_IN_PVP) && pvpInfo.endTimer == 0)
6236 pvpInfo.endTimer = time(0); // start toggle-off
6239 if(zone->flags & AREA_FLAG_SANCTUARY) // in sanctuary
6241 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_SANCTUARY);
6242 if(sWorld.IsFFAPvPRealm())
6243 RemoveFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6245 else
6247 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_SANCTUARY);
6250 if(zone->flags & AREA_FLAG_CAPITAL) // in capital city
6252 SetFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6253 SetRestType(REST_TYPE_IN_CITY);
6254 InnEnter(time(0),GetMapId(),0,0,0);
6256 if(sWorld.IsFFAPvPRealm())
6257 RemoveFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6259 else // anywhere else
6261 if(HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING)) // but resting (walk from city or maybe in tavern or leave tavern recently)
6263 if(GetRestType()==REST_TYPE_IN_TAVERN) // has been in tavern. Is still in?
6265 if(GetMapId()!=GetInnPosMapId() || sqrt((GetPositionX()-GetInnPosX())*(GetPositionX()-GetInnPosX())+(GetPositionY()-GetInnPosY())*(GetPositionY()-GetInnPosY())+(GetPositionZ()-GetInnPosZ())*(GetPositionZ()-GetInnPosZ()))>40)
6267 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6268 SetRestType(REST_TYPE_NO);
6270 if(sWorld.IsFFAPvPRealm())
6271 SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6274 else // not in tavern (leave city then)
6276 RemoveFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING);
6277 SetRestType(REST_TYPE_NO);
6279 // Set player to FFA PVP when not in rested environment.
6280 if(sWorld.IsFFAPvPRealm())
6281 SetFlag(PLAYER_FLAGS,PLAYER_FLAGS_FFA_PVP);
6286 // remove items with area/map limitations (delete only for alive player to allow back in ghost mode)
6287 // if player resurrected at teleport this will be applied in resurrect code
6288 if(isAlive())
6289 DestroyZoneLimitedItem( true, newZone );
6291 // recent client version not send leave/join channel packets for built-in local channels
6292 UpdateLocalChannels( newZone );
6294 // group update
6295 if(GetGroup())
6296 SetGroupUpdateFlag(GROUP_UPDATE_FLAG_ZONE);
6298 UpdateZoneDependentAuras(newZone);
6301 //If players are too far way of duel flag... then player loose the duel
6302 void Player::CheckDuelDistance(time_t currTime)
6304 if(!duel)
6305 return;
6307 uint64 duelFlagGUID = GetUInt64Value(PLAYER_DUEL_ARBITER);
6308 GameObject* obj = ObjectAccessor::GetGameObject(*this, duelFlagGUID);
6309 if(!obj)
6310 return;
6312 if(duel->outOfBound == 0)
6314 if(!IsWithinDistInMap(obj, 50))
6316 duel->outOfBound = currTime;
6318 WorldPacket data(SMSG_DUEL_OUTOFBOUNDS, 0);
6319 GetSession()->SendPacket(&data);
6322 else
6324 if(IsWithinDistInMap(obj, 40))
6326 duel->outOfBound = 0;
6328 WorldPacket data(SMSG_DUEL_INBOUNDS, 0);
6329 GetSession()->SendPacket(&data);
6331 else if(currTime >= (duel->outOfBound+10))
6333 DuelComplete(DUEL_FLED);
6338 void Player::DuelComplete(DuelCompleteType type)
6340 // duel not requested
6341 if(!duel)
6342 return;
6344 WorldPacket data(SMSG_DUEL_COMPLETE, (1));
6345 data << (uint8)((type != DUEL_INTERUPTED) ? 1 : 0);
6346 GetSession()->SendPacket(&data);
6347 duel->opponent->GetSession()->SendPacket(&data);
6349 if(type != DUEL_INTERUPTED)
6351 data.Initialize(SMSG_DUEL_WINNER, (1+20)); // we guess size
6352 data << (uint8)((type==DUEL_WON) ? 0 : 1); // 0 = just won; 1 = fled
6353 data << duel->opponent->GetName();
6354 data << GetName();
6355 SendMessageToSet(&data,true);
6358 // cool-down duel spell
6359 /*data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6361 data<<GetGUID();
6362 data<<uint8(0x0);
6364 data<<(uint32)7266;
6365 data<<uint32(0x0);
6366 GetSession()->SendPacket(&data);
6367 data.Initialize(SMSG_SPELL_COOLDOWN, 17);
6368 data<<duel->opponent->GetGUID();
6369 data<<uint8(0x0);
6370 data<<(uint32)7266;
6371 data<<uint32(0x0);
6372 duel->opponent->GetSession()->SendPacket(&data);*/
6374 //Remove Duel Flag object
6375 GameObject* obj = ObjectAccessor::GetGameObject(*this, GetUInt64Value(PLAYER_DUEL_ARBITER));
6376 if(obj)
6377 duel->initiator->RemoveGameObject(obj,true);
6379 /* remove auras */
6380 std::vector<uint32> auras2remove;
6381 AuraMap const& vAuras = duel->opponent->GetAuras();
6382 for (AuraMap::const_iterator i = vAuras.begin(); i != vAuras.end(); ++i)
6384 if (!i->second->IsPositive() && i->second->GetCasterGUID() == GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6385 auras2remove.push_back(i->second->GetId());
6388 for(size_t i=0; i<auras2remove.size(); i++)
6389 duel->opponent->RemoveAurasDueToSpell(auras2remove[i]);
6391 auras2remove.clear();
6392 AuraMap const& auras = GetAuras();
6393 for (AuraMap::const_iterator i = auras.begin(); i != auras.end(); ++i)
6395 if (!i->second->IsPositive() && i->second->GetCasterGUID() == duel->opponent->GetGUID() && i->second->GetAuraApplyTime() >= duel->startTime)
6396 auras2remove.push_back(i->second->GetId());
6398 for(size_t i=0; i<auras2remove.size(); i++)
6399 RemoveAurasDueToSpell(auras2remove[i]);
6401 // cleanup combo points
6402 if(GetComboTarget()==duel->opponent->GetGUID())
6403 ClearComboPoints();
6404 else if(GetComboTarget()==duel->opponent->GetPetGUID())
6405 ClearComboPoints();
6407 if(duel->opponent->GetComboTarget()==GetGUID())
6408 duel->opponent->ClearComboPoints();
6409 else if(duel->opponent->GetComboTarget()==GetPetGUID())
6410 duel->opponent->ClearComboPoints();
6412 //cleanups
6413 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6414 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6415 duel->opponent->SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
6416 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 0);
6418 delete duel->opponent->duel;
6419 duel->opponent->duel = NULL;
6420 delete duel;
6421 duel = NULL;
6424 //---------------------------------------------------------//
6426 void Player::_ApplyItemMods(Item *item, uint8 slot,bool apply)
6428 if(slot >= INVENTORY_SLOT_BAG_END || !item)
6429 return;
6431 // not apply/remove mods for broken item
6432 if(item->IsBroken())
6433 return;
6435 ItemPrototype const *proto = item->GetProto();
6437 if(!proto)
6438 return;
6440 sLog.outDetail("applying mods for item %u ",item->GetGUIDLow());
6442 uint32 attacktype = Player::GetAttackBySlot(slot);
6443 if(attacktype < MAX_ATTACK)
6444 _ApplyWeaponDependentAuraMods(item,WeaponAttackType(attacktype),apply);
6446 _ApplyItemBonuses(proto,slot,apply);
6448 if( slot==EQUIPMENT_SLOT_RANGED )
6449 _ApplyAmmoBonuses();
6451 ApplyItemEquipSpell(item,apply);
6452 ApplyEnchantment(item, apply);
6454 if(proto->Socket[0].Color) //only (un)equipping of items with sockets can influence metagems, so no need to waste time with normal items
6455 CorrectMetaGemEnchants(slot, apply);
6457 sLog.outDebug("_ApplyItemMods complete.");
6460 void Player::_ApplyItemBonuses(ItemPrototype const *proto, uint8 slot, bool apply)
6462 if(slot >= INVENTORY_SLOT_BAG_END || !proto)
6463 return;
6465 for (int i = 0; i < 10; i++)
6467 uint32 statType = 0;
6468 int32 val = 0;
6470 if(proto->ScalingStatDistribution)
6472 if(ScalingStatDistributionEntry const *ssd = sScalingStatDistributionStore.LookupEntry(proto->ScalingStatDistribution))
6474 statType = ssd->StatMod[i];
6476 if(uint32 modifier = ssd->Modifier[i])
6478 uint32 level = ((getLevel() > ssd->MaxLevel) ? ssd->MaxLevel : getLevel());
6479 if(ScalingStatValuesEntry const *ssv = sScalingStatValuesStore.LookupEntry(level))
6481 int multiplier = ssv->Multiplier[proto->GetScalingStatValuesColumn()];
6482 val = (multiplier * modifier) / 10000;
6487 else
6489 statType = proto->ItemStat[i].ItemStatType;
6490 val = float(proto->ItemStat[i].ItemStatValue);
6493 if(val == 0)
6494 continue;
6496 switch (statType)
6498 case ITEM_MOD_MANA:
6499 HandleStatModifier(UNIT_MOD_MANA, BASE_VALUE, float(val), apply);
6500 break;
6501 case ITEM_MOD_HEALTH: // modify HP
6502 HandleStatModifier(UNIT_MOD_HEALTH, BASE_VALUE, float(val), apply);
6503 break;
6504 case ITEM_MOD_AGILITY: // modify agility
6505 HandleStatModifier(UNIT_MOD_STAT_AGILITY, BASE_VALUE, float(val), apply);
6506 ApplyStatBuffMod(STAT_AGILITY, float(val), apply);
6507 break;
6508 case ITEM_MOD_STRENGTH: //modify strength
6509 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, BASE_VALUE, float(val), apply);
6510 ApplyStatBuffMod(STAT_STRENGTH, float(val), apply);
6511 break;
6512 case ITEM_MOD_INTELLECT: //modify intellect
6513 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, BASE_VALUE, float(val), apply);
6514 ApplyStatBuffMod(STAT_INTELLECT, float(val), apply);
6515 break;
6516 case ITEM_MOD_SPIRIT: //modify spirit
6517 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, BASE_VALUE, float(val), apply);
6518 ApplyStatBuffMod(STAT_SPIRIT, float(val), apply);
6519 break;
6520 case ITEM_MOD_STAMINA: //modify stamina
6521 HandleStatModifier(UNIT_MOD_STAT_STAMINA, BASE_VALUE, float(val), apply);
6522 ApplyStatBuffMod(STAT_STAMINA, float(val), apply);
6523 break;
6524 case ITEM_MOD_DEFENSE_SKILL_RATING:
6525 ApplyRatingMod(CR_DEFENSE_SKILL, int32(val), apply);
6526 break;
6527 case ITEM_MOD_DODGE_RATING:
6528 ApplyRatingMod(CR_DODGE, int32(val), apply);
6529 break;
6530 case ITEM_MOD_PARRY_RATING:
6531 ApplyRatingMod(CR_PARRY, int32(val), apply);
6532 break;
6533 case ITEM_MOD_BLOCK_RATING:
6534 ApplyRatingMod(CR_BLOCK, int32(val), apply);
6535 break;
6536 case ITEM_MOD_HIT_MELEE_RATING:
6537 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6538 break;
6539 case ITEM_MOD_HIT_RANGED_RATING:
6540 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6541 break;
6542 case ITEM_MOD_HIT_SPELL_RATING:
6543 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6544 break;
6545 case ITEM_MOD_CRIT_MELEE_RATING:
6546 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6547 break;
6548 case ITEM_MOD_CRIT_RANGED_RATING:
6549 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6550 break;
6551 case ITEM_MOD_CRIT_SPELL_RATING:
6552 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6553 break;
6554 case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
6555 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6556 break;
6557 case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
6558 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6559 break;
6560 case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
6561 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6562 break;
6563 case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
6564 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6565 break;
6566 case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
6567 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6568 break;
6569 case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
6570 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6571 break;
6572 case ITEM_MOD_HASTE_MELEE_RATING:
6573 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6574 break;
6575 case ITEM_MOD_HASTE_RANGED_RATING:
6576 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6577 break;
6578 case ITEM_MOD_HASTE_SPELL_RATING:
6579 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6580 break;
6581 case ITEM_MOD_HIT_RATING:
6582 ApplyRatingMod(CR_HIT_MELEE, int32(val), apply);
6583 ApplyRatingMod(CR_HIT_RANGED, int32(val), apply);
6584 ApplyRatingMod(CR_HIT_SPELL, int32(val), apply);
6585 break;
6586 case ITEM_MOD_CRIT_RATING:
6587 ApplyRatingMod(CR_CRIT_MELEE, int32(val), apply);
6588 ApplyRatingMod(CR_CRIT_RANGED, int32(val), apply);
6589 ApplyRatingMod(CR_CRIT_SPELL, int32(val), apply);
6590 break;
6591 case ITEM_MOD_HIT_TAKEN_RATING:
6592 ApplyRatingMod(CR_HIT_TAKEN_MELEE, int32(val), apply);
6593 ApplyRatingMod(CR_HIT_TAKEN_RANGED, int32(val), apply);
6594 ApplyRatingMod(CR_HIT_TAKEN_SPELL, int32(val), apply);
6595 break;
6596 case ITEM_MOD_CRIT_TAKEN_RATING:
6597 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6598 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6599 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6600 break;
6601 case ITEM_MOD_RESILIENCE_RATING:
6602 ApplyRatingMod(CR_CRIT_TAKEN_MELEE, int32(val), apply);
6603 ApplyRatingMod(CR_CRIT_TAKEN_RANGED, int32(val), apply);
6604 ApplyRatingMod(CR_CRIT_TAKEN_SPELL, int32(val), apply);
6605 break;
6606 case ITEM_MOD_HASTE_RATING:
6607 ApplyRatingMod(CR_HASTE_MELEE, int32(val), apply);
6608 ApplyRatingMod(CR_HASTE_RANGED, int32(val), apply);
6609 ApplyRatingMod(CR_HASTE_SPELL, int32(val), apply);
6610 break;
6611 case ITEM_MOD_EXPERTISE_RATING:
6612 ApplyRatingMod(CR_EXPERTISE, int32(val), apply);
6613 break;
6614 case ITEM_MOD_ARMOR_PENETRATION_RATING:
6615 ApplyRatingMod(CR_ARMOR_PENETRATION, int32(val), apply);
6616 break;
6620 if (proto->Armor)
6621 HandleStatModifier(UNIT_MOD_ARMOR, BASE_VALUE, float(proto->Armor), apply);
6623 if (proto->Block)
6624 HandleBaseModValue(SHIELD_BLOCK_VALUE, FLAT_MOD, float(proto->Block), apply);
6626 if (proto->HolyRes)
6627 HandleStatModifier(UNIT_MOD_RESISTANCE_HOLY, BASE_VALUE, float(proto->HolyRes), apply);
6629 if (proto->FireRes)
6630 HandleStatModifier(UNIT_MOD_RESISTANCE_FIRE, BASE_VALUE, float(proto->FireRes), apply);
6632 if (proto->NatureRes)
6633 HandleStatModifier(UNIT_MOD_RESISTANCE_NATURE, BASE_VALUE, float(proto->NatureRes), apply);
6635 if (proto->FrostRes)
6636 HandleStatModifier(UNIT_MOD_RESISTANCE_FROST, BASE_VALUE, float(proto->FrostRes), apply);
6638 if (proto->ShadowRes)
6639 HandleStatModifier(UNIT_MOD_RESISTANCE_SHADOW, BASE_VALUE, float(proto->ShadowRes), apply);
6641 if (proto->ArcaneRes)
6642 HandleStatModifier(UNIT_MOD_RESISTANCE_ARCANE, BASE_VALUE, float(proto->ArcaneRes), apply);
6644 WeaponAttackType attType = BASE_ATTACK;
6645 float damage = 0.0f;
6647 if( slot == EQUIPMENT_SLOT_RANGED && (
6648 proto->InventoryType == INVTYPE_RANGED || proto->InventoryType == INVTYPE_THROWN ||
6649 proto->InventoryType == INVTYPE_RANGEDRIGHT ))
6651 attType = RANGED_ATTACK;
6653 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6655 attType = OFF_ATTACK;
6658 if (proto->Damage[0].DamageMin > 0 )
6660 damage = apply ? proto->Damage[0].DamageMin : BASE_MINDAMAGE;
6661 SetBaseWeaponDamage(attType, MINDAMAGE, damage);
6662 //sLog.outError("applying mindam: assigning %f to weapon mindamage, now is: %f", damage, GetWeaponDamageRange(attType, MINDAMAGE));
6665 if (proto->Damage[0].DamageMax > 0 )
6667 damage = apply ? proto->Damage[0].DamageMax : BASE_MAXDAMAGE;
6668 SetBaseWeaponDamage(attType, MAXDAMAGE, damage);
6671 if(!IsUseEquipedWeapon(slot==EQUIPMENT_SLOT_MAINHAND))
6672 return;
6674 if (proto->Delay)
6676 if(slot == EQUIPMENT_SLOT_RANGED)
6677 SetAttackTime(RANGED_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6678 else if(slot==EQUIPMENT_SLOT_MAINHAND)
6679 SetAttackTime(BASE_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6680 else if(slot==EQUIPMENT_SLOT_OFFHAND)
6681 SetAttackTime(OFF_ATTACK, apply ? proto->Delay: BASE_ATTACK_TIME);
6684 if(CanModifyStats() && (damage || proto->Delay))
6685 UpdateDamagePhysical(attType);
6688 void Player::_ApplyWeaponDependentAuraMods(Item *item,WeaponAttackType attackType,bool apply)
6690 AuraList const& auraCritList = GetAurasByType(SPELL_AURA_MOD_CRIT_PERCENT);
6691 for(AuraList::const_iterator itr = auraCritList.begin(); itr!=auraCritList.end();++itr)
6692 _ApplyWeaponDependentAuraCritMod(item,attackType,*itr,apply);
6694 AuraList const& auraDamageFlatList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_DONE);
6695 for(AuraList::const_iterator itr = auraDamageFlatList.begin(); itr!=auraDamageFlatList.end();++itr)
6696 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6698 AuraList const& auraDamagePCTList = GetAurasByType(SPELL_AURA_MOD_DAMAGE_PERCENT_DONE);
6699 for(AuraList::const_iterator itr = auraDamagePCTList.begin(); itr!=auraDamagePCTList.end();++itr)
6700 _ApplyWeaponDependentAuraDamageMod(item,attackType,*itr,apply);
6703 void Player::_ApplyWeaponDependentAuraCritMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6705 // generic not weapon specific case processes in aura code
6706 if(aura->GetSpellProto()->EquippedItemClass == -1)
6707 return;
6709 BaseModGroup mod = BASEMOD_END;
6710 switch(attackType)
6712 case BASE_ATTACK: mod = CRIT_PERCENTAGE; break;
6713 case OFF_ATTACK: mod = OFFHAND_CRIT_PERCENTAGE;break;
6714 case RANGED_ATTACK: mod = RANGED_CRIT_PERCENTAGE; break;
6715 default: return;
6718 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6720 HandleBaseModValue(mod, FLAT_MOD, float (aura->GetModifier()->m_amount), apply);
6724 void Player::_ApplyWeaponDependentAuraDamageMod(Item *item, WeaponAttackType attackType, Aura* aura, bool apply)
6726 // ignore spell mods for not wands
6727 Modifier const* modifier = aura->GetModifier();
6728 if((modifier->m_miscvalue & SPELL_SCHOOL_MASK_NORMAL)==0 && (getClassMask() & CLASSMASK_WAND_USERS)==0)
6729 return;
6731 // generic not weapon specific case processes in aura code
6732 if(aura->GetSpellProto()->EquippedItemClass == -1)
6733 return;
6735 UnitMods unitMod = UNIT_MOD_END;
6736 switch(attackType)
6738 case BASE_ATTACK: unitMod = UNIT_MOD_DAMAGE_MAINHAND; break;
6739 case OFF_ATTACK: unitMod = UNIT_MOD_DAMAGE_OFFHAND; break;
6740 case RANGED_ATTACK: unitMod = UNIT_MOD_DAMAGE_RANGED; break;
6741 default: return;
6744 UnitModifierType unitModType = TOTAL_VALUE;
6745 switch(modifier->m_auraname)
6747 case SPELL_AURA_MOD_DAMAGE_DONE: unitModType = TOTAL_VALUE; break;
6748 case SPELL_AURA_MOD_DAMAGE_PERCENT_DONE: unitModType = TOTAL_PCT; break;
6749 default: return;
6752 if (item->IsFitToSpellRequirements(aura->GetSpellProto()))
6754 HandleStatModifier(unitMod, unitModType, float(modifier->m_amount),apply);
6758 void Player::ApplyItemEquipSpell(Item *item, bool apply, bool form_change)
6760 if(!item)
6761 return;
6763 ItemPrototype const *proto = item->GetProto();
6764 if(!proto)
6765 return;
6767 for (int i = 0; i < 5; i++)
6769 _Spell const& spellData = proto->Spells[i];
6771 // no spell
6772 if(!spellData.SpellId )
6773 continue;
6775 // wrong triggering type
6776 if(apply && spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_EQUIP)
6777 continue;
6779 // check if it is valid spell
6780 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellData.SpellId);
6781 if(!spellproto)
6782 continue;
6784 ApplyEquipSpell(spellproto,item,apply,form_change);
6788 void Player::ApplyEquipSpell(SpellEntry const* spellInfo, Item* item, bool apply, bool form_change)
6790 if(apply)
6792 // Cannot be used in this stance/form
6793 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)!=0)
6794 return;
6796 if(form_change) // check aura active state from other form
6798 bool found = false;
6799 for (int k=0; k < 3; ++k)
6801 spellEffectPair spair = spellEffectPair(spellInfo->Id, k);
6802 for (AuraMap::iterator iter = m_Auras.lower_bound(spair); iter != m_Auras.upper_bound(spair); ++iter)
6804 if(!item || iter->second->GetCastItemGUID() == item->GetGUID())
6806 found = true;
6807 break;
6810 if(found)
6811 break;
6814 if(found) // and skip re-cast already active aura at form change
6815 return;
6818 DEBUG_LOG("WORLD: cast %s Equip spellId - %i", (item ? "item" : "itemset"), spellInfo->Id);
6820 CastSpell(this,spellInfo,true,item);
6822 else
6824 if(form_change) // check aura compatibility
6826 // Cannot be used in this stance/form
6827 if(GetErrorAtShapeshiftedCast(spellInfo, m_form)==0)
6828 return; // and remove only not compatible at form change
6831 if(item)
6832 RemoveAurasDueToItemSpell(item,spellInfo->Id); // un-apply all spells , not only at-equipped
6833 else
6834 RemoveAurasDueToSpell(spellInfo->Id); // un-apply spell (item set case)
6838 void Player::UpdateEquipSpellsAtFormChange()
6840 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6842 if(m_items[i] && !m_items[i]->IsBroken())
6844 ApplyItemEquipSpell(m_items[i],false,true); // remove spells that not fit to form
6845 ApplyItemEquipSpell(m_items[i],true,true); // add spells that fit form but not active
6849 // item set bonuses not dependent from item broken state
6850 for(size_t setindex = 0; setindex < ItemSetEff.size(); ++setindex)
6852 ItemSetEffect* eff = ItemSetEff[setindex];
6853 if(!eff)
6854 continue;
6856 for(uint32 y=0;y<8; ++y)
6858 SpellEntry const* spellInfo = eff->spells[y];
6859 if(!spellInfo)
6860 continue;
6862 ApplyEquipSpell(spellInfo,NULL,false,true); // remove spells that not fit to form
6863 ApplyEquipSpell(spellInfo,NULL,true,true); // add spells that fit form but not active
6868 void Player::CastItemCombatSpell(Item *item,Unit* Target, WeaponAttackType attType)
6870 if(!item || item->IsBroken())
6871 return;
6873 ItemPrototype const *proto = item->GetProto();
6874 if(!proto)
6875 return;
6877 if (!Target || Target == this )
6878 return;
6880 for (int i = 0; i < 5; i++)
6882 _Spell const& spellData = proto->Spells[i];
6884 // no spell
6885 if(!spellData.SpellId )
6886 continue;
6888 // wrong triggering type
6889 if(spellData.SpellTrigger != ITEM_SPELLTRIGGER_CHANCE_ON_HIT)
6890 continue;
6892 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellData.SpellId);
6893 if(!spellInfo)
6895 sLog.outError("WORLD: unknown Item spellid %i", spellData.SpellId);
6896 continue;
6899 // not allow proc extra attack spell at extra attack
6900 if( m_extraAttacks && IsSpellHaveEffect(spellInfo,SPELL_EFFECT_ADD_EXTRA_ATTACKS) )
6901 return;
6903 float chance = spellInfo->procChance;
6905 if(spellData.SpellPPMRate)
6907 uint32 WeaponSpeed = GetAttackTime(attType);
6908 chance = GetPPMProcChance(WeaponSpeed, spellData.SpellPPMRate);
6910 else if(chance > 100.0f)
6912 chance = GetWeaponProcChance();
6915 if (roll_chance_f(chance))
6916 CastSpell(Target, spellInfo->Id, true, item);
6919 // item combat enchantments
6920 for(int e_slot = 0; e_slot < MAX_ENCHANTMENT_SLOT; ++e_slot)
6922 uint32 enchant_id = item->GetEnchantmentId(EnchantmentSlot(e_slot));
6923 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
6924 if(!pEnchant) continue;
6925 for (int s=0;s<3;s++)
6927 if(pEnchant->type[s]!=ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL)
6928 continue;
6930 SpellEntry const *spellInfo = sSpellStore.LookupEntry(pEnchant->spellid[s]);
6931 if (!spellInfo)
6933 sLog.outError("Player::CastItemCombatSpell Enchant %i, cast unknown spell %i", pEnchant->ID, pEnchant->spellid[s]);
6934 continue;
6937 float chance = pEnchant->amount[s] != 0 ? float(pEnchant->amount[s]) : GetWeaponProcChance();
6938 if (roll_chance_f(chance))
6940 if(IsPositiveSpell(pEnchant->spellid[s]))
6941 CastSpell(this, pEnchant->spellid[s], true, item);
6942 else
6943 CastSpell(Target, pEnchant->spellid[s], true, item);
6949 void Player::_RemoveAllItemMods()
6951 sLog.outDebug("_RemoveAllItemMods start.");
6953 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6955 if(m_items[i])
6957 ItemPrototype const *proto = m_items[i]->GetProto();
6958 if(!proto)
6959 continue;
6961 // item set bonuses not dependent from item broken state
6962 if(proto->ItemSet)
6963 RemoveItemsSetItem(this,proto);
6965 if(m_items[i]->IsBroken())
6966 continue;
6968 ApplyItemEquipSpell(m_items[i],false);
6969 ApplyEnchantment(m_items[i], false);
6973 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
6975 if(m_items[i])
6977 if(m_items[i]->IsBroken())
6978 continue;
6979 ItemPrototype const *proto = m_items[i]->GetProto();
6980 if(!proto)
6981 continue;
6983 uint32 attacktype = Player::GetAttackBySlot(i);
6984 if(attacktype < MAX_ATTACK)
6985 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),false);
6987 _ApplyItemBonuses(proto,i, false);
6989 if( i == EQUIPMENT_SLOT_RANGED )
6990 _ApplyAmmoBonuses();
6994 sLog.outDebug("_RemoveAllItemMods complete.");
6997 void Player::_ApplyAllItemMods()
6999 sLog.outDebug("_ApplyAllItemMods start.");
7001 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7003 if(m_items[i])
7005 if(m_items[i]->IsBroken())
7006 continue;
7008 ItemPrototype const *proto = m_items[i]->GetProto();
7009 if(!proto)
7010 continue;
7012 uint32 attacktype = Player::GetAttackBySlot(i);
7013 if(attacktype < MAX_ATTACK)
7014 _ApplyWeaponDependentAuraMods(m_items[i],WeaponAttackType(attacktype),true);
7016 _ApplyItemBonuses(proto,i, true);
7018 if( i == EQUIPMENT_SLOT_RANGED )
7019 _ApplyAmmoBonuses();
7023 for (int i = 0; i < INVENTORY_SLOT_BAG_END; i++)
7025 if(m_items[i])
7027 ItemPrototype const *proto = m_items[i]->GetProto();
7028 if(!proto)
7029 continue;
7031 // item set bonuses not dependent from item broken state
7032 if(proto->ItemSet)
7033 AddItemsSetItem(this,m_items[i]);
7035 if(m_items[i]->IsBroken())
7036 continue;
7038 ApplyItemEquipSpell(m_items[i],true);
7039 ApplyEnchantment(m_items[i], true);
7043 sLog.outDebug("_ApplyAllItemMods complete.");
7046 void Player::_ApplyAmmoBonuses()
7048 // check ammo
7049 uint32 ammo_id = GetUInt32Value(PLAYER_AMMO_ID);
7050 if(!ammo_id)
7051 return;
7053 float currentAmmoDPS;
7055 ItemPrototype const *ammo_proto = objmgr.GetItemPrototype( ammo_id );
7056 if( !ammo_proto || ammo_proto->Class!=ITEM_CLASS_PROJECTILE || !CheckAmmoCompatibility(ammo_proto))
7057 currentAmmoDPS = 0.0f;
7058 else
7059 currentAmmoDPS = ammo_proto->Damage[0].DamageMin;
7061 if(currentAmmoDPS == GetAmmoDPS())
7062 return;
7064 m_ammoDPS = currentAmmoDPS;
7066 if(CanModifyStats())
7067 UpdateDamagePhysical(RANGED_ATTACK);
7070 bool Player::CheckAmmoCompatibility(const ItemPrototype *ammo_proto) const
7072 if(!ammo_proto)
7073 return false;
7075 // check ranged weapon
7076 Item *weapon = GetWeaponForAttack( RANGED_ATTACK );
7077 if(!weapon || weapon->IsBroken() )
7078 return false;
7080 ItemPrototype const* weapon_proto = weapon->GetProto();
7081 if(!weapon_proto || weapon_proto->Class!=ITEM_CLASS_WEAPON )
7082 return false;
7084 // check ammo ws. weapon compatibility
7085 switch(weapon_proto->SubClass)
7087 case ITEM_SUBCLASS_WEAPON_BOW:
7088 case ITEM_SUBCLASS_WEAPON_CROSSBOW:
7089 if(ammo_proto->SubClass!=ITEM_SUBCLASS_ARROW)
7090 return false;
7091 break;
7092 case ITEM_SUBCLASS_WEAPON_GUN:
7093 if(ammo_proto->SubClass!=ITEM_SUBCLASS_BULLET)
7094 return false;
7095 break;
7096 default:
7097 return false;
7100 return true;
7103 /* If in a battleground a player dies, and an enemy removes the insignia, the player's bones is lootable
7104 Called by remove insignia spell effect */
7105 void Player::RemovedInsignia(Player* looterPlr)
7107 if (!GetBattleGroundId())
7108 return;
7110 // If not released spirit, do it !
7111 if(m_deathTimer > 0)
7113 m_deathTimer = 0;
7114 BuildPlayerRepop();
7115 RepopAtGraveyard();
7118 Corpse *corpse = GetCorpse();
7119 if (!corpse)
7120 return;
7122 // We have to convert player corpse to bones, not to be able to resurrect there
7123 // SpawnCorpseBones isn't handy, 'cos it saves player while he in BG
7124 Corpse *bones = ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
7125 if (!bones)
7126 return;
7128 // Now we must make bones lootable, and send player loot
7129 bones->SetFlag(CORPSE_FIELD_DYNAMIC_FLAGS, CORPSE_DYNFLAG_LOOTABLE);
7131 // We store the level of our player in the gold field
7132 // We retrieve this information at Player::SendLoot()
7133 bones->loot.gold = getLevel();
7134 bones->lootRecipient = looterPlr;
7135 looterPlr->SendLoot(bones->GetGUID(), LOOT_INSIGNIA);
7138 /*Loot type MUST be
7139 1-corpse, go
7140 2-skinning
7141 3-Fishing
7144 void Player::SendLootRelease( uint64 guid )
7146 WorldPacket data( SMSG_LOOT_RELEASE_RESPONSE, (8+1) );
7147 data << uint64(guid) << uint8(1);
7148 SendDirectMessage( &data );
7151 void Player::SendLoot(uint64 guid, LootType loot_type)
7153 Loot *loot = 0;
7154 PermissionTypes permission = ALL_PERMISSION;
7156 sLog.outDebug("Player::SendLoot");
7157 if (IS_GAMEOBJECT_GUID(guid))
7159 sLog.outDebug(" IS_GAMEOBJECT_GUID(guid)");
7160 GameObject *go =
7161 ObjectAccessor::GetGameObject(*this, guid);
7163 // not check distance for GO in case owned GO (fishing bobber case, for example)
7164 // And permit out of range GO with no owner in case fishing hole
7165 if (!go || (loot_type != LOOT_FISHINGHOLE && (loot_type != LOOT_FISHING || go->GetOwnerGUID() != GetGUID()) && !go->IsWithinDistInMap(this,INTERACTION_DISTANCE)))
7167 SendLootRelease(guid);
7168 return;
7171 loot = &go->loot;
7173 if(go->getLootState() == GO_READY)
7175 uint32 lootid = go->GetLootId();
7177 if(lootid)
7179 sLog.outDebug(" if(lootid)");
7180 loot->clear();
7181 loot->FillLoot(lootid, LootTemplates_Gameobject, this);
7184 if(loot_type == LOOT_FISHING)
7185 go->getFishLoot(loot);
7187 go->SetLootState(GO_ACTIVATED);
7190 else if (IS_ITEM_GUID(guid))
7192 Item *item = GetItemByGuid( guid );
7194 if (!item)
7196 SendLootRelease(guid);
7197 return;
7200 if(loot_type == LOOT_DISENCHANTING)
7202 loot = &item->loot;
7204 if(!item->m_lootGenerated)
7206 item->m_lootGenerated = true;
7207 loot->clear();
7208 loot->FillLoot(item->GetProto()->DisenchantID, LootTemplates_Disenchant, this);
7211 else if(loot_type == LOOT_PROSPECTING)
7213 loot = &item->loot;
7215 if(!item->m_lootGenerated)
7217 item->m_lootGenerated = true;
7218 loot->clear();
7219 loot->FillLoot(item->GetEntry(), LootTemplates_Prospecting, this);
7222 else if(loot_type == LOOT_MILLING)
7224 loot = &item->loot;
7226 if(!item->m_lootGenerated)
7228 item->m_lootGenerated = true;
7229 loot->clear();
7230 loot->FillLoot(item->GetEntry(), LootTemplates_Milling, this);
7233 else
7235 loot = &item->loot;
7237 if(!item->m_lootGenerated)
7239 item->m_lootGenerated = true;
7240 loot->clear();
7241 loot->FillLoot(item->GetEntry(), LootTemplates_Item, this);
7243 loot->generateMoneyLoot(item->GetProto()->MinMoneyLoot,item->GetProto()->MaxMoneyLoot);
7247 else if (IS_CORPSE_GUID(guid)) // remove insignia
7249 Corpse *bones = ObjectAccessor::GetCorpse(*this, guid);
7251 if (!bones || !((loot_type == LOOT_CORPSE) || (loot_type == LOOT_INSIGNIA)) || (bones->GetType() != CORPSE_BONES) )
7253 SendLootRelease(guid);
7254 return;
7257 loot = &bones->loot;
7259 if (!bones->lootForBody)
7261 bones->lootForBody = true;
7262 uint32 pLevel = bones->loot.gold;
7263 bones->loot.clear();
7264 // It may need a better formula
7265 // Now it works like this: lvl10: ~6copper, lvl70: ~9silver
7266 bones->loot.gold = (uint32)( urand(50, 150) * 0.016f * pow( ((float)pLevel)/5.76f, 2.5f) * sWorld.getRate(RATE_DROP_MONEY) );
7269 if (bones->lootRecipient != this)
7270 permission = NONE_PERMISSION;
7272 else
7274 Creature *creature = ObjectAccessor::GetCreature(*this, guid);
7276 // must be in range and creature must be alive for pickpocket and must be dead for another loot
7277 if (!creature || creature->isAlive()!=(loot_type == LOOT_PICKPOCKETING) || !creature->IsWithinDistInMap(this,INTERACTION_DISTANCE))
7279 SendLootRelease(guid);
7280 return;
7283 if(loot_type == LOOT_PICKPOCKETING && IsFriendlyTo(creature))
7285 SendLootRelease(guid);
7286 return;
7289 loot = &creature->loot;
7291 if(loot_type == LOOT_PICKPOCKETING)
7293 if ( !creature->lootForPickPocketed )
7295 creature->lootForPickPocketed = true;
7296 loot->clear();
7298 if (uint32 lootid = creature->GetCreatureInfo()->pickpocketLootId)
7299 loot->FillLoot(lootid, LootTemplates_Pickpocketing, this);
7301 // Generate extra money for pick pocket loot
7302 const uint32 a = urand(0, creature->getLevel()/2);
7303 const uint32 b = urand(0, getLevel()/2);
7304 loot->gold = uint32(10 * (a + b) * sWorld.getRate(RATE_DROP_MONEY));
7307 else
7309 // the player whose group may loot the corpse
7310 Player *recipient = creature->GetLootRecipient();
7311 if (!recipient)
7313 creature->SetLootRecipient(this);
7314 recipient = this;
7317 if (creature->lootForPickPocketed)
7319 creature->lootForPickPocketed = false;
7320 loot->clear();
7323 if(!creature->lootForBody)
7325 creature->lootForBody = true;
7326 loot->clear();
7328 if (uint32 lootid = creature->GetCreatureInfo()->lootid)
7329 loot->FillLoot(lootid, LootTemplates_Creature, recipient);
7331 loot->generateMoneyLoot(creature->GetCreatureInfo()->mingold,creature->GetCreatureInfo()->maxgold);
7333 if(Group* group = recipient->GetGroup())
7335 group->UpdateLooterGuid(creature,true);
7337 switch (group->GetLootMethod())
7339 case GROUP_LOOT:
7340 // GroupLoot delete items over threshold (threshold even not implemented), and roll them. Items with quality<threshold, round robin
7341 group->GroupLoot(recipient->GetGUID(), loot, creature);
7342 break;
7343 case NEED_BEFORE_GREED:
7344 group->NeedBeforeGreed(recipient->GetGUID(), loot, creature);
7345 break;
7346 case MASTER_LOOT:
7347 group->MasterLoot(recipient->GetGUID(), loot, creature);
7348 break;
7349 default:
7350 break;
7355 // possible only if creature->lootForBody && loot->empty() at spell cast check
7356 if (loot_type == LOOT_SKINNING)
7358 loot->clear();
7359 loot->FillLoot(creature->GetCreatureInfo()->SkinLootId, LootTemplates_Skinning, this);
7361 // set group rights only for loot_type != LOOT_SKINNING
7362 else
7364 if(Group* group = GetGroup())
7366 if( group == recipient->GetGroup() )
7368 if(group->GetLootMethod() == FREE_FOR_ALL)
7369 permission = ALL_PERMISSION;
7370 else if(group->GetLooterGuid() == GetGUID())
7372 if(group->GetLootMethod() == MASTER_LOOT)
7373 permission = MASTER_PERMISSION;
7374 else
7375 permission = ALL_PERMISSION;
7377 else
7378 permission = GROUP_PERMISSION;
7380 else
7381 permission = NONE_PERMISSION;
7383 else if(recipient == this)
7384 permission = ALL_PERMISSION;
7385 else
7386 permission = NONE_PERMISSION;
7391 SetLootGUID(guid);
7393 QuestItemList *q_list = 0;
7394 if (permission != NONE_PERMISSION)
7396 QuestItemMap const& lootPlayerQuestItems = loot->GetPlayerQuestItems();
7397 QuestItemMap::const_iterator itr = lootPlayerQuestItems.find(GetGUIDLow());
7398 if (itr == lootPlayerQuestItems.end())
7399 q_list = loot->FillQuestLoot(this);
7400 else
7401 q_list = itr->second;
7404 QuestItemList *ffa_list = 0;
7405 if (permission != NONE_PERMISSION)
7407 QuestItemMap const& lootPlayerFFAItems = loot->GetPlayerFFAItems();
7408 QuestItemMap::const_iterator itr = lootPlayerFFAItems.find(GetGUIDLow());
7409 if (itr == lootPlayerFFAItems.end())
7410 ffa_list = loot->FillFFALoot(this);
7411 else
7412 ffa_list = itr->second;
7415 QuestItemList *conditional_list = 0;
7416 if (permission != NONE_PERMISSION)
7418 QuestItemMap const& lootPlayerNonQuestNonFFAConditionalItems = loot->GetPlayerNonQuestNonFFAConditionalItems();
7419 QuestItemMap::const_iterator itr = lootPlayerNonQuestNonFFAConditionalItems.find(GetGUIDLow());
7420 if (itr == lootPlayerNonQuestNonFFAConditionalItems.end())
7421 conditional_list = loot->FillNonQuestNonFFAConditionalLoot(this);
7422 else
7423 conditional_list = itr->second;
7426 // LOOT_PICKPOCKETING, LOOT_PROSPECTING, LOOT_DISENCHANTING, LOOT_INSIGNIA and LOOT_MILLING unsupported by client, sending LOOT_SKINNING instead
7427 if(loot_type == LOOT_PICKPOCKETING || loot_type == LOOT_DISENCHANTING || loot_type == LOOT_PROSPECTING || loot_type == LOOT_INSIGNIA || loot_type == LOOT_MILLING)
7428 loot_type = LOOT_SKINNING;
7430 if(loot_type == LOOT_FISHINGHOLE)
7431 loot_type = LOOT_FISHING;
7433 WorldPacket data(SMSG_LOOT_RESPONSE, (9+50)); // we guess size
7435 data << uint64(guid);
7436 data << uint8(loot_type);
7437 data << LootView(*loot, q_list, ffa_list, conditional_list, this, permission);
7439 SendDirectMessage(&data);
7441 // add 'this' player as one of the players that are looting 'loot'
7442 if (permission != NONE_PERMISSION)
7443 loot->AddLooter(GetGUID());
7445 if ( loot_type == LOOT_CORPSE && !IS_ITEM_GUID(guid) )
7446 SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_LOOTING);
7449 void Player::SendNotifyLootMoneyRemoved()
7451 WorldPacket data(SMSG_LOOT_CLEAR_MONEY, 0);
7452 GetSession()->SendPacket( &data );
7455 void Player::SendNotifyLootItemRemoved(uint8 lootSlot)
7457 WorldPacket data(SMSG_LOOT_REMOVED, 1);
7458 data << uint8(lootSlot);
7459 GetSession()->SendPacket( &data );
7462 void Player::SendUpdateWorldState(uint32 Field, uint32 Value)
7464 WorldPacket data(SMSG_UPDATE_WORLD_STATE, 8);
7465 data << Field;
7466 data << Value;
7467 GetSession()->SendPacket(&data);
7470 void Player::SendInitWorldStates()
7472 // data depends on zoneid/mapid...
7473 BattleGround* bg = GetBattleGround();
7474 uint16 NumberOfFields = 0;
7475 uint32 mapid = GetMapId();
7476 uint32 zoneid = GetZoneId();
7477 uint32 areaid = GetAreaId();
7478 sLog.outDebug("Sending SMSG_INIT_WORLD_STATES to Map:%u, Zone: %u", mapid, zoneid);
7479 // may be exist better way to do this...
7480 switch(zoneid)
7482 case 0:
7483 case 1:
7484 case 4:
7485 case 8:
7486 case 10:
7487 case 11:
7488 case 12:
7489 case 36:
7490 case 38:
7491 case 40:
7492 case 41:
7493 case 51:
7494 case 267:
7495 case 1519:
7496 case 1537:
7497 case 2257:
7498 case 2918:
7499 NumberOfFields = 6;
7500 break;
7501 case 2597:
7502 NumberOfFields = 81;
7503 break;
7504 case 3277:
7505 NumberOfFields = 14;
7506 break;
7507 case 3358:
7508 case 3820:
7509 NumberOfFields = 38;
7510 break;
7511 case 3483:
7512 NumberOfFields = 22;
7513 break;
7514 case 3519:
7515 NumberOfFields = 36;
7516 break;
7517 case 3521:
7518 NumberOfFields = 35;
7519 break;
7520 case 3698:
7521 case 3702:
7522 case 3968:
7523 NumberOfFields = 9;
7524 break;
7525 case 3703:
7526 NumberOfFields = 9;
7527 break;
7528 default:
7529 NumberOfFields = 10;
7530 break;
7533 WorldPacket data(SMSG_INIT_WORLD_STATES, (4+4+4+2+(NumberOfFields*8)));
7534 data << uint32(mapid); // mapid
7535 data << uint32(zoneid); // zone id
7536 data << uint32(areaid); // area id, new 2.1.0
7537 data << uint16(NumberOfFields); // count of uint64 blocks
7538 data << uint32(0x8d8) << uint32(0x0); // 1
7539 data << uint32(0x8d7) << uint32(0x0); // 2
7540 data << uint32(0x8d6) << uint32(0x0); // 3
7541 data << uint32(0x8d5) << uint32(0x0); // 4
7542 data << uint32(0x8d4) << uint32(0x0); // 5
7543 data << uint32(0x8d3) << uint32(0x0); // 6
7544 if(mapid == 530) // Outland
7546 data << uint32(0x9bf) << uint32(0x0); // 7
7547 data << uint32(0x9bd) << uint32(0xF); // 8
7548 data << uint32(0x9bb) << uint32(0xF); // 9
7550 switch(zoneid)
7552 case 1:
7553 case 11:
7554 case 12:
7555 case 38:
7556 case 40:
7557 case 51:
7558 case 1519:
7559 case 1537:
7560 case 2257:
7561 break;
7562 case 2597: // AV
7563 data << uint32(0x7ae) << uint32(0x1); // 7
7564 data << uint32(0x532) << uint32(0x1); // 8
7565 data << uint32(0x531) << uint32(0x0); // 9
7566 data << uint32(0x52e) << uint32(0x0); // 10
7567 data << uint32(0x571) << uint32(0x0); // 11
7568 data << uint32(0x570) << uint32(0x0); // 12
7569 data << uint32(0x567) << uint32(0x1); // 13
7570 data << uint32(0x566) << uint32(0x1); // 14
7571 data << uint32(0x550) << uint32(0x1); // 15
7572 data << uint32(0x544) << uint32(0x0); // 16
7573 data << uint32(0x536) << uint32(0x0); // 17
7574 data << uint32(0x535) << uint32(0x1); // 18
7575 data << uint32(0x518) << uint32(0x0); // 19
7576 data << uint32(0x517) << uint32(0x0); // 20
7577 data << uint32(0x574) << uint32(0x0); // 21
7578 data << uint32(0x573) << uint32(0x0); // 22
7579 data << uint32(0x572) << uint32(0x0); // 23
7580 data << uint32(0x56f) << uint32(0x0); // 24
7581 data << uint32(0x56e) << uint32(0x0); // 25
7582 data << uint32(0x56d) << uint32(0x0); // 26
7583 data << uint32(0x56c) << uint32(0x0); // 27
7584 data << uint32(0x56b) << uint32(0x0); // 28
7585 data << uint32(0x56a) << uint32(0x1); // 29
7586 data << uint32(0x569) << uint32(0x1); // 30
7587 data << uint32(0x568) << uint32(0x1); // 13
7588 data << uint32(0x565) << uint32(0x0); // 32
7589 data << uint32(0x564) << uint32(0x0); // 33
7590 data << uint32(0x563) << uint32(0x0); // 34
7591 data << uint32(0x562) << uint32(0x0); // 35
7592 data << uint32(0x561) << uint32(0x0); // 36
7593 data << uint32(0x560) << uint32(0x0); // 37
7594 data << uint32(0x55f) << uint32(0x0); // 38
7595 data << uint32(0x55e) << uint32(0x0); // 39
7596 data << uint32(0x55d) << uint32(0x0); // 40
7597 data << uint32(0x3c6) << uint32(0x4); // 41
7598 data << uint32(0x3c4) << uint32(0x6); // 42
7599 data << uint32(0x3c2) << uint32(0x4); // 43
7600 data << uint32(0x516) << uint32(0x1); // 44
7601 data << uint32(0x515) << uint32(0x0); // 45
7602 data << uint32(0x3b6) << uint32(0x6); // 46
7603 data << uint32(0x55c) << uint32(0x0); // 47
7604 data << uint32(0x55b) << uint32(0x0); // 48
7605 data << uint32(0x55a) << uint32(0x0); // 49
7606 data << uint32(0x559) << uint32(0x0); // 50
7607 data << uint32(0x558) << uint32(0x0); // 51
7608 data << uint32(0x557) << uint32(0x0); // 52
7609 data << uint32(0x556) << uint32(0x0); // 53
7610 data << uint32(0x555) << uint32(0x0); // 54
7611 data << uint32(0x554) << uint32(0x1); // 55
7612 data << uint32(0x553) << uint32(0x1); // 56
7613 data << uint32(0x552) << uint32(0x1); // 57
7614 data << uint32(0x551) << uint32(0x1); // 58
7615 data << uint32(0x54f) << uint32(0x0); // 59
7616 data << uint32(0x54e) << uint32(0x0); // 60
7617 data << uint32(0x54d) << uint32(0x1); // 61
7618 data << uint32(0x54c) << uint32(0x0); // 62
7619 data << uint32(0x54b) << uint32(0x0); // 63
7620 data << uint32(0x545) << uint32(0x0); // 64
7621 data << uint32(0x543) << uint32(0x1); // 65
7622 data << uint32(0x542) << uint32(0x0); // 66
7623 data << uint32(0x540) << uint32(0x0); // 67
7624 data << uint32(0x53f) << uint32(0x0); // 68
7625 data << uint32(0x53e) << uint32(0x0); // 69
7626 data << uint32(0x53d) << uint32(0x0); // 70
7627 data << uint32(0x53c) << uint32(0x0); // 71
7628 data << uint32(0x53b) << uint32(0x0); // 72
7629 data << uint32(0x53a) << uint32(0x1); // 73
7630 data << uint32(0x539) << uint32(0x0); // 74
7631 data << uint32(0x538) << uint32(0x0); // 75
7632 data << uint32(0x537) << uint32(0x0); // 76
7633 data << uint32(0x534) << uint32(0x0); // 77
7634 data << uint32(0x533) << uint32(0x0); // 78
7635 data << uint32(0x530) << uint32(0x0); // 79
7636 data << uint32(0x52f) << uint32(0x0); // 80
7637 data << uint32(0x52d) << uint32(0x1); // 81
7638 break;
7639 case 3277: // WS
7640 if (bg && bg->GetTypeID() == BATTLEGROUND_WS)
7641 bg->FillInitialWorldStates(data);
7642 else
7644 data << uint32(0x62d) << uint32(0x0); // 7 1581 alliance flag captures
7645 data << uint32(0x62e) << uint32(0x0); // 8 1582 horde flag captures
7646 data << uint32(0x609) << uint32(0x0); // 9 1545 unk, set to 1 on alliance flag pickup...
7647 data << uint32(0x60a) << uint32(0x0); // 10 1546 unk, set to 1 on horde flag pickup, after drop it's -1
7648 data << uint32(0x60b) << uint32(0x2); // 11 1547 unk
7649 data << uint32(0x641) << uint32(0x3); // 12 1601 unk (max flag captures?)
7650 data << uint32(0x922) << uint32(0x1); // 13 2338 horde (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7651 data << uint32(0x923) << uint32(0x1); // 14 2339 alliance (0 - hide, 1 - flag ok, 2 - flag picked up (flashing), 3 - flag picked up (not flashing)
7653 break;
7654 case 3358: // AB
7655 if (bg && bg->GetTypeID() == BATTLEGROUND_AB)
7656 bg->FillInitialWorldStates(data);
7657 else
7659 data << uint32(0x6e7) << uint32(0x0); // 7 1767 stables alliance
7660 data << uint32(0x6e8) << uint32(0x0); // 8 1768 stables horde
7661 data << uint32(0x6e9) << uint32(0x0); // 9 1769 unk, ST?
7662 data << uint32(0x6ea) << uint32(0x0); // 10 1770 stables (show/hide)
7663 data << uint32(0x6ec) << uint32(0x0); // 11 1772 farm (0 - horde controlled, 1 - alliance controlled)
7664 data << uint32(0x6ed) << uint32(0x0); // 12 1773 farm (show/hide)
7665 data << uint32(0x6ee) << uint32(0x0); // 13 1774 farm color
7666 data << uint32(0x6ef) << uint32(0x0); // 14 1775 gold mine color, may be FM?
7667 data << uint32(0x6f0) << uint32(0x0); // 15 1776 alliance resources
7668 data << uint32(0x6f1) << uint32(0x0); // 16 1777 horde resources
7669 data << uint32(0x6f2) << uint32(0x0); // 17 1778 horde bases
7670 data << uint32(0x6f3) << uint32(0x0); // 18 1779 alliance bases
7671 data << uint32(0x6f4) << uint32(0x7d0); // 19 1780 max resources (2000)
7672 data << uint32(0x6f6) << uint32(0x0); // 20 1782 blacksmith color
7673 data << uint32(0x6f7) << uint32(0x0); // 21 1783 blacksmith (show/hide)
7674 data << uint32(0x6f8) << uint32(0x0); // 22 1784 unk, bs?
7675 data << uint32(0x6f9) << uint32(0x0); // 23 1785 unk, bs?
7676 data << uint32(0x6fb) << uint32(0x0); // 24 1787 gold mine (0 - horde contr, 1 - alliance contr)
7677 data << uint32(0x6fc) << uint32(0x0); // 25 1788 gold mine (0 - conflict, 1 - horde)
7678 data << uint32(0x6fd) << uint32(0x0); // 26 1789 gold mine (1 - show/0 - hide)
7679 data << uint32(0x6fe) << uint32(0x0); // 27 1790 gold mine color
7680 data << uint32(0x700) << uint32(0x0); // 28 1792 gold mine color, wtf?, may be LM?
7681 data << uint32(0x701) << uint32(0x0); // 29 1793 lumber mill color (0 - conflict, 1 - horde contr)
7682 data << uint32(0x702) << uint32(0x0); // 30 1794 lumber mill (show/hide)
7683 data << uint32(0x703) << uint32(0x0); // 31 1795 lumber mill color color
7684 data << uint32(0x732) << uint32(0x1); // 32 1842 stables (1 - uncontrolled)
7685 data << uint32(0x733) << uint32(0x1); // 33 1843 gold mine (1 - uncontrolled)
7686 data << uint32(0x734) << uint32(0x1); // 34 1844 lumber mill (1 - uncontrolled)
7687 data << uint32(0x735) << uint32(0x1); // 35 1845 farm (1 - uncontrolled)
7688 data << uint32(0x736) << uint32(0x1); // 36 1846 blacksmith (1 - uncontrolled)
7689 data << uint32(0x745) << uint32(0x2); // 37 1861 unk
7690 data << uint32(0x7a3) << uint32(0x708); // 38 1955 warning limit (1800)
7692 break;
7693 case 3820: // EY
7694 if (bg && bg->GetTypeID() == BATTLEGROUND_EY)
7695 bg->FillInitialWorldStates(data);
7696 else
7698 data << uint32(0xac1) << uint32(0x0); // 7 2753 Horde Bases
7699 data << uint32(0xac0) << uint32(0x0); // 8 2752 Alliance Bases
7700 data << uint32(0xab6) << uint32(0x0); // 9 2742 Mage Tower - Horde conflict
7701 data << uint32(0xab5) << uint32(0x0); // 10 2741 Mage Tower - Alliance conflict
7702 data << uint32(0xab4) << uint32(0x0); // 11 2740 Fel Reaver - Horde conflict
7703 data << uint32(0xab3) << uint32(0x0); // 12 2739 Fel Reaver - Alliance conflict
7704 data << uint32(0xab2) << uint32(0x0); // 13 2738 Draenei - Alliance conflict
7705 data << uint32(0xab1) << uint32(0x0); // 14 2737 Draenei - Horde conflict
7706 data << uint32(0xab0) << uint32(0x0); // 15 2736 unk // 0 at start
7707 data << uint32(0xaaf) << uint32(0x0); // 16 2735 unk // 0 at start
7708 data << uint32(0xaad) << uint32(0x0); // 17 2733 Draenei - Horde control
7709 data << uint32(0xaac) << uint32(0x0); // 18 2732 Draenei - Alliance control
7710 data << uint32(0xaab) << uint32(0x1); // 19 2731 Draenei uncontrolled (1 - yes, 0 - no)
7711 data << uint32(0xaaa) << uint32(0x0); // 20 2730 Mage Tower - Alliance control
7712 data << uint32(0xaa9) << uint32(0x0); // 21 2729 Mage Tower - Horde control
7713 data << uint32(0xaa8) << uint32(0x1); // 22 2728 Mage Tower uncontrolled (1 - yes, 0 - no)
7714 data << uint32(0xaa7) << uint32(0x0); // 23 2727 Fel Reaver - Horde control
7715 data << uint32(0xaa6) << uint32(0x0); // 24 2726 Fel Reaver - Alliance control
7716 data << uint32(0xaa5) << uint32(0x1); // 25 2725 Fel Reaver uncontrolled (1 - yes, 0 - no)
7717 data << uint32(0xaa4) << uint32(0x0); // 26 2724 Boold Elf - Horde control
7718 data << uint32(0xaa3) << uint32(0x0); // 27 2723 Boold Elf - Alliance control
7719 data << uint32(0xaa2) << uint32(0x1); // 28 2722 Boold Elf uncontrolled (1 - yes, 0 - no)
7720 data << uint32(0xac5) << uint32(0x1); // 29 2757 Flag (1 - show, 0 - hide) - doesn't work exactly this way!
7721 data << uint32(0xad2) << uint32(0x1); // 30 2770 Horde top-stats (1 - show, 0 - hide) // 02 -> horde picked up the flag
7722 data << uint32(0xad1) << uint32(0x1); // 31 2769 Alliance top-stats (1 - show, 0 - hide) // 02 -> alliance picked up the flag
7723 data << uint32(0xabe) << uint32(0x0); // 32 2750 Horde resources
7724 data << uint32(0xabd) << uint32(0x0); // 33 2749 Alliance resources
7725 data << uint32(0xa05) << uint32(0x8e); // 34 2565 unk, constant?
7726 data << uint32(0xaa0) << uint32(0x0); // 35 2720 Capturing progress-bar (100 -> empty (only grey), 0 -> blue|red (no grey), default 0)
7727 data << uint32(0xa9f) << uint32(0x0); // 36 2719 Capturing progress-bar (0 - left, 100 - right)
7728 data << uint32(0xa9e) << uint32(0x0); // 37 2718 Capturing progress-bar (1 - show, 0 - hide)
7729 data << uint32(0xc0d) << uint32(0x17b); // 38 3085 unk
7730 // and some more ... unknown
7732 break;
7733 case 3483: // Hellfire Peninsula
7734 data << uint32(0x9ba) << uint32(0x1); // 10
7735 data << uint32(0x9b9) << uint32(0x1); // 11
7736 data << uint32(0x9b5) << uint32(0x0); // 12
7737 data << uint32(0x9b4) << uint32(0x1); // 13
7738 data << uint32(0x9b3) << uint32(0x0); // 14
7739 data << uint32(0x9b2) << uint32(0x0); // 15
7740 data << uint32(0x9b1) << uint32(0x1); // 16
7741 data << uint32(0x9b0) << uint32(0x0); // 17
7742 data << uint32(0x9ae) << uint32(0x0); // 18 horde pvp objectives captured
7743 data << uint32(0x9ac) << uint32(0x0); // 19
7744 data << uint32(0x9a8) << uint32(0x0); // 20
7745 data << uint32(0x9a7) << uint32(0x0); // 21
7746 data << uint32(0x9a6) << uint32(0x1); // 22
7747 break;
7748 case 3519: // Terokkar Forest
7749 data << uint32(0xa41) << uint32(0x0); // 10
7750 data << uint32(0xa40) << uint32(0x14); // 11
7751 data << uint32(0xa3f) << uint32(0x0); // 12
7752 data << uint32(0xa3e) << uint32(0x0); // 13
7753 data << uint32(0xa3d) << uint32(0x5); // 14
7754 data << uint32(0xa3c) << uint32(0x0); // 15
7755 data << uint32(0xa87) << uint32(0x0); // 16
7756 data << uint32(0xa86) << uint32(0x0); // 17
7757 data << uint32(0xa85) << uint32(0x0); // 18
7758 data << uint32(0xa84) << uint32(0x0); // 19
7759 data << uint32(0xa83) << uint32(0x0); // 20
7760 data << uint32(0xa82) << uint32(0x0); // 21
7761 data << uint32(0xa81) << uint32(0x0); // 22
7762 data << uint32(0xa80) << uint32(0x0); // 23
7763 data << uint32(0xa7e) << uint32(0x0); // 24
7764 data << uint32(0xa7d) << uint32(0x0); // 25
7765 data << uint32(0xa7c) << uint32(0x0); // 26
7766 data << uint32(0xa7b) << uint32(0x0); // 27
7767 data << uint32(0xa7a) << uint32(0x0); // 28
7768 data << uint32(0xa79) << uint32(0x0); // 29
7769 data << uint32(0x9d0) << uint32(0x5); // 30
7770 data << uint32(0x9ce) << uint32(0x0); // 31
7771 data << uint32(0x9cd) << uint32(0x0); // 32
7772 data << uint32(0x9cc) << uint32(0x0); // 33
7773 data << uint32(0xa88) << uint32(0x0); // 34
7774 data << uint32(0xad0) << uint32(0x0); // 35
7775 data << uint32(0xacf) << uint32(0x1); // 36
7776 break;
7777 case 3521: // Zangarmarsh
7778 data << uint32(0x9e1) << uint32(0x0); // 10
7779 data << uint32(0x9e0) << uint32(0x0); // 11
7780 data << uint32(0x9df) << uint32(0x0); // 12
7781 data << uint32(0xa5d) << uint32(0x1); // 13
7782 data << uint32(0xa5c) << uint32(0x0); // 14
7783 data << uint32(0xa5b) << uint32(0x1); // 15
7784 data << uint32(0xa5a) << uint32(0x0); // 16
7785 data << uint32(0xa59) << uint32(0x1); // 17
7786 data << uint32(0xa58) << uint32(0x0); // 18
7787 data << uint32(0xa57) << uint32(0x0); // 19
7788 data << uint32(0xa56) << uint32(0x0); // 20
7789 data << uint32(0xa55) << uint32(0x1); // 21
7790 data << uint32(0xa54) << uint32(0x0); // 22
7791 data << uint32(0x9e7) << uint32(0x0); // 23
7792 data << uint32(0x9e6) << uint32(0x0); // 24
7793 data << uint32(0x9e5) << uint32(0x0); // 25
7794 data << uint32(0xa00) << uint32(0x0); // 26
7795 data << uint32(0x9ff) << uint32(0x1); // 27
7796 data << uint32(0x9fe) << uint32(0x0); // 28
7797 data << uint32(0x9fd) << uint32(0x0); // 29
7798 data << uint32(0x9fc) << uint32(0x1); // 30
7799 data << uint32(0x9fb) << uint32(0x0); // 31
7800 data << uint32(0xa62) << uint32(0x0); // 32
7801 data << uint32(0xa61) << uint32(0x1); // 33
7802 data << uint32(0xa60) << uint32(0x1); // 34
7803 data << uint32(0xa5f) << uint32(0x0); // 35
7804 break;
7805 case 3698: // Nagrand Arena
7806 data << uint32(0xa0f) << uint32(0x0); // 7
7807 data << uint32(0xa10) << uint32(0x0); // 8
7808 data << uint32(0xa11) << uint32(0x0); // 9
7809 break;
7810 case 3702: // Blade's Edge Arena
7811 data << uint32(0x9f0) << uint32(0x0); // 7
7812 data << uint32(0x9f1) << uint32(0x0); // 8
7813 data << uint32(0x9f3) << uint32(0x0); // 9
7814 break;
7815 case 3968: // Ruins of Lordaeron
7816 data << uint32(0xbb8) << uint32(0x0); // 7
7817 data << uint32(0xbb9) << uint32(0x0); // 8
7818 data << uint32(0xbba) << uint32(0x0); // 9
7819 break;
7820 case 3703: // Shattrath City
7821 break;
7822 default:
7823 data << uint32(0x914) << uint32(0x0); // 7
7824 data << uint32(0x913) << uint32(0x0); // 8
7825 data << uint32(0x912) << uint32(0x0); // 9
7826 data << uint32(0x915) << uint32(0x0); // 10
7827 break;
7829 GetSession()->SendPacket(&data);
7832 uint32 Player::GetXPRestBonus(uint32 xp)
7834 uint32 rested_bonus = (uint32)GetRestBonus(); // xp for each rested bonus
7836 if(rested_bonus > xp) // max rested_bonus == xp or (r+x) = 200% xp
7837 rested_bonus = xp;
7839 SetRestBonus( GetRestBonus() - rested_bonus);
7841 sLog.outDetail("Player gain %u xp (+ %u Rested Bonus). Rested points=%f",xp+rested_bonus,rested_bonus,GetRestBonus());
7842 return rested_bonus;
7845 void Player::SetBindPoint(uint64 guid)
7847 WorldPacket data(SMSG_BINDER_CONFIRM, 8);
7848 data << uint64(guid);
7849 GetSession()->SendPacket( &data );
7852 void Player::SendTalentWipeConfirm(uint64 guid)
7854 WorldPacket data(MSG_TALENT_WIPE_CONFIRM, (8+4));
7855 data << uint64(guid);
7856 data << uint32(resetTalentsCost());
7857 GetSession()->SendPacket( &data );
7860 void Player::SendPetSkillWipeConfirm()
7862 Pet* pet = GetPet();
7863 if(!pet)
7864 return;
7865 WorldPacket data(SMSG_PET_UNLEARN_CONFIRM, (8+4));
7866 data << pet->GetGUID();
7867 data << uint32(pet->resetTalentsCost());
7868 GetSession()->SendPacket( &data );
7871 /*********************************************************/
7872 /*** STORAGE SYSTEM ***/
7873 /*********************************************************/
7875 void Player::SetVirtualItemSlot( uint8 i, Item* item)
7877 assert(i < 3);
7878 if(i < 2 && item)
7880 if(!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT))
7881 return;
7882 uint32 charges = item->GetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT);
7883 if(charges == 0)
7884 return;
7885 if(charges > 1)
7886 item->SetEnchantmentCharges(TEMP_ENCHANTMENT_SLOT,charges-1);
7887 else if(charges <= 1)
7889 ApplyEnchantment(item,TEMP_ENCHANTMENT_SLOT,false);
7890 item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT);
7895 void Player::SetSheath( uint32 sheathed )
7897 switch (sheathed)
7899 case SHEATH_STATE_UNARMED: // no prepared weapon
7900 SetVirtualItemSlot(0,NULL);
7901 SetVirtualItemSlot(1,NULL);
7902 SetVirtualItemSlot(2,NULL);
7903 break;
7904 case SHEATH_STATE_MELEE: // prepared melee weapon
7906 SetVirtualItemSlot(0,GetWeaponForAttack(BASE_ATTACK,true));
7907 SetVirtualItemSlot(1,GetWeaponForAttack(OFF_ATTACK,true));
7908 SetVirtualItemSlot(2,NULL);
7909 }; break;
7910 case SHEATH_STATE_RANGED: // prepared ranged weapon
7911 SetVirtualItemSlot(0,NULL);
7912 SetVirtualItemSlot(1,NULL);
7913 SetVirtualItemSlot(2,GetWeaponForAttack(RANGED_ATTACK,true));
7914 break;
7915 default:
7916 SetVirtualItemSlot(0,NULL);
7917 SetVirtualItemSlot(1,NULL);
7918 SetVirtualItemSlot(2,NULL);
7919 break;
7921 SetByteValue(UNIT_FIELD_BYTES_2, 0, sheathed); // this must visualize Sheath changing for other players...
7924 uint8 Player::FindEquipSlot( ItemPrototype const* proto, uint32 slot, bool swap ) const
7926 uint8 pClass = getClass();
7928 uint8 slots[4];
7929 slots[0] = NULL_SLOT;
7930 slots[1] = NULL_SLOT;
7931 slots[2] = NULL_SLOT;
7932 slots[3] = NULL_SLOT;
7933 switch( proto->InventoryType )
7935 case INVTYPE_HEAD:
7936 slots[0] = EQUIPMENT_SLOT_HEAD;
7937 break;
7938 case INVTYPE_NECK:
7939 slots[0] = EQUIPMENT_SLOT_NECK;
7940 break;
7941 case INVTYPE_SHOULDERS:
7942 slots[0] = EQUIPMENT_SLOT_SHOULDERS;
7943 break;
7944 case INVTYPE_BODY:
7945 slots[0] = EQUIPMENT_SLOT_BODY;
7946 break;
7947 case INVTYPE_CHEST:
7948 slots[0] = EQUIPMENT_SLOT_CHEST;
7949 break;
7950 case INVTYPE_ROBE:
7951 slots[0] = EQUIPMENT_SLOT_CHEST;
7952 break;
7953 case INVTYPE_WAIST:
7954 slots[0] = EQUIPMENT_SLOT_WAIST;
7955 break;
7956 case INVTYPE_LEGS:
7957 slots[0] = EQUIPMENT_SLOT_LEGS;
7958 break;
7959 case INVTYPE_FEET:
7960 slots[0] = EQUIPMENT_SLOT_FEET;
7961 break;
7962 case INVTYPE_WRISTS:
7963 slots[0] = EQUIPMENT_SLOT_WRISTS;
7964 break;
7965 case INVTYPE_HANDS:
7966 slots[0] = EQUIPMENT_SLOT_HANDS;
7967 break;
7968 case INVTYPE_FINGER:
7969 slots[0] = EQUIPMENT_SLOT_FINGER1;
7970 slots[1] = EQUIPMENT_SLOT_FINGER2;
7971 break;
7972 case INVTYPE_TRINKET:
7973 slots[0] = EQUIPMENT_SLOT_TRINKET1;
7974 slots[1] = EQUIPMENT_SLOT_TRINKET2;
7975 break;
7976 case INVTYPE_CLOAK:
7977 slots[0] = EQUIPMENT_SLOT_BACK;
7978 break;
7979 case INVTYPE_WEAPON:
7981 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7983 // suggest offhand slot only if know dual wielding
7984 // (this will be replace mainhand weapon at auto equip instead unwonted "you don't known dual wielding" ...
7985 if(CanDualWield())
7986 slots[1] = EQUIPMENT_SLOT_OFFHAND;
7987 };break;
7988 case INVTYPE_SHIELD:
7989 slots[0] = EQUIPMENT_SLOT_OFFHAND;
7990 break;
7991 case INVTYPE_RANGED:
7992 slots[0] = EQUIPMENT_SLOT_RANGED;
7993 break;
7994 case INVTYPE_2HWEAPON:
7995 slots[0] = EQUIPMENT_SLOT_MAINHAND;
7996 break;
7997 case INVTYPE_TABARD:
7998 slots[0] = EQUIPMENT_SLOT_TABARD;
7999 break;
8000 case INVTYPE_WEAPONMAINHAND:
8001 slots[0] = EQUIPMENT_SLOT_MAINHAND;
8002 break;
8003 case INVTYPE_WEAPONOFFHAND:
8004 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8005 break;
8006 case INVTYPE_HOLDABLE:
8007 slots[0] = EQUIPMENT_SLOT_OFFHAND;
8008 break;
8009 case INVTYPE_THROWN:
8010 slots[0] = EQUIPMENT_SLOT_RANGED;
8011 break;
8012 case INVTYPE_RANGEDRIGHT:
8013 slots[0] = EQUIPMENT_SLOT_RANGED;
8014 break;
8015 case INVTYPE_BAG:
8016 slots[0] = INVENTORY_SLOT_BAG_1;
8017 slots[1] = INVENTORY_SLOT_BAG_2;
8018 slots[2] = INVENTORY_SLOT_BAG_3;
8019 slots[3] = INVENTORY_SLOT_BAG_4;
8020 break;
8021 case INVTYPE_RELIC:
8023 switch(proto->SubClass)
8025 case ITEM_SUBCLASS_ARMOR_LIBRAM:
8026 if (pClass == CLASS_PALADIN)
8027 slots[0] = EQUIPMENT_SLOT_RANGED;
8028 break;
8029 case ITEM_SUBCLASS_ARMOR_IDOL:
8030 if (pClass == CLASS_DRUID)
8031 slots[0] = EQUIPMENT_SLOT_RANGED;
8032 break;
8033 case ITEM_SUBCLASS_ARMOR_TOTEM:
8034 if (pClass == CLASS_SHAMAN)
8035 slots[0] = EQUIPMENT_SLOT_RANGED;
8036 break;
8037 case ITEM_SUBCLASS_ARMOR_MISC:
8038 if (pClass == CLASS_WARLOCK)
8039 slots[0] = EQUIPMENT_SLOT_RANGED;
8040 break;
8041 case ITEM_SUBCLASS_ARMOR_SIGIL:
8042 if (pClass == CLASS_DEATH_KNIGHT)
8043 slots[0] = EQUIPMENT_SLOT_RANGED;
8044 break;
8046 break;
8048 default :
8049 return NULL_SLOT;
8052 if( slot != NULL_SLOT )
8054 if( swap || !GetItemByPos( INVENTORY_SLOT_BAG_0, slot ) )
8056 for (int i = 0; i < 4; i++)
8058 if ( slots[i] == slot )
8059 return slot;
8063 else
8065 // search free slot at first
8066 for (int i = 0; i < 4; i++)
8068 if ( slots[i] != NULL_SLOT && !GetItemByPos( INVENTORY_SLOT_BAG_0, slots[i] ) )
8070 // in case 2hand equipped weapon offhand slot empty but not free
8071 if(slots[i]==EQUIPMENT_SLOT_OFFHAND)
8073 Item* mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );
8074 if(!mainItem || mainItem->GetProto()->InventoryType != INVTYPE_2HWEAPON)
8075 return slots[i];
8077 else
8078 return slots[i];
8082 // if not found free and can swap return first appropriate from used
8083 for (int i = 0; i < 4; i++)
8085 if ( slots[i] != NULL_SLOT && swap )
8086 return slots[i];
8090 // no free position
8091 return NULL_SLOT;
8094 uint8 Player::CanUnequipItems( uint32 item, uint32 count ) const
8096 Item *pItem;
8097 uint32 tempcount = 0;
8099 uint8 res = EQUIP_ERR_OK;
8101 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
8103 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8104 if( pItem && pItem->GetEntry() == item )
8106 uint8 ires = CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i, false);
8107 if(ires==EQUIP_ERR_OK)
8109 tempcount += pItem->GetCount();
8110 if( tempcount >= count )
8111 return EQUIP_ERR_OK;
8113 else
8114 res = ires;
8117 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
8119 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8120 if( pItem && pItem->GetEntry() == item )
8122 tempcount += pItem->GetCount();
8123 if( tempcount >= count )
8124 return EQUIP_ERR_OK;
8127 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8129 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8130 if( pItem && pItem->GetEntry() == item )
8132 tempcount += pItem->GetCount();
8133 if( tempcount >= count )
8134 return EQUIP_ERR_OK;
8137 Bag *pBag;
8138 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8140 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8141 if( pBag )
8143 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8145 pItem = GetItemByPos( i, j );
8146 if( pItem && pItem->GetEntry() == item )
8148 tempcount += pItem->GetCount();
8149 if( tempcount >= count )
8150 return EQUIP_ERR_OK;
8156 // not found req. item count and have unequippable items
8157 return res;
8160 uint32 Player::GetItemCount( uint32 item, bool inBankAlso, Item* skipItem ) const
8162 uint32 count = 0;
8163 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8165 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8166 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8167 count += pItem->GetCount();
8169 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8171 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8172 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8173 count += pItem->GetCount();
8175 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8177 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8178 if( pBag )
8179 count += pBag->GetItemCount(item,skipItem);
8182 if(skipItem && skipItem->GetProto()->GemProperties)
8184 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8186 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8187 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8188 count += pItem->GetGemCountWithID(item);
8192 if(inBankAlso)
8194 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8196 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8197 if( pItem && pItem != skipItem && pItem->GetEntry() == item )
8198 count += pItem->GetCount();
8200 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8202 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8203 if( pBag )
8204 count += pBag->GetItemCount(item,skipItem);
8207 if(skipItem && skipItem->GetProto()->GemProperties)
8209 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8211 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8212 if( pItem && pItem != skipItem && pItem->GetProto()->Socket[0].Color )
8213 count += pItem->GetGemCountWithID(item);
8218 return count;
8221 Item* Player::GetItemByGuid( uint64 guid ) const
8223 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8225 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8226 if( pItem && pItem->GetGUID() == guid )
8227 return pItem;
8229 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8231 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8232 if( pItem && pItem->GetGUID() == guid )
8233 return pItem;
8236 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8238 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8239 if( pBag )
8241 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8243 Item* pItem = pBag->GetItemByPos( j );
8244 if( pItem && pItem->GetGUID() == guid )
8245 return pItem;
8249 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8251 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8252 if( pBag )
8254 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8256 Item* pItem = pBag->GetItemByPos( j );
8257 if( pItem && pItem->GetGUID() == guid )
8258 return pItem;
8263 return NULL;
8266 Item* Player::GetItemByPos( uint16 pos ) const
8268 uint8 bag = pos >> 8;
8269 uint8 slot = pos & 255;
8270 return GetItemByPos( bag, slot );
8273 Item* Player::GetItemByPos( uint8 bag, uint8 slot ) const
8275 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < BANK_SLOT_BAG_END || slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8276 return m_items[slot];
8277 else if(bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END
8278 || bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8280 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8281 if ( pBag )
8282 return pBag->GetItemByPos(slot);
8284 return NULL;
8287 Item* Player::GetWeaponForAttack(WeaponAttackType attackType, bool useable) const
8289 uint16 slot;
8290 switch (attackType)
8292 case BASE_ATTACK: slot = EQUIPMENT_SLOT_MAINHAND; break;
8293 case OFF_ATTACK: slot = EQUIPMENT_SLOT_OFFHAND; break;
8294 case RANGED_ATTACK: slot = EQUIPMENT_SLOT_RANGED; break;
8295 default: return NULL;
8298 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, slot);
8299 if (!item || item->GetProto()->Class != ITEM_CLASS_WEAPON)
8300 return NULL;
8302 if(!useable)
8303 return item;
8305 if( item->IsBroken() || !IsUseEquipedWeapon(attackType==BASE_ATTACK) )
8306 return NULL;
8308 return item;
8311 Item* Player::GetShield(bool useable) const
8313 Item* item = GetItemByPos(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND);
8314 if (!item || item->GetProto()->Class != ITEM_CLASS_ARMOR)
8315 return NULL;
8317 if(!useable)
8318 return item;
8320 if( item->IsBroken())
8321 return NULL;
8323 return item;
8326 uint32 Player::GetAttackBySlot( uint8 slot )
8328 switch(slot)
8330 case EQUIPMENT_SLOT_MAINHAND: return BASE_ATTACK;
8331 case EQUIPMENT_SLOT_OFFHAND: return OFF_ATTACK;
8332 case EQUIPMENT_SLOT_RANGED: return RANGED_ATTACK;
8333 default: return MAX_ATTACK;
8337 bool Player::HasBankBagSlot( uint8 slot ) const
8339 uint32 maxslot = GetByteValue(PLAYER_BYTES_2, 2) + BANK_SLOT_BAG_START;
8340 if( slot < maxslot )
8341 return true;
8342 return false;
8345 bool Player::IsInventoryPos( uint8 bag, uint8 slot )
8347 if( bag == INVENTORY_SLOT_BAG_0 && slot == NULL_SLOT )
8348 return true;
8349 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END ) )
8350 return true;
8351 if( bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END )
8352 return true;
8353 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= KEYRING_SLOT_START && slot < QUESTBAG_SLOT_END ) )
8354 return true;
8355 return false;
8358 bool Player::IsEquipmentPos( uint8 bag, uint8 slot )
8360 if( bag == INVENTORY_SLOT_BAG_0 && ( slot < EQUIPMENT_SLOT_END ) )
8361 return true;
8362 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8363 return true;
8364 return false;
8367 bool Player::IsBankPos( uint8 bag, uint8 slot )
8369 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END ) )
8370 return true;
8371 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8372 return true;
8373 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8374 return true;
8375 return false;
8378 bool Player::IsBagPos( uint16 pos )
8380 uint8 bag = pos >> 8;
8381 uint8 slot = pos & 255;
8382 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END ) )
8383 return true;
8384 if( bag == INVENTORY_SLOT_BAG_0 && ( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END ) )
8385 return true;
8386 return false;
8389 bool Player::IsValidPos( uint8 bag, uint8 slot )
8391 // post selected
8392 if(bag == NULL_BAG)
8393 return true;
8395 if (bag == INVENTORY_SLOT_BAG_0)
8397 // any post selected
8398 if (slot == NULL_SLOT)
8399 return true;
8401 // equipment
8402 if (slot < EQUIPMENT_SLOT_END)
8403 return true;
8405 // bag equip slots
8406 if (slot >= INVENTORY_SLOT_BAG_START && slot < INVENTORY_SLOT_BAG_END)
8407 return true;
8409 // backpack slots
8410 if (slot >= INVENTORY_SLOT_ITEM_START && slot < INVENTORY_SLOT_ITEM_END)
8411 return true;
8413 // keyring slots
8414 if (slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_END)
8415 return true;
8417 // bank main slots
8418 if (slot >= BANK_SLOT_ITEM_START && slot < BANK_SLOT_ITEM_END)
8419 return true;
8421 // bank bag slots
8422 if (slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END)
8423 return true;
8425 return false;
8428 // bag content slots
8429 if (bag >= INVENTORY_SLOT_BAG_START && bag < INVENTORY_SLOT_BAG_END)
8431 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8432 if(!pBag)
8433 return false;
8435 // any post selected
8436 if (slot == NULL_SLOT)
8437 return true;
8439 return slot < pBag->GetBagSize();
8442 // bank bag content slots
8443 if( bag >= BANK_SLOT_BAG_START && bag < BANK_SLOT_BAG_END )
8445 Bag* pBag = (Bag*)GetItemByPos (INVENTORY_SLOT_BAG_0, bag);
8446 if(!pBag)
8447 return false;
8449 // any post selected
8450 if (slot == NULL_SLOT)
8451 return true;
8453 return slot < pBag->GetBagSize();
8456 // where this?
8457 return false;
8461 bool Player::HasItemCount( uint32 item, uint32 count, bool inBankAlso ) const
8463 uint32 tempcount = 0;
8464 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; i++)
8466 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8467 if( pItem && pItem->GetEntry() == item )
8469 tempcount += pItem->GetCount();
8470 if( tempcount >= count )
8471 return true;
8474 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
8476 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8477 if( pItem && pItem->GetEntry() == item )
8479 tempcount += pItem->GetCount();
8480 if( tempcount >= count )
8481 return true;
8484 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
8486 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8488 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8490 Item* pItem = GetItemByPos( i, j );
8491 if( pItem && pItem->GetEntry() == item )
8493 tempcount += pItem->GetCount();
8494 if( tempcount >= count )
8495 return true;
8501 if(inBankAlso)
8503 for(int i = BANK_SLOT_ITEM_START; i < BANK_SLOT_ITEM_END; i++)
8505 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8506 if( pItem && pItem->GetEntry() == item )
8508 tempcount += pItem->GetCount();
8509 if( tempcount >= count )
8510 return true;
8513 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
8515 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8517 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8519 Item* pItem = GetItemByPos( i, j );
8520 if( pItem && pItem->GetEntry() == item )
8522 tempcount += pItem->GetCount();
8523 if( tempcount >= count )
8524 return true;
8531 return false;
8534 Item* Player::GetItemOrItemWithGemEquipped( uint32 item ) const
8536 Item *pItem;
8537 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
8539 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8540 if( pItem && pItem->GetEntry() == item )
8541 return pItem;
8544 ItemPrototype const *pProto = objmgr.GetItemPrototype(item);
8545 if (pProto && pProto->GemProperties)
8547 for(int i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; i++)
8549 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8550 if( pItem && pItem->GetProto()->Socket[0].Color )
8552 if (pItem->GetGemCountWithID(item) > 0 )
8553 return pItem;
8558 return NULL;
8561 uint8 Player::_CanTakeMoreSimilarItems(uint32 entry, uint32 count, Item* pItem, uint32* no_space_count ) const
8563 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8564 if( !pProto )
8566 if(no_space_count)
8567 *no_space_count = count;
8568 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8571 // no maximum
8572 if(pProto->MaxCount == 0)
8573 return EQUIP_ERR_OK;
8575 uint32 curcount = GetItemCount(pProto->ItemId,true,pItem);
8577 if( curcount + count > pProto->MaxCount )
8579 if(no_space_count)
8580 *no_space_count = count +curcount - pProto->MaxCount;
8581 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8584 return EQUIP_ERR_OK;
8587 bool Player::HasItemTotemCategory( uint32 TotemCategory ) const
8589 Item *pItem;
8590 for(uint8 i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_ITEM_END; ++i)
8592 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8593 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8594 return true;
8596 for(uint8 i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; ++i)
8598 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
8599 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8600 return true;
8602 for(uint8 i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
8604 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
8606 for(uint32 j = 0; j < pBag->GetBagSize(); ++j)
8608 pItem = GetItemByPos( i, j );
8609 if( pItem && IsTotemCategoryCompatiableWith(pItem->GetProto()->TotemCategory,TotemCategory ))
8610 return true;
8614 return false;
8617 uint8 Player::_CanStoreItem_InSpecificSlot( uint8 bag, uint8 slot, ItemPosCountVec &dest, ItemPrototype const *pProto, uint32& count, bool swap, Item* pSrcItem ) const
8619 Item* pItem2 = GetItemByPos( bag, slot );
8621 // ignore move item (this slot will be empty at move)
8622 if(pItem2==pSrcItem)
8623 pItem2 = NULL;
8625 uint32 need_space;
8627 // empty specific slot - check item fit to slot
8628 if( !pItem2 || swap )
8630 if( bag == INVENTORY_SLOT_BAG_0 )
8632 // keyring case
8633 if(slot >= KEYRING_SLOT_START && slot < KEYRING_SLOT_START+GetMaxKeyringSize() && !(pProto->BagFamily & BAG_FAMILY_MASK_KEYS))
8634 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8636 // vanitypet case
8637 if(slot >= VANITYPET_SLOT_START && slot < VANITYPET_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS))
8638 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8640 // currencytoken case
8641 if(slot >= CURRENCYTOKEN_SLOT_START && slot < CURRENCYTOKEN_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS))
8642 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8644 // guestbag case
8645 if(slot >= QUESTBAG_SLOT_START && slot < QUESTBAG_SLOT_END && !(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS))
8646 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8648 // prevent cheating
8649 if(slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END || slot >= PLAYER_SLOT_END)
8650 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8652 else
8654 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8655 if( !pBag )
8656 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8658 ItemPrototype const* pBagProto = pBag->GetProto();
8659 if( !pBagProto )
8660 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8662 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8663 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8666 // non empty stack with space
8667 need_space = pProto->Stackable;
8669 // non empty slot, check item type
8670 else
8672 // check item type
8673 if(pItem2->GetEntry() != pProto->ItemId)
8674 return EQUIP_ERR_ITEM_CANT_STACK;
8676 // check free space
8677 if(pItem2->GetCount() >= pProto->Stackable)
8678 return EQUIP_ERR_ITEM_CANT_STACK;
8680 need_space = pProto->Stackable - pItem2->GetCount();
8683 if(need_space > count)
8684 need_space = count;
8686 ItemPosCount newPosition = ItemPosCount((bag << 8) | slot, need_space);
8687 if(!newPosition.isContainedIn(dest))
8689 dest.push_back(newPosition);
8690 count -= need_space;
8692 return EQUIP_ERR_OK;
8695 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
8697 // skip specific bag already processed in first called _CanStoreItem_InBag
8698 if(bag==skip_bag)
8699 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8701 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
8702 if( !pBag )
8703 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8705 ItemPrototype const* pBagProto = pBag->GetProto();
8706 if( !pBagProto )
8707 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8709 // specialized bag mode or non-specilized
8710 if( non_specialized != (pBagProto->Class == ITEM_CLASS_CONTAINER && pBagProto->SubClass == ITEM_SUBCLASS_CONTAINER) )
8711 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8713 if( !ItemCanGoIntoBag(pProto,pBagProto) )
8714 return EQUIP_ERR_ITEM_DOESNT_GO_INTO_BAG;
8716 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
8718 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8719 if(j==skip_slot)
8720 continue;
8722 Item* pItem2 = GetItemByPos( bag, j );
8724 // ignore move item (this slot will be empty at move)
8725 if(pItem2==pSrcItem)
8726 pItem2 = NULL;
8728 // if merge skip empty, if !merge skip non-empty
8729 if((pItem2!=NULL)!=merge)
8730 continue;
8732 if( pItem2 )
8734 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->Stackable )
8736 uint32 need_space = pProto->Stackable - pItem2->GetCount();
8737 if(need_space > count)
8738 need_space = count;
8740 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8741 if(!newPosition.isContainedIn(dest))
8743 dest.push_back(newPosition);
8744 count -= need_space;
8746 if(count==0)
8747 return EQUIP_ERR_OK;
8751 else
8753 uint32 need_space = pProto->Stackable;
8754 if(need_space > count)
8755 need_space = count;
8757 ItemPosCount newPosition = ItemPosCount((bag << 8) | j, need_space);
8758 if(!newPosition.isContainedIn(dest))
8760 dest.push_back(newPosition);
8761 count -= need_space;
8763 if(count==0)
8764 return EQUIP_ERR_OK;
8768 return EQUIP_ERR_OK;
8771 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
8773 for(uint32 j = slot_begin; j < slot_end; j++)
8775 // skip specific slot already processed in first called _CanStoreItem_InSpecificSlot
8776 if(INVENTORY_SLOT_BAG_0==skip_bag && j==skip_slot)
8777 continue;
8779 Item* pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, j );
8781 // ignore move item (this slot will be empty at move)
8782 if(pItem2==pSrcItem)
8783 pItem2 = NULL;
8785 // if merge skip empty, if !merge skip non-empty
8786 if((pItem2!=NULL)!=merge)
8787 continue;
8789 if( pItem2 )
8791 if(pItem2->GetEntry() == pProto->ItemId && pItem2->GetCount() < pProto->Stackable )
8793 uint32 need_space = pProto->Stackable - pItem2->GetCount();
8794 if(need_space > count)
8795 need_space = count;
8796 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8797 if(!newPosition.isContainedIn(dest))
8799 dest.push_back(newPosition);
8800 count -= need_space;
8802 if(count==0)
8803 return EQUIP_ERR_OK;
8807 else
8809 uint32 need_space = pProto->Stackable;
8810 if(need_space > count)
8811 need_space = count;
8813 ItemPosCount newPosition = ItemPosCount((INVENTORY_SLOT_BAG_0 << 8) | j, need_space);
8814 if(!newPosition.isContainedIn(dest))
8816 dest.push_back(newPosition);
8817 count -= need_space;
8819 if(count==0)
8820 return EQUIP_ERR_OK;
8824 return EQUIP_ERR_OK;
8827 uint8 Player::_CanStoreItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, uint32 entry, uint32 count, Item *pItem, bool swap, uint32* no_space_count ) const
8829 sLog.outDebug( "STORAGE: CanStoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, entry, count);
8831 ItemPrototype const *pProto = objmgr.GetItemPrototype(entry);
8832 if( !pProto )
8834 if(no_space_count)
8835 *no_space_count = count;
8836 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED :EQUIP_ERR_ITEM_NOT_FOUND;
8839 if(pItem && pItem->IsBindedNotWith(GetGUID()))
8841 if(no_space_count)
8842 *no_space_count = count;
8843 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
8846 // check count of items (skip for auto move for same player from bank)
8847 uint32 no_similar_count = 0; // can't store this amount similar items
8848 uint8 res = _CanTakeMoreSimilarItems(entry,count,pItem,&no_similar_count);
8849 if(res!=EQUIP_ERR_OK)
8851 if(count==no_similar_count)
8853 if(no_space_count)
8854 *no_space_count = no_similar_count;
8855 return res;
8857 count -= no_similar_count;
8860 // in specific slot
8861 if( bag != NULL_BAG && slot != NULL_SLOT )
8863 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
8864 if(res!=EQUIP_ERR_OK)
8866 if(no_space_count)
8867 *no_space_count = count + no_similar_count;
8868 return res;
8871 if(count==0)
8873 if(no_similar_count==0)
8874 return EQUIP_ERR_OK;
8876 if(no_space_count)
8877 *no_space_count = count + no_similar_count;
8878 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8882 // not specific slot or have space for partly store only in specific slot
8884 // in specific bag
8885 if( bag != NULL_BAG )
8887 // search stack in bag for merge to
8888 if( pProto->Stackable > 1 )
8890 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8892 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
8893 if(res!=EQUIP_ERR_OK)
8895 if(no_space_count)
8896 *no_space_count = count + no_similar_count;
8897 return res;
8900 if(count==0)
8902 if(no_similar_count==0)
8903 return EQUIP_ERR_OK;
8905 if(no_space_count)
8906 *no_space_count = count + no_similar_count;
8907 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8910 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
8911 if(res!=EQUIP_ERR_OK)
8913 if(no_space_count)
8914 *no_space_count = count + no_similar_count;
8915 return res;
8918 if(count==0)
8920 if(no_similar_count==0)
8921 return EQUIP_ERR_OK;
8923 if(no_space_count)
8924 *no_space_count = count + no_similar_count;
8925 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8928 else // equipped bag
8930 // we need check 2 time (specialized/non_specialized), use NULL_BAG to prevent skipping bag
8931 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
8932 if(res!=EQUIP_ERR_OK)
8933 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
8935 if(res!=EQUIP_ERR_OK)
8937 if(no_space_count)
8938 *no_space_count = count + no_similar_count;
8939 return res;
8942 if(count==0)
8944 if(no_similar_count==0)
8945 return EQUIP_ERR_OK;
8947 if(no_space_count)
8948 *no_space_count = count + no_similar_count;
8949 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8954 // search free slot in bag for place to
8955 if( bag == INVENTORY_SLOT_BAG_0 ) // inventory
8957 // search free slot - keyring case
8958 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
8960 uint32 keyringSize = GetMaxKeyringSize();
8961 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
8962 if(res!=EQUIP_ERR_OK)
8964 if(no_space_count)
8965 *no_space_count = count + no_similar_count;
8966 return res;
8969 if(count==0)
8971 if(no_similar_count==0)
8972 return EQUIP_ERR_OK;
8974 if(no_space_count)
8975 *no_space_count = count + no_similar_count;
8976 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
8979 else if(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
8981 res = _CanStoreItem_InInventorySlots(VANITYPET_SLOT_START,VANITYPET_SLOT_END,dest,pProto,count,false,pItem,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;
8999 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9001 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9002 if(res!=EQUIP_ERR_OK)
9004 if(no_space_count)
9005 *no_space_count = count + no_similar_count;
9006 return res;
9009 if(count==0)
9011 if(no_similar_count==0)
9012 return EQUIP_ERR_OK;
9014 if(no_space_count)
9015 *no_space_count = count + no_similar_count;
9016 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9019 else if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9021 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9022 if(res!=EQUIP_ERR_OK)
9024 if(no_space_count)
9025 *no_space_count = count + no_similar_count;
9026 return res;
9029 if(count==0)
9031 if(no_similar_count==0)
9032 return EQUIP_ERR_OK;
9034 if(no_space_count)
9035 *no_space_count = count + no_similar_count;
9036 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9040 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9041 if(res!=EQUIP_ERR_OK)
9043 if(no_space_count)
9044 *no_space_count = count + no_similar_count;
9045 return res;
9048 if(count==0)
9050 if(no_similar_count==0)
9051 return EQUIP_ERR_OK;
9053 if(no_space_count)
9054 *no_space_count = count + no_similar_count;
9055 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9058 else // equipped bag
9060 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9061 if(res!=EQUIP_ERR_OK)
9062 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9064 if(res!=EQUIP_ERR_OK)
9066 if(no_space_count)
9067 *no_space_count = count + no_similar_count;
9068 return res;
9071 if(count==0)
9073 if(no_similar_count==0)
9074 return EQUIP_ERR_OK;
9076 if(no_space_count)
9077 *no_space_count = count + no_similar_count;
9078 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9083 // not specific bag or have space for partly store only in specific bag
9085 // search stack for merge to
9086 if( pProto->Stackable > 1 )
9088 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,true,pItem,bag,slot);
9089 if(res!=EQUIP_ERR_OK)
9091 if(no_space_count)
9092 *no_space_count = count + no_similar_count;
9093 return res;
9096 if(count==0)
9098 if(no_similar_count==0)
9099 return EQUIP_ERR_OK;
9101 if(no_space_count)
9102 *no_space_count = count + no_similar_count;
9103 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9106 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,true,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 if( pProto->BagFamily )
9126 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9128 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9129 if(res!=EQUIP_ERR_OK)
9130 continue;
9132 if(count==0)
9134 if(no_similar_count==0)
9135 return EQUIP_ERR_OK;
9137 if(no_space_count)
9138 *no_space_count = count + no_similar_count;
9139 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9144 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9146 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9147 if(res!=EQUIP_ERR_OK)
9148 continue;
9150 if(count==0)
9152 if(no_similar_count==0)
9153 return EQUIP_ERR_OK;
9155 if(no_space_count)
9156 *no_space_count = count + no_similar_count;
9157 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9162 // search free slot - special bag case
9163 if( pProto->BagFamily )
9165 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9167 uint32 keyringSize = GetMaxKeyringSize();
9168 res = _CanStoreItem_InInventorySlots(KEYRING_SLOT_START,KEYRING_SLOT_START+keyringSize,dest,pProto,count,false,pItem,bag,slot);
9169 if(res!=EQUIP_ERR_OK)
9171 if(no_space_count)
9172 *no_space_count = count + no_similar_count;
9173 return res;
9176 if(count==0)
9178 if(no_similar_count==0)
9179 return EQUIP_ERR_OK;
9181 if(no_space_count)
9182 *no_space_count = count + no_similar_count;
9183 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9186 else if(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
9188 res = _CanStoreItem_InInventorySlots(VANITYPET_SLOT_START,VANITYPET_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9189 if(res!=EQUIP_ERR_OK)
9191 if(no_space_count)
9192 *no_space_count = count + no_similar_count;
9193 return res;
9196 if(count==0)
9198 if(no_similar_count==0)
9199 return EQUIP_ERR_OK;
9201 if(no_space_count)
9202 *no_space_count = count + no_similar_count;
9203 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9206 else if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9208 res = _CanStoreItem_InInventorySlots(CURRENCYTOKEN_SLOT_START,CURRENCYTOKEN_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9209 if(res!=EQUIP_ERR_OK)
9211 if(no_space_count)
9212 *no_space_count = count + no_similar_count;
9213 return res;
9216 if(count==0)
9218 if(no_similar_count==0)
9219 return EQUIP_ERR_OK;
9221 if(no_space_count)
9222 *no_space_count = count + no_similar_count;
9223 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9226 else if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9228 res = _CanStoreItem_InInventorySlots(QUESTBAG_SLOT_START,QUESTBAG_SLOT_END,dest,pProto,count,false,pItem,bag,slot);
9229 if(res!=EQUIP_ERR_OK)
9231 if(no_space_count)
9232 *no_space_count = count + no_similar_count;
9233 return res;
9236 if(count==0)
9238 if(no_similar_count==0)
9239 return EQUIP_ERR_OK;
9241 if(no_space_count)
9242 *no_space_count = count + no_similar_count;
9243 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9247 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9249 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9250 if(res!=EQUIP_ERR_OK)
9251 continue;
9253 if(count==0)
9255 if(no_similar_count==0)
9256 return EQUIP_ERR_OK;
9258 if(no_space_count)
9259 *no_space_count = count + no_similar_count;
9260 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9265 // search free slot
9266 res = _CanStoreItem_InInventorySlots(INVENTORY_SLOT_ITEM_START,INVENTORY_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9267 if(res!=EQUIP_ERR_OK)
9269 if(no_space_count)
9270 *no_space_count = count + no_similar_count;
9271 return res;
9274 if(count==0)
9276 if(no_similar_count==0)
9277 return EQUIP_ERR_OK;
9279 if(no_space_count)
9280 *no_space_count = count + no_similar_count;
9281 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9284 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9286 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
9287 if(res!=EQUIP_ERR_OK)
9288 continue;
9290 if(count==0)
9292 if(no_similar_count==0)
9293 return EQUIP_ERR_OK;
9295 if(no_space_count)
9296 *no_space_count = count + no_similar_count;
9297 return EQUIP_ERR_CANT_CARRY_MORE_OF_THIS;
9301 if(no_space_count)
9302 *no_space_count = count + no_similar_count;
9304 return EQUIP_ERR_INVENTORY_FULL;
9307 //////////////////////////////////////////////////////////////////////////
9308 uint8 Player::CanStoreItems( Item **pItems,int count) const
9310 Item *pItem2;
9312 // fill space table
9313 int inv_slot_items[INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START];
9314 int inv_bags[INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START][MAX_BAG_SIZE];
9315 int inv_keys[KEYRING_SLOT_END-KEYRING_SLOT_START];
9316 int inv_pets[VANITYPET_SLOT_END-VANITYPET_SLOT_START];
9317 int inv_tokens[CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START];
9318 int inv_quests[QUESTBAG_SLOT_END-QUESTBAG_SLOT_START];
9320 memset(inv_slot_items,0,sizeof(int)*(INVENTORY_SLOT_ITEM_END-INVENTORY_SLOT_ITEM_START));
9321 memset(inv_bags,0,sizeof(int)*(INVENTORY_SLOT_BAG_END-INVENTORY_SLOT_BAG_START)*MAX_BAG_SIZE);
9322 memset(inv_keys,0,sizeof(int)*(KEYRING_SLOT_END-KEYRING_SLOT_START));
9323 memset(inv_pets,0,sizeof(int)*(VANITYPET_SLOT_END-VANITYPET_SLOT_START));
9324 memset(inv_tokens,0,sizeof(int)*(CURRENCYTOKEN_SLOT_END-CURRENCYTOKEN_SLOT_START));
9325 memset(inv_quests,0,sizeof(int)*(QUESTBAG_SLOT_END-QUESTBAG_SLOT_START));
9327 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
9329 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9331 if (pItem2 && !pItem2->IsInTrade())
9333 inv_slot_items[i-INVENTORY_SLOT_ITEM_START] = pItem2->GetCount();
9337 for(int i = KEYRING_SLOT_START; i < KEYRING_SLOT_END; i++)
9339 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9341 if (pItem2 && !pItem2->IsInTrade())
9343 inv_keys[i-KEYRING_SLOT_START] = pItem2->GetCount();
9347 for(int i = VANITYPET_SLOT_START; i < VANITYPET_SLOT_END; i++)
9349 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9351 if (pItem2 && !pItem2->IsInTrade())
9353 inv_pets[i-VANITYPET_SLOT_START] = pItem2->GetCount();
9357 for(int i = CURRENCYTOKEN_SLOT_START; i < CURRENCYTOKEN_SLOT_END; i++)
9359 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9361 if (pItem2 && !pItem2->IsInTrade())
9363 inv_tokens[i-CURRENCYTOKEN_SLOT_START] = pItem2->GetCount();
9367 for(int i = QUESTBAG_SLOT_START; i < QUESTBAG_SLOT_END; i++)
9369 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
9371 if (pItem2 && !pItem2->IsInTrade())
9373 inv_quests[i-QUESTBAG_SLOT_START] = pItem2->GetCount();
9377 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
9379 if(Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
9381 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9383 pItem2 = GetItemByPos( i, j );
9384 if (pItem2 && !pItem2->IsInTrade())
9386 inv_bags[i-INVENTORY_SLOT_BAG_START][j] = pItem2->GetCount();
9392 // check free space for all items
9393 for (int k=0;k<count;k++)
9395 Item *pItem = pItems[k];
9397 // no item
9398 if (!pItem) continue;
9400 sLog.outDebug( "STORAGE: CanStoreItems %i. item = %u, count = %u", k+1, pItem->GetEntry(), pItem->GetCount());
9401 ItemPrototype const *pProto = pItem->GetProto();
9403 // strange item
9404 if( !pProto )
9405 return EQUIP_ERR_ITEM_NOT_FOUND;
9407 // item it 'bind'
9408 if(pItem->IsBindedNotWith(GetGUID()))
9409 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9411 Bag *pBag;
9412 ItemPrototype const *pBagProto;
9414 // item is 'one item only'
9415 uint8 res = CanTakeMoreSimilarItems(pItem);
9416 if(res != EQUIP_ERR_OK)
9417 return res;
9419 // search stack for merge to
9420 if( pProto->Stackable > 1 )
9422 bool b_found = false;
9424 for(int t = KEYRING_SLOT_START; t < KEYRING_SLOT_END; t++)
9426 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9427 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_keys[t-KEYRING_SLOT_START] + pItem->GetCount() <= pProto->Stackable )
9429 inv_keys[t-KEYRING_SLOT_START] += pItem->GetCount();
9430 b_found = true;
9431 break;
9434 if (b_found) continue;
9436 for(int t = VANITYPET_SLOT_START; t < VANITYPET_SLOT_END; t++)
9438 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9439 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_pets[t-VANITYPET_SLOT_START] + pItem->GetCount() <= pProto->Stackable )
9441 inv_pets[t-VANITYPET_SLOT_START] += pItem->GetCount();
9442 b_found = true;
9443 break;
9446 if (b_found) continue;
9448 for(int t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; t++)
9450 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9451 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_tokens[t-CURRENCYTOKEN_SLOT_START] + pItem->GetCount() <= pProto->Stackable )
9453 inv_tokens[t-CURRENCYTOKEN_SLOT_START] += pItem->GetCount();
9454 b_found = true;
9455 break;
9458 if (b_found) continue;
9460 for(int t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; t++)
9462 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9463 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_quests[t-QUESTBAG_SLOT_START] + pItem->GetCount() <= pProto->Stackable )
9465 inv_quests[t-QUESTBAG_SLOT_START] += pItem->GetCount();
9466 b_found = true;
9467 break;
9470 if (b_found) continue;
9472 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9474 pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9475 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_slot_items[t-INVENTORY_SLOT_ITEM_START] + pItem->GetCount() <= pProto->Stackable )
9477 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] += pItem->GetCount();
9478 b_found = true;
9479 break;
9482 if (b_found) continue;
9484 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9486 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9487 if( pBag )
9489 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9491 pItem2 = GetItemByPos( t, j );
9492 if( pItem2 && pItem2->GetEntry() == pItem->GetEntry() && inv_bags[t-INVENTORY_SLOT_BAG_START][j] + pItem->GetCount() <= pProto->Stackable )
9494 inv_bags[t-INVENTORY_SLOT_BAG_START][j] += pItem->GetCount();
9495 b_found = true;
9496 break;
9501 if (b_found) continue;
9504 // special bag case
9505 if( pProto->BagFamily )
9507 bool b_found = false;
9508 if(pProto->BagFamily & BAG_FAMILY_MASK_KEYS)
9510 uint32 keyringSize = GetMaxKeyringSize();
9511 for(uint32 t = KEYRING_SLOT_START; t < KEYRING_SLOT_START+keyringSize; ++t)
9513 if( inv_keys[t-KEYRING_SLOT_START] == 0 )
9515 inv_keys[t-KEYRING_SLOT_START] = 1;
9516 b_found = true;
9517 break;
9522 if (b_found) continue;
9524 if(pProto->BagFamily & BAG_FAMILY_MASK_VANITY_PETS)
9526 for(uint32 t = VANITYPET_SLOT_START; t < VANITYPET_SLOT_END; ++t)
9528 if( inv_pets[t-VANITYPET_SLOT_START] == 0 )
9530 inv_pets[t-VANITYPET_SLOT_START] = 1;
9531 b_found = true;
9532 break;
9537 if (b_found) continue;
9539 if(pProto->BagFamily & BAG_FAMILY_MASK_CURRENCY_TOKENS)
9541 for(uint32 t = CURRENCYTOKEN_SLOT_START; t < CURRENCYTOKEN_SLOT_END; ++t)
9543 if( inv_tokens[t-CURRENCYTOKEN_SLOT_START] == 0 )
9545 inv_tokens[t-CURRENCYTOKEN_SLOT_START] = 1;
9546 b_found = true;
9547 break;
9552 if (b_found) continue;
9554 if(pProto->BagFamily & BAG_FAMILY_MASK_QUEST_ITEMS)
9556 for(uint32 t = QUESTBAG_SLOT_START; t < QUESTBAG_SLOT_END; ++t)
9558 if( inv_quests[t-QUESTBAG_SLOT_START] == 0 )
9560 inv_quests[t-QUESTBAG_SLOT_START] = 1;
9561 b_found = true;
9562 break;
9567 if (b_found) continue;
9569 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9571 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9572 if( pBag )
9574 pBagProto = pBag->GetProto();
9576 // not plain container check
9577 if( pBagProto && (pBagProto->Class != ITEM_CLASS_CONTAINER || pBagProto->SubClass != ITEM_SUBCLASS_CONTAINER) &&
9578 ItemCanGoIntoBag(pProto,pBagProto) )
9580 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9582 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9584 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9585 b_found = true;
9586 break;
9592 if (b_found) continue;
9595 // search free slot
9596 bool b_found = false;
9597 for(int t = INVENTORY_SLOT_ITEM_START; t < INVENTORY_SLOT_ITEM_END; t++)
9599 if( inv_slot_items[t-INVENTORY_SLOT_ITEM_START] == 0 )
9601 inv_slot_items[t-INVENTORY_SLOT_ITEM_START] = 1;
9602 b_found = true;
9603 break;
9606 if (b_found) continue;
9608 // search free slot in bags
9609 for(int t = INVENTORY_SLOT_BAG_START; !b_found && t < INVENTORY_SLOT_BAG_END; t++)
9611 pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, t );
9612 if( pBag )
9614 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
9616 if( inv_bags[t-INVENTORY_SLOT_BAG_START][j] == 0 )
9618 inv_bags[t-INVENTORY_SLOT_BAG_START][j] = 1;
9619 b_found = true;
9620 break;
9626 // no free slot found?
9627 if (!b_found)
9628 return EQUIP_ERR_INVENTORY_FULL;
9631 return EQUIP_ERR_OK;
9634 //////////////////////////////////////////////////////////////////////////
9635 uint8 Player::CanEquipNewItem( uint8 slot, uint16 &dest, uint32 item, uint32 count, bool swap ) const
9637 dest = 0;
9638 Item *pItem = Item::CreateItem( item, count, this );
9639 if( pItem )
9641 uint8 result = CanEquipItem(slot, dest, pItem, swap );
9642 delete pItem;
9643 return result;
9646 return EQUIP_ERR_ITEM_NOT_FOUND;
9649 uint8 Player::CanEquipItem( uint8 slot, uint16 &dest, Item *pItem, bool swap, bool not_loading ) const
9651 dest = 0;
9652 if( pItem )
9654 sLog.outDebug( "STORAGE: CanEquipItem slot = %u, item = %u, count = %u", slot, pItem->GetEntry(), pItem->GetCount());
9655 ItemPrototype const *pProto = pItem->GetProto();
9656 if( pProto )
9658 // May be here should be more stronger checks; STUNNED checked
9659 // ROOT, CONFUSED, DISTRACTED, FLEEING this needs to be checked.
9660 if (not_loading && hasUnitState(UNIT_STAT_STUNNED))
9661 return EQUIP_ERR_YOU_ARE_STUNNED;
9663 if(pItem->IsBindedNotWith(GetGUID()))
9664 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9666 // check count of items (skip for auto move for same player from bank)
9667 uint8 res = CanTakeMoreSimilarItems(pItem);
9668 if(res != EQUIP_ERR_OK)
9669 return res;
9671 // do not allow equipping gear except weapons, offhands, projectiles, relics in
9672 // - combat
9673 // - in-progress arenas
9674 if( !pProto->CanChangeEquipStateInCombat() )
9676 if( isInCombat() )
9677 return EQUIP_ERR_NOT_IN_COMBAT;
9679 if(BattleGround* bg = GetBattleGround())
9680 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9681 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9684 if(isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer != 0)
9685 return EQUIP_ERR_CANT_DO_RIGHT_NOW; // maybe exist better err
9687 if(IsNonMeleeSpellCasted(false))
9688 return EQUIP_ERR_CANT_DO_RIGHT_NOW;
9690 uint8 eslot = FindEquipSlot( pProto, slot, swap );
9691 if( eslot == NULL_SLOT )
9692 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9694 uint8 msg = CanUseItem( pItem , not_loading );
9695 if( msg != EQUIP_ERR_OK )
9696 return msg;
9697 if( !swap && GetItemByPos( INVENTORY_SLOT_BAG_0, eslot ) )
9698 return EQUIP_ERR_NO_EQUIPMENT_SLOT_AVAILABLE;
9700 // check unique-equipped on item
9701 if (pProto->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED)
9703 // there is an equip limit on this item
9704 Item* tItem = GetItemOrItemWithGemEquipped(pProto->ItemId);
9705 if (tItem && (!swap || tItem->GetSlot() != eslot ) )
9706 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
9709 // check unique-equipped on gems
9710 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
9712 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
9713 if(!enchant_id)
9714 continue;
9715 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
9716 if(!enchantEntry)
9717 continue;
9719 ItemPrototype const* pGem = objmgr.GetItemPrototype(enchantEntry->GemID);
9720 if(pGem && (pGem->Flags & ITEM_FLAGS_UNIQUE_EQUIPPED))
9722 Item* tItem = GetItemOrItemWithGemEquipped(enchantEntry->GemID);
9723 if(tItem && (!swap || tItem->GetSlot() != eslot ))
9724 return EQUIP_ERR_ITEM_UNIQUE_EQUIPABLE;
9728 // check unique-equipped special item classes
9729 if (pProto->Class == ITEM_CLASS_QUIVER)
9731 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i)
9733 if( Item* pBag = GetItemByPos( INVENTORY_SLOT_BAG_0, i ) )
9735 if( ItemPrototype const* pBagProto = pBag->GetProto() )
9737 if( pBagProto->Class==pProto->Class && pBagProto->SubClass==pProto->SubClass &&
9738 (!swap || pBag->GetSlot() != eslot ) )
9740 if(pBagProto->SubClass == ITEM_SUBCLASS_AMMO_POUCH)
9741 return EQUIP_ERR_CAN_EQUIP_ONLY1_AMMOPOUCH;
9742 else
9743 return EQUIP_ERR_CAN_EQUIP_ONLY1_QUIVER;
9750 uint32 type = pProto->InventoryType;
9752 if(eslot == EQUIPMENT_SLOT_OFFHAND)
9754 if( type == INVTYPE_WEAPON || type == INVTYPE_WEAPONOFFHAND )
9756 if(!CanDualWield())
9757 return EQUIP_ERR_CANT_DUAL_WIELD;
9760 Item *mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );
9761 if(mainItem)
9763 if(mainItem->GetProto()->InventoryType == INVTYPE_2HWEAPON)
9764 return EQUIP_ERR_CANT_EQUIP_WITH_TWOHANDED;
9768 // equip two-hand weapon case (with possible unequip 2 items)
9769 if( type == INVTYPE_2HWEAPON )
9771 if(eslot != EQUIPMENT_SLOT_MAINHAND)
9772 return EQUIP_ERR_ITEM_CANT_BE_EQUIPPED;
9774 // offhand item must can be stored in inventory for offhand item and it also must be unequipped
9775 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
9776 ItemPosCountVec off_dest;
9777 if( offItem && (!not_loading ||
9778 CanUnequipItem(uint16(INVENTORY_SLOT_BAG_0) << 8 | EQUIPMENT_SLOT_OFFHAND,false) != EQUIP_ERR_OK ||
9779 CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false ) != EQUIP_ERR_OK ) )
9780 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_INVENTORY_FULL;
9782 dest = ((INVENTORY_SLOT_BAG_0 << 8) | eslot);
9783 return EQUIP_ERR_OK;
9786 if( !swap )
9787 return EQUIP_ERR_ITEM_NOT_FOUND;
9788 else
9789 return EQUIP_ERR_ITEMS_CANT_BE_SWAPPED;
9792 uint8 Player::CanUnequipItem( uint16 pos, bool swap ) const
9794 // Applied only to equipped items and bank bags
9795 if(!IsEquipmentPos(pos) && !IsBagPos(pos))
9796 return EQUIP_ERR_OK;
9798 Item* pItem = GetItemByPos(pos);
9800 // Applied only to existed equipped item
9801 if( !pItem )
9802 return EQUIP_ERR_OK;
9804 sLog.outDebug( "STORAGE: CanUnequipItem slot = %u, item = %u, count = %u", pos, pItem->GetEntry(), pItem->GetCount());
9806 ItemPrototype const *pProto = pItem->GetProto();
9807 if( !pProto )
9808 return EQUIP_ERR_ITEM_NOT_FOUND;
9810 // do not allow unequipping gear except weapons, offhands, projectiles, relics in
9811 // - combat
9812 // - in-progress arenas
9813 if( !pProto->CanChangeEquipStateInCombat() )
9815 if( isInCombat() )
9816 return EQUIP_ERR_NOT_IN_COMBAT;
9818 if(BattleGround* bg = GetBattleGround())
9819 if( bg->isArena() && bg->GetStatus() == STATUS_IN_PROGRESS )
9820 return EQUIP_ERR_NOT_DURING_ARENA_MATCH;
9823 if(!swap && pItem->IsBag() && !((Bag*)pItem)->IsEmpty())
9824 return EQUIP_ERR_CAN_ONLY_DO_WITH_EMPTY_BAGS;
9826 return EQUIP_ERR_OK;
9829 uint8 Player::CanBankItem( uint8 bag, uint8 slot, ItemPosCountVec &dest, Item *pItem, bool swap, bool not_loading ) const
9831 if( !pItem )
9832 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9834 uint32 count = pItem->GetCount();
9836 sLog.outDebug( "STORAGE: CanBankItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), pItem->GetCount());
9837 ItemPrototype const *pProto = pItem->GetProto();
9838 if( !pProto )
9839 return swap ? EQUIP_ERR_ITEMS_CANT_BE_SWAPPED : EQUIP_ERR_ITEM_NOT_FOUND;
9841 if( pItem->IsBindedNotWith(GetGUID()) )
9842 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
9844 // check count of items (skip for auto move for same player from bank)
9845 uint8 res = CanTakeMoreSimilarItems(pItem);
9846 if(res != EQUIP_ERR_OK)
9847 return res;
9849 // in specific slot
9850 if( bag != NULL_BAG && slot != NULL_SLOT )
9852 if( pProto->InventoryType == INVTYPE_BAG )
9854 Bag *pBag = (Bag*)pItem;
9855 if( pBag )
9857 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9859 if( !HasBankBagSlot( slot ) )
9860 return EQUIP_ERR_MUST_PURCHASE_THAT_BAG_SLOT;
9861 if( uint8 cantuse = CanUseItem( pItem, not_loading ) != EQUIP_ERR_OK )
9862 return cantuse;
9864 else
9866 if( !pBag->IsEmpty() )
9867 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9871 else
9873 if( slot >= BANK_SLOT_BAG_START && slot < BANK_SLOT_BAG_END )
9874 return EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT;
9877 res = _CanStoreItem_InSpecificSlot(bag,slot,dest,pProto,count,swap,pItem);
9878 if(res!=EQUIP_ERR_OK)
9879 return res;
9881 if(count==0)
9882 return EQUIP_ERR_OK;
9885 // not specific slot or have space for partly store only in specific slot
9887 // in specific bag
9888 if( bag != NULL_BAG )
9890 if( pProto->InventoryType == INVTYPE_BAG )
9892 Bag *pBag = (Bag*)pItem;
9893 if( pBag && !pBag->IsEmpty() )
9894 return EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG;
9897 // search stack in bag for merge to
9898 if( pProto->Stackable > 1 )
9900 if( bag == INVENTORY_SLOT_BAG_0 )
9902 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9903 if(res!=EQUIP_ERR_OK)
9904 return res;
9906 if(count==0)
9907 return EQUIP_ERR_OK;
9909 else
9911 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,false,pItem,NULL_BAG,slot);
9912 if(res!=EQUIP_ERR_OK)
9913 res = _CanStoreItem_InBag(bag,dest,pProto,count,true,true,pItem,NULL_BAG,slot);
9915 if(res!=EQUIP_ERR_OK)
9916 return res;
9918 if(count==0)
9919 return EQUIP_ERR_OK;
9923 // search free slot in bag
9924 if( bag == INVENTORY_SLOT_BAG_0 )
9926 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
9927 if(res!=EQUIP_ERR_OK)
9928 return res;
9930 if(count==0)
9931 return EQUIP_ERR_OK;
9933 else
9935 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,false,pItem,NULL_BAG,slot);
9936 if(res!=EQUIP_ERR_OK)
9937 res = _CanStoreItem_InBag(bag,dest,pProto,count,false,true,pItem,NULL_BAG,slot);
9939 if(res!=EQUIP_ERR_OK)
9940 return res;
9942 if(count==0)
9943 return EQUIP_ERR_OK;
9947 // not specific bag or have space for partly store only in specific bag
9949 // search stack for merge to
9950 if( pProto->Stackable > 1 )
9952 // in slots
9953 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,true,pItem,bag,slot);
9954 if(res!=EQUIP_ERR_OK)
9955 return res;
9957 if(count==0)
9958 return EQUIP_ERR_OK;
9960 // in special bags
9961 if( pProto->BagFamily )
9963 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9965 res = _CanStoreItem_InBag(i,dest,pProto,count,true,false,pItem,bag,slot);
9966 if(res!=EQUIP_ERR_OK)
9967 continue;
9969 if(count==0)
9970 return EQUIP_ERR_OK;
9974 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9976 res = _CanStoreItem_InBag(i,dest,pProto,count,true,true,pItem,bag,slot);
9977 if(res!=EQUIP_ERR_OK)
9978 continue;
9980 if(count==0)
9981 return EQUIP_ERR_OK;
9985 // search free place in special bag
9986 if( pProto->BagFamily )
9988 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
9990 res = _CanStoreItem_InBag(i,dest,pProto,count,false,false,pItem,bag,slot);
9991 if(res!=EQUIP_ERR_OK)
9992 continue;
9994 if(count==0)
9995 return EQUIP_ERR_OK;
9999 // search free space
10000 res = _CanStoreItem_InInventorySlots(BANK_SLOT_ITEM_START,BANK_SLOT_ITEM_END,dest,pProto,count,false,pItem,bag,slot);
10001 if(res!=EQUIP_ERR_OK)
10002 return res;
10004 if(count==0)
10005 return EQUIP_ERR_OK;
10007 for(int i = BANK_SLOT_BAG_START; i < BANK_SLOT_BAG_END; i++)
10009 res = _CanStoreItem_InBag(i,dest,pProto,count,false,true,pItem,bag,slot);
10010 if(res!=EQUIP_ERR_OK)
10011 continue;
10013 if(count==0)
10014 return EQUIP_ERR_OK;
10016 return EQUIP_ERR_BANK_FULL;
10019 uint8 Player::CanUseItem( Item *pItem, bool not_loading ) const
10021 if( pItem )
10023 sLog.outDebug( "STORAGE: CanUseItem item = %u", pItem->GetEntry());
10024 if( !isAlive() && not_loading )
10025 return EQUIP_ERR_YOU_ARE_DEAD;
10026 //if( isStunned() )
10027 // return EQUIP_ERR_YOU_ARE_STUNNED;
10028 ItemPrototype const *pProto = pItem->GetProto();
10029 if( pProto )
10031 if( pItem->IsBindedNotWith(GetGUID()) )
10032 return EQUIP_ERR_DONT_OWN_THAT_ITEM;
10033 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10034 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10035 if( pItem->GetSkill() != 0 )
10037 if( GetSkillValue( pItem->GetSkill() ) == 0 )
10038 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10040 if( pProto->RequiredSkill != 0 )
10042 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10043 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10044 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10045 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10047 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10048 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10049 if( pProto->RequiredReputationFaction && uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank )
10050 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10051 if( getLevel() < pProto->RequiredLevel )
10052 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10053 return EQUIP_ERR_OK;
10056 return EQUIP_ERR_ITEM_NOT_FOUND;
10059 bool Player::CanUseItem( ItemPrototype const *pProto )
10061 // Used by group, function NeedBeforeGreed, to know if a prototype can be used by a player
10063 if( pProto )
10065 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10066 return false;
10067 if( pProto->RequiredSkill != 0 )
10069 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10070 return false;
10071 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10072 return false;
10074 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10075 return false;
10076 if( getLevel() < pProto->RequiredLevel )
10077 return false;
10078 return true;
10080 return false;
10083 uint8 Player::CanUseAmmo( uint32 item ) const
10085 sLog.outDebug( "STORAGE: CanUseAmmo item = %u", item);
10086 if( !isAlive() )
10087 return EQUIP_ERR_YOU_ARE_DEAD;
10088 //if( isStunned() )
10089 // return EQUIP_ERR_YOU_ARE_STUNNED;
10090 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
10091 if( pProto )
10093 if( pProto->InventoryType!= INVTYPE_AMMO )
10094 return EQUIP_ERR_ONLY_AMMO_CAN_GO_HERE;
10095 if( (pProto->AllowableClass & getClassMask()) == 0 || (pProto->AllowableRace & getRaceMask()) == 0 )
10096 return EQUIP_ERR_YOU_CAN_NEVER_USE_THAT_ITEM;
10097 if( pProto->RequiredSkill != 0 )
10099 if( GetSkillValue( pProto->RequiredSkill ) == 0 )
10100 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10101 else if( GetSkillValue( pProto->RequiredSkill ) < pProto->RequiredSkillRank )
10102 return EQUIP_ERR_ERR_CANT_EQUIP_SKILL;
10104 if( pProto->RequiredSpell != 0 && !HasSpell( pProto->RequiredSpell ) )
10105 return EQUIP_ERR_NO_REQUIRED_PROFICIENCY;
10106 /*if( GetReputation() < pProto->RequiredReputation )
10107 return EQUIP_ERR_CANT_EQUIP_REPUTATION;
10109 if( getLevel() < pProto->RequiredLevel )
10110 return EQUIP_ERR_CANT_EQUIP_LEVEL_I;
10112 // Requires No Ammo
10113 if(GetDummyAura(46699))
10114 return EQUIP_ERR_BAG_FULL6;
10116 return EQUIP_ERR_OK;
10118 return EQUIP_ERR_ITEM_NOT_FOUND;
10121 void Player::SetAmmo( uint32 item )
10123 if(!item)
10124 return;
10126 // already set
10127 if( GetUInt32Value(PLAYER_AMMO_ID) == item )
10128 return;
10130 // check ammo
10131 if(item)
10133 uint8 msg = CanUseAmmo( item );
10134 if( msg != EQUIP_ERR_OK )
10136 SendEquipError( msg, NULL, NULL );
10137 return;
10141 SetUInt32Value(PLAYER_AMMO_ID, item);
10143 _ApplyAmmoBonuses();
10146 void Player::RemoveAmmo()
10148 SetUInt32Value(PLAYER_AMMO_ID, 0);
10150 m_ammoDPS = 0.0f;
10152 if(CanModifyStats())
10153 UpdateDamagePhysical(RANGED_ATTACK);
10156 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10157 Item* Player::StoreNewItem( ItemPosCountVec const& dest, uint32 item, bool update,int32 randomPropertyId )
10159 uint32 count = 0;
10160 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); ++itr)
10161 count += itr->count;
10163 Item *pItem = Item::CreateItem( item, count, this );
10164 if( pItem )
10166 ItemAddedQuestCheck( item, count );
10167 if(randomPropertyId)
10168 pItem->SetItemRandomProperties(randomPropertyId);
10169 pItem = StoreItem( dest, pItem, update );
10171 return pItem;
10174 Item* Player::StoreItem( ItemPosCountVec const& dest, Item* pItem, bool update )
10176 if( !pItem )
10177 return NULL;
10179 Item* lastItem = pItem;
10181 for(ItemPosCountVec::const_iterator itr = dest.begin(); itr != dest.end(); )
10183 uint16 pos = itr->pos;
10184 uint32 count = itr->count;
10186 ++itr;
10188 if(itr == dest.end())
10190 lastItem = _StoreItem(pos,pItem,count,false,update);
10191 break;
10194 lastItem = _StoreItem(pos,pItem,count,true,update);
10197 return lastItem;
10200 // Return stored item (if stored to stack, it can diff. from pItem). And pItem ca be deleted in this case.
10201 Item* Player::_StoreItem( uint16 pos, Item *pItem, uint32 count, bool clone, bool update )
10203 if( !pItem )
10204 return NULL;
10206 uint8 bag = pos >> 8;
10207 uint8 slot = pos & 255;
10209 sLog.outDebug( "STORAGE: StoreItem bag = %u, slot = %u, item = %u, count = %u", bag, slot, pItem->GetEntry(), count);
10211 Item *pItem2 = GetItemByPos( bag, slot );
10213 if( !pItem2 )
10215 if(clone)
10216 pItem = pItem->CloneItem(count,this);
10217 else
10218 pItem->SetCount(count);
10220 if(!pItem)
10221 return NULL;
10223 if( pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10224 pItem->GetProto()->Bonding == BIND_QUEST_ITEM ||
10225 pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
10226 pItem->SetBinding( true );
10228 if( bag == INVENTORY_SLOT_BAG_0 )
10230 m_items[slot] = pItem;
10231 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10232 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10233 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10235 pItem->SetSlot( slot );
10236 pItem->SetContainer( NULL );
10238 if( IsInWorld() && update )
10240 pItem->AddToWorld();
10241 pItem->SendUpdateToPlayer( this );
10244 pItem->SetState(ITEM_CHANGED, this);
10246 else
10248 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10249 if( pBag )
10251 pBag->StoreItem( slot, pItem, update );
10252 if( IsInWorld() && update )
10254 pItem->AddToWorld();
10255 pItem->SendUpdateToPlayer( this );
10257 pItem->SetState(ITEM_CHANGED, this);
10258 pBag->SetState(ITEM_CHANGED, this);
10262 AddEnchantmentDurations(pItem);
10263 AddItemDurations(pItem);
10265 return pItem;
10267 else
10269 if( pItem2->GetProto()->Bonding == BIND_WHEN_PICKED_UP ||
10270 pItem2->GetProto()->Bonding == BIND_QUEST_ITEM ||
10271 pItem2->GetProto()->Bonding == BIND_WHEN_EQUIPED && IsBagPos(pos) )
10272 pItem2->SetBinding( true );
10274 pItem2->SetCount( pItem2->GetCount() + count );
10275 if( IsInWorld() && update )
10276 pItem2->SendUpdateToPlayer( this );
10278 if(!clone)
10280 // delete item (it not in any slot currently)
10281 if( IsInWorld() && update )
10283 pItem->RemoveFromWorld();
10284 pItem->DestroyForPlayer( this );
10287 RemoveEnchantmentDurations(pItem);
10288 RemoveItemDurations(pItem);
10290 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10291 pItem->SetState(ITEM_REMOVED, this);
10293 // AddItemDurations(pItem2); - pItem2 already have duration listed for player
10294 AddEnchantmentDurations(pItem2);
10296 pItem2->SetState(ITEM_CHANGED, this);
10298 return pItem2;
10302 Item* Player::EquipNewItem( uint16 pos, uint32 item, uint32 count, bool update )
10304 Item *pItem = Item::CreateItem( item, count, this );
10305 if( pItem )
10307 ItemAddedQuestCheck( item, count );
10308 Item * retItem = EquipItem( pos, pItem, update );
10310 return retItem;
10312 return NULL;
10315 Item* Player::EquipItem( uint16 pos, Item *pItem, bool update )
10317 if( pItem )
10319 AddEnchantmentDurations(pItem);
10320 AddItemDurations(pItem);
10322 uint8 bag = pos >> 8;
10323 uint8 slot = pos & 255;
10325 Item *pItem2 = GetItemByPos( bag, slot );
10327 if( !pItem2 )
10329 VisualizeItem( slot, pItem);
10331 if(isAlive())
10333 ItemPrototype const *pProto = pItem->GetProto();
10335 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10336 if(pProto && pProto->ItemSet)
10337 AddItemsSetItem(this,pItem);
10339 _ApplyItemMods(pItem, slot, true);
10341 if(pProto && isInCombat()&& pProto->Class == ITEM_CLASS_WEAPON && m_weaponChangeTimer == 0)
10343 uint32 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_5s;
10345 if (getClass() == CLASS_ROGUE)
10346 cooldownSpell = SPELL_ID_WEAPON_SWITCH_COOLDOWN_1_0s;
10348 SpellEntry const* spellProto = sSpellStore.LookupEntry(cooldownSpell);
10350 if (!spellProto)
10351 sLog.outError("Weapon switch cooldown spell %u couldn't be found in Spell.dbc", cooldownSpell);
10352 else
10354 m_weaponChangeTimer = spellProto->StartRecoveryTime;
10356 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4);
10357 data << uint64(GetGUID());
10358 data << uint8(1);
10359 data << uint32(cooldownSpell);
10360 data << uint32(0);
10361 GetSession()->SendPacket(&data);
10366 if( IsInWorld() && update )
10368 pItem->AddToWorld();
10369 pItem->SendUpdateToPlayer( this );
10372 ApplyEquipCooldown(pItem);
10374 if( slot == EQUIPMENT_SLOT_MAINHAND )
10375 UpdateExpertise(BASE_ATTACK);
10376 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10377 UpdateExpertise(OFF_ATTACK);
10379 else
10381 pItem2->SetCount( pItem2->GetCount() + pItem->GetCount() );
10382 if( IsInWorld() && update )
10383 pItem2->SendUpdateToPlayer( this );
10385 // delete item (it not in any slot currently)
10386 //pItem->DeleteFromDB();
10387 if( IsInWorld() && update )
10389 pItem->RemoveFromWorld();
10390 pItem->DestroyForPlayer( this );
10393 RemoveEnchantmentDurations(pItem);
10394 RemoveItemDurations(pItem);
10396 pItem->SetOwnerGUID(GetGUID()); // prevent error at next SetState in case trade/mail/buy from vendor
10397 pItem->SetState(ITEM_REMOVED, this);
10398 pItem2->SetState(ITEM_CHANGED, this);
10400 ApplyEquipCooldown(pItem2);
10402 return pItem2;
10406 return pItem;
10409 void Player::QuickEquipItem( uint16 pos, Item *pItem)
10411 if( pItem )
10413 AddEnchantmentDurations(pItem);
10414 AddItemDurations(pItem);
10416 uint8 slot = pos & 255;
10417 VisualizeItem( slot, pItem);
10419 if( IsInWorld() )
10421 pItem->AddToWorld();
10422 pItem->SendUpdateToPlayer( this );
10427 void Player::SetVisibleItemSlot(uint8 slot, Item *pItem)
10429 // PLAYER_VISIBLE_ITEM_i_CREATOR // Size: 2
10430 // PLAYER_VISIBLE_ITEM_i_0 // Size: 12
10431 // entry // Size: 1
10432 // inspected enchantments // Size: 6
10433 // ? // Size: 5
10434 // PLAYER_VISIBLE_ITEM_i_PROPERTIES // Size: 1 (property,suffix factor)
10435 // PLAYER_VISIBLE_ITEM_i_PAD // Size: 1
10436 // // = 16
10438 if(pItem)
10440 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetUInt64Value(ITEM_FIELD_CREATOR));
10442 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10443 SetUInt32Value(VisibleBase + 0, pItem->GetEntry());
10445 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10446 SetUInt32Value(VisibleBase + 1 + i, pItem->GetEnchantmentId(EnchantmentSlot(i)));
10448 // Use SetInt16Value to prevent set high part to FFFF for negative value
10449 SetInt16Value( PLAYER_VISIBLE_ITEM_1_PROPERTIES + (slot * MAX_VISIBLE_ITEM_OFFSET), 0, pItem->GetItemRandomPropertyId());
10450 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), pItem->GetItemSuffixFactor());
10452 else
10454 SetUInt64Value(PLAYER_VISIBLE_ITEM_1_CREATOR + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10456 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (slot * MAX_VISIBLE_ITEM_OFFSET);
10457 SetUInt32Value(VisibleBase + 0, 0);
10459 for(int i = 0; i < MAX_INSPECTED_ENCHANTMENT_SLOT; ++i)
10460 SetUInt32Value(VisibleBase + 1 + i, 0);
10462 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 0 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10463 SetUInt32Value(PLAYER_VISIBLE_ITEM_1_PROPERTIES + 1 + (slot * MAX_VISIBLE_ITEM_OFFSET), 0);
10467 void Player::VisualizeItem( uint8 slot, Item *pItem)
10469 if(!pItem)
10470 return;
10472 // check also BIND_WHEN_PICKED_UP and BIND_QUEST_ITEM for .additem or .additemset case by GM (not binded at adding to inventory)
10473 if( pItem->GetProto()->Bonding == BIND_WHEN_EQUIPED || pItem->GetProto()->Bonding == BIND_WHEN_PICKED_UP || pItem->GetProto()->Bonding == BIND_QUEST_ITEM )
10474 pItem->SetBinding( true );
10476 sLog.outDebug( "STORAGE: EquipItem slot = %u, item = %u", slot, pItem->GetEntry());
10478 m_items[slot] = pItem;
10479 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), pItem->GetGUID() );
10480 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, GetGUID() );
10481 pItem->SetUInt64Value( ITEM_FIELD_OWNER, GetGUID() );
10482 pItem->SetSlot( slot );
10483 pItem->SetContainer( NULL );
10485 if( slot < EQUIPMENT_SLOT_END )
10486 SetVisibleItemSlot(slot,pItem);
10488 pItem->SetState(ITEM_CHANGED, this);
10491 void Player::RemoveItem( uint8 bag, uint8 slot, bool update )
10493 // note: removeitem does not actually change the item
10494 // it only takes the item out of storage temporarily
10495 // note2: if removeitem is to be used for delinking
10496 // the item must be removed from the player's updatequeue
10498 Item *pItem = GetItemByPos( bag, slot );
10499 if( pItem )
10501 sLog.outDebug( "STORAGE: RemoveItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10503 RemoveEnchantmentDurations(pItem);
10504 RemoveItemDurations(pItem);
10506 if( bag == INVENTORY_SLOT_BAG_0 )
10508 if ( slot < INVENTORY_SLOT_BAG_END )
10510 ItemPrototype const *pProto = pItem->GetProto();
10511 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10513 if(pProto && pProto->ItemSet)
10514 RemoveItemsSetItem(this,pProto);
10516 _ApplyItemMods(pItem, slot, false);
10518 // remove item dependent auras and casts (only weapon and armor slots)
10519 if(slot < EQUIPMENT_SLOT_END)
10520 RemoveItemDependentAurasAndCasts(pItem);
10522 // remove held enchantments
10523 if ( slot == EQUIPMENT_SLOT_MAINHAND )
10525 if (pItem->GetItemSuffixFactor())
10527 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_3);
10528 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_4);
10530 else
10532 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_0);
10533 pItem->ClearEnchantment(PROP_ENCHANTMENT_SLOT_1);
10538 m_items[slot] = NULL;
10539 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10541 if ( slot < EQUIPMENT_SLOT_END )
10542 SetVisibleItemSlot(slot,NULL);
10544 else
10546 Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag );
10547 if( pBag )
10548 pBag->RemoveItem(slot, update);
10550 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10551 // pItem->SetUInt64Value( ITEM_FIELD_OWNER, 0 ); not clear owner at remove (it will be set at store). This used in mail and auction code
10552 pItem->SetSlot( NULL_SLOT );
10553 if( IsInWorld() && update )
10554 pItem->SendUpdateToPlayer( this );
10556 if( slot == EQUIPMENT_SLOT_MAINHAND )
10557 UpdateExpertise(BASE_ATTACK);
10558 else if( slot == EQUIPMENT_SLOT_OFFHAND )
10559 UpdateExpertise(OFF_ATTACK);
10563 // Common operation need to remove item from inventory without delete in trade, auction, guild bank, mail....
10564 void Player::MoveItemFromInventory(uint8 bag, uint8 slot, bool update)
10566 if(Item* it = GetItemByPos(bag,slot))
10568 ItemRemovedQuestCheck(it->GetEntry(),it->GetCount());
10569 RemoveItem( bag,slot,update);
10570 it->RemoveFromUpdateQueueOf(this);
10571 if(it->IsInWorld())
10573 it->RemoveFromWorld();
10574 it->DestroyForPlayer( this );
10579 // Common operation need to add item from inventory without delete in trade, guild bank, mail....
10580 void Player::MoveItemToInventory(ItemPosCountVec const& dest, Item* pItem, bool update, bool in_characterInventoryDB)
10582 // update quest counters
10583 ItemAddedQuestCheck(pItem->GetEntry(),pItem->GetCount());
10585 // store item
10586 Item* pLastItem = StoreItem( dest, pItem, update);
10588 // only set if not merged to existed stack (pItem can be deleted already but we can compare pointers any way)
10589 if(pLastItem==pItem)
10591 // update owner for last item (this can be original item with wrong owner
10592 if(pLastItem->GetOwnerGUID() != GetGUID())
10593 pLastItem->SetOwnerGUID(GetGUID());
10595 // if this original item then it need create record in inventory
10596 // in case trade we already have item in other player inventory
10597 pLastItem->SetState(in_characterInventoryDB ? ITEM_CHANGED : ITEM_NEW, this);
10601 void Player::DestroyItem( uint8 bag, uint8 slot, bool update )
10603 Item *pItem = GetItemByPos( bag, slot );
10604 if( pItem )
10606 sLog.outDebug( "STORAGE: DestroyItem bag = %u, slot = %u, item = %u", bag, slot, pItem->GetEntry());
10608 // start from destroy contained items (only equipped bag can have its)
10609 if (pItem->IsBag() && pItem->IsEquipped()) // this also prevent infinity loop if empty bag stored in bag==slot
10611 for (int i = 0; i < MAX_BAG_SIZE; i++)
10612 DestroyItem(slot,i,update);
10615 if(pItem->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_WRAPPED))
10616 CharacterDatabase.PExecute("DELETE FROM character_gifts WHERE item_guid = '%u'", pItem->GetGUIDLow());
10618 RemoveEnchantmentDurations(pItem);
10619 RemoveItemDurations(pItem);
10621 ItemRemovedQuestCheck( pItem->GetEntry(), pItem->GetCount() );
10623 if( bag == INVENTORY_SLOT_BAG_0 )
10625 SetUInt64Value((uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot*2)), 0);
10627 // equipment and equipped bags can have applied bonuses
10628 if ( slot < INVENTORY_SLOT_BAG_END )
10630 ItemPrototype const *pProto = pItem->GetProto();
10632 // item set bonuses applied only at equip and removed at unequip, and still active for broken items
10633 if(pProto && pProto->ItemSet)
10634 RemoveItemsSetItem(this,pProto);
10636 _ApplyItemMods(pItem, slot, false);
10639 if ( slot < EQUIPMENT_SLOT_END )
10641 // remove item dependent auras and casts (only weapon and armor slots)
10642 RemoveItemDependentAurasAndCasts(pItem);
10644 // equipment visual show
10645 SetVisibleItemSlot(slot,NULL);
10648 m_items[slot] = NULL;
10650 else if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, bag ))
10651 pBag->RemoveItem(slot, update);
10653 if( IsInWorld() && update )
10655 pItem->RemoveFromWorld();
10656 pItem->DestroyForPlayer(this);
10659 //pItem->SetOwnerGUID(0);
10660 pItem->SetUInt64Value( ITEM_FIELD_CONTAINED, 0 );
10661 pItem->SetSlot( NULL_SLOT );
10662 pItem->SetState(ITEM_REMOVED, this);
10666 void Player::DestroyItemCount( uint32 item, uint32 count, bool update, bool unequip_check)
10668 sLog.outDebug( "STORAGE: DestroyItemCount item = %u, count = %u", item, count);
10669 Item *pItem;
10670 ItemPrototype const *pProto;
10671 uint32 remcount = 0;
10673 // in inventory
10674 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10676 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10677 if( pItem && pItem->GetEntry() == item )
10679 if( pItem->GetCount() + remcount <= count )
10681 // all items in inventory can unequipped
10682 remcount += pItem->GetCount();
10683 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10685 if(remcount >=count)
10686 return;
10688 else
10690 pProto = pItem->GetProto();
10691 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10692 pItem->SetCount( pItem->GetCount() - count + remcount );
10693 if( IsInWorld() & update )
10694 pItem->SendUpdateToPlayer( this );
10695 pItem->SetState(ITEM_CHANGED, this);
10696 return;
10700 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
10702 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10703 if( pItem && pItem->GetEntry() == item )
10705 if( pItem->GetCount() + remcount <= count )
10707 // all keys can be unequipped
10708 remcount += pItem->GetCount();
10709 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10711 if(remcount >=count)
10712 return;
10714 else
10716 pProto = pItem->GetProto();
10717 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10718 pItem->SetCount( pItem->GetCount() - count + remcount );
10719 if( IsInWorld() & update )
10720 pItem->SendUpdateToPlayer( this );
10721 pItem->SetState(ITEM_CHANGED, this);
10722 return;
10727 // in inventory bags
10728 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10730 if(Bag *pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
10732 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10734 pItem = pBag->GetItemByPos(j);
10735 if( pItem && pItem->GetEntry() == item )
10737 // all items in bags can be unequipped
10738 if( pItem->GetCount() + remcount <= count )
10740 remcount += pItem->GetCount();
10741 DestroyItem( i, j, update );
10743 if(remcount >=count)
10744 return;
10746 else
10748 pProto = pItem->GetProto();
10749 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10750 pItem->SetCount( pItem->GetCount() - count + remcount );
10751 if( IsInWorld() && update )
10752 pItem->SendUpdateToPlayer( this );
10753 pItem->SetState(ITEM_CHANGED, this);
10754 return;
10761 // in equipment and bag list
10762 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10764 pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10765 if( pItem && pItem->GetEntry() == item )
10767 if( pItem->GetCount() + remcount <= count )
10769 if(!unequip_check || CanUnequipItem(INVENTORY_SLOT_BAG_0 << 8 | i,false) == EQUIP_ERR_OK )
10771 remcount += pItem->GetCount();
10772 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10774 if(remcount >=count)
10775 return;
10778 else
10780 pProto = pItem->GetProto();
10781 ItemRemovedQuestCheck( pItem->GetEntry(), count - remcount );
10782 pItem->SetCount( pItem->GetCount() - count + remcount );
10783 if( IsInWorld() & update )
10784 pItem->SendUpdateToPlayer( this );
10785 pItem->SetState(ITEM_CHANGED, this);
10786 return;
10792 void Player::DestroyZoneLimitedItem( bool update, uint32 new_zone )
10794 sLog.outDebug( "STORAGE: DestroyZoneLimitedItem in map %u and area %u", GetMapId(), new_zone );
10796 // in inventory
10797 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10799 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10800 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10801 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10803 for(int i = KEYRING_SLOT_START; i < QUESTBAG_SLOT_END; i++)
10805 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10806 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10807 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10810 // in inventory bags
10811 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10813 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10814 if( pBag )
10816 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10818 Item* pItem = pBag->GetItemByPos(j);
10819 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10820 DestroyItem( i, j, update);
10825 // in equipment and bag list
10826 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10828 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10829 if( pItem && pItem->IsLimitedToAnotherMapOrZone(GetMapId(),new_zone) )
10830 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10834 void Player::DestroyConjuredItems( bool update )
10836 // used when entering arena
10837 // destroys all conjured items
10838 sLog.outDebug( "STORAGE: DestroyConjuredItems" );
10840 // in inventory
10841 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
10843 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10844 if( pItem && pItem->GetProto() &&
10845 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10846 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10847 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10850 // in inventory bags
10851 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
10853 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10854 if( pBag )
10856 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
10858 Item* pItem = pBag->GetItemByPos(j);
10859 if( pItem && pItem->GetProto() &&
10860 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10861 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10862 DestroyItem( i, j, update);
10867 // in equipment and bag list
10868 for(int i = EQUIPMENT_SLOT_START; i < INVENTORY_SLOT_BAG_END; i++)
10870 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
10871 if( pItem && pItem->GetProto() &&
10872 (pItem->GetProto()->Class == ITEM_CLASS_CONSUMABLE) &&
10873 (pItem->GetProto()->Flags & ITEM_FLAGS_CONJURED) )
10874 DestroyItem( INVENTORY_SLOT_BAG_0, i, update);
10878 void Player::DestroyItemCount( Item* pItem, uint32 &count, bool update )
10880 if(!pItem)
10881 return;
10883 sLog.outDebug( "STORAGE: DestroyItemCount item (GUID: %u, Entry: %u) count = %u", pItem->GetGUIDLow(),pItem->GetEntry(), count);
10885 if( pItem->GetCount() <= count )
10887 count-= pItem->GetCount();
10889 DestroyItem( pItem->GetBagSlot(),pItem->GetSlot(), update);
10891 else
10893 ItemRemovedQuestCheck( pItem->GetEntry(), count);
10894 pItem->SetCount( pItem->GetCount() - count );
10895 count = 0;
10896 if( IsInWorld() & update )
10897 pItem->SendUpdateToPlayer( this );
10898 pItem->SetState(ITEM_CHANGED, this);
10902 void Player::SplitItem( uint16 src, uint16 dst, uint32 count )
10904 uint8 srcbag = src >> 8;
10905 uint8 srcslot = src & 255;
10907 uint8 dstbag = dst >> 8;
10908 uint8 dstslot = dst & 255;
10910 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
10911 if( !pSrcItem )
10913 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10914 return;
10917 // not let split all items (can be only at cheating)
10918 if(pSrcItem->GetCount() == count)
10920 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10921 return;
10924 // not let split more existed items (can be only at cheating)
10925 if(pSrcItem->GetCount() < count)
10927 SendEquipError( EQUIP_ERR_TRIED_TO_SPLIT_MORE_THAN_COUNT, pSrcItem, NULL );
10928 return;
10931 if(pSrcItem->m_lootGenerated) // prevent split looting item (item
10933 //best error message found for attempting to split while looting
10934 SendEquipError( EQUIP_ERR_COULDNT_SPLIT_ITEMS, pSrcItem, NULL );
10935 return;
10938 sLog.outDebug( "STORAGE: SplitItem bag = %u, slot = %u, item = %u, count = %u", dstbag, dstslot, pSrcItem->GetEntry(), count);
10939 Item *pNewItem = pSrcItem->CloneItem( count, this );
10940 if( !pNewItem )
10942 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, pSrcItem, NULL );
10943 return;
10946 if( IsInventoryPos( dst ) )
10948 // change item amount before check (for unique max count check)
10949 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10951 ItemPosCountVec dest;
10952 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pNewItem, false );
10953 if( msg != EQUIP_ERR_OK )
10955 delete pNewItem;
10956 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10957 SendEquipError( msg, pSrcItem, NULL );
10958 return;
10961 if( IsInWorld() )
10962 pSrcItem->SendUpdateToPlayer( this );
10963 pSrcItem->SetState(ITEM_CHANGED, this);
10964 StoreItem( dest, pNewItem, true);
10966 else if( IsBankPos ( dst ) )
10968 // change item amount before check (for unique max count check)
10969 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10971 ItemPosCountVec dest;
10972 uint8 msg = CanBankItem( dstbag, dstslot, dest, pNewItem, false );
10973 if( msg != EQUIP_ERR_OK )
10975 delete pNewItem;
10976 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10977 SendEquipError( msg, pSrcItem, NULL );
10978 return;
10981 if( IsInWorld() )
10982 pSrcItem->SendUpdateToPlayer( this );
10983 pSrcItem->SetState(ITEM_CHANGED, this);
10984 BankItem( dest, pNewItem, true);
10986 else if( IsEquipmentPos ( dst ) )
10988 // change item amount before check (for unique max count check), provide space for splitted items
10989 pSrcItem->SetCount( pSrcItem->GetCount() - count );
10991 uint16 dest;
10992 uint8 msg = CanEquipItem( dstslot, dest, pNewItem, false );
10993 if( msg != EQUIP_ERR_OK )
10995 delete pNewItem;
10996 pSrcItem->SetCount( pSrcItem->GetCount() + count );
10997 SendEquipError( msg, pSrcItem, NULL );
10998 return;
11001 if( IsInWorld() )
11002 pSrcItem->SendUpdateToPlayer( this );
11003 pSrcItem->SetState(ITEM_CHANGED, this);
11004 EquipItem( dest, pNewItem, true);
11005 AutoUnequipOffhandIfNeed();
11009 void Player::SwapItem( uint16 src, uint16 dst )
11011 uint8 srcbag = src >> 8;
11012 uint8 srcslot = src & 255;
11014 uint8 dstbag = dst >> 8;
11015 uint8 dstslot = dst & 255;
11017 Item *pSrcItem = GetItemByPos( srcbag, srcslot );
11018 Item *pDstItem = GetItemByPos( dstbag, dstslot );
11020 if( !pSrcItem )
11021 return;
11023 sLog.outDebug( "STORAGE: SwapItem bag = %u, slot = %u, item = %u", dstbag, dstslot, pSrcItem->GetEntry());
11025 if(!isAlive() )
11027 SendEquipError( EQUIP_ERR_YOU_ARE_DEAD, pSrcItem, pDstItem );
11028 return;
11031 if(pSrcItem->m_lootGenerated) // prevent swap looting item
11033 //best error message found for attempting to swap while looting
11034 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pSrcItem, NULL );
11035 return;
11038 // check unequip potability for equipped items and bank bags
11039 if(IsEquipmentPos ( src ) || IsBagPos ( src ))
11041 // bags can be swapped with empty bag slots
11042 uint8 msg = CanUnequipItem( src, !IsBagPos ( src ) || IsBagPos ( dst ));
11043 if(msg != EQUIP_ERR_OK)
11045 SendEquipError( msg, pSrcItem, pDstItem );
11046 return;
11050 // prevent put equipped/bank bag in self
11051 if( IsBagPos ( src ) && srcslot == dstbag)
11053 SendEquipError( EQUIP_ERR_NONEMPTY_BAG_OVER_OTHER_BAG, pSrcItem, pDstItem );
11054 return;
11057 if( !pDstItem )
11059 if( IsInventoryPos( dst ) )
11061 ItemPosCountVec dest;
11062 uint8 msg = CanStoreItem( dstbag, dstslot, dest, pSrcItem, false );
11063 if( msg != EQUIP_ERR_OK )
11065 SendEquipError( msg, pSrcItem, NULL );
11066 return;
11069 RemoveItem(srcbag, srcslot, true);
11070 StoreItem( dest, pSrcItem, true);
11072 else if( IsBankPos ( dst ) )
11074 ItemPosCountVec dest;
11075 uint8 msg = CanBankItem( dstbag, dstslot, dest, pSrcItem, false);
11076 if( msg != EQUIP_ERR_OK )
11078 SendEquipError( msg, pSrcItem, NULL );
11079 return;
11082 RemoveItem(srcbag, srcslot, true);
11083 BankItem( dest, pSrcItem, true);
11085 else if( IsEquipmentPos ( dst ) )
11087 uint16 dest;
11088 uint8 msg = CanEquipItem( dstslot, dest, pSrcItem, false );
11089 if( msg != EQUIP_ERR_OK )
11091 SendEquipError( msg, pSrcItem, NULL );
11092 return;
11095 RemoveItem(srcbag, srcslot, true);
11096 EquipItem( dest, pSrcItem, true);
11097 AutoUnequipOffhandIfNeed();
11100 else // if (!pDstItem)
11102 if(pDstItem->m_lootGenerated) // prevent swap looting item
11104 //best error message found for attempting to swap while looting
11105 SendEquipError( EQUIP_ERR_CANT_DO_RIGHT_NOW, pDstItem, NULL );
11106 return;
11109 // check unequip potability for equipped items and bank bags
11110 if(IsEquipmentPos ( dst ) || IsBagPos ( dst ))
11112 // bags can be swapped with empty bag slots
11113 uint8 msg = CanUnequipItem( dst, !IsBagPos ( dst ) || IsBagPos ( src ) );
11114 if(msg != EQUIP_ERR_OK)
11116 SendEquipError( msg, pSrcItem, pDstItem );
11117 return;
11121 // attempt merge to / fill target item
11123 uint8 msg;
11124 ItemPosCountVec sDest;
11125 uint16 eDest;
11126 if( IsInventoryPos( dst ) )
11127 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, false );
11128 else if( IsBankPos ( dst ) )
11129 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, false );
11130 else if( IsEquipmentPos ( dst ) )
11131 msg = CanEquipItem( dstslot, eDest, pSrcItem, false );
11132 else
11133 return;
11135 // can be merge/fill
11136 if(msg == EQUIP_ERR_OK)
11138 if( pSrcItem->GetCount() + pDstItem->GetCount() <= pSrcItem->GetProto()->Stackable )
11140 RemoveItem(srcbag, srcslot, true);
11142 if( IsInventoryPos( dst ) )
11143 StoreItem( sDest, pSrcItem, true);
11144 else if( IsBankPos ( dst ) )
11145 BankItem( sDest, pSrcItem, true);
11146 else if( IsEquipmentPos ( dst ) )
11148 EquipItem( eDest, pSrcItem, true);
11149 AutoUnequipOffhandIfNeed();
11152 else
11154 pSrcItem->SetCount( pSrcItem->GetCount() + pDstItem->GetCount() - pSrcItem->GetProto()->Stackable );
11155 pDstItem->SetCount( pSrcItem->GetProto()->Stackable );
11156 pSrcItem->SetState(ITEM_CHANGED, this);
11157 pDstItem->SetState(ITEM_CHANGED, this);
11158 if( IsInWorld() )
11160 pSrcItem->SendUpdateToPlayer( this );
11161 pDstItem->SendUpdateToPlayer( this );
11164 return;
11168 // impossible merge/fill, do real swap
11169 uint8 msg;
11171 // check src->dest move possibility
11172 ItemPosCountVec sDest;
11173 uint16 eDest;
11174 if( IsInventoryPos( dst ) )
11175 msg = CanStoreItem( dstbag, dstslot, sDest, pSrcItem, true );
11176 else if( IsBankPos( dst ) )
11177 msg = CanBankItem( dstbag, dstslot, sDest, pSrcItem, true );
11178 else if( IsEquipmentPos( dst ) )
11180 msg = CanEquipItem( dstslot, eDest, pSrcItem, true );
11181 if( msg == EQUIP_ERR_OK )
11182 msg = CanUnequipItem( eDest, true );
11185 if( msg != EQUIP_ERR_OK )
11187 SendEquipError( msg, pSrcItem, pDstItem );
11188 return;
11191 // check dest->src move possibility
11192 ItemPosCountVec sDest2;
11193 uint16 eDest2;
11194 if( IsInventoryPos( src ) )
11195 msg = CanStoreItem( srcbag, srcslot, sDest2, pDstItem, true );
11196 else if( IsBankPos( src ) )
11197 msg = CanBankItem( srcbag, srcslot, sDest2, pDstItem, true );
11198 else if( IsEquipmentPos( src ) )
11200 msg = CanEquipItem( srcslot, eDest2, pDstItem, true);
11201 if( msg == EQUIP_ERR_OK )
11202 msg = CanUnequipItem( eDest2, true);
11205 if( msg != EQUIP_ERR_OK )
11207 SendEquipError( msg, pDstItem, pSrcItem );
11208 return;
11211 // now do moves, remove...
11212 RemoveItem(dstbag, dstslot, false);
11213 RemoveItem(srcbag, srcslot, false);
11215 // add to dest
11216 if( IsInventoryPos( dst ) )
11217 StoreItem(sDest, pSrcItem, true);
11218 else if( IsBankPos( dst ) )
11219 BankItem(sDest, pSrcItem, true);
11220 else if( IsEquipmentPos( dst ) )
11221 EquipItem(eDest, pSrcItem, true);
11223 // add to src
11224 if( IsInventoryPos( src ) )
11225 StoreItem(sDest2, pDstItem, true);
11226 else if( IsBankPos( src ) )
11227 BankItem(sDest2, pDstItem, true);
11228 else if( IsEquipmentPos( src ) )
11229 EquipItem(eDest2, pDstItem, true);
11231 AutoUnequipOffhandIfNeed();
11235 void Player::AddItemToBuyBackSlot( Item *pItem )
11237 if( pItem )
11239 uint32 slot = m_currentBuybackSlot;
11240 // if current back slot non-empty search oldest or free
11241 if(m_items[slot])
11243 uint32 oldest_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 );
11244 uint32 oldest_slot = BUYBACK_SLOT_START;
11246 for(uint32 i = BUYBACK_SLOT_START+1; i < BUYBACK_SLOT_END; ++i )
11248 // found empty
11249 if(!m_items[i])
11251 slot = i;
11252 break;
11255 uint32 i_time = GetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + i - BUYBACK_SLOT_START);
11257 if(oldest_time > i_time)
11259 oldest_time = i_time;
11260 oldest_slot = i;
11264 // find oldest
11265 slot = oldest_slot;
11268 RemoveItemFromBuyBackSlot( slot, true );
11269 sLog.outDebug( "STORAGE: AddItemToBuyBackSlot item = %u, slot = %u", pItem->GetEntry(), slot);
11271 m_items[slot] = pItem;
11272 time_t base = time(NULL);
11273 uint32 etime = uint32(base - m_logintime + (30 * 3600));
11274 uint32 eslot = slot - BUYBACK_SLOT_START;
11276 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, pItem->GetGUID() );
11277 ItemPrototype const *pProto = pItem->GetProto();
11278 if( pProto )
11279 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, pProto->SellPrice * pItem->GetCount() );
11280 else
11281 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11282 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, (uint32)etime );
11284 // move to next (for non filled list is move most optimized choice)
11285 if(m_currentBuybackSlot < BUYBACK_SLOT_END-1)
11286 ++m_currentBuybackSlot;
11290 Item* Player::GetItemFromBuyBackSlot( uint32 slot )
11292 sLog.outDebug( "STORAGE: GetItemFromBuyBackSlot slot = %u", slot);
11293 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11294 return m_items[slot];
11295 return NULL;
11298 void Player::RemoveItemFromBuyBackSlot( uint32 slot, bool del )
11300 sLog.outDebug( "STORAGE: RemoveItemFromBuyBackSlot slot = %u", slot);
11301 if( slot >= BUYBACK_SLOT_START && slot < BUYBACK_SLOT_END )
11303 Item *pItem = m_items[slot];
11304 if( pItem )
11306 pItem->RemoveFromWorld();
11307 if(del) pItem->SetState(ITEM_REMOVED, this);
11310 m_items[slot] = NULL;
11312 uint32 eslot = slot - BUYBACK_SLOT_START;
11313 SetUInt64Value( PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + eslot * 2, 0 );
11314 SetUInt32Value( PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0 );
11315 SetUInt32Value( PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0 );
11317 // if current backslot is filled set to now free slot
11318 if(m_items[m_currentBuybackSlot])
11319 m_currentBuybackSlot = slot;
11323 void Player::SendEquipError( uint8 msg, Item* pItem, Item *pItem2 )
11325 sLog.outDebug( "WORLD: Sent SMSG_INVENTORY_CHANGE_FAILURE (%u)",msg);
11326 WorldPacket data( SMSG_INVENTORY_CHANGE_FAILURE, (msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I ? 22 : 18) );
11327 data << uint8(msg);
11329 if(msg)
11331 data << uint64(pItem ? pItem->GetGUID() : 0);
11332 data << uint64(pItem2 ? pItem2->GetGUID() : 0);
11333 data << uint8(0); // not 0 there...
11335 if(msg == EQUIP_ERR_CANT_EQUIP_LEVEL_I)
11337 uint32 level = 0;
11339 if(pItem)
11340 if(ItemPrototype const* proto = pItem->GetProto())
11341 level = proto->RequiredLevel;
11343 data << uint32(level); // new 2.4.0
11346 GetSession()->SendPacket(&data);
11349 void Player::SendBuyError( uint8 msg, Creature* pCreature, uint32 item, uint32 param )
11351 sLog.outDebug( "WORLD: Sent SMSG_BUY_FAILED" );
11352 WorldPacket data( SMSG_BUY_FAILED, (8+4+4+1) );
11353 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11354 data << uint32(item);
11355 if( param > 0 )
11356 data << uint32(param);
11357 data << uint8(msg);
11358 GetSession()->SendPacket(&data);
11361 void Player::SendSellError( uint8 msg, Creature* pCreature, uint64 guid, uint32 param )
11363 sLog.outDebug( "WORLD: Sent SMSG_SELL_ITEM" );
11364 WorldPacket data( SMSG_SELL_ITEM,(8+8+(param?4:0)+1)); // last check 2.0.10
11365 data << uint64(pCreature ? pCreature->GetGUID() : 0);
11366 data << uint64(guid);
11367 if( param > 0 )
11368 data << uint32(param);
11369 data << uint8(msg);
11370 GetSession()->SendPacket(&data);
11373 void Player::ClearTrade()
11375 tradeGold = 0;
11376 acceptTrade = false;
11377 for(int i = 0; i < TRADE_SLOT_COUNT; i++)
11378 tradeItems[i] = NULL_SLOT;
11381 void Player::TradeCancel(bool sendback)
11383 if(pTrader)
11385 // send yellow "Trade canceled" message to both traders
11386 WorldSession* ws;
11387 ws = GetSession();
11388 if(sendback)
11389 ws->SendCancelTrade();
11390 ws = pTrader->GetSession();
11391 if(!ws->PlayerLogout())
11392 ws->SendCancelTrade();
11394 // cleanup
11395 ClearTrade();
11396 pTrader->ClearTrade();
11397 // prevent loss of reference
11398 pTrader->pTrader = NULL;
11399 pTrader = NULL;
11403 void Player::UpdateItemDuration(uint32 time, bool realtimeonly)
11405 if(m_itemDuration.empty())
11406 return;
11408 sLog.outDebug("Player::UpdateItemDuration(%u,%u)", time,realtimeonly);
11410 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); )
11412 Item* item = *itr;
11413 ++itr; // current element can be erased in UpdateDuration
11415 if (realtimeonly && item->GetProto()->Duration < 0 || !realtimeonly)
11416 item->UpdateDuration(this,time);
11420 void Player::UpdateEnchantTime(uint32 time)
11422 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11424 assert(itr->item);
11425 next=itr;
11426 if(!itr->item->GetEnchantmentId(itr->slot))
11428 next = m_enchantDuration.erase(itr);
11430 else if(itr->leftduration <= time)
11432 ApplyEnchantment(itr->item,itr->slot,false,false);
11433 itr->item->ClearEnchantment(itr->slot);
11434 next = m_enchantDuration.erase(itr);
11436 else if(itr->leftduration > time)
11438 itr->leftduration -= time;
11439 ++next;
11444 void Player::AddEnchantmentDurations(Item *item)
11446 for(int x=0;x<MAX_ENCHANTMENT_SLOT;++x)
11448 if(!item->GetEnchantmentId(EnchantmentSlot(x)))
11449 continue;
11451 uint32 duration = item->GetEnchantmentDuration(EnchantmentSlot(x));
11452 if( duration > 0 )
11453 AddEnchantmentDuration(item,EnchantmentSlot(x),duration);
11457 void Player::RemoveEnchantmentDurations(Item *item)
11459 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();)
11461 if(itr->item == item)
11463 // save duration in item
11464 item->SetEnchantmentDuration(EnchantmentSlot(itr->slot),itr->leftduration);
11465 itr = m_enchantDuration.erase(itr);
11467 else
11468 ++itr;
11472 void Player::RemoveAllEnchantments(EnchantmentSlot slot)
11474 // remove enchantments from equipped items first to clean up the m_enchantDuration list
11475 for(EnchantDurationList::iterator itr = m_enchantDuration.begin(),next;itr != m_enchantDuration.end();itr=next)
11477 next = itr;
11478 if(itr->slot==slot)
11480 if(itr->item && itr->item->GetEnchantmentId(slot))
11482 // remove from stats
11483 ApplyEnchantment(itr->item,slot,false,false);
11484 // remove visual
11485 itr->item->ClearEnchantment(slot);
11487 // remove from update list
11488 next = m_enchantDuration.erase(itr);
11490 else
11491 ++next;
11494 // remove enchants from inventory items
11495 // NOTE: no need to remove these from stats, since these aren't equipped
11496 // in inventory
11497 for(int i = INVENTORY_SLOT_ITEM_START; i < INVENTORY_SLOT_ITEM_END; i++)
11499 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11500 if( pItem && pItem->GetEnchantmentId(slot) )
11501 pItem->ClearEnchantment(slot);
11504 // in inventory bags
11505 for(int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; i++)
11507 Bag* pBag = (Bag*)GetItemByPos( INVENTORY_SLOT_BAG_0, i );
11508 if( pBag )
11510 for(uint32 j = 0; j < pBag->GetBagSize(); j++)
11512 Item* pItem = pBag->GetItemByPos(j);
11513 if( pItem && pItem->GetEnchantmentId(slot) )
11514 pItem->ClearEnchantment(slot);
11520 // duration == 0 will remove item enchant
11521 void Player::AddEnchantmentDuration(Item *item,EnchantmentSlot slot,uint32 duration)
11523 if(!item)
11524 return;
11526 if(slot >= MAX_ENCHANTMENT_SLOT)
11527 return;
11529 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11531 if(itr->item == item && itr->slot == slot)
11533 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
11534 m_enchantDuration.erase(itr);
11535 break;
11538 if(item && duration > 0 )
11540 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), item->GetGUID(),slot,uint32(duration/1000));
11541 m_enchantDuration.push_back(EnchantDuration(item,slot,duration));
11545 void Player::ApplyEnchantment(Item *item,bool apply)
11547 for(uint32 slot = 0; slot < MAX_ENCHANTMENT_SLOT; ++slot)
11548 ApplyEnchantment(item, EnchantmentSlot(slot), apply);
11551 void Player::ApplyEnchantment(Item *item,EnchantmentSlot slot,bool apply, bool apply_dur, bool ignore_condition)
11553 if(!item)
11554 return;
11556 if(!item->IsEquipped())
11557 return;
11559 if(slot >= MAX_ENCHANTMENT_SLOT)
11560 return;
11562 uint32 enchant_id = item->GetEnchantmentId(slot);
11563 if(!enchant_id)
11564 return;
11566 SpellItemEnchantmentEntry const *pEnchant = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
11567 if(!pEnchant)
11568 return;
11570 if(!ignore_condition && pEnchant->EnchantmentCondition && !((Player*)this)->EnchantmentFitsRequirements(pEnchant->EnchantmentCondition, -1))
11571 return;
11573 for (int s=0; s<3; s++)
11575 uint32 enchant_display_type = pEnchant->type[s];
11576 uint32 enchant_amount = pEnchant->amount[s];
11577 uint32 enchant_spell_id = pEnchant->spellid[s];
11579 switch(enchant_display_type)
11581 case ITEM_ENCHANTMENT_TYPE_NONE:
11582 break;
11583 case ITEM_ENCHANTMENT_TYPE_COMBAT_SPELL:
11584 // processed in Player::CastItemCombatSpell
11585 break;
11586 case ITEM_ENCHANTMENT_TYPE_DAMAGE:
11587 if (item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11588 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, float(enchant_amount), apply);
11589 else if (item->GetSlot() == EQUIPMENT_SLOT_OFFHAND)
11590 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, float(enchant_amount), apply);
11591 else if (item->GetSlot() == EQUIPMENT_SLOT_RANGED)
11592 HandleStatModifier(UNIT_MOD_DAMAGE_RANGED, TOTAL_VALUE, float(enchant_amount), apply);
11593 break;
11594 case ITEM_ENCHANTMENT_TYPE_EQUIP_SPELL:
11595 if(enchant_spell_id)
11597 if(apply)
11599 int32 basepoints = int32(enchant_amount);
11600 // Random Property Exist - try found basepoints for spell (basepoints depends from item suffix factor)
11601 if (item->GetItemRandomPropertyId() !=0 && !enchant_amount)
11603 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11604 if (item_rand)
11606 // Search enchant_amount
11607 for (int k=0; k<3; k++)
11609 if(item_rand->enchant_id[k] == enchant_id)
11611 basepoints = int32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11612 break;
11617 // Cast custom spell vs all equal basepoints getted from enchant_amount
11618 if (basepoints)
11619 CastCustomSpell(this,enchant_spell_id,&basepoints,&basepoints,&basepoints,true,item);
11620 else
11621 CastSpell(this,enchant_spell_id,true,item);
11623 else
11624 RemoveAurasDueToItemSpell(item,enchant_spell_id);
11626 break;
11627 case ITEM_ENCHANTMENT_TYPE_RESISTANCE:
11628 if (!enchant_amount)
11630 ItemRandomSuffixEntry const *item_rand = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11631 if(item_rand)
11633 for (int k=0; k<3; k++)
11635 if(item_rand->enchant_id[k] == enchant_id)
11637 enchant_amount = uint32((item_rand->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11638 break;
11644 HandleStatModifier(UnitMods(UNIT_MOD_RESISTANCE_START + enchant_spell_id), TOTAL_VALUE, float(enchant_amount), apply);
11645 break;
11646 case ITEM_ENCHANTMENT_TYPE_STAT:
11648 if (!enchant_amount)
11650 ItemRandomSuffixEntry const *item_rand_suffix = sItemRandomSuffixStore.LookupEntry(abs(item->GetItemRandomPropertyId()));
11651 if(item_rand_suffix)
11653 for (int k=0; k<3; k++)
11655 if(item_rand_suffix->enchant_id[k] == enchant_id)
11657 enchant_amount = uint32((item_rand_suffix->prefix[k]*item->GetItemSuffixFactor()) / 10000 );
11658 break;
11664 sLog.outDebug("Adding %u to stat nb %u",enchant_amount,enchant_spell_id);
11665 switch (enchant_spell_id)
11667 case ITEM_MOD_AGILITY:
11668 sLog.outDebug("+ %u AGILITY",enchant_amount);
11669 HandleStatModifier(UNIT_MOD_STAT_AGILITY, TOTAL_VALUE, float(enchant_amount), apply);
11670 ApplyStatBuffMod(STAT_AGILITY, enchant_amount, apply);
11671 break;
11672 case ITEM_MOD_STRENGTH:
11673 sLog.outDebug("+ %u STRENGTH",enchant_amount);
11674 HandleStatModifier(UNIT_MOD_STAT_STRENGTH, TOTAL_VALUE, float(enchant_amount), apply);
11675 ApplyStatBuffMod(STAT_STRENGTH, enchant_amount, apply);
11676 break;
11677 case ITEM_MOD_INTELLECT:
11678 sLog.outDebug("+ %u INTELLECT",enchant_amount);
11679 HandleStatModifier(UNIT_MOD_STAT_INTELLECT, TOTAL_VALUE, float(enchant_amount), apply);
11680 ApplyStatBuffMod(STAT_INTELLECT, enchant_amount, apply);
11681 break;
11682 case ITEM_MOD_SPIRIT:
11683 sLog.outDebug("+ %u SPIRIT",enchant_amount);
11684 HandleStatModifier(UNIT_MOD_STAT_SPIRIT, TOTAL_VALUE, float(enchant_amount), apply);
11685 ApplyStatBuffMod(STAT_SPIRIT, enchant_amount, apply);
11686 break;
11687 case ITEM_MOD_STAMINA:
11688 sLog.outDebug("+ %u STAMINA",enchant_amount);
11689 HandleStatModifier(UNIT_MOD_STAT_STAMINA, TOTAL_VALUE, float(enchant_amount), apply);
11690 ApplyStatBuffMod(STAT_STAMINA, enchant_amount, apply);
11691 break;
11692 case ITEM_MOD_DEFENSE_SKILL_RATING:
11693 ((Player*)this)->ApplyRatingMod(CR_DEFENSE_SKILL, enchant_amount, apply);
11694 sLog.outDebug("+ %u DEFENCE", enchant_amount);
11695 break;
11696 case ITEM_MOD_DODGE_RATING:
11697 ((Player*)this)->ApplyRatingMod(CR_DODGE, enchant_amount, apply);
11698 sLog.outDebug("+ %u DODGE", enchant_amount);
11699 break;
11700 case ITEM_MOD_PARRY_RATING:
11701 ((Player*)this)->ApplyRatingMod(CR_PARRY, enchant_amount, apply);
11702 sLog.outDebug("+ %u PARRY", enchant_amount);
11703 break;
11704 case ITEM_MOD_BLOCK_RATING:
11705 ((Player*)this)->ApplyRatingMod(CR_BLOCK, enchant_amount, apply);
11706 sLog.outDebug("+ %u SHIELD_BLOCK", enchant_amount);
11707 break;
11708 case ITEM_MOD_HIT_MELEE_RATING:
11709 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11710 sLog.outDebug("+ %u MELEE_HIT", enchant_amount);
11711 break;
11712 case ITEM_MOD_HIT_RANGED_RATING:
11713 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11714 sLog.outDebug("+ %u RANGED_HIT", enchant_amount);
11715 break;
11716 case ITEM_MOD_HIT_SPELL_RATING:
11717 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11718 sLog.outDebug("+ %u SPELL_HIT", enchant_amount);
11719 break;
11720 case ITEM_MOD_CRIT_MELEE_RATING:
11721 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11722 sLog.outDebug("+ %u MELEE_CRIT", enchant_amount);
11723 break;
11724 case ITEM_MOD_CRIT_RANGED_RATING:
11725 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11726 sLog.outDebug("+ %u RANGED_CRIT", enchant_amount);
11727 break;
11728 case ITEM_MOD_CRIT_SPELL_RATING:
11729 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11730 sLog.outDebug("+ %u SPELL_CRIT", enchant_amount);
11731 break;
11732 // Values from ITEM_STAT_MELEE_HA_RATING to ITEM_MOD_HASTE_RANGED_RATING are never used
11733 // in Enchantments
11734 // case ITEM_MOD_HIT_TAKEN_MELEE_RATING:
11735 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11736 // break;
11737 // case ITEM_MOD_HIT_TAKEN_RANGED_RATING:
11738 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11739 // break;
11740 // case ITEM_MOD_HIT_TAKEN_SPELL_RATING:
11741 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11742 // break;
11743 // case ITEM_MOD_CRIT_TAKEN_MELEE_RATING:
11744 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11745 // break;
11746 // case ITEM_MOD_CRIT_TAKEN_RANGED_RATING:
11747 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11748 // break;
11749 // case ITEM_MOD_CRIT_TAKEN_SPELL_RATING:
11750 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11751 // break;
11752 // case ITEM_MOD_HASTE_MELEE_RATING:
11753 // ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11754 // break;
11755 // case ITEM_MOD_HASTE_RANGED_RATING:
11756 // ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11757 // break;
11758 case ITEM_MOD_HASTE_SPELL_RATING:
11759 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11760 break;
11761 case ITEM_MOD_HIT_RATING:
11762 ((Player*)this)->ApplyRatingMod(CR_HIT_MELEE, enchant_amount, apply);
11763 ((Player*)this)->ApplyRatingMod(CR_HIT_RANGED, enchant_amount, apply);
11764 ((Player*)this)->ApplyRatingMod(CR_HIT_SPELL, enchant_amount, apply);
11765 sLog.outDebug("+ %u HIT", enchant_amount);
11766 break;
11767 case ITEM_MOD_CRIT_RATING:
11768 ((Player*)this)->ApplyRatingMod(CR_CRIT_MELEE, enchant_amount, apply);
11769 ((Player*)this)->ApplyRatingMod(CR_CRIT_RANGED, enchant_amount, apply);
11770 ((Player*)this)->ApplyRatingMod(CR_CRIT_SPELL, enchant_amount, apply);
11771 sLog.outDebug("+ %u CRITICAL", enchant_amount);
11772 break;
11773 // Values ITEM_MOD_HIT_TAKEN_RATING and ITEM_MOD_CRIT_TAKEN_RATING are never used in Enchantment
11774 // case ITEM_MOD_HIT_TAKEN_RATING:
11775 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_MELEE, enchant_amount, apply);
11776 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_RANGED, enchant_amount, apply);
11777 // ((Player*)this)->ApplyRatingMod(CR_HIT_TAKEN_SPELL, enchant_amount, apply);
11778 // break;
11779 // case ITEM_MOD_CRIT_TAKEN_RATING:
11780 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11781 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11782 // ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11783 // break;
11784 case ITEM_MOD_RESILIENCE_RATING:
11785 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_MELEE, enchant_amount, apply);
11786 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_RANGED, enchant_amount, apply);
11787 ((Player*)this)->ApplyRatingMod(CR_CRIT_TAKEN_SPELL, enchant_amount, apply);
11788 sLog.outDebug("+ %u RESILIENCE", enchant_amount);
11789 break;
11790 case ITEM_MOD_HASTE_RATING:
11791 ((Player*)this)->ApplyRatingMod(CR_HASTE_MELEE, enchant_amount, apply);
11792 ((Player*)this)->ApplyRatingMod(CR_HASTE_RANGED, enchant_amount, apply);
11793 ((Player*)this)->ApplyRatingMod(CR_HASTE_SPELL, enchant_amount, apply);
11794 sLog.outDebug("+ %u HASTE", enchant_amount);
11795 break;
11796 case ITEM_MOD_EXPERTISE_RATING:
11797 ((Player*)this)->ApplyRatingMod(CR_EXPERTISE, enchant_amount, apply);
11798 sLog.outDebug("+ %u EXPERTISE", enchant_amount);
11799 break;
11800 case ITEM_MOD_ARMOR_PENETRATION_RATING:
11801 ((Player*)this)->ApplyRatingMod(CR_ARMOR_PENETRATION, enchant_amount, apply);
11802 sLog.outDebug("+ %u ARMOR PENETRATION", enchant_amount);
11803 break;
11804 default:
11805 break;
11807 break;
11809 case ITEM_ENCHANTMENT_TYPE_TOTEM: // Shaman Rockbiter Weapon
11811 if(getClass() == CLASS_SHAMAN)
11813 float addValue = 0.0f;
11814 if(item->GetSlot() == EQUIPMENT_SLOT_MAINHAND)
11816 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11817 HandleStatModifier(UNIT_MOD_DAMAGE_MAINHAND, TOTAL_VALUE, addValue, apply);
11819 else if(item->GetSlot() == EQUIPMENT_SLOT_OFFHAND )
11821 addValue = float(enchant_amount * item->GetProto()->Delay/1000.0f);
11822 HandleStatModifier(UNIT_MOD_DAMAGE_OFFHAND, TOTAL_VALUE, addValue, apply);
11825 break;
11827 default:
11828 sLog.outError("Unknown item enchantment display type: %d",enchant_display_type);
11829 break;
11830 } /*switch(enchant_display_type)*/
11831 } /*for*/
11833 // visualize enchantment at player and equipped items
11834 if(slot < MAX_INSPECTED_ENCHANTMENT_SLOT)
11836 int VisibleBase = PLAYER_VISIBLE_ITEM_1_0 + (item->GetSlot() * MAX_VISIBLE_ITEM_OFFSET);
11837 SetUInt32Value(VisibleBase + 1 + slot, apply? item->GetEnchantmentId(slot) : 0);
11840 if(apply_dur)
11842 if(apply)
11844 // set duration
11845 uint32 duration = item->GetEnchantmentDuration(slot);
11846 if(duration > 0)
11847 AddEnchantmentDuration(item,slot,duration);
11849 else
11851 // duration == 0 will remove EnchantDuration
11852 AddEnchantmentDuration(item,slot,0);
11857 void Player::SendEnchantmentDurations()
11859 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
11861 GetSession()->SendItemEnchantTimeUpdate(GetGUID(), itr->item->GetGUID(),itr->slot,uint32(itr->leftduration)/1000);
11865 void Player::SendItemDurations()
11867 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end();++itr)
11869 (*itr)->SendTimeUpdate(this);
11873 void Player::SendNewItem(Item *item, uint32 count, bool received, bool created, bool broadcast)
11875 if(!item) // prevent crash
11876 return;
11878 // last check 2.0.10
11879 WorldPacket data( SMSG_ITEM_PUSH_RESULT, (8+4+4+4+1+4+4+4+4+4) );
11880 data << GetGUID(); // player GUID
11881 data << uint32(received); // 0=looted, 1=from npc
11882 data << uint32(created); // 0=received, 1=created
11883 data << uint32(1); // always 0x01 (probably meant to be count of listed items)
11884 data << (uint8)item->GetBagSlot(); // bagslot
11885 // item slot, but when added to stack: 0xFFFFFFFF
11886 data << (uint32) ((item->GetCount()==count) ? item->GetSlot() : -1);
11887 data << uint32(item->GetEntry()); // item id
11888 data << uint32(item->GetItemSuffixFactor()); // SuffixFactor
11889 data << uint32(item->GetItemRandomPropertyId()); // random item property id
11890 data << uint32(count); // count of items
11891 data << GetItemCount(item->GetEntry()); // count of items in inventory
11893 if (broadcast && GetGroup())
11894 GetGroup()->BroadcastPacket(&data);
11895 else
11896 GetSession()->SendPacket(&data);
11899 /*********************************************************/
11900 /*** QUEST SYSTEM ***/
11901 /*********************************************************/
11903 void Player::PrepareQuestMenu( uint64 guid )
11905 Object *pObject;
11906 QuestRelations* pObjectQR;
11907 QuestRelations* pObjectQIR;
11908 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11909 if( pCreature )
11911 pObject = (Object*)pCreature;
11912 pObjectQR = &objmgr.mCreatureQuestRelations;
11913 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
11915 else
11917 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
11918 if( pGameObject )
11920 pObject = (Object*)pGameObject;
11921 pObjectQR = &objmgr.mGOQuestRelations;
11922 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
11924 else
11925 return;
11928 QuestMenu &qm = PlayerTalkClass->GetQuestMenu();
11929 qm.ClearMenu();
11931 for(QuestRelations::const_iterator i = pObjectQIR->lower_bound(pObject->GetEntry()); i != pObjectQIR->upper_bound(pObject->GetEntry()); ++i)
11933 uint32 quest_id = i->second;
11934 QuestStatus status = GetQuestStatus( quest_id );
11935 if ( status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus( quest_id ) )
11936 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11937 else if ( status == QUEST_STATUS_INCOMPLETE )
11938 qm.AddMenuItem(quest_id, DIALOG_STATUS_INCOMPLETE);
11939 else if (status == QUEST_STATUS_AVAILABLE )
11940 qm.AddMenuItem(quest_id, DIALOG_STATUS_CHAT);
11943 for(QuestRelations::const_iterator i = pObjectQR->lower_bound(pObject->GetEntry()); i != pObjectQR->upper_bound(pObject->GetEntry()); ++i)
11945 uint32 quest_id = i->second;
11946 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11947 if(!pQuest) continue;
11949 QuestStatus status = GetQuestStatus( quest_id );
11951 if (pQuest->IsAutoComplete() && CanTakeQuest(pQuest, false))
11952 qm.AddMenuItem(quest_id, DIALOG_STATUS_REWARD_REP);
11953 else if ( status == QUEST_STATUS_NONE && CanTakeQuest( pQuest, false ) )
11954 qm.AddMenuItem(quest_id, DIALOG_STATUS_AVAILABLE);
11958 void Player::SendPreparedQuest( uint64 guid )
11960 QuestMenu& questMenu = PlayerTalkClass->GetQuestMenu();
11961 if( questMenu.Empty() )
11962 return;
11964 QuestMenuItem const& qmi0 = questMenu.GetItem( 0 );
11966 uint32 status = qmi0.m_qIcon;
11968 // single element case
11969 if ( questMenu.MenuItemCount() == 1 )
11971 // Auto open -- maybe also should verify there is no greeting
11972 uint32 quest_id = qmi0.m_qId;
11973 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
11974 if ( pQuest )
11976 if( status == DIALOG_STATUS_REWARD_REP && !GetQuestRewardStatus( quest_id ) )
11977 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanRewardQuest(pQuest,false), true );
11978 else if( status == DIALOG_STATUS_INCOMPLETE )
11979 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, false, true );
11980 // Send completable on repeatable quest if player don't have quest
11981 else if( pQuest->IsRepeatable() && !pQuest->IsDaily() )
11982 PlayerTalkClass->SendQuestGiverRequestItems( pQuest, guid, CanCompleteRepeatableQuest(pQuest), true );
11983 else
11984 PlayerTalkClass->SendQuestGiverQuestDetails( pQuest, guid, true );
11987 // multiply entries
11988 else
11990 QEmote qe;
11991 qe._Delay = 0;
11992 qe._Emote = 0;
11993 std::string title = "";
11994 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
11995 if( pCreature )
11997 uint32 textid = pCreature->GetNpcTextId();
11998 GossipText * gossiptext = objmgr.GetGossipText(textid);
11999 if( !gossiptext )
12001 qe._Delay = 0; //TEXTEMOTE_MESSAGE; //zyg: player emote
12002 qe._Emote = 0; //TEXTEMOTE_HELLO; //zyg: NPC emote
12003 title = "";
12005 else
12007 qe = gossiptext->Options[0].Emotes[0];
12009 if(!gossiptext->Options[0].Text_0.empty())
12011 title = gossiptext->Options[0].Text_0;
12013 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12014 if (loc_idx >= 0)
12016 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12017 if (nl)
12019 if (nl->Text_0[0].size() > loc_idx && !nl->Text_0[0][loc_idx].empty())
12020 title = nl->Text_0[0][loc_idx];
12024 else
12026 title = gossiptext->Options[0].Text_1;
12028 int loc_idx = GetSession()->GetSessionDbLocaleIndex();
12029 if (loc_idx >= 0)
12031 NpcTextLocale const *nl = objmgr.GetNpcTextLocale(textid);
12032 if (nl)
12034 if (nl->Text_1[0].size() > loc_idx && !nl->Text_1[0][loc_idx].empty())
12035 title = nl->Text_1[0][loc_idx];
12041 PlayerTalkClass->SendQuestGiverQuestList( qe, title, guid );
12045 bool Player::IsActiveQuest( uint32 quest_id ) const
12047 QuestStatusMap::const_iterator itr = mQuestStatus.find(quest_id);
12049 return itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE;
12052 Quest const * Player::GetNextQuest( uint64 guid, Quest const *pQuest )
12054 Object *pObject;
12055 QuestRelations* pObjectQR;
12056 QuestRelations* pObjectQIR;
12058 Creature *pCreature = ObjectAccessor::GetCreature(*this, guid);
12059 if( pCreature )
12061 pObject = (Object*)pCreature;
12062 pObjectQR = &objmgr.mCreatureQuestRelations;
12063 pObjectQIR = &objmgr.mCreatureQuestInvolvedRelations;
12065 else
12067 GameObject *pGameObject = ObjectAccessor::GetGameObject(*this, guid);
12068 if( pGameObject )
12070 pObject = (Object*)pGameObject;
12071 pObjectQR = &objmgr.mGOQuestRelations;
12072 pObjectQIR = &objmgr.mGOQuestInvolvedRelations;
12074 else
12075 return NULL;
12078 uint32 nextQuestID = pQuest->GetNextQuestInChain();
12079 for(QuestRelations::const_iterator itr = pObjectQR->lower_bound(pObject->GetEntry()); itr != pObjectQR->upper_bound(pObject->GetEntry()); ++itr)
12081 if (itr->second == nextQuestID)
12082 return objmgr.GetQuestTemplate(nextQuestID);
12085 return NULL;
12088 bool Player::CanSeeStartQuest( Quest const *pQuest )
12090 if( SatisfyQuestRace( pQuest, false ) && SatisfyQuestSkillOrClass( pQuest, false ) &&
12091 SatisfyQuestExclusiveGroup( pQuest, false ) && SatisfyQuestReputation( pQuest, false ) &&
12092 SatisfyQuestPreviousQuest( pQuest, false ) && SatisfyQuestNextChain( pQuest, false ) &&
12093 SatisfyQuestPrevChain( pQuest, false ) && SatisfyQuestDay( pQuest, false ) )
12095 return getLevel() + sWorld.getConfig(CONFIG_QUEST_HIGH_LEVEL_HIDE_DIFF) >= pQuest->GetMinLevel();
12098 return false;
12101 bool Player::CanTakeQuest( Quest const *pQuest, bool msg )
12103 return SatisfyQuestStatus( pQuest, msg ) && SatisfyQuestExclusiveGroup( pQuest, msg )
12104 && SatisfyQuestRace( pQuest, msg ) && SatisfyQuestLevel( pQuest, msg )
12105 && SatisfyQuestSkillOrClass( pQuest, msg ) && SatisfyQuestReputation( pQuest, msg )
12106 && SatisfyQuestPreviousQuest( pQuest, msg ) && SatisfyQuestTimed( pQuest, msg )
12107 && SatisfyQuestNextChain( pQuest, msg ) && SatisfyQuestPrevChain( pQuest, msg )
12108 && SatisfyQuestDay( pQuest, msg );
12111 bool Player::CanAddQuest( Quest const *pQuest, bool msg )
12113 if( !SatisfyQuestLog( msg ) )
12114 return false;
12116 uint32 srcitem = pQuest->GetSrcItemId();
12117 if( srcitem > 0 )
12119 uint32 count = pQuest->GetSrcItemCount();
12120 ItemPosCountVec dest;
12121 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12123 // player already have max number (in most case 1) source item, no additional item needed and quest can be added.
12124 if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12125 return true;
12126 else if( msg != EQUIP_ERR_OK )
12128 SendEquipError( msg, NULL, NULL );
12129 return false;
12132 return true;
12135 bool Player::CanCompleteQuest( uint32 quest_id )
12137 if( quest_id )
12139 QuestStatusData& q_status = mQuestStatus[quest_id];
12140 if( q_status.m_status == QUEST_STATUS_COMPLETE )
12141 return false; // not allow re-complete quest
12143 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12145 if(!qInfo)
12146 return false;
12148 // auto complete quest
12149 if (qInfo->IsAutoComplete() && CanTakeQuest(qInfo, false))
12150 return true;
12152 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
12155 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12157 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12159 if( qInfo->ReqItemCount[i]!= 0 && q_status.m_itemcount[i] < qInfo->ReqItemCount[i] )
12160 return false;
12164 if ( qInfo->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12166 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12168 if( qInfo->ReqCreatureOrGOId[i] == 0 )
12169 continue;
12171 if( qInfo->ReqCreatureOrGOCount[i] != 0 && q_status.m_creatureOrGOcount[i] < qInfo->ReqCreatureOrGOCount[i] )
12172 return false;
12176 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_EXPLORATION_OR_EVENT ) && !q_status.m_explored )
12177 return false;
12179 if ( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && q_status.m_timer == 0 )
12180 return false;
12182 if ( qInfo->GetRewOrReqMoney() < 0 )
12184 if ( GetMoney() < uint32(-qInfo->GetRewOrReqMoney()) )
12185 return false;
12188 uint32 repFacId = qInfo->GetRepObjectiveFaction();
12189 if ( repFacId && GetReputation(repFacId) < qInfo->GetRepObjectiveValue() )
12190 return false;
12192 return true;
12195 return false;
12198 bool Player::CanCompleteRepeatableQuest( Quest const *pQuest )
12200 // Solve problem that player don't have the quest and try complete it.
12201 // if repeatable she must be able to complete event if player don't have it.
12202 // Seem that all repeatable quest are DELIVER Flag so, no need to add more.
12203 if( !CanTakeQuest(pQuest, false) )
12204 return false;
12206 if (pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER) )
12207 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12208 if( pQuest->ReqItemId[i] && pQuest->ReqItemCount[i] && !HasItemCount(pQuest->ReqItemId[i],pQuest->ReqItemCount[i]) )
12209 return false;
12211 if( !CanRewardQuest(pQuest, false) )
12212 return false;
12214 return true;
12217 bool Player::CanRewardQuest( Quest const *pQuest, bool msg )
12219 // not auto complete quest and not completed quest (only cheating case, then ignore without message)
12220 if(!pQuest->IsAutoComplete() && GetQuestStatus(pQuest->GetQuestId()) != QUEST_STATUS_COMPLETE)
12221 return false;
12223 // daily quest can't be rewarded (25 daily quest already completed)
12224 if(!SatisfyQuestDay(pQuest,true))
12225 return false;
12227 // rewarded and not repeatable quest (only cheating case, then ignore without message)
12228 if(GetQuestRewardStatus(pQuest->GetQuestId()))
12229 return false;
12231 // prevent receive reward with quest items in bank
12232 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12234 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12236 if( pQuest->ReqItemCount[i]!= 0 &&
12237 GetItemCount(pQuest->ReqItemId[i]) < pQuest->ReqItemCount[i] )
12239 if(msg)
12240 SendEquipError( EQUIP_ERR_ITEM_NOT_FOUND, NULL, NULL );
12241 return false;
12246 // prevent receive reward with low money and GetRewOrReqMoney() < 0
12247 if(pQuest->GetRewOrReqMoney() < 0 && GetMoney() < uint32(-pQuest->GetRewOrReqMoney()) )
12248 return false;
12250 return true;
12253 bool Player::CanRewardQuest( Quest const *pQuest, uint32 reward, bool msg )
12255 // prevent receive reward with quest items in bank or for not completed quest
12256 if(!CanRewardQuest(pQuest,msg))
12257 return false;
12259 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12261 if( pQuest->RewChoiceItemId[reward] )
12263 ItemPosCountVec dest;
12264 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] );
12265 if( res != EQUIP_ERR_OK )
12267 SendEquipError( res, NULL, NULL );
12268 return false;
12273 if ( pQuest->GetRewItemsCount() > 0 )
12275 for (uint32 i = 0; i < pQuest->GetRewItemsCount(); ++i)
12277 if( pQuest->RewItemId[i] )
12279 ItemPosCountVec dest;
12280 uint8 res = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] );
12281 if( res != EQUIP_ERR_OK )
12283 SendEquipError( res, NULL, NULL );
12284 return false;
12290 return true;
12293 void Player::AddQuest( Quest const *pQuest, Object *questGiver )
12295 uint16 log_slot = FindQuestSlot( 0 );
12296 assert(log_slot < MAX_QUEST_LOG_SIZE);
12298 uint32 quest_id = pQuest->GetQuestId();
12300 // if not exist then created with set uState==NEW and rewarded=false
12301 QuestStatusData& questStatusData = mQuestStatus[quest_id];
12302 if (questStatusData.uState != QUEST_NEW)
12303 questStatusData.uState = QUEST_CHANGED;
12305 // check for repeatable quests status reset
12306 questStatusData.m_status = QUEST_STATUS_INCOMPLETE;
12307 questStatusData.m_explored = false;
12309 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
12311 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12312 questStatusData.m_itemcount[i] = 0;
12315 if ( pQuest->HasFlag(QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO) )
12317 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
12318 questStatusData.m_creatureOrGOcount[i] = 0;
12321 GiveQuestSourceItem( pQuest );
12322 AdjustQuestReqItemCount( pQuest );
12324 if( pQuest->GetRepObjectiveFaction() )
12325 SetFactionVisibleForFactionId(pQuest->GetRepObjectiveFaction());
12327 uint32 qtime = 0;
12328 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
12330 uint32 limittime = pQuest->GetLimitTime();
12332 // shared timed quest
12333 if(questGiver && questGiver->GetTypeId()==TYPEID_PLAYER)
12334 limittime = ((Player*)questGiver)->getQuestStatusMap()[quest_id].m_timer / 1000;
12336 AddTimedQuest( quest_id );
12337 questStatusData.m_timer = limittime * 1000;
12338 qtime = static_cast<uint32>(time(NULL)) + limittime;
12340 else
12341 questStatusData.m_timer = 0;
12343 SetQuestSlot(log_slot, quest_id, qtime);
12345 //starting initial quest script
12346 if(questGiver && pQuest->GetQuestStartScript()!=0)
12347 sWorld.ScriptsStart(sQuestStartScripts, pQuest->GetQuestStartScript(), questGiver, this);
12349 UpdateForQuestsGO();
12352 void Player::CompleteQuest( uint32 quest_id )
12354 if( quest_id )
12356 SetQuestStatus( quest_id, QUEST_STATUS_COMPLETE );
12358 uint16 log_slot = FindQuestSlot( quest_id );
12359 if( log_slot < MAX_QUEST_LOG_SIZE)
12360 SetQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12362 if(Quest const* qInfo = objmgr.GetQuestTemplate(quest_id))
12364 if( qInfo->HasFlag(QUEST_FLAGS_AUTO_REWARDED) )
12365 RewardQuest(qInfo,0,this,false);
12366 else
12367 SendQuestComplete( quest_id );
12372 void Player::IncompleteQuest( uint32 quest_id )
12374 if( quest_id )
12376 SetQuestStatus( quest_id, QUEST_STATUS_INCOMPLETE );
12378 uint16 log_slot = FindQuestSlot( quest_id );
12379 if( log_slot < MAX_QUEST_LOG_SIZE)
12380 RemoveQuestSlotState(log_slot,QUEST_STATE_COMPLETE);
12384 void Player::RewardQuest( Quest const *pQuest, uint32 reward, Object* questGiver, bool announce )
12386 uint32 quest_id = pQuest->GetQuestId();
12388 for (int i = 0; i < QUEST_OBJECTIVES_COUNT; i++ )
12390 if ( pQuest->ReqItemId[i] )
12391 DestroyItemCount( pQuest->ReqItemId[i], pQuest->ReqItemCount[i], true);
12394 //if( qInfo->HasSpecialFlag( QUEST_FLAGS_TIMED ) )
12395 // SetTimedQuest( 0 );
12396 m_timedquests.erase(pQuest->GetQuestId());
12398 if ( pQuest->GetRewChoiceItemsCount() > 0 )
12400 if( pQuest->RewChoiceItemId[reward] )
12402 ItemPosCountVec dest;
12403 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewChoiceItemId[reward], pQuest->RewChoiceItemCount[reward] ) == EQUIP_ERR_OK )
12405 Item* item = StoreNewItem( dest, pQuest->RewChoiceItemId[reward], true);
12406 SendNewItem(item, pQuest->RewChoiceItemCount[reward], true, false);
12411 if ( pQuest->GetRewItemsCount() > 0 )
12413 for (uint32 i=0; i < pQuest->GetRewItemsCount(); ++i)
12415 if( pQuest->RewItemId[i] )
12417 ItemPosCountVec dest;
12418 if( CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, pQuest->RewItemId[i], pQuest->RewItemCount[i] ) == EQUIP_ERR_OK )
12420 Item* item = StoreNewItem( dest, pQuest->RewItemId[i], true);
12421 SendNewItem(item, pQuest->RewItemCount[i], true, false);
12427 RewardReputation( pQuest );
12429 if( pQuest->GetRewSpellCast() > 0 )
12430 CastSpell( this, pQuest->GetRewSpellCast(), true);
12431 else if( pQuest->GetRewSpell() > 0)
12432 CastSpell( this, pQuest->GetRewSpell(), true);
12434 uint16 log_slot = FindQuestSlot( quest_id );
12435 if( log_slot < MAX_QUEST_LOG_SIZE)
12436 SetQuestSlot(log_slot,0);
12438 QuestStatusData& q_status = mQuestStatus[quest_id];
12440 // Not give XP in case already completed once repeatable quest
12441 uint32 XP = q_status.m_rewarded ? 0 : uint32(pQuest->XPValue( this )*sWorld.getRate(RATE_XP_QUEST));
12443 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
12444 GiveXP( XP , NULL );
12445 else
12446 ModifyMoney( int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)) );
12448 // Give player extra money if GetRewOrReqMoney > 0 and get ReqMoney if negative
12449 ModifyMoney( pQuest->GetRewOrReqMoney() );
12451 // honor reward
12452 if(pQuest->GetRewHonorableKills())
12453 RewardHonor(NULL, 0, MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
12455 // title reward
12456 if(pQuest->GetCharTitleId())
12458 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
12459 SetTitle(titleEntry);
12462 // Send reward mail
12463 if(pQuest->GetRewMailTemplateId())
12465 MailMessageType mailType;
12466 uint32 senderGuidOrEntry;
12467 switch(questGiver->GetTypeId())
12469 case TYPEID_UNIT:
12470 mailType = MAIL_CREATURE;
12471 senderGuidOrEntry = questGiver->GetEntry();
12472 break;
12473 case TYPEID_GAMEOBJECT:
12474 mailType = MAIL_GAMEOBJECT;
12475 senderGuidOrEntry = questGiver->GetEntry();
12476 break;
12477 case TYPEID_ITEM:
12478 mailType = MAIL_ITEM;
12479 senderGuidOrEntry = questGiver->GetEntry();
12480 break;
12481 case TYPEID_PLAYER:
12482 mailType = MAIL_NORMAL;
12483 senderGuidOrEntry = questGiver->GetGUIDLow();
12484 break;
12485 default:
12486 mailType = MAIL_NORMAL;
12487 senderGuidOrEntry = GetGUIDLow();
12488 break;
12491 Loot questMailLoot;
12493 questMailLoot.FillLoot(pQuest->GetQuestId(), LootTemplates_QuestMail, this);
12495 // fill mail
12496 MailItemsInfo mi; // item list preparing
12498 for(size_t i = 0; mi.size() < MAX_MAIL_ITEMS && i < questMailLoot.items.size(); ++i)
12500 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i,this))
12502 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12504 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12505 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12510 for(size_t i = 0; mi.size() < MAX_MAIL_ITEMS && i < questMailLoot.quest_items.size(); ++i)
12512 if(LootItem* lootitem = questMailLoot.LootItemInSlot(i+questMailLoot.items.size(),this))
12514 if(Item* item = Item::CreateItem(lootitem->itemid,lootitem->count,this))
12516 item->SaveToDB(); // save for prevent lost at next mail load, if send fail then item will deleted
12517 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
12522 WorldSession::SendMailTo(this, mailType, MAIL_STATIONERY_NORMAL, senderGuidOrEntry, GetGUIDLow(), "", 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE,pQuest->GetRewMailDelaySecs(),pQuest->GetRewMailTemplateId());
12525 if(pQuest->IsDaily())
12527 SetDailyQuestStatus(quest_id);
12528 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST, 1);
12531 if ( !pQuest->IsRepeatable() )
12532 SetQuestStatus(quest_id, QUEST_STATUS_COMPLETE);
12533 else
12534 SetQuestStatus(quest_id, QUEST_STATUS_NONE);
12536 q_status.m_rewarded = true;
12538 if(announce)
12539 SendQuestReward( pQuest, XP, questGiver );
12541 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12542 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT);
12543 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST);
12546 void Player::FailQuest( uint32 quest_id )
12548 if( quest_id )
12550 IncompleteQuest( quest_id );
12552 uint16 log_slot = FindQuestSlot( quest_id );
12553 if( log_slot < MAX_QUEST_LOG_SIZE)
12555 SetQuestSlotTimer(log_slot, 1 );
12556 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12558 SendQuestFailed( quest_id );
12562 void Player::FailTimedQuest( uint32 quest_id )
12564 if( quest_id )
12566 QuestStatusData& q_status = mQuestStatus[quest_id];
12568 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
12569 q_status.m_timer = 0;
12571 IncompleteQuest( quest_id );
12573 uint16 log_slot = FindQuestSlot( quest_id );
12574 if( log_slot < MAX_QUEST_LOG_SIZE)
12576 SetQuestSlotTimer(log_slot, 1 );
12577 SetQuestSlotState(log_slot,QUEST_STATE_FAIL);
12579 SendQuestTimerFailed( quest_id );
12583 bool Player::SatisfyQuestSkillOrClass( Quest const* qInfo, bool msg )
12585 int32 zoneOrSort = qInfo->GetZoneOrSort();
12586 int32 skillOrClass = qInfo->GetSkillOrClass();
12588 // skip zone zoneOrSort and 0 case skillOrClass
12589 if( zoneOrSort >= 0 && skillOrClass == 0 )
12590 return true;
12592 int32 questSort = -zoneOrSort;
12593 uint8 reqSortClass = ClassByQuestSort(questSort);
12595 // check class sort cases in zoneOrSort
12596 if( reqSortClass != 0 && getClass() != reqSortClass)
12598 if( msg )
12599 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12600 return false;
12603 // check class
12604 if( skillOrClass < 0 )
12606 uint8 reqClass = -int32(skillOrClass);
12607 if(getClass() != reqClass)
12609 if( msg )
12610 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12611 return false;
12614 // check skill
12615 else if( skillOrClass > 0 )
12617 uint32 reqSkill = skillOrClass;
12618 if( GetSkillValue( reqSkill ) < qInfo->GetRequiredSkillValue() )
12620 if( msg )
12621 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12622 return false;
12626 return true;
12629 bool Player::SatisfyQuestLevel( Quest const* qInfo, bool msg )
12631 if( getLevel() < qInfo->GetMinLevel() )
12633 if( msg )
12634 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12635 return false;
12637 return true;
12640 bool Player::SatisfyQuestLog( bool msg )
12642 // exist free slot
12643 if( FindQuestSlot(0) < MAX_QUEST_LOG_SIZE )
12644 return true;
12646 if( msg )
12648 WorldPacket data( SMSG_QUESTLOG_FULL, 0 );
12649 GetSession()->SendPacket( &data );
12650 sLog.outDebug( "WORLD: Sent QUEST_LOG_FULL_MESSAGE" );
12652 return false;
12655 bool Player::SatisfyQuestPreviousQuest( Quest const* qInfo, bool msg )
12657 // No previous quest (might be first quest in a series)
12658 if( qInfo->prevQuests.empty())
12659 return true;
12661 for(Quest::PrevQuests::const_iterator iter = qInfo->prevQuests.begin(); iter != qInfo->prevQuests.end(); ++iter )
12663 uint32 prevId = abs(*iter);
12665 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12666 Quest const* qPrevInfo = objmgr.GetQuestTemplate(prevId);
12668 if( qPrevInfo && i_prevstatus != mQuestStatus.end() )
12670 // If any of the positive previous quests completed, return true
12671 if( *iter > 0 && i_prevstatus->second.m_rewarded )
12673 // skip one-from-all exclusive group
12674 if(qPrevInfo->GetExclusiveGroup() >= 0)
12675 return true;
12677 // each-from-all exclusive group ( < 0)
12678 // can be start if only all quests in prev quest exclusive group completed and rewarded
12679 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12680 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12682 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12684 for(; iter != end; ++iter)
12686 uint32 exclude_Id = iter->second;
12688 // skip checked quest id, only state of other quests in group is interesting
12689 if(exclude_Id == prevId)
12690 continue;
12692 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12694 // alternative quest from group also must be completed and rewarded(reported)
12695 if( i_exstatus == mQuestStatus.end() || !i_exstatus->second.m_rewarded )
12697 if( msg )
12698 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12699 return false;
12702 return true;
12704 // If any of the negative previous quests active, return true
12705 if( *iter < 0 && (i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12706 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId))))
12708 // skip one-from-all exclusive group
12709 if(qPrevInfo->GetExclusiveGroup() >= 0)
12710 return true;
12712 // each-from-all exclusive group ( < 0)
12713 // can be start if only all quests in prev quest exclusive group active
12714 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qPrevInfo->GetExclusiveGroup());
12715 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qPrevInfo->GetExclusiveGroup());
12717 assert(iter!=end); // always must be found if qPrevInfo->ExclusiveGroup != 0
12719 for(; iter != end; ++iter)
12721 uint32 exclude_Id = iter->second;
12723 // skip checked quest id, only state of other quests in group is interesting
12724 if(exclude_Id == prevId)
12725 continue;
12727 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12729 // alternative quest from group also must be active
12730 if( i_exstatus == mQuestStatus.end() ||
12731 i_exstatus->second.m_status != QUEST_STATUS_INCOMPLETE &&
12732 (i_prevstatus->second.m_status != QUEST_STATUS_COMPLETE || GetQuestRewardStatus(prevId)) )
12734 if( msg )
12735 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12736 return false;
12739 return true;
12744 // Has only positive prev. quests in non-rewarded state
12745 // and negative prev. quests in non-active state
12746 if( msg )
12747 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12749 return false;
12752 bool Player::SatisfyQuestRace( Quest const* qInfo, bool msg )
12754 uint32 reqraces = qInfo->GetRequiredRaces();
12755 if ( reqraces == 0 )
12756 return true;
12757 if( (reqraces & getRaceMask()) == 0 )
12759 if( msg )
12760 SendCanTakeQuestResponse( INVALIDREASON_QUEST_FAILED_WRONG_RACE );
12761 return false;
12763 return true;
12766 bool Player::SatisfyQuestReputation( Quest const* qInfo, bool msg )
12768 uint32 fIdMin = qInfo->GetRequiredMinRepFaction(); //Min required rep
12769 if(fIdMin && GetReputation(fIdMin) < qInfo->GetRequiredMinRepValue())
12771 if( msg )
12772 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12773 return false;
12776 uint32 fIdMax = qInfo->GetRequiredMaxRepFaction(); //Max required rep
12777 if(fIdMax && GetReputation(fIdMax) >= qInfo->GetRequiredMaxRepValue())
12779 if( msg )
12780 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12781 return false;
12784 return true;
12787 bool Player::SatisfyQuestStatus( Quest const* qInfo, bool msg )
12789 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetQuestId() );
12790 if ( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE )
12792 if( msg )
12793 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ALREADY_ON );
12794 return false;
12796 return true;
12799 bool Player::SatisfyQuestTimed( Quest const* qInfo, bool msg )
12801 if ( (find(m_timedquests.begin(), m_timedquests.end(), qInfo->GetQuestId()) != m_timedquests.end()) && qInfo->HasFlag(QUEST_MANGOS_FLAGS_TIMED) )
12803 if( msg )
12804 SendCanTakeQuestResponse( INVALIDREASON_QUEST_ONLY_ONE_TIMED );
12805 return false;
12807 return true;
12810 bool Player::SatisfyQuestExclusiveGroup( Quest const* qInfo, bool msg )
12812 // non positive exclusive group, if > 0 then can be start if any other quest in exclusive group already started/completed
12813 if(qInfo->GetExclusiveGroup() <= 0)
12814 return true;
12816 ObjectMgr::ExclusiveQuestGroups::iterator iter = objmgr.mExclusiveQuestGroups.lower_bound(qInfo->GetExclusiveGroup());
12817 ObjectMgr::ExclusiveQuestGroups::iterator end = objmgr.mExclusiveQuestGroups.upper_bound(qInfo->GetExclusiveGroup());
12819 assert(iter!=end); // always must be found if qInfo->ExclusiveGroup != 0
12821 for(; iter != end; ++iter)
12823 uint32 exclude_Id = iter->second;
12825 // skip checked quest id, only state of other quests in group is interesting
12826 if(exclude_Id == qInfo->GetQuestId())
12827 continue;
12829 // not allow have daily quest if daily quest from exclusive group already recently completed
12830 Quest const* Nquest = objmgr.GetQuestTemplate(exclude_Id);
12831 if( !SatisfyQuestDay(Nquest, false) )
12833 if( msg )
12834 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12835 return false;
12838 QuestStatusMap::iterator i_exstatus = mQuestStatus.find( exclude_Id );
12840 // alternative quest already started or completed
12841 if( i_exstatus != mQuestStatus.end()
12842 && (i_exstatus->second.m_status == QUEST_STATUS_COMPLETE || i_exstatus->second.m_status == QUEST_STATUS_INCOMPLETE) )
12844 if( msg )
12845 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12846 return false;
12849 return true;
12852 bool Player::SatisfyQuestNextChain( Quest const* qInfo, bool msg )
12854 if(!qInfo->GetNextQuestInChain())
12855 return true;
12857 // next quest in chain already started or completed
12858 QuestStatusMap::iterator itr = mQuestStatus.find( qInfo->GetNextQuestInChain() );
12859 if( itr != mQuestStatus.end()
12860 && (itr->second.m_status == QUEST_STATUS_COMPLETE || itr->second.m_status == QUEST_STATUS_INCOMPLETE) )
12862 if( msg )
12863 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12864 return false;
12867 // check for all quests further up the chain
12868 // only necessary if there are quest chains with more than one quest that can be skipped
12869 //return SatisfyQuestNextChain( qInfo->GetNextQuestInChain(), msg );
12870 return true;
12873 bool Player::SatisfyQuestPrevChain( Quest const* qInfo, bool msg )
12875 // No previous quest in chain
12876 if( qInfo->prevChainQuests.empty())
12877 return true;
12879 for(Quest::PrevChainQuests::const_iterator iter = qInfo->prevChainQuests.begin(); iter != qInfo->prevChainQuests.end(); ++iter )
12881 uint32 prevId = *iter;
12883 QuestStatusMap::iterator i_prevstatus = mQuestStatus.find( prevId );
12885 if( i_prevstatus != mQuestStatus.end() )
12887 // If any of the previous quests in chain active, return false
12888 if( i_prevstatus->second.m_status == QUEST_STATUS_INCOMPLETE
12889 || (i_prevstatus->second.m_status == QUEST_STATUS_COMPLETE && !GetQuestRewardStatus(prevId)))
12891 if( msg )
12892 SendCanTakeQuestResponse( INVALIDREASON_DONT_HAVE_REQ );
12893 return false;
12897 // check for all quests further down the chain
12898 // only necessary if there are quest chains with more than one quest that can be skipped
12899 //if( !SatisfyQuestPrevChain( prevId, msg ) )
12900 // return false;
12903 // No previous quest in chain active
12904 return true;
12907 bool Player::SatisfyQuestDay( Quest const* qInfo, bool msg )
12909 if(!qInfo->IsDaily())
12910 return true;
12912 bool have_slot = false;
12913 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
12915 uint32 id = GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx);
12916 if(qInfo->GetQuestId()==id)
12917 return false;
12919 if(!id)
12920 have_slot = true;
12923 if(!have_slot)
12925 if( msg )
12926 SendCanTakeQuestResponse( INVALIDREASON_DAILY_QUESTS_REMAINING );
12927 return false;
12930 return true;
12933 bool Player::GiveQuestSourceItem( Quest const *pQuest )
12935 uint32 srcitem = pQuest->GetSrcItemId();
12936 if( srcitem > 0 )
12938 uint32 count = pQuest->GetSrcItemCount();
12939 if( count <= 0 )
12940 count = 1;
12942 ItemPosCountVec dest;
12943 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, srcitem, count );
12944 if( msg == EQUIP_ERR_OK )
12946 Item * item = StoreNewItem(dest, srcitem, true);
12947 SendNewItem(item, count, true, false);
12948 return true;
12950 // player already have max amount required item, just report success
12951 else if( msg == EQUIP_ERR_CANT_CARRY_MORE_OF_THIS )
12952 return true;
12953 else
12954 SendEquipError( msg, NULL, NULL );
12955 return false;
12958 return true;
12961 bool Player::TakeQuestSourceItem( uint32 quest_id, bool msg )
12963 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12964 if( qInfo )
12966 uint32 srcitem = qInfo->GetSrcItemId();
12967 if( srcitem > 0 )
12969 uint32 count = qInfo->GetSrcItemCount();
12970 if( count <= 0 )
12971 count = 1;
12973 // exist one case when destroy source quest item not possible:
12974 // non un-equippable item (equipped non-empty bag, for example)
12975 uint8 res = CanUnequipItems(srcitem,count);
12976 if(res != EQUIP_ERR_OK)
12978 if(msg)
12979 SendEquipError( res, NULL, NULL );
12980 return false;
12983 DestroyItemCount(srcitem, count, true, true);
12986 return true;
12989 bool Player::GetQuestRewardStatus( uint32 quest_id ) const
12991 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
12992 if( qInfo )
12994 // for repeatable quests: rewarded field is set after first reward only to prevent getting XP more than once
12995 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
12996 if( itr != mQuestStatus.end() && itr->second.m_status != QUEST_STATUS_NONE
12997 && !qInfo->IsRepeatable() )
12998 return itr->second.m_rewarded;
13000 return false;
13002 return false;
13005 QuestStatus Player::GetQuestStatus( uint32 quest_id ) const
13007 if( quest_id )
13009 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13010 if( itr != mQuestStatus.end() )
13011 return itr->second.m_status;
13013 return QUEST_STATUS_NONE;
13016 bool Player::CanShareQuest(uint32 quest_id) const
13018 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13019 if( qInfo && qInfo->HasFlag(QUEST_FLAGS_SHARABLE) )
13021 QuestStatusMap::const_iterator itr = mQuestStatus.find( quest_id );
13022 if( itr != mQuestStatus.end() )
13023 return itr->second.m_status == QUEST_STATUS_NONE || itr->second.m_status == QUEST_STATUS_INCOMPLETE;
13025 return false;
13028 void Player::SetQuestStatus( uint32 quest_id, QuestStatus status )
13030 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13031 if( qInfo )
13033 if( status == QUEST_STATUS_NONE || status == QUEST_STATUS_INCOMPLETE || status == QUEST_STATUS_COMPLETE )
13035 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) )
13036 m_timedquests.erase(qInfo->GetQuestId());
13039 QuestStatusData& q_status = mQuestStatus[quest_id];
13041 q_status.m_status = status;
13042 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13045 UpdateForQuestsGO();
13048 // not used in MaNGOS, but used in scripting code
13049 uint32 Player::GetReqKillOrCastCurrentCount(uint32 quest_id, int32 entry)
13051 Quest const* qInfo = objmgr.GetQuestTemplate(quest_id);
13052 if( !qInfo )
13053 return 0;
13055 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13056 if ( qInfo->ReqCreatureOrGOId[j] == entry )
13057 return mQuestStatus[quest_id].m_creatureOrGOcount[j];
13059 return 0;
13062 void Player::AdjustQuestReqItemCount( Quest const* pQuest )
13064 if ( pQuest->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13066 for(int i = 0; i < QUEST_OBJECTIVES_COUNT; i++)
13068 uint32 reqitemcount = pQuest->ReqItemCount[i];
13069 if( reqitemcount != 0 )
13071 uint32 quest_id = pQuest->GetQuestId();
13072 uint32 curitemcount = GetItemCount(pQuest->ReqItemId[i],true);
13074 QuestStatusData& q_status = mQuestStatus[quest_id];
13075 q_status.m_itemcount[i] = std::min(curitemcount, reqitemcount);
13076 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13082 uint16 Player::FindQuestSlot( uint32 quest_id ) const
13084 for ( uint16 i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13085 if ( GetQuestSlotQuestId(i) == quest_id )
13086 return i;
13088 return MAX_QUEST_LOG_SIZE;
13091 void Player::AreaExploredOrEventHappens( uint32 questId )
13093 if( questId )
13095 uint16 log_slot = FindQuestSlot( questId );
13096 if( log_slot < MAX_QUEST_LOG_SIZE)
13098 QuestStatusData& q_status = mQuestStatus[questId];
13100 if(!q_status.m_explored)
13102 q_status.m_explored = true;
13103 if (q_status.uState != QUEST_NEW)
13104 q_status.uState = QUEST_CHANGED;
13107 if( CanCompleteQuest( questId ) )
13108 CompleteQuest( questId );
13112 //not used in mangosd, function for external script library
13113 void Player::GroupEventHappens( uint32 questId, WorldObject const* pEventObject )
13115 if( Group *pGroup = GetGroup() )
13117 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
13119 Player *pGroupGuy = itr->getSource();
13121 // for any leave or dead (with not released body) group member at appropriate distance
13122 if( pGroupGuy && pGroupGuy->IsAtGroupRewardDistance(pEventObject) && !pGroupGuy->GetCorpse() )
13123 pGroupGuy->AreaExploredOrEventHappens(questId);
13126 else
13127 AreaExploredOrEventHappens(questId);
13130 void Player::ItemAddedQuestCheck( uint32 entry, uint32 count )
13132 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13134 uint32 questid = GetQuestSlotQuestId(i);
13135 if ( questid == 0 )
13136 continue;
13138 QuestStatusData& q_status = mQuestStatus[questid];
13140 if ( q_status.m_status != QUEST_STATUS_INCOMPLETE )
13141 continue;
13143 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13144 if( !qInfo || !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13145 continue;
13147 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13149 uint32 reqitem = qInfo->ReqItemId[j];
13150 if ( reqitem == entry )
13152 uint32 reqitemcount = qInfo->ReqItemCount[j];
13153 uint32 curitemcount = q_status.m_itemcount[j];
13154 if ( curitemcount < reqitemcount )
13156 uint32 additemcount = ( curitemcount + count <= reqitemcount ? count : reqitemcount - curitemcount);
13157 q_status.m_itemcount[j] += additemcount;
13158 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13160 SendQuestUpdateAddItem( qInfo, j, additemcount );
13162 if ( CanCompleteQuest( questid ) )
13163 CompleteQuest( questid );
13164 return;
13168 UpdateForQuestsGO();
13169 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM, entry);
13172 void Player::ItemRemovedQuestCheck( uint32 entry, uint32 count )
13174 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13176 uint32 questid = GetQuestSlotQuestId(i);
13177 if(!questid)
13178 continue;
13179 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13180 if ( !qInfo )
13181 continue;
13182 if( !qInfo->HasFlag( QUEST_MANGOS_FLAGS_DELIVER ) )
13183 continue;
13185 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13187 uint32 reqitem = qInfo->ReqItemId[j];
13188 if ( reqitem == entry )
13190 QuestStatusData& q_status = mQuestStatus[questid];
13192 uint32 reqitemcount = qInfo->ReqItemCount[j];
13193 uint32 curitemcount;
13194 if( q_status.m_status != QUEST_STATUS_COMPLETE )
13195 curitemcount = q_status.m_itemcount[j];
13196 else
13197 curitemcount = GetItemCount(entry,true);
13198 if ( curitemcount < reqitemcount + count )
13200 uint32 remitemcount = ( curitemcount <= reqitemcount ? count : count + reqitemcount - curitemcount);
13201 q_status.m_itemcount[j] = curitemcount - remitemcount;
13202 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13204 IncompleteQuest( questid );
13206 return;
13210 UpdateForQuestsGO();
13213 void Player::KilledMonster( uint32 entry, uint64 guid )
13215 uint32 addkillcount = 1;
13216 GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE, entry, addkillcount);
13217 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13219 uint32 questid = GetQuestSlotQuestId(i);
13220 if(!questid)
13221 continue;
13223 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13224 if( !qInfo )
13225 continue;
13226 // just if !ingroup || !noraidgroup || raidgroup
13227 QuestStatusData& q_status = mQuestStatus[questid];
13228 if( q_status.m_status == QUEST_STATUS_INCOMPLETE && (!GetGroup() || !GetGroup()->isRaidGroup() || qInfo->GetType() == QUEST_TYPE_RAID))
13230 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST) )
13232 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13234 // skip GO activate objective or none
13235 if(qInfo->ReqCreatureOrGOId[j] <=0)
13236 continue;
13238 // skip Cast at creature objective
13239 if(qInfo->ReqSpell[j] !=0 )
13240 continue;
13242 uint32 reqkill = qInfo->ReqCreatureOrGOId[j];
13244 if ( reqkill == entry )
13246 uint32 reqkillcount = qInfo->ReqCreatureOrGOCount[j];
13247 uint32 curkillcount = q_status.m_creatureOrGOcount[j];
13248 if ( curkillcount < reqkillcount )
13250 q_status.m_creatureOrGOcount[j] = curkillcount + addkillcount;
13251 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13253 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curkillcount, addkillcount);
13255 if ( CanCompleteQuest( questid ) )
13256 CompleteQuest( questid );
13258 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13259 continue;
13267 void Player::CastedCreatureOrGO( uint32 entry, uint64 guid, uint32 spell_id )
13269 bool isCreature = IS_CREATURE_GUID(guid);
13271 uint32 addCastCount = 1;
13272 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13274 uint32 questid = GetQuestSlotQuestId(i);
13275 if(!questid)
13276 continue;
13278 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13279 if ( !qInfo )
13280 continue;
13282 QuestStatusData& q_status = mQuestStatus[questid];
13284 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13286 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST ) )
13288 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13290 // skip kill creature objective (0) or wrong spell casts
13291 if(qInfo->ReqSpell[j] != spell_id )
13292 continue;
13294 uint32 reqTarget = 0;
13296 if(isCreature)
13298 // creature activate objectives
13299 if(qInfo->ReqCreatureOrGOId[j] > 0)
13300 // checked at quest_template loading
13301 reqTarget = qInfo->ReqCreatureOrGOId[j];
13303 else
13305 // GO activate objective
13306 if(qInfo->ReqCreatureOrGOId[j] < 0)
13307 // checked at quest_template loading
13308 reqTarget = - qInfo->ReqCreatureOrGOId[j];
13311 // other not this creature/GO related objectives
13312 if( reqTarget != entry )
13313 continue;
13315 uint32 reqCastCount = qInfo->ReqCreatureOrGOCount[j];
13316 uint32 curCastCount = q_status.m_creatureOrGOcount[j];
13317 if ( curCastCount < reqCastCount )
13319 q_status.m_creatureOrGOcount[j] = curCastCount + addCastCount;
13320 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13322 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curCastCount, addCastCount);
13325 if ( CanCompleteQuest( questid ) )
13326 CompleteQuest( questid );
13328 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13329 break;
13336 void Player::TalkedToCreature( uint32 entry, uint64 guid )
13338 uint32 addTalkCount = 1;
13339 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13341 uint32 questid = GetQuestSlotQuestId(i);
13342 if(!questid)
13343 continue;
13345 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13346 if ( !qInfo )
13347 continue;
13349 QuestStatusData& q_status = mQuestStatus[questid];
13351 if ( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13353 if( qInfo->HasFlag( QUEST_MANGOS_FLAGS_KILL_OR_CAST | QUEST_MANGOS_FLAGS_SPEAKTO ) )
13355 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13357 // skip spell casts and Gameobject objectives
13358 if(qInfo->ReqSpell[j] > 0 || qInfo->ReqCreatureOrGOId[j] < 0)
13359 continue;
13361 uint32 reqTarget = 0;
13363 if(qInfo->ReqCreatureOrGOId[j] > 0) // creature activate objectives
13364 // checked at quest_template loading
13365 reqTarget = qInfo->ReqCreatureOrGOId[j];
13366 else
13367 continue;
13369 if ( reqTarget == entry )
13371 uint32 reqTalkCount = qInfo->ReqCreatureOrGOCount[j];
13372 uint32 curTalkCount = q_status.m_creatureOrGOcount[j];
13373 if ( curTalkCount < reqTalkCount )
13375 q_status.m_creatureOrGOcount[j] = curTalkCount + addTalkCount;
13376 if (q_status.uState != QUEST_NEW) q_status.uState = QUEST_CHANGED;
13378 SendQuestUpdateAddCreatureOrGo( qInfo, guid, j, curTalkCount, addTalkCount);
13380 if ( CanCompleteQuest( questid ) )
13381 CompleteQuest( questid );
13383 // same objective target can be in many active quests, but not in 2 objectives for single quest (code optimization).
13384 continue;
13392 void Player::MoneyChanged( uint32 count )
13394 for( int i = 0; i < MAX_QUEST_LOG_SIZE; i++ )
13396 uint32 questid = GetQuestSlotQuestId(i);
13397 if (!questid)
13398 continue;
13400 Quest const* qInfo = objmgr.GetQuestTemplate(questid);
13401 if( qInfo && qInfo->GetRewOrReqMoney() < 0 )
13403 QuestStatusData& q_status = mQuestStatus[questid];
13405 if( q_status.m_status == QUEST_STATUS_INCOMPLETE )
13407 if(int32(count) >= -qInfo->GetRewOrReqMoney())
13409 if ( CanCompleteQuest( questid ) )
13410 CompleteQuest( questid );
13413 else if( q_status.m_status == QUEST_STATUS_COMPLETE )
13415 if(int32(count) < -qInfo->GetRewOrReqMoney())
13416 IncompleteQuest( questid );
13422 bool Player::HasQuestForItem( uint32 itemid ) const
13424 for( QuestStatusMap::const_iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
13426 QuestStatusData const& q_status = i->second;
13428 if (q_status.m_status == QUEST_STATUS_INCOMPLETE)
13430 Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
13431 if(!qinfo)
13432 continue;
13434 // hide quest if player is in raid-group and quest is no raid quest
13435 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
13436 continue;
13438 // There should be no mixed ReqItem/ReqSource drop
13439 // This part for ReqItem drop
13440 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
13442 if(itemid == qinfo->ReqItemId[j] && q_status.m_itemcount[j] < qinfo->ReqItemCount[j] )
13443 return true;
13445 // This part - for ReqSource
13446 for (int j = 0; j < QUEST_SOURCE_ITEM_IDS_COUNT; j++)
13448 // examined item is a source item
13449 if (qinfo->ReqSourceId[j] == itemid && qinfo->ReqSourceRef[j] > 0 && qinfo->ReqSourceRef[j] <= QUEST_OBJECTIVES_COUNT)
13451 uint32 idx = qinfo->ReqSourceRef[j]-1;
13453 // total count of created ReqItems and SourceItems is less than ReqItemCount
13454 if(qinfo->ReqItemId[idx] != 0 &&
13455 q_status.m_itemcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid,true) < qinfo->ReqItemCount[idx] * qinfo->ReqSourceCount[j])
13456 return true;
13458 // total count of casted ReqCreatureOrGOs and SourceItems is less than ReqCreatureOrGOCount
13459 if (qinfo->ReqCreatureOrGOId[idx] != 0)
13461 if(q_status.m_creatureOrGOcount[idx] * qinfo->ReqSourceCount[j] + GetItemCount(itemid,true) < qinfo->ReqCreatureOrGOCount[idx] * qinfo->ReqSourceCount[j])
13462 return true;
13464 // spell with SPELL_EFFECT_QUEST_COMPLETE or SPELL_EFFECT_SEND_EVENT (with script) case
13465 else if(qinfo->ReqSpell[idx] != 0)
13467 // not casted and need more reagents/item for use.
13468 if(!q_status.m_explored && GetItemCount(itemid,true) < qinfo->ReqSourceCount[j])
13469 return true;
13475 return false;
13478 void Player::SendQuestComplete( uint32 quest_id )
13480 if( quest_id )
13482 WorldPacket data( SMSG_QUESTUPDATE_COMPLETE, 4 );
13483 data << uint32(quest_id);
13484 GetSession()->SendPacket( &data );
13485 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_COMPLETE quest = %u", quest_id );
13489 void Player::SendQuestReward( Quest const *pQuest, uint32 XP, Object * questGiver )
13491 uint32 questid = pQuest->GetQuestId();
13492 sLog.outDebug( "WORLD: Sent SMSG_QUESTGIVER_QUEST_COMPLETE quest = %u", questid );
13493 WorldPacket data( SMSG_QUESTGIVER_QUEST_COMPLETE, (4+4+4+4+4) );
13494 data << uint32(questid);
13496 if ( getLevel() < sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL) )
13498 data << uint32(XP);
13499 data << uint32(pQuest->GetRewOrReqMoney());
13501 else
13503 data << uint32(0);
13504 data << uint32(pQuest->GetRewOrReqMoney() + int32(pQuest->GetRewMoneyMaxLevel() * sWorld.getRate(RATE_DROP_MONEY)));
13507 data << uint32(10*MaNGOS::Honor::hk_honor_at_level(getLevel(), pQuest->GetRewHonorableKills()));
13508 data << uint32(pQuest->GetBonusTalents()); // bonus talents
13509 GetSession()->SendPacket( &data );
13511 if (pQuest->GetQuestCompleteScript() != 0)
13512 sWorld.ScriptsStart(sQuestEndScripts, pQuest->GetQuestCompleteScript(), questGiver, this);
13515 void Player::SendQuestFailed( uint32 quest_id )
13517 if( quest_id )
13519 WorldPacket data( SMSG_QUESTGIVER_QUEST_FAILED, 4+4 );
13520 data << quest_id;
13521 data << uint32(0); // failed reason (4 for inventory is full)
13522 GetSession()->SendPacket( &data );
13523 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_FAILED");
13527 void Player::SendQuestTimerFailed( uint32 quest_id )
13529 if( quest_id )
13531 WorldPacket data( SMSG_QUESTUPDATE_FAILEDTIMER, 4 );
13532 data << quest_id;
13533 GetSession()->SendPacket( &data );
13534 sLog.outDebug("WORLD: Sent SMSG_QUESTUPDATE_FAILEDTIMER");
13538 void Player::SendCanTakeQuestResponse( uint32 msg )
13540 WorldPacket data( SMSG_QUESTGIVER_QUEST_INVALID, 4 );
13541 data << uint32(msg);
13542 GetSession()->SendPacket( &data );
13543 sLog.outDebug("WORLD: Sent SMSG_QUESTGIVER_QUEST_INVALID");
13546 void Player::SendPushToPartyResponse( Player *pPlayer, uint32 msg )
13548 if( pPlayer )
13550 WorldPacket data( MSG_QUEST_PUSH_RESULT, (8+1) );
13551 data << uint64(pPlayer->GetGUID());
13552 data << uint8(msg); // valid values: 0-8
13553 GetSession()->SendPacket( &data );
13554 sLog.outDebug("WORLD: Sent MSG_QUEST_PUSH_RESULT");
13558 void Player::SendQuestUpdateAddItem( Quest const* pQuest, uint32 item_idx, uint32 count )
13560 WorldPacket data( SMSG_QUESTUPDATE_ADD_ITEM, 0 );
13561 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_ITEM" );
13562 //data << pQuest->ReqItemId[item_idx];
13563 //data << count;
13564 GetSession()->SendPacket( &data );
13567 void Player::SendQuestUpdateAddCreatureOrGo( Quest const* pQuest, uint64 guid, uint32 creatureOrGO_idx, uint32 old_count, uint32 add_count )
13569 assert(old_count + add_count < 256 && "mob/GO count store in 8 bits 2^8 = 256 (0..256)");
13571 int32 entry = pQuest->ReqCreatureOrGOId[ creatureOrGO_idx ];
13572 if (entry < 0)
13573 // client expected gameobject template id in form (id|0x80000000)
13574 entry = (-entry) | 0x80000000;
13576 WorldPacket data( SMSG_QUESTUPDATE_ADD_KILL, (4*4+8) );
13577 sLog.outDebug( "WORLD: Sent SMSG_QUESTUPDATE_ADD_KILL" );
13578 data << uint32(pQuest->GetQuestId());
13579 data << uint32(entry);
13580 data << uint32(old_count + add_count);
13581 data << uint32(pQuest->ReqCreatureOrGOCount[ creatureOrGO_idx ]);
13582 data << uint64(guid);
13583 GetSession()->SendPacket(&data);
13585 uint16 log_slot = FindQuestSlot( pQuest->GetQuestId() );
13586 if( log_slot < MAX_QUEST_LOG_SIZE)
13587 SetQuestSlotCounter(log_slot,creatureOrGO_idx,GetQuestSlotCounter(log_slot,creatureOrGO_idx)+add_count);
13590 /*********************************************************/
13591 /*** LOAD SYSTEM ***/
13592 /*********************************************************/
13594 bool Player::MinimalLoadFromDB( QueryResult *result, uint32 guid )
13596 bool delete_result = true;
13597 if(!result)
13599 // 0 1 2 3 4 5 6 7 8 9
13600 result = CharacterDatabase.PQuery("SELECT guid, data, name, position_x, position_y, position_z, map, totaltime, leveltime, at_login FROM characters WHERE guid = '%u'",guid);
13601 if(!result) return false;
13603 else delete_result = false;
13605 Field *fields = result->Fetch();
13607 if(!LoadValues( fields[1].GetString()))
13609 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
13610 if(delete_result) delete result;
13611 return false;
13614 // overwrite possible wrong/corrupted guid
13615 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13617 m_name = fields[2].GetCppString();
13619 Relocate(fields[3].GetFloat(),fields[4].GetFloat(),fields[5].GetFloat());
13620 SetMapId(fields[6].GetUInt32());
13621 // the instance id is not needed at character enum
13623 m_Played_time[0] = fields[7].GetUInt32();
13624 m_Played_time[1] = fields[8].GetUInt32();
13626 m_atLoginFlags = fields[9].GetUInt32();
13628 // I don't see these used anywhere ..
13629 /*_LoadGroup();
13631 _LoadBoundInstances();*/
13633 if (delete_result) delete result;
13635 for (int i = 0; i < PLAYER_SLOTS_COUNT; i++)
13636 m_items[i] = NULL;
13638 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
13639 m_deathState = DEAD;
13641 return true;
13644 void Player::_LoadDeclinedNames(QueryResult* result)
13646 if(!result)
13647 return;
13649 if(m_declinedname)
13650 delete m_declinedname;
13652 m_declinedname = new DeclinedName;
13653 Field *fields = result->Fetch();
13654 for(int i = 0; i < MAX_DECLINED_NAME_CASES; ++i)
13655 m_declinedname->name[i] = fields[i].GetCppString();
13657 delete result;
13660 bool Player::LoadPositionFromDB(uint32& mapid, float& x,float& y,float& z,float& o, bool& in_flight, uint64 guid)
13662 QueryResult *result = CharacterDatabase.PQuery("SELECT position_x,position_y,position_z,orientation,map,taxi_path FROM characters WHERE guid = '%u'",GUID_LOPART(guid));
13663 if(!result)
13664 return false;
13666 Field *fields = result->Fetch();
13668 x = fields[0].GetFloat();
13669 y = fields[1].GetFloat();
13670 z = fields[2].GetFloat();
13671 o = fields[3].GetFloat();
13672 mapid = fields[4].GetUInt32();
13673 in_flight = !fields[5].GetCppString().empty();
13675 delete result;
13676 return true;
13679 bool Player::LoadValuesArrayFromDB(Tokens& data, uint64 guid)
13681 QueryResult *result = CharacterDatabase.PQuery("SELECT data FROM characters WHERE guid='%u'",GUID_LOPART(guid));
13682 if( !result )
13683 return false;
13685 Field *fields = result->Fetch();
13687 data = StrSplit(fields[0].GetCppString(), " ");
13689 delete result;
13691 return true;
13694 uint32 Player::GetUInt32ValueFromArray(Tokens const& data, uint16 index)
13696 if(index >= data.size())
13697 return 0;
13699 return (uint32)atoi(data[index].c_str());
13702 float Player::GetFloatValueFromArray(Tokens const& data, uint16 index)
13704 float result;
13705 uint32 temp = Player::GetUInt32ValueFromArray(data,index);
13706 memcpy(&result, &temp, sizeof(result));
13708 return result;
13711 uint32 Player::GetUInt32ValueFromDB(uint16 index, uint64 guid)
13713 Tokens data;
13714 if(!LoadValuesArrayFromDB(data,guid))
13715 return 0;
13717 return GetUInt32ValueFromArray(data,index);
13720 float Player::GetFloatValueFromDB(uint16 index, uint64 guid)
13722 float result;
13723 uint32 temp = Player::GetUInt32ValueFromDB(index, guid);
13724 memcpy(&result, &temp, sizeof(result));
13726 return result;
13729 bool Player::LoadFromDB( uint32 guid, SqlQueryHolder *holder )
13731 //// 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
13732 //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);
13733 QueryResult *result = holder->GetResult(PLAYER_LOGIN_QUERY_LOADFROM);
13735 if(!result)
13737 sLog.outError("ERROR: Player (GUID: %u) not found in table `characters`, can't load. ",guid);
13738 return false;
13741 Field *fields = result->Fetch();
13743 uint32 dbAccountId = fields[1].GetUInt32();
13745 // check if the character's account in the db and the logged in account match.
13746 // player should be able to load/delete character only with correct account!
13747 if( dbAccountId != GetSession()->GetAccountId() )
13749 sLog.outError("ERROR: Player (GUID: %u) loading from wrong account (is: %u, should be: %u)",guid,GetSession()->GetAccountId(),dbAccountId);
13750 delete result;
13751 return false;
13754 Object::_Create( guid, 0, HIGHGUID_PLAYER );
13756 m_name = fields[3].GetCppString();
13758 // check name limitations
13759 if(!ObjectMgr::IsValidName(m_name) || GetSession()->GetSecurity() == SEC_PLAYER && objmgr.IsReservedName(m_name))
13761 delete result;
13762 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login | '%u' WHERE guid ='%u'", uint32(AT_LOGIN_RENAME),guid);
13763 return false;
13766 if(!LoadValues( fields[2].GetString()))
13768 sLog.outError("ERROR: Player #%d have broken data in `data` field. Can't be loaded.",GUID_LOPART(guid));
13769 delete result;
13770 return false;
13773 // overwrite possible wrong/corrupted guid
13774 SetUInt64Value(OBJECT_FIELD_GUID, MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER));
13776 // cleanup inventory related item value fields (its will be filled correctly in _LoadInventory)
13777 for(uint8 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
13779 SetUInt64Value( (uint16)(PLAYER_FIELD_INV_SLOT_HEAD + (slot * 2) ), 0 );
13780 SetVisibleItemSlot(slot,NULL);
13782 if (m_items[slot])
13784 delete m_items[slot];
13785 m_items[slot] = NULL;
13789 // update money limits
13790 if(GetMoney() > MAX_MONEY_AMOUNT)
13791 SetMoney(MAX_MONEY_AMOUNT);
13793 sLog.outDebug("Load Basic value of player %s is: ", m_name.c_str());
13794 outDebugValues();
13796 m_race = fields[4].GetUInt8();
13797 //Need to call it to initialize m_team (m_team can be calculated from m_race)
13798 //Other way is to saves m_team into characters table.
13799 setFactionForRace(m_race);
13800 SetCharm(0);
13802 m_class = fields[5].GetUInt8();
13804 PlayerInfo const *info = objmgr.GetPlayerInfo(m_race, m_class);
13805 if(!info)
13807 sLog.outError("Player have incorrect race/class pair. Can't be loaded.");
13808 delete result;
13809 return false;
13812 InitPrimaryProffesions(); // to max set before any spell loaded
13814 uint32 transGUID = fields[24].GetUInt32();
13815 Relocate(fields[6].GetFloat(),fields[7].GetFloat(),fields[8].GetFloat(),fields[10].GetFloat());
13816 SetFallInformation(0, fields[8].GetFloat());
13817 SetMapId(fields[9].GetUInt32());
13818 SetDifficulty(fields[32].GetUInt32()); // may be changed in _LoadGroup
13820 _LoadGroup(holder->GetResult(PLAYER_LOGIN_QUERY_LOADGROUP));
13822 // check arena teams integrity
13823 for(uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
13825 uint32 arena_team_id = GetArenaTeamId(arena_slot);
13826 if(!arena_team_id)
13827 continue;
13829 if(ArenaTeam * at = objmgr.GetArenaTeamById(arena_team_id))
13830 if(at->HaveMember(GetGUID()))
13831 continue;
13833 // arena team not exist or not member, cleanup fields
13834 for(int j =0; j < 6; ++j)
13835 SetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + arena_slot * 6 + j, 0);
13838 _LoadBoundInstances(holder->GetResult(PLAYER_LOGIN_QUERY_LOADBOUNDINSTANCES));
13840 if(!IsPositionValid())
13842 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());
13844 SetMapId(info->mapId);
13845 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
13847 transGUID = 0;
13849 m_movementInfo.t_x = 0.0f;
13850 m_movementInfo.t_y = 0.0f;
13851 m_movementInfo.t_z = 0.0f;
13852 m_movementInfo.t_o = 0.0f;
13855 // load the player's map here if it's not already loaded
13856 Map *map = GetMap();
13857 // since the player may not be bound to the map yet, make sure subsequent
13858 // getmap calls won't create new maps
13859 SetInstanceId(map->GetInstanceId());
13861 SaveRecallPosition();
13863 if (transGUID != 0)
13865 m_movementInfo.t_x = fields[20].GetFloat();
13866 m_movementInfo.t_y = fields[21].GetFloat();
13867 m_movementInfo.t_z = fields[22].GetFloat();
13868 m_movementInfo.t_o = fields[23].GetFloat();
13870 if( !MaNGOS::IsValidMapCoord(
13871 GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13872 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o) ||
13873 // transport size limited
13874 m_movementInfo.t_x > 50 || m_movementInfo.t_y > 50 || m_movementInfo.t_z > 50 )
13876 sLog.outError("ERROR: Player (guidlow %d) have invalid transport coordinates (X: %f Y: %f Z: %f O: %f). Teleport to default race/class locations.",
13877 guid,GetPositionX()+m_movementInfo.t_x,GetPositionY()+m_movementInfo.t_y,
13878 GetPositionZ()+m_movementInfo.t_z,GetOrientation()+m_movementInfo.t_o);
13880 SetMapId(info->mapId);
13881 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
13883 m_movementInfo.t_x = 0.0f;
13884 m_movementInfo.t_y = 0.0f;
13885 m_movementInfo.t_z = 0.0f;
13886 m_movementInfo.t_o = 0.0f;
13888 transGUID = 0;
13892 if (transGUID != 0)
13894 for (MapManager::TransportSet::iterator iter = MapManager::Instance().m_Transports.begin(); iter != MapManager::Instance().m_Transports.end(); ++iter)
13896 if( (*iter)->GetGUIDLow() == transGUID)
13898 m_transport = *iter;
13899 m_transport->AddPassenger(this);
13900 SetMapId(m_transport->GetMapId());
13901 break;
13905 if(!m_transport)
13907 sLog.outError("ERROR: Player (guidlow %d) have invalid transport guid (%u). Teleport to default race/class locations.",
13908 guid,transGUID);
13910 SetMapId(info->mapId);
13911 Relocate(info->positionX,info->positionY,info->positionZ,0.0f);
13913 m_movementInfo.t_x = 0.0f;
13914 m_movementInfo.t_y = 0.0f;
13915 m_movementInfo.t_z = 0.0f;
13916 m_movementInfo.t_o = 0.0f;
13918 transGUID = 0;
13922 time_t now = time(NULL);
13923 time_t logoutTime = time_t(fields[16].GetUInt64());
13925 // since last logout (in seconds)
13926 uint64 time_diff = uint64(now - logoutTime);
13928 // set value, including drunk invisibility detection
13929 // calculate sobering. after 15 minutes logged out, the player will be sober again
13930 float soberFactor;
13931 if(time_diff > 15*MINUTE)
13932 soberFactor = 0;
13933 else
13934 soberFactor = 1-time_diff/(15.0f*MINUTE);
13935 uint16 newDrunkenValue = uint16(soberFactor*(GetUInt32Value(PLAYER_BYTES_3) & 0xFFFE));
13936 SetDrunkValue(newDrunkenValue);
13938 m_rest_bonus = fields[15].GetFloat();
13939 //speed collect rest bonus in offline, in logout, far from tavern, city (section/in hour)
13940 float bubble0 = 0.031;
13941 //speed collect rest bonus in offline, in logout, in tavern, city (section/in hour)
13942 float bubble1 = 0.125;
13944 if((int32)fields[16].GetUInt32() > 0)
13946 float bubble = fields[17].GetUInt32() > 0
13947 ? bubble1*sWorld.getRate(RATE_REST_OFFLINE_IN_TAVERN_OR_CITY)
13948 : bubble0*sWorld.getRate(RATE_REST_OFFLINE_IN_WILDERNESS);
13950 SetRestBonus(GetRestBonus()+ time_diff*((float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)/72000)*bubble);
13953 m_cinematic = fields[12].GetUInt32();
13954 m_Played_time[0]= fields[13].GetUInt32();
13955 m_Played_time[1]= fields[14].GetUInt32();
13957 m_resetTalentsCost = fields[18].GetUInt32();
13958 m_resetTalentsTime = time_t(fields[19].GetUInt64());
13960 // reserve some flags
13961 uint32 old_safe_flags = GetUInt32Value(PLAYER_FLAGS) & ( PLAYER_FLAGS_HIDE_CLOAK | PLAYER_FLAGS_HIDE_HELM );
13963 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GM) )
13964 SetUInt32Value(PLAYER_FLAGS, 0 | old_safe_flags);
13966 m_taxi.LoadTaxiMask( fields[11].GetString() ); // must be before InitTaxiNodesForLevel
13968 uint32 extraflags = fields[25].GetUInt32();
13970 m_stableSlots = fields[26].GetUInt32();
13971 if(m_stableSlots > 4)
13973 sLog.outError("Player can have not more 4 stable slots, but have in DB %u",uint32(m_stableSlots));
13974 m_stableSlots = 4;
13977 m_atLoginFlags = fields[27].GetUInt32();
13979 // Honor system
13980 // Update Honor kills data
13981 m_lastHonorUpdateTime = logoutTime;
13982 UpdateHonorFields();
13984 m_deathExpireTime = (time_t)fields[30].GetUInt64();
13985 if(m_deathExpireTime > now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP)
13986 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP-1;
13988 std::string taxi_nodes = fields[31].GetCppString();
13990 delete result;
13992 // clear channel spell data (if saved at channel spell casting)
13993 SetUInt64Value(UNIT_FIELD_CHANNEL_OBJECT, 0);
13994 SetUInt32Value(UNIT_CHANNEL_SPELL,0);
13996 // clear charm/summon related fields
13997 SetCharm(NULL);
13998 SetPet(NULL);
13999 SetCharmerGUID(NULL);
14000 SetOwnerGUID(NULL);
14001 SetCreatorGUID(NULL);
14003 // reset some aura modifiers before aura apply
14004 SetFarSight(NULL);
14005 SetUInt32Value(PLAYER_TRACK_CREATURES, 0 );
14006 SetUInt32Value(PLAYER_TRACK_RESOURCES, 0 );
14008 // reset skill modifiers and set correct unlearn flags
14009 for (uint32 i = 0; i < PLAYER_MAX_SKILLS; i++)
14011 SetUInt32Value(PLAYER_SKILL_BONUS_INDEX(i),0);
14013 // set correct unlearn bit
14014 uint32 id = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
14015 if(!id) continue;
14017 SkillLineEntry const *pSkill = sSkillLineStore.LookupEntry(id);
14018 if(!pSkill) continue;
14020 // enable unlearn button for primary professions only
14021 if (pSkill->categoryId == SKILL_CATEGORY_PROFESSION)
14022 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,1));
14023 else
14024 SetUInt32Value(PLAYER_SKILL_INDEX(i), MAKE_PAIR32(id,0));
14027 // make sure the unit is considered out of combat for proper loading
14028 ClearInCombat();
14030 // make sure the unit is considered not in duel for proper loading
14031 SetUInt64Value(PLAYER_DUEL_ARBITER, 0);
14032 SetUInt32Value(PLAYER_DUEL_TEAM, 0);
14034 // remember loaded power/health values to restore after stats initialization and modifier applying
14035 uint32 savedHealth = GetHealth();
14036 uint32 savedPower[MAX_POWERS];
14037 for(uint32 i = 0; i < MAX_POWERS; ++i)
14038 savedPower[i] = GetPower(Powers(i));
14040 // reset stats before loading any modifiers
14041 InitStatsForLevel();
14042 InitTaxiNodesForLevel();
14043 InitGlyphsForLevel();
14044 InitRunes();
14046 // apply original stats mods before spell loading or item equipment that call before equip _RemoveStatsMods()
14048 //mails are loaded only when needed ;-) - when player in game click on mailbox.
14049 //_LoadMail();
14051 _LoadAuras(holder->GetResult(PLAYER_LOGIN_QUERY_LOADAURAS), time_diff);
14053 // add ghost flag (must be after aura load: PLAYER_FLAGS_GHOST set in aura)
14054 if( HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_GHOST) )
14055 m_deathState = DEAD;
14057 _LoadSpells(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLS));
14059 // after spell load
14060 InitTalentForLevel();
14061 learnSkillRewardedSpells();
14063 // after spell load, learn rewarded spell if need also
14064 _LoadQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADQUESTSTATUS));
14065 _LoadDailyQuestStatus(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDAILYQUESTSTATUS));
14067 _LoadTutorials(holder->GetResult(PLAYER_LOGIN_QUERY_LOADTUTORIALS));
14069 // must be before inventory (some items required reputation check)
14070 _LoadReputation(holder->GetResult(PLAYER_LOGIN_QUERY_LOADREPUTATION));
14072 _LoadInventory(holder->GetResult(PLAYER_LOGIN_QUERY_LOADINVENTORY), time_diff);
14074 // update items with duration and realtime
14075 UpdateItemDuration(time_diff, true);
14077 _LoadActions(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACTIONS));
14079 // unread mails and next delivery time, actual mails not loaded
14080 _LoadMailInit(holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILCOUNT), holder->GetResult(PLAYER_LOGIN_QUERY_LOADMAILDATE));
14082 m_social = sSocialMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSOCIALLIST), GetGUIDLow());
14084 if(!_LoadHomeBind(holder->GetResult(PLAYER_LOGIN_QUERY_LOADHOMEBIND)))
14085 return false;
14087 // check PLAYER_CHOSEN_TITLE compatibility with PLAYER__FIELD_KNOWN_TITLES
14088 // note: PLAYER__FIELD_KNOWN_TITLES updated at quest status loaded
14089 if(uint32 curTitle = GetUInt32Value(PLAYER_CHOSEN_TITLE))
14091 if(!HasTitle(curTitle))
14092 SetUInt32Value(PLAYER_CHOSEN_TITLE,0);
14095 // Not finish taxi flight path
14096 if(!m_taxi.LoadTaxiDestinationsFromString(taxi_nodes))
14098 // problems with taxi path loading
14099 TaxiNodesEntry const* nodeEntry = NULL;
14100 if(uint32 node_id = m_taxi.GetTaxiSource())
14101 nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14103 if(!nodeEntry) // don't know taxi start node, to homebind
14105 sLog.outError("Character %u have wrong data in taxi destination list, teleport to homebind.",GetGUIDLow());
14106 SetMapId(m_homebindMapId);
14107 Relocate( m_homebindX, m_homebindY, m_homebindZ,0.0f);
14108 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14110 else // have start node, to it
14112 sLog.outError("Character %u have too short taxi destination list, teleport to original node.",GetGUIDLow());
14113 SetMapId(nodeEntry->map_id);
14114 Relocate(nodeEntry->x, nodeEntry->y, nodeEntry->z,0.0f);
14115 SaveRecallPosition(); // save as recall also to prevent recall and fall from sky
14117 m_taxi.ClearTaxiDestinations();
14119 else if(uint32 node_id = m_taxi.GetTaxiSource())
14121 // save source node as recall coord to prevent recall and fall from sky
14122 TaxiNodesEntry const* nodeEntry = sTaxiNodesStore.LookupEntry(node_id);
14123 assert(nodeEntry); // checked in m_taxi.LoadTaxiDestinationsFromString
14124 m_recallMap = nodeEntry->map_id;
14125 m_recallX = nodeEntry->x;
14126 m_recallY = nodeEntry->y;
14127 m_recallZ = nodeEntry->z;
14129 // flight will started later
14132 _LoadSpellCooldowns(holder->GetResult(PLAYER_LOGIN_QUERY_LOADSPELLCOOLDOWNS));
14134 // Spell code allow apply any auras to dead character in load time in aura/spell/item loading
14135 // Do now before stats re-calculation cleanup for ghost state unexpected auras
14136 if(!isAlive())
14137 RemoveAllAurasOnDeath();
14139 //apply all stat bonuses from items and auras
14140 SetCanModifyStats(true);
14141 UpdateAllStats();
14143 // restore remembered power/health values (but not more max values)
14144 SetHealth(savedHealth > GetMaxHealth() ? GetMaxHealth() : savedHealth);
14145 for(uint32 i = 0; i < MAX_POWERS; ++i)
14146 SetPower(Powers(i),savedPower[i] > GetMaxPower(Powers(i)) ? GetMaxPower(Powers(i)) : savedPower[i]);
14148 sLog.outDebug("The value of player %s after load item and aura is: ", m_name.c_str());
14149 outDebugValues();
14151 // GM state
14152 if(GetSession()->GetSecurity() > SEC_PLAYER)
14154 switch(sWorld.getConfig(CONFIG_GM_LOGIN_STATE))
14156 default:
14157 case 0: break; // disable
14158 case 1: SetGameMaster(true); break; // enable
14159 case 2: // save state
14160 if(extraflags & PLAYER_EXTRA_GM_ON)
14161 SetGameMaster(true);
14162 break;
14165 switch(sWorld.getConfig(CONFIG_GM_ACCEPT_TICKETS))
14167 default:
14168 case 0: break; // disable
14169 case 1: SetAcceptTicket(true); break; // enable
14170 case 2: // save state
14171 if(extraflags & PLAYER_EXTRA_GM_ACCEPT_TICKETS)
14172 SetAcceptTicket(true);
14173 break;
14176 switch(sWorld.getConfig(CONFIG_GM_CHAT))
14178 default:
14179 case 0: break; // disable
14180 case 1: SetGMChat(true); break; // enable
14181 case 2: // save state
14182 if(extraflags & PLAYER_EXTRA_GM_CHAT)
14183 SetGMChat(true);
14184 break;
14187 switch(sWorld.getConfig(CONFIG_GM_WISPERING_TO))
14189 default:
14190 case 0: break; // disable
14191 case 1: SetAcceptWhispers(true); break; // enable
14192 case 2: // save state
14193 if(extraflags & PLAYER_EXTRA_ACCEPT_WHISPERS)
14194 SetAcceptWhispers(true);
14195 break;
14199 _LoadDeclinedNames(holder->GetResult(PLAYER_LOGIN_QUERY_LOADDECLINEDNAMES));
14201 m_achievementMgr.LoadFromDB(holder->GetResult(PLAYER_LOGIN_QUERY_LOADACHIEVEMENTS), holder->GetResult(PLAYER_LOGIN_QUERY_LOADCRITERIAPROGRESS));
14202 m_achievementMgr.CheckAllAchievementCriteria();
14203 return true;
14206 bool Player::isAllowedToLoot(Creature* creature)
14208 if(Player* recipient = creature->GetLootRecipient())
14210 if (recipient == this)
14211 return true;
14212 if( Group* otherGroup = recipient->GetGroup())
14214 Group* thisGroup = GetGroup();
14215 if(!thisGroup)
14216 return false;
14217 return thisGroup == otherGroup;
14219 return false;
14221 else
14222 // prevent other players from looting if the recipient got disconnected
14223 return !creature->hasLootRecipient();
14226 void Player::_LoadActions(QueryResult *result)
14228 m_actionButtons.clear();
14230 //QueryResult *result = CharacterDatabase.PQuery("SELECT button,action,type,misc FROM character_action WHERE guid = '%u' ORDER BY button",GetGUIDLow());
14232 if(result)
14236 Field *fields = result->Fetch();
14238 uint8 button = fields[0].GetUInt8();
14240 addActionButton(button, fields[1].GetUInt16(), fields[2].GetUInt8(), fields[3].GetUInt8());
14242 m_actionButtons[button].uState = ACTIONBUTTON_UNCHANGED;
14244 while( result->NextRow() );
14246 delete result;
14250 void Player::_LoadAuras(QueryResult *result, uint32 timediff)
14252 m_Auras.clear();
14253 for (int i = 0; i < TOTAL_AURAS; i++)
14254 m_modAuras[i].clear();
14256 //QueryResult *result = CharacterDatabase.PQuery("SELECT caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges FROM character_aura WHERE guid = '%u'",GetGUIDLow());
14258 if(result)
14262 Field *fields = result->Fetch();
14263 uint64 caster_guid = fields[0].GetUInt64();
14264 uint32 spellid = fields[1].GetUInt32();
14265 uint32 effindex = fields[2].GetUInt32();
14266 uint32 stackcount = fields[3].GetUInt32();
14267 int32 damage = (int32)fields[4].GetUInt32();
14268 int32 maxduration = (int32)fields[5].GetUInt32();
14269 int32 remaintime = (int32)fields[6].GetUInt32();
14270 int32 remaincharges = (int32)fields[7].GetUInt32();
14272 SpellEntry const* spellproto = sSpellStore.LookupEntry(spellid);
14273 if(!spellproto)
14275 sLog.outError("Unknown aura (spellid %u, effindex %u), ignore.",spellid,effindex);
14276 continue;
14279 if(effindex >= 3)
14281 sLog.outError("Invalid effect index (spellid %u, effindex %u), ignore.",spellid,effindex);
14282 continue;
14285 // negative effects should continue counting down after logout
14286 if (remaintime != -1 && !IsPositiveEffect(spellid, effindex))
14288 if(remaintime <= int32(timediff))
14289 continue;
14291 remaintime -= timediff;
14294 // prevent wrong values of remaincharges
14295 if(spellproto->procCharges)
14297 if(remaincharges <= 0 || remaincharges > spellproto->procCharges)
14298 remaincharges = spellproto->procCharges;
14300 else
14301 remaincharges = -1;
14303 //do not load single target auras (unless they were cast by the player)
14304 if (caster_guid != GetGUID() && IsSingleTargetSpell(spellproto))
14305 continue;
14307 for(uint32 i=0; i<stackcount; i++)
14309 Aura* aura = CreateAura(spellproto, effindex, NULL, this, NULL);
14310 if(!damage)
14311 damage = aura->GetModifier()->m_amount;
14312 aura->SetLoadedState(caster_guid,damage,maxduration,remaintime,remaincharges);
14313 AddAura(aura);
14314 sLog.outString("Added aura spellid %u, effect %u", spellproto->Id, effindex);
14317 while( result->NextRow() );
14319 delete result;
14322 if(m_class == CLASS_WARRIOR)
14323 CastSpell(this,SPELL_ID_PASSIVE_BATTLE_STANCE,true);
14326 void Player::LoadCorpse()
14328 if( isAlive() )
14330 ObjectAccessor::Instance().ConvertCorpseForPlayer(GetGUID());
14332 else
14334 if(Corpse *corpse = GetCorpse())
14336 ApplyModFlag(PLAYER_FIELD_BYTES, PLAYER_FIELD_BYTE_RELEASE_TIMER, corpse && !sMapStore.LookupEntry(corpse->GetMapId())->Instanceable() );
14338 else
14340 //Prevent Dead Player login without corpse
14341 ResurrectPlayer(0.5f);
14346 void Player::_LoadInventory(QueryResult *result, uint32 timediff)
14348 //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());
14349 std::map<uint64, Bag*> bagMap; // fast guid lookup for bags
14350 //NOTE: the "order by `bag`" is important because it makes sure
14351 //the bagMap is filled before items in the bags are loaded
14352 //NOTE2: the "order by `slot`" is needed because mainhand weapons are (wrongly?)
14353 //expected to be equipped before offhand items (TODO: fixme)
14355 uint32 zone = GetZoneId();
14357 if (result)
14359 std::list<Item*> problematicItems;
14361 // prevent items from being added to the queue when stored
14362 m_itemUpdateQueueBlocked = true;
14365 Field *fields = result->Fetch();
14366 uint32 bag_guid = fields[1].GetUInt32();
14367 uint8 slot = fields[2].GetUInt8();
14368 uint32 item_guid = fields[3].GetUInt32();
14369 uint32 item_id = fields[4].GetUInt32();
14371 ItemPrototype const * proto = objmgr.GetItemPrototype(item_id);
14373 if(!proto)
14375 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14376 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid);
14377 sLog.outError( "Player::_LoadInventory: Player %s has an unknown item (id: #%u) in inventory, deleted.", GetName(),item_id );
14378 continue;
14381 Item *item = NewItemOrBag(proto);
14383 if(!item->LoadFromDB(item_guid, GetGUID(), result))
14385 sLog.outError( "Player::_LoadInventory: Player %s has broken item (id: #%u) in inventory, deleted.", GetName(),item_id );
14386 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14387 item->FSetState(ITEM_REMOVED);
14388 item->SaveToDB(); // it also deletes item object !
14389 continue;
14392 // not allow have in alive state item limited to another map/zone
14393 if(isAlive() && item->IsLimitedToAnotherMapOrZone(GetMapId(),zone) )
14395 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14396 item->FSetState(ITEM_REMOVED);
14397 item->SaveToDB(); // it also deletes item object !
14398 continue;
14401 // "Conjured items disappear if you are logged out for more than 15 minutes"
14402 if ((timediff > 15*60) && (item->HasFlag(ITEM_FIELD_FLAGS, ITEM_FLAGS_CONJURED)))
14404 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14405 item->FSetState(ITEM_REMOVED);
14406 item->SaveToDB(); // it also deletes item object !
14407 continue;
14410 bool success = true;
14412 if (!bag_guid)
14414 // the item is not in a bag
14415 item->SetContainer( NULL );
14416 item->SetSlot(slot);
14418 if( IsInventoryPos( INVENTORY_SLOT_BAG_0, slot ) )
14420 ItemPosCountVec dest;
14421 if( CanStoreItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false ) == EQUIP_ERR_OK )
14422 item = StoreItem(dest, item, true);
14423 else
14424 success = false;
14426 else if( IsEquipmentPos( INVENTORY_SLOT_BAG_0, slot ) )
14428 uint16 dest;
14429 if( CanEquipItem( slot, dest, item, false, false ) == EQUIP_ERR_OK )
14430 QuickEquipItem(dest, item);
14431 else
14432 success = false;
14434 else if( IsBankPos( INVENTORY_SLOT_BAG_0, slot ) )
14436 ItemPosCountVec dest;
14437 if( CanBankItem( INVENTORY_SLOT_BAG_0, slot, dest, item, false, false ) == EQUIP_ERR_OK )
14438 item = BankItem(dest, item, true);
14439 else
14440 success = false;
14443 if(success)
14445 // store bags that may contain items in them
14446 if(item->IsBag() && IsBagPos(item->GetPos()))
14447 bagMap[item_guid] = (Bag*)item;
14450 else
14452 item->SetSlot(NULL_SLOT);
14453 // the item is in a bag, find the bag
14454 std::map<uint64, Bag*>::iterator itr = bagMap.find(bag_guid);
14455 if(itr != bagMap.end())
14456 itr->second->StoreItem(slot, item, true );
14457 else
14458 success = false;
14461 // item's state may have changed after stored
14462 if (success)
14463 item->SetState(ITEM_UNCHANGED, this);
14464 else
14466 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);
14467 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item_guid);
14468 problematicItems.push_back(item);
14470 } while (result->NextRow());
14472 delete result;
14473 m_itemUpdateQueueBlocked = false;
14475 // send by mail problematic items
14476 while(!problematicItems.empty())
14478 // fill mail
14479 MailItemsInfo mi; // item list preparing
14481 for(int i = 0; !problematicItems.empty() && i < MAX_MAIL_ITEMS; ++i)
14483 Item* item = problematicItems.front();
14484 problematicItems.pop_front();
14486 mi.AddItem(item->GetGUIDLow(), item->GetEntry(), item);
14489 std::string subject = GetSession()->GetMangosString(LANG_NOT_EQUIPPED_ITEM);
14491 WorldSession::SendMailTo(this, MAIL_NORMAL, MAIL_STATIONERY_GM, GetGUIDLow(), GetGUIDLow(), subject, 0, &mi, 0, 0, MAIL_CHECK_MASK_NONE);
14494 //if(isAlive())
14495 _ApplyAllItemMods();
14498 // load mailed item which should receive current player
14499 void Player::_LoadMailedItems(Mail *mail)
14501 QueryResult* result = CharacterDatabase.PQuery("SELECT item_guid, item_template FROM mail_items WHERE mail_id='%u'", mail->messageID);
14502 if(!result)
14503 return;
14507 Field *fields = result->Fetch();
14508 uint32 item_guid_low = fields[0].GetUInt32();
14509 uint32 item_template = fields[1].GetUInt32();
14511 mail->AddItem(item_guid_low, item_template);
14513 ItemPrototype const *proto = objmgr.GetItemPrototype(item_template);
14515 if(!proto)
14517 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);
14518 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14519 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item_guid_low);
14520 continue;
14523 Item *item = NewItemOrBag(proto);
14525 if(!item->LoadFromDB(item_guid_low, 0))
14527 sLog.outError( "Player::_LoadMailedItems - Item in mail (%u) doesn't exist !!!! - item guid: %u, deleted from mail", mail->messageID, item_guid_low);
14528 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", item_guid_low);
14529 item->FSetState(ITEM_REMOVED);
14530 item->SaveToDB(); // it also deletes item object !
14531 continue;
14534 AddMItem(item);
14535 } while (result->NextRow());
14537 delete result;
14540 void Player::_LoadMailInit(QueryResult *resultUnread, QueryResult *resultDelivery)
14542 //set a count of unread mails
14543 //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);
14544 if (resultUnread)
14546 Field *fieldMail = resultUnread->Fetch();
14547 unReadMails = fieldMail[0].GetUInt8();
14548 delete resultUnread;
14551 // store nearest delivery time (it > 0 and if it < current then at next player update SendNewMaill will be called)
14552 //resultMails = CharacterDatabase.PQuery("SELECT MIN(deliver_time) FROM mail WHERE receiver = '%u' AND (checked & 1)=0", GUID_LOPART(playerGuid));
14553 if (resultDelivery)
14555 Field *fieldMail = resultDelivery->Fetch();
14556 m_nextMailDelivereTime = (time_t)fieldMail[0].GetUInt64();
14557 delete resultDelivery;
14561 void Player::_LoadMail()
14563 m_mail.clear();
14564 //mails are in right order 0 1 2 3 4 5 6 7 8 9 10 11 12 13
14565 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());
14566 if(result)
14570 Field *fields = result->Fetch();
14571 Mail *m = new Mail;
14572 m->messageID = fields[0].GetUInt32();
14573 m->messageType = fields[1].GetUInt8();
14574 m->sender = fields[2].GetUInt32();
14575 m->receiver = fields[3].GetUInt32();
14576 m->subject = fields[4].GetCppString();
14577 m->itemTextId = fields[5].GetUInt32();
14578 bool has_items = fields[6].GetBool();
14579 m->expire_time = (time_t)fields[7].GetUInt64();
14580 m->deliver_time = (time_t)fields[8].GetUInt64();
14581 m->money = fields[9].GetUInt32();
14582 m->COD = fields[10].GetUInt32();
14583 m->checked = fields[11].GetUInt32();
14584 m->stationery = fields[12].GetUInt8();
14585 m->mailTemplateId = fields[13].GetInt16();
14587 if(m->mailTemplateId && !sMailTemplateStore.LookupEntry(m->mailTemplateId))
14589 sLog.outError( "Player::_LoadMail - Mail (%u) have not existed MailTemplateId (%u), remove at load", m->messageID, m->mailTemplateId);
14590 m->mailTemplateId = 0;
14593 m->state = MAIL_STATE_UNCHANGED;
14595 if (has_items)
14596 _LoadMailedItems(m);
14598 m_mail.push_back(m);
14599 } while( result->NextRow() );
14600 delete result;
14602 m_mailsLoaded = true;
14605 void Player::LoadPet()
14607 //fixme: the pet should still be loaded if the player is not in world
14608 // just not added to the map
14609 if(IsInWorld())
14611 Pet *pet = new Pet;
14612 if(!pet->LoadPetFromDB(this,0,0,true))
14613 delete pet;
14617 void Player::_LoadQuestStatus(QueryResult *result)
14619 mQuestStatus.clear();
14621 uint32 slot = 0;
14623 //// 0 1 2 3 4 5 6 7 8 9 10 11 12
14624 //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());
14626 if(result)
14630 Field *fields = result->Fetch();
14632 uint32 quest_id = fields[0].GetUInt32();
14633 // used to be new, no delete?
14634 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14635 if( pQuest )
14637 // find or create
14638 QuestStatusData& questStatusData = mQuestStatus[quest_id];
14640 uint32 qstatus = fields[1].GetUInt32();
14641 if(qstatus < MAX_QUEST_STATUS)
14642 questStatusData.m_status = QuestStatus(qstatus);
14643 else
14645 questStatusData.m_status = QUEST_STATUS_NONE;
14646 sLog.outError("Player %s have invalid quest %d status (%d), replaced by QUEST_STATUS_NONE(0).",GetName(),quest_id,qstatus);
14649 questStatusData.m_rewarded = ( fields[2].GetUInt8() > 0 );
14650 questStatusData.m_explored = ( fields[3].GetUInt8() > 0 );
14652 time_t quest_time = time_t(fields[4].GetUInt64());
14654 if( pQuest->HasFlag( QUEST_MANGOS_FLAGS_TIMED ) && !GetQuestRewardStatus(quest_id) && questStatusData.m_status != QUEST_STATUS_NONE )
14656 AddTimedQuest( quest_id );
14658 if (quest_time <= sWorld.GetGameTime())
14659 questStatusData.m_timer = 1;
14660 else
14661 questStatusData.m_timer = (quest_time - sWorld.GetGameTime()) * 1000;
14663 else
14664 quest_time = 0;
14666 questStatusData.m_creatureOrGOcount[0] = fields[5].GetUInt32();
14667 questStatusData.m_creatureOrGOcount[1] = fields[6].GetUInt32();
14668 questStatusData.m_creatureOrGOcount[2] = fields[7].GetUInt32();
14669 questStatusData.m_creatureOrGOcount[3] = fields[8].GetUInt32();
14670 questStatusData.m_itemcount[0] = fields[9].GetUInt32();
14671 questStatusData.m_itemcount[1] = fields[10].GetUInt32();
14672 questStatusData.m_itemcount[2] = fields[11].GetUInt32();
14673 questStatusData.m_itemcount[3] = fields[12].GetUInt32();
14675 questStatusData.uState = QUEST_UNCHANGED;
14677 // add to quest log
14678 if( slot < MAX_QUEST_LOG_SIZE &&
14679 ( questStatusData.m_status==QUEST_STATUS_INCOMPLETE ||
14680 questStatusData.m_status==QUEST_STATUS_COMPLETE &&
14681 (!questStatusData.m_rewarded || pQuest->IsDaily()) ) )
14683 SetQuestSlot(slot,quest_id,quest_time);
14685 if(questStatusData.m_status == QUEST_STATUS_COMPLETE)
14686 SetQuestSlotState(slot,QUEST_STATE_COMPLETE);
14688 for(uint8 idx = 0; idx < QUEST_OBJECTIVES_COUNT; ++idx)
14689 if(questStatusData.m_creatureOrGOcount[idx])
14690 SetQuestSlotCounter(slot,idx,questStatusData.m_creatureOrGOcount[idx]);
14692 ++slot;
14695 if(questStatusData.m_rewarded)
14697 // learn rewarded spell if unknown
14698 learnQuestRewardedSpells(pQuest);
14700 // set rewarded title if any
14701 if(pQuest->GetCharTitleId())
14703 if(CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(pQuest->GetCharTitleId()))
14704 SetTitle(titleEntry);
14708 sLog.outDebug("Quest status is {%u} for quest {%u} for player (GUID: %u)", questStatusData.m_status, quest_id, GetGUIDLow());
14711 while( result->NextRow() );
14713 delete result;
14716 // clear quest log tail
14717 for ( uint16 i = slot; i < MAX_QUEST_LOG_SIZE; ++i )
14718 SetQuestSlot(i,0);
14721 void Player::_LoadDailyQuestStatus(QueryResult *result)
14723 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
14724 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
14726 //QueryResult *result = CharacterDatabase.PQuery("SELECT quest,time FROM character_queststatus_daily WHERE guid = '%u'", GetGUIDLow());
14728 if(result)
14730 uint32 quest_daily_idx = 0;
14734 if(quest_daily_idx >= PLAYER_MAX_DAILY_QUESTS) // max amount with exist data in query
14736 sLog.outError("Player (GUID: %u) have more 25 daily quest records in `charcter_queststatus_daily`",GetGUIDLow());
14737 break;
14740 Field *fields = result->Fetch();
14742 uint32 quest_id = fields[0].GetUInt32();
14744 // save _any_ from daily quest times (it must be after last reset anyway)
14745 m_lastDailyQuestTime = (time_t)fields[1].GetUInt64();
14747 Quest const* pQuest = objmgr.GetQuestTemplate(quest_id);
14748 if( !pQuest )
14749 continue;
14751 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
14752 ++quest_daily_idx;
14754 sLog.outDebug("Daily quest {%u} cooldown for player (GUID: %u)", quest_id, GetGUIDLow());
14756 while( result->NextRow() );
14758 delete result;
14761 m_DailyQuestChanged = false;
14764 void Player::_LoadReputation(QueryResult *result)
14766 m_factions.clear();
14768 // Set initial reputations (so everything is nifty before DB data load)
14769 SetInitialFactions();
14771 //QueryResult *result = CharacterDatabase.PQuery("SELECT faction,standing,flags FROM character_reputation WHERE guid = '%u'",GetGUIDLow());
14773 if(result)
14777 Field *fields = result->Fetch();
14779 FactionEntry const *factionEntry = sFactionStore.LookupEntry(fields[0].GetUInt32());
14780 if( factionEntry && (factionEntry->reputationListID >= 0))
14782 FactionState* faction = &m_factions[factionEntry->reputationListID];
14784 // update standing to current
14785 faction->Standing = int32(fields[1].GetUInt32());
14787 uint32 dbFactionFlags = fields[2].GetUInt32();
14789 if( dbFactionFlags & FACTION_FLAG_VISIBLE )
14790 SetFactionVisible(faction); // have internal checks for forced invisibility
14792 if( dbFactionFlags & FACTION_FLAG_INACTIVE)
14793 SetFactionInactive(faction,true); // have internal checks for visibility requirement
14795 if( dbFactionFlags & FACTION_FLAG_AT_WAR ) // DB at war
14796 SetFactionAtWar(faction,true); // have internal checks for FACTION_FLAG_PEACE_FORCED
14797 else // DB not at war
14799 // allow remove if visible (and then not FACTION_FLAG_INVISIBLE_FORCED or FACTION_FLAG_HIDDEN)
14800 if( faction->Flags & FACTION_FLAG_VISIBLE )
14801 SetFactionAtWar(faction,false); // have internal checks for FACTION_FLAG_PEACE_FORCED
14804 // set atWar for hostile
14805 if(GetReputationRank(factionEntry) <= REP_HOSTILE)
14806 SetFactionAtWar(faction,true);
14808 // reset changed flag if values similar to saved in DB
14809 if(faction->Flags==dbFactionFlags)
14810 faction->Changed = false;
14813 while( result->NextRow() );
14815 delete result;
14819 void Player::_LoadSpells(QueryResult *result)
14821 for (PlayerSpellMap::iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
14822 delete itr->second;
14823 m_spells.clear();
14825 //QueryResult *result = CharacterDatabase.PQuery("SELECT spell,slot,active FROM character_spell WHERE guid = '%u'",GetGUIDLow());
14827 if(result)
14831 Field *fields = result->Fetch();
14833 addSpell(fields[0].GetUInt16(), fields[2].GetBool(), false, true, fields[1].GetUInt16(), fields[3].GetBool());
14835 while( result->NextRow() );
14837 delete result;
14841 void Player::_LoadTutorials(QueryResult *result)
14843 //QueryResult *result = CharacterDatabase.PQuery("SELECT tut0,tut1,tut2,tut3,tut4,tut5,tut6,tut7 FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetAccountId(), realmid);
14845 if(result)
14849 Field *fields = result->Fetch();
14851 for (int iI=0; iI<8; iI++)
14852 m_Tutorials[iI] = fields[iI].GetUInt32();
14854 while( result->NextRow() );
14856 delete result;
14859 m_TutorialsChanged = false;
14862 void Player::_LoadGroup(QueryResult *result)
14864 //QueryResult *result = CharacterDatabase.PQuery("SELECT leaderGuid FROM group_member WHERE memberGuid='%u'", GetGUIDLow());
14865 if(result)
14867 uint64 leaderGuid = MAKE_NEW_GUID((*result)[0].GetUInt32(), 0, HIGHGUID_PLAYER);
14868 delete result;
14869 Group* group = objmgr.GetGroupByLeader(leaderGuid);
14870 if(group)
14872 uint8 subgroup = group->GetMemberGroup(GetGUID());
14873 SetGroup(group, subgroup);
14874 if(getLevel() >= LEVELREQUIREMENT_HEROIC)
14876 // the group leader may change the instance difficulty while the player is offline
14877 SetDifficulty(group->GetDifficulty());
14883 void Player::_LoadBoundInstances(QueryResult *result)
14885 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
14886 m_boundInstances[i].clear();
14888 Group *group = GetGroup();
14890 //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));
14891 if(result)
14895 Field *fields = result->Fetch();
14896 bool perm = fields[1].GetBool();
14897 uint32 mapId = fields[2].GetUInt32();
14898 uint32 instanceId = fields[0].GetUInt32();
14899 uint8 difficulty = fields[3].GetUInt8();
14900 time_t resetTime = (time_t)fields[4].GetUInt64();
14901 // the resettime for normal instances is only saved when the InstanceSave is unloaded
14902 // so the value read from the DB may be wrong here but only if the InstanceSave is loaded
14903 // and in that case it is not used
14905 if(!perm && group)
14907 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);
14908 CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND instance = '%d'", GetGUIDLow(), instanceId);
14909 continue;
14912 // since non permanent binds are always solo bind, they can always be reset
14913 InstanceSave *save = sInstanceSaveManager.AddInstanceSave(mapId, instanceId, difficulty, resetTime, !perm, true);
14914 if(save) BindToInstance(save, perm, true);
14915 } while(result->NextRow());
14916 delete result;
14920 InstancePlayerBind* Player::GetBoundInstance(uint32 mapid, uint8 difficulty)
14922 // some instances only have one difficulty
14923 const MapEntry* entry = sMapStore.LookupEntry(mapid);
14924 if(!entry || !entry->SupportsHeroicMode()) difficulty = DIFFICULTY_NORMAL;
14926 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
14927 if(itr != m_boundInstances[difficulty].end())
14928 return &itr->second;
14929 else
14930 return NULL;
14933 void Player::UnbindInstance(uint32 mapid, uint8 difficulty, bool unload)
14935 BoundInstancesMap::iterator itr = m_boundInstances[difficulty].find(mapid);
14936 UnbindInstance(itr, difficulty, unload);
14939 void Player::UnbindInstance(BoundInstancesMap::iterator &itr, uint8 difficulty, bool unload)
14941 if(itr != m_boundInstances[difficulty].end())
14943 if(!unload) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%u' AND instance = '%u'", GetGUIDLow(), itr->second.save->GetInstanceId());
14944 itr->second.save->RemovePlayer(this); // save can become invalid
14945 m_boundInstances[difficulty].erase(itr++);
14949 InstancePlayerBind* Player::BindToInstance(InstanceSave *save, bool permanent, bool load)
14951 if(save)
14953 InstancePlayerBind& bind = m_boundInstances[save->GetDifficulty()][save->GetMapId()];
14954 if(bind.save)
14956 // update the save when the group kills a boss
14957 if(permanent != bind.perm || save != bind.save)
14958 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());
14960 else
14961 if(!load) CharacterDatabase.PExecute("INSERT INTO character_instance (guid, instance, permanent) VALUES ('%u', '%u', '%u')", GetGUIDLow(), save->GetInstanceId(), permanent);
14963 if(bind.save != save)
14965 if(bind.save) bind.save->RemovePlayer(this);
14966 save->AddPlayer(this);
14969 if(permanent) save->SetCanReset(false);
14971 bind.save = save;
14972 bind.perm = permanent;
14973 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());
14974 return &bind;
14976 else
14977 return NULL;
14980 void Player::SendRaidInfo()
14982 WorldPacket data(SMSG_RAID_INSTANCE_INFO, 4);
14984 uint32 counter = 0, i;
14985 for(i = 0; i < TOTAL_DIFFICULTIES; i++)
14986 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
14987 if(itr->second.perm) counter++;
14989 data << counter;
14990 for(i = 0; i < TOTAL_DIFFICULTIES; i++)
14992 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
14994 if(itr->second.perm)
14996 InstanceSave *save = itr->second.save;
14997 data << (save->GetMapId());
14998 data << (uint32)(save->GetResetTime() - time(NULL));
14999 data << save->GetInstanceId();
15000 data << uint32(counter);
15001 counter--;
15005 GetSession()->SendPacket(&data);
15009 - called on every successful teleportation to a map
15011 void Player::SendSavedInstances()
15013 bool hasBeenSaved = false;
15014 WorldPacket data;
15016 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15018 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15020 if(itr->second.perm) // only permanent binds are sent
15022 hasBeenSaved = true;
15023 break;
15028 //Send opcode 811. true or false means, whether you have current raid/heroic instances
15029 data.Initialize(SMSG_UPDATE_INSTANCE_OWNERSHIP);
15030 data << uint32(hasBeenSaved);
15031 GetSession()->SendPacket(&data);
15033 if(!hasBeenSaved)
15034 return;
15036 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15038 for (BoundInstancesMap::iterator itr = m_boundInstances[i].begin(); itr != m_boundInstances[i].end(); ++itr)
15040 if(itr->second.perm)
15042 data.Initialize(SMSG_UPDATE_LAST_INSTANCE);
15043 data << uint32(itr->second.save->GetMapId());
15044 GetSession()->SendPacket(&data);
15050 /// convert the player's binds to the group
15051 void Player::ConvertInstancesToGroup(Player *player, Group *group, uint64 player_guid)
15053 bool has_binds = false;
15054 bool has_solo = false;
15056 if(player) { player_guid = player->GetGUID(); if(!group) group = player->GetGroup(); }
15057 assert(player_guid);
15059 // copy all binds to the group, when changing leader it's assumed the character
15060 // will not have any solo binds
15062 if(player)
15064 for(uint8 i = 0; i < TOTAL_DIFFICULTIES; i++)
15066 for (BoundInstancesMap::iterator itr = player->m_boundInstances[i].begin(); itr != player->m_boundInstances[i].end();)
15068 has_binds = true;
15069 if(group) group->BindToInstance(itr->second.save, itr->second.perm, true);
15070 // permanent binds are not removed
15071 if(!itr->second.perm)
15073 player->UnbindInstance(itr, i, true); // increments itr
15074 has_solo = true;
15076 else
15077 ++itr;
15082 // if the player's not online we don't know what binds it has
15083 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));
15084 // the following should not get executed when changing leaders
15085 if(!player || has_solo) CharacterDatabase.PExecute("DELETE FROM character_instance WHERE guid = '%d' AND permanent = 0", GUID_LOPART(player_guid));
15088 bool Player::_LoadHomeBind(QueryResult *result)
15090 bool ok = false;
15091 //QueryResult *result = CharacterDatabase.PQuery("SELECT map,zone,position_x,position_y,position_z FROM character_homebind WHERE guid = '%u'", GUID_LOPART(playerGuid));
15092 if (result)
15094 Field *fields = result->Fetch();
15095 m_homebindMapId = fields[0].GetUInt32();
15096 m_homebindZoneId = fields[1].GetUInt16();
15097 m_homebindX = fields[2].GetFloat();
15098 m_homebindY = fields[3].GetFloat();
15099 m_homebindZ = fields[4].GetFloat();
15100 delete result;
15102 // accept saved data only for valid position (and non instanceable)
15103 if( MapManager::IsValidMapCoord(m_homebindMapId,m_homebindX,m_homebindY,m_homebindZ) &&
15104 !sMapStore.LookupEntry(m_homebindMapId)->Instanceable() )
15106 ok = true;
15108 else
15109 CharacterDatabase.PExecute("DELETE FROM character_homebind WHERE guid = '%u'", GetGUIDLow());
15112 if(!ok)
15114 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(), getClass());
15115 if(!info) return false;
15117 m_homebindMapId = info->mapId;
15118 m_homebindZoneId = info->zoneId;
15119 m_homebindX = info->positionX;
15120 m_homebindY = info->positionY;
15121 m_homebindZ = info->positionZ;
15123 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);
15126 DEBUG_LOG("Setting player home position: mapid is: %u, zoneid is %u, X is %f, Y is %f, Z is %f\n",
15127 m_homebindMapId, m_homebindZoneId, m_homebindX, m_homebindY, m_homebindZ);
15129 return true;
15132 /*********************************************************/
15133 /*** SAVE SYSTEM ***/
15134 /*********************************************************/
15136 void Player::SaveToDB()
15138 // delay auto save at any saves (manual, in code, or autosave)
15139 m_nextSave = sWorld.getConfig(CONFIG_INTERVAL_SAVE);
15141 // first save/honor gain after midnight will also update the player's honor fields
15142 UpdateHonorFields();
15144 // Must saved before enter into BattleGround
15145 if(InBattleGround())
15146 return;
15148 int is_save_resting = HasFlag(PLAYER_FLAGS, PLAYER_FLAGS_RESTING) ? 1 : 0;
15149 //save, far from tavern/city
15150 //save, but in tavern/city
15151 sLog.outDebug("The value of player %s at save: ", m_name.c_str());
15152 outDebugValues();
15154 // save state (after auras removing), if aura remove some flags then it must set it back by self)
15155 uint32 tmp_bytes = GetUInt32Value(UNIT_FIELD_BYTES_1);
15156 uint32 tmp_bytes2 = GetUInt32Value(UNIT_FIELD_BYTES_2);
15157 uint32 tmp_flags = GetUInt32Value(UNIT_FIELD_FLAGS);
15158 uint32 tmp_pflags = GetUInt32Value(PLAYER_FLAGS);
15159 uint32 tmp_displayid = GetDisplayId();
15161 // Set player sit state to standing on save, also stealth and shifted form
15162 SetByteValue(UNIT_FIELD_BYTES_1, 0, 0); // stand state
15163 SetByteValue(UNIT_FIELD_BYTES_2, 3, 0); // shapeshift
15164 SetByteValue(UNIT_FIELD_BYTES_1, 3, 0); // stand flags?
15165 RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_STUNNED);
15166 SetDisplayId(GetNativeDisplayId());
15168 bool inworld = IsInWorld();
15170 CharacterDatabase.BeginTransaction();
15172 CharacterDatabase.PExecute("DELETE FROM characters WHERE guid = '%u'",GetGUIDLow());
15174 std::string sql_name = m_name;
15175 CharacterDatabase.escape_string(sql_name);
15177 std::ostringstream ss;
15178 ss << "INSERT INTO characters (guid,account,name,race,class,"
15179 "map, dungeon_difficulty, position_x, position_y, position_z, orientation, data, "
15180 "taximask, online, cinematic, "
15181 "totaltime, leveltime, rest_bonus, logout_time, is_logout_resting, resettalents_cost, resettalents_time, "
15182 "trans_x, trans_y, trans_z, trans_o, transguid, extra_flags, stable_slots, at_login, zone, "
15183 "death_expire_time, taxi_path) VALUES ("
15184 << GetGUIDLow() << ", "
15185 << GetSession()->GetAccountId() << ", '"
15186 << sql_name << "', "
15187 << m_race << ", "
15188 << m_class << ", ";
15190 bool save_to_dest = false;
15191 if(IsBeingTeleported())
15193 // don't save to battlegrounds or arenas
15194 const MapEntry *entry = sMapStore.LookupEntry(GetTeleportDest().mapid);
15195 if(entry && entry->map_type != MAP_BATTLEGROUND && entry->map_type != MAP_ARENA)
15196 save_to_dest = true;
15199 if(!save_to_dest)
15201 ss << GetMapId() << ", "
15202 << (uint32)GetDifficulty() << ", "
15203 << finiteAlways(GetPositionX()) << ", "
15204 << finiteAlways(GetPositionY()) << ", "
15205 << finiteAlways(GetPositionZ()) << ", "
15206 << finiteAlways(GetOrientation()) << ", '";
15208 else
15210 ss << GetTeleportDest().mapid << ", "
15211 << (uint32)GetDifficulty() << ", "
15212 << finiteAlways(GetTeleportDest().x) << ", "
15213 << finiteAlways(GetTeleportDest().y) << ", "
15214 << finiteAlways(GetTeleportDest().z) << ", "
15215 << finiteAlways(GetTeleportDest().o) << ", '";
15218 uint16 i;
15219 for( i = 0; i < m_valuesCount; i++ )
15221 ss << GetUInt32Value(i) << " ";
15224 ss << "', '";
15226 for( i = 0; i < 8; i++ )
15227 ss << m_taxi.GetTaximask(i) << " ";
15229 ss << "', ";
15230 ss << (inworld ? 1 : 0);
15232 ss << ", ";
15233 ss << m_cinematic;
15235 ss << ", ";
15236 ss << m_Played_time[0];
15237 ss << ", ";
15238 ss << m_Played_time[1];
15240 ss << ", ";
15241 ss << finiteAlways(m_rest_bonus);
15242 ss << ", ";
15243 ss << (uint64)time(NULL);
15244 ss << ", ";
15245 ss << is_save_resting;
15246 ss << ", ";
15247 ss << m_resetTalentsCost;
15248 ss << ", ";
15249 ss << (uint64)m_resetTalentsTime;
15251 ss << ", ";
15252 ss << finiteAlways(m_movementInfo.t_x);
15253 ss << ", ";
15254 ss << finiteAlways(m_movementInfo.t_y);
15255 ss << ", ";
15256 ss << finiteAlways(m_movementInfo.t_z);
15257 ss << ", ";
15258 ss << finiteAlways(m_movementInfo.t_o);
15259 ss << ", ";
15260 if (m_transport)
15261 ss << m_transport->GetGUIDLow();
15262 else
15263 ss << "0";
15265 ss << ", ";
15266 ss << m_ExtraFlags;
15268 ss << ", ";
15269 ss << uint32(m_stableSlots); // to prevent save uint8 as char
15271 ss << ", ";
15272 ss << uint32(m_atLoginFlags);
15274 ss << ", ";
15275 ss << GetZoneId();
15277 ss << ", ";
15278 ss << (uint64)m_deathExpireTime;
15280 ss << ", '";
15281 ss << m_taxi.SaveTaxiDestinationsToString();
15282 ss << "' )";
15284 CharacterDatabase.Execute( ss.str().c_str() );
15286 if(m_mailsUpdated) //save mails only when needed
15287 _SaveMail();
15289 _SaveInventory();
15290 _SaveQuestStatus();
15291 _SaveDailyQuestStatus();
15292 _SaveTutorials();
15293 _SaveSpells();
15294 _SaveSpellCooldowns();
15295 _SaveActions();
15296 _SaveAuras();
15297 _SaveReputation();
15299 CharacterDatabase.CommitTransaction();
15301 // restore state (before aura apply, if aura remove flag then aura must set it ack by self)
15302 SetDisplayId(tmp_displayid);
15303 SetUInt32Value(UNIT_FIELD_BYTES_1, tmp_bytes);
15304 SetUInt32Value(UNIT_FIELD_BYTES_2, tmp_bytes2);
15305 SetUInt32Value(UNIT_FIELD_FLAGS, tmp_flags);
15306 SetUInt32Value(PLAYER_FLAGS, tmp_pflags);
15308 // save pet (hunter pet level and experience and all type pets health/mana).
15309 if(Pet* pet = GetPet())
15310 pet->SavePetToDB(PET_SAVE_AS_CURRENT);
15311 m_achievementMgr.SaveToDB();
15314 // fast save function for item/money cheating preventing - save only inventory and money state
15315 void Player::SaveInventoryAndGoldToDB()
15317 _SaveInventory();
15318 //money is in data field
15319 SaveDataFieldToDB();
15322 void Player::_SaveActions()
15324 for(ActionButtonList::iterator itr = m_actionButtons.begin(); itr != m_actionButtons.end(); )
15326 switch (itr->second.uState)
15328 case ACTIONBUTTON_NEW:
15329 CharacterDatabase.PExecute("INSERT INTO character_action (guid,button,action,type,misc) VALUES ('%u', '%u', '%u', '%u', '%u')",
15330 GetGUIDLow(), (uint32)itr->first, (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc );
15331 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15332 ++itr;
15333 break;
15334 case ACTIONBUTTON_CHANGED:
15335 CharacterDatabase.PExecute("UPDATE character_action SET action = '%u', type = '%u', misc= '%u' WHERE guid= '%u' AND button= '%u' ",
15336 (uint32)itr->second.action, (uint32)itr->second.type, (uint32)itr->second.misc, GetGUIDLow(), (uint32)itr->first );
15337 itr->second.uState = ACTIONBUTTON_UNCHANGED;
15338 ++itr;
15339 break;
15340 case ACTIONBUTTON_DELETED:
15341 CharacterDatabase.PExecute("DELETE FROM character_action WHERE guid = '%u' and button = '%u'", GetGUIDLow(), (uint32)itr->first );
15342 m_actionButtons.erase(itr++);
15343 break;
15344 default:
15345 ++itr;
15346 break;
15351 void Player::_SaveAuras()
15353 CharacterDatabase.PExecute("DELETE FROM character_aura WHERE guid = '%u'",GetGUIDLow());
15355 AuraMap const& auras = GetAuras();
15357 if (auras.empty())
15358 return;
15360 spellEffectPair lastEffectPair = auras.begin()->first;
15361 uint32 stackCounter = 1;
15363 for(AuraMap::const_iterator itr = auras.begin(); ; ++itr)
15365 if(itr == auras.end() || lastEffectPair != itr->first)
15367 AuraMap::const_iterator itr2 = itr;
15368 // save previous spellEffectPair to db
15369 itr2--;
15370 SpellEntry const *spellInfo = itr2->second->GetSpellProto();
15372 //skip all auras from spells that are passive or need a shapeshift
15373 if (!(itr2->second->IsPassive() || itr2->second->IsRemovedOnShapeLost()))
15375 //do not save single target auras (unless they were cast by the player)
15376 if (!(itr2->second->GetCasterGUID() != GetGUID() && IsSingleTargetSpell(spellInfo)))
15378 uint8 i;
15379 // or apply at cast SPELL_AURA_MOD_SHAPESHIFT or SPELL_AURA_MOD_STEALTH auras
15380 for (i = 0; i < 3; i++)
15381 if (spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_SHAPESHIFT ||
15382 spellInfo->EffectApplyAuraName[i] == SPELL_AURA_MOD_STEALTH)
15383 break;
15385 if (i == 3)
15387 CharacterDatabase.PExecute("INSERT INTO character_aura (guid,caster_guid,spell,effect_index,stackcount,amount,maxduration,remaintime,remaincharges) "
15388 "VALUES ('%u', '" I64FMTD "' ,'%u', '%u', '%u', '%d', '%d', '%d', '%d')",
15389 GetGUIDLow(), itr2->second->GetCasterGUID(), (uint32)itr2->second->GetId(), (uint32)itr2->second->GetEffIndex(), stackCounter, itr2->second->GetModifier()->m_amount,int(itr2->second->GetAuraMaxDuration()),int(itr2->second->GetAuraDuration()),int(itr2->second->m_procCharges));
15394 if(itr == auras.end())
15395 break;
15398 if (lastEffectPair == itr->first)
15399 stackCounter++;
15400 else
15402 lastEffectPair = itr->first;
15403 stackCounter = 1;
15408 void Player::_SaveInventory()
15410 // force items in buyback slots to new state
15411 // and remove those that aren't already
15412 for (uint8 i = BUYBACK_SLOT_START; i < BUYBACK_SLOT_END; i++)
15414 Item *item = m_items[i];
15415 if (!item || item->GetState() == ITEM_NEW) continue;
15416 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15417 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", item->GetGUIDLow());
15418 m_items[i]->FSetState(ITEM_NEW);
15421 // update enchantment durations
15422 for(EnchantDurationList::iterator itr = m_enchantDuration.begin();itr != m_enchantDuration.end();++itr)
15424 itr->item->SetEnchantmentDuration(itr->slot,itr->leftduration);
15427 // if no changes
15428 if (m_itemUpdateQueue.empty()) return;
15430 // do not save if the update queue is corrupt
15431 bool error = false;
15432 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15434 Item *item = m_itemUpdateQueue[i];
15435 if(!item || item->GetState() == ITEM_REMOVED) continue;
15436 Item *test = GetItemByPos( item->GetBagSlot(), item->GetSlot());
15438 if (test == NULL)
15440 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());
15441 error = true;
15443 else if (test != item)
15445 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());
15446 error = true;
15450 if (error)
15452 sLog.outError("Player::_SaveInventory - one or more errors occurred save aborted!");
15453 ChatHandler(this).SendSysMessage(LANG_ITEM_SAVE_FAILED);
15454 return;
15457 for(size_t i = 0; i < m_itemUpdateQueue.size(); i++)
15459 Item *item = m_itemUpdateQueue[i];
15460 if(!item) continue;
15462 Bag *container = item->GetContainer();
15463 uint32 bag_guid = container ? container->GetGUIDLow() : 0;
15465 switch(item->GetState())
15467 case ITEM_NEW:
15468 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());
15469 break;
15470 case ITEM_CHANGED:
15471 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());
15472 break;
15473 case ITEM_REMOVED:
15474 CharacterDatabase.PExecute("DELETE FROM character_inventory WHERE item = '%u'", item->GetGUIDLow());
15475 break;
15476 case ITEM_UNCHANGED:
15477 break;
15480 item->SaveToDB(); // item have unchanged inventory record and can be save standalone
15482 m_itemUpdateQueue.clear();
15485 void Player::_SaveMail()
15487 if (!m_mailsLoaded)
15488 return;
15490 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); ++itr)
15492 Mail *m = (*itr);
15493 if (m->state == MAIL_STATE_CHANGED)
15495 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'",
15496 m->itemTextId, m->HasItems() ? 1 : 0, (uint64)m->expire_time, (uint64)m->deliver_time, m->money, m->COD, m->checked, m->messageID);
15497 if(m->removedItems.size())
15499 for(std::vector<uint32>::iterator itr2 = m->removedItems.begin(); itr2 != m->removedItems.end(); ++itr2)
15500 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE item_guid = '%u'", *itr2);
15501 m->removedItems.clear();
15503 m->state = MAIL_STATE_UNCHANGED;
15505 else if (m->state == MAIL_STATE_DELETED)
15507 if (m->HasItems())
15508 for(std::vector<MailItemInfo>::iterator itr2 = m->items.begin(); itr2 != m->items.end(); ++itr2)
15509 CharacterDatabase.PExecute("DELETE FROM item_instance WHERE guid = '%u'", itr2->item_guid);
15510 if (m->itemTextId)
15511 CharacterDatabase.PExecute("DELETE FROM item_text WHERE id = '%u'", m->itemTextId);
15512 CharacterDatabase.PExecute("DELETE FROM mail WHERE id = '%u'", m->messageID);
15513 CharacterDatabase.PExecute("DELETE FROM mail_items WHERE mail_id = '%u'", m->messageID);
15517 //deallocate deleted mails...
15518 for (PlayerMails::iterator itr = m_mail.begin(); itr != m_mail.end(); )
15520 if ((*itr)->state == MAIL_STATE_DELETED)
15522 Mail* m = *itr;
15523 m_mail.erase(itr);
15524 delete m;
15525 itr = m_mail.begin();
15527 else
15528 ++itr;
15531 m_mailsUpdated = false;
15534 void Player::_SaveQuestStatus()
15536 // we don't need transactions here.
15537 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
15539 switch (i->second.uState)
15541 case QUEST_NEW :
15542 CharacterDatabase.PExecute("INSERT INTO character_queststatus (guid,quest,status,rewarded,explored,timer,mobcount1,mobcount2,mobcount3,mobcount4,itemcount1,itemcount2,itemcount3,itemcount4) "
15543 "VALUES ('%u', '%u', '%u', '%u', '%u', '" I64FMTD "', '%u', '%u', '%u', '%u', '%u', '%u', '%u', '%u')",
15544 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]);
15545 break;
15546 case QUEST_CHANGED :
15547 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' ",
15548 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 );
15549 break;
15550 case QUEST_UNCHANGED:
15551 break;
15553 i->second.uState = QUEST_UNCHANGED;
15557 void Player::_SaveDailyQuestStatus()
15559 if(!m_DailyQuestChanged)
15560 return;
15562 m_DailyQuestChanged = false;
15564 // save last daily quest time for all quests: we need only mostly reset time for reset check anyway
15566 // we don't need transactions here.
15567 CharacterDatabase.PExecute("DELETE FROM character_queststatus_daily WHERE guid = '%u'",GetGUIDLow());
15568 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
15569 if(GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
15570 CharacterDatabase.PExecute("INSERT INTO character_queststatus_daily (guid,quest,time) VALUES ('%u', '%u','" I64FMTD "')",
15571 GetGUIDLow(), GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx),uint64(m_lastDailyQuestTime));
15574 void Player::_SaveReputation()
15576 for(FactionStateList::iterator itr = m_factions.begin(); itr != m_factions.end(); ++itr)
15578 if (itr->second.Changed)
15580 CharacterDatabase.PExecute("DELETE FROM character_reputation WHERE guid = '%u' AND faction='%u'", GetGUIDLow(), itr->second.ID);
15581 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);
15582 itr->second.Changed = false;
15587 void Player::_SaveSpells()
15589 for (PlayerSpellMap::const_iterator itr = m_spells.begin(), next = m_spells.begin(); itr != m_spells.end(); itr = next)
15591 ++next;
15592 if (itr->second->state == PLAYERSPELL_REMOVED || itr->second->state == PLAYERSPELL_CHANGED)
15593 CharacterDatabase.PExecute("DELETE FROM character_spell WHERE guid = '%u' and spell = '%u'", GetGUIDLow(), itr->first);
15594 if (itr->second->state == PLAYERSPELL_NEW || itr->second->state == PLAYERSPELL_CHANGED)
15595 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);
15597 if (itr->second->state == PLAYERSPELL_REMOVED)
15598 _removeSpell(itr->first);
15599 else
15600 itr->second->state = PLAYERSPELL_UNCHANGED;
15604 void Player::_SaveTutorials()
15606 if(!m_TutorialsChanged)
15607 return;
15609 uint32 Rows=0;
15610 // it's better than rebuilding indexes multiple times
15611 QueryResult *result = CharacterDatabase.PQuery("SELECT count(*) AS r FROM character_tutorial WHERE account = '%u' AND realmid = '%u'", GetSession()->GetAccountId(), realmID );
15612 if(result)
15614 Rows = result->Fetch()[0].GetUInt32();
15615 delete result;
15618 if (Rows)
15620 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'",
15621 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 );
15623 else
15625 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]);
15628 m_TutorialsChanged = false;
15631 void Player::outDebugValues() const
15633 if(!sLog.IsOutDebug()) // optimize disabled debug output
15634 return;
15636 sLog.outDebug("HP is: \t\t\t%u\t\tMP is: \t\t\t%u",GetMaxHealth(), GetMaxPower(POWER_MANA));
15637 sLog.outDebug("AGILITY is: \t\t%f\t\tSTRENGTH is: \t\t%f",GetStat(STAT_AGILITY), GetStat(STAT_STRENGTH));
15638 sLog.outDebug("INTELLECT is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_INTELLECT), GetStat(STAT_SPIRIT));
15639 sLog.outDebug("STAMINA is: \t\t%f\t\tSPIRIT is: \t\t%f",GetStat(STAT_STAMINA), GetStat(STAT_SPIRIT));
15640 sLog.outDebug("Armor is: \t\t%u\t\tBlock is: \t\t%f",GetArmor(), GetFloatValue(PLAYER_BLOCK_PERCENTAGE));
15641 sLog.outDebug("HolyRes is: \t\t%u\t\tFireRes is: \t\t%u",GetResistance(SPELL_SCHOOL_HOLY), GetResistance(SPELL_SCHOOL_FIRE));
15642 sLog.outDebug("NatureRes is: \t\t%u\t\tFrostRes is: \t\t%u",GetResistance(SPELL_SCHOOL_NATURE), GetResistance(SPELL_SCHOOL_FROST));
15643 sLog.outDebug("ShadowRes is: \t\t%u\t\tArcaneRes is: \t\t%u",GetResistance(SPELL_SCHOOL_SHADOW), GetResistance(SPELL_SCHOOL_ARCANE));
15644 sLog.outDebug("MIN_DAMAGE is: \t\t%f\tMAX_DAMAGE is: \t\t%f",GetFloatValue(UNIT_FIELD_MINDAMAGE), GetFloatValue(UNIT_FIELD_MAXDAMAGE));
15645 sLog.outDebug("MIN_OFFHAND_DAMAGE is: \t%f\tMAX_OFFHAND_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINOFFHANDDAMAGE), GetFloatValue(UNIT_FIELD_MAXOFFHANDDAMAGE));
15646 sLog.outDebug("MIN_RANGED_DAMAGE is: \t%f\tMAX_RANGED_DAMAGE is: \t%f",GetFloatValue(UNIT_FIELD_MINRANGEDDAMAGE), GetFloatValue(UNIT_FIELD_MAXRANGEDDAMAGE));
15647 sLog.outDebug("ATTACK_TIME is: \t%u\t\tRANGE_ATTACK_TIME is: \t%u",GetAttackTime(BASE_ATTACK), GetAttackTime(RANGED_ATTACK));
15650 /*********************************************************/
15651 /*** FLOOD FILTER SYSTEM ***/
15652 /*********************************************************/
15654 void Player::UpdateSpeakTime()
15656 // ignore chat spam protection for GMs in any mode
15657 if(GetSession()->GetSecurity() > SEC_PLAYER)
15658 return;
15660 time_t current = time (NULL);
15661 if(m_speakTime > current)
15663 uint32 max_count = sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_COUNT);
15664 if(!max_count)
15665 return;
15667 ++m_speakCount;
15668 if(m_speakCount >= max_count)
15670 // prevent overwrite mute time, if message send just before mutes set, for example.
15671 time_t new_mute = current + sWorld.getConfig(CONFIG_CHATFLOOD_MUTE_TIME);
15672 if(GetSession()->m_muteTime < new_mute)
15673 GetSession()->m_muteTime = new_mute;
15675 m_speakCount = 0;
15678 else
15679 m_speakCount = 0;
15681 m_speakTime = current + sWorld.getConfig(CONFIG_CHATFLOOD_MESSAGE_DELAY);
15684 bool Player::CanSpeak() const
15686 return GetSession()->m_muteTime <= time (NULL);
15689 /*********************************************************/
15690 /*** LOW LEVEL FUNCTIONS:Notifiers ***/
15691 /*********************************************************/
15693 void Player::SendAttackSwingNotInRange()
15695 WorldPacket data(SMSG_ATTACKSWING_NOTINRANGE, 0);
15696 GetSession()->SendPacket( &data );
15699 void Player::SavePositionInDB(uint32 mapid, float x,float y,float z,float o,uint32 zone,uint64 guid)
15701 std::ostringstream ss;
15702 ss << "UPDATE characters SET position_x='"<<x<<"',position_y='"<<y
15703 << "',position_z='"<<z<<"',orientation='"<<o<<"',map='"<<mapid
15704 << "',zone='"<<zone<<"',trans_x='0',trans_y='0',trans_z='0',"
15705 << "transguid='0',taxi_path='' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15706 sLog.outDebug(ss.str().c_str());
15707 CharacterDatabase.Execute(ss.str().c_str());
15710 void Player::SaveDataFieldToDB()
15712 std::ostringstream ss;
15713 ss<<"UPDATE characters SET data='";
15715 for(uint16 i = 0; i < m_valuesCount; i++ )
15717 ss << GetUInt32Value(i) << " ";
15719 ss<<"' WHERE guid='"<< GUID_LOPART(GetGUIDLow()) <<"'";
15721 CharacterDatabase.Execute(ss.str().c_str());
15724 bool Player::SaveValuesArrayInDB(Tokens const& tokens, uint64 guid)
15726 std::ostringstream ss2;
15727 ss2<<"UPDATE characters SET data='";
15728 int i=0;
15729 for (Tokens::const_iterator iter = tokens.begin(); iter != tokens.end(); ++iter, ++i)
15731 ss2<<tokens[i]<<" ";
15733 ss2<<"' WHERE guid='"<< GUID_LOPART(guid) <<"'";
15735 return CharacterDatabase.Execute(ss2.str().c_str());
15738 void Player::SetUInt32ValueInArray(Tokens& tokens,uint16 index, uint32 value)
15740 char buf[11];
15741 snprintf(buf,11,"%u",value);
15743 if(index >= tokens.size())
15744 return;
15746 tokens[index] = buf;
15749 void Player::SetUInt32ValueInDB(uint16 index, uint32 value, uint64 guid)
15751 Tokens tokens;
15752 if(!LoadValuesArrayFromDB(tokens,guid))
15753 return;
15755 if(index >= tokens.size())
15756 return;
15758 char buf[11];
15759 snprintf(buf,11,"%u",value);
15760 tokens[index] = buf;
15762 SaveValuesArrayInDB(tokens,guid);
15765 void Player::SetFloatValueInDB(uint16 index, float value, uint64 guid)
15767 uint32 temp;
15768 memcpy(&temp, &value, sizeof(value));
15769 Player::SetUInt32ValueInDB(index, temp, guid);
15772 void Player::Customize(uint64 guid, uint8 gender, uint8 skin, uint8 face, uint8 hairStyle, uint8 hairColor, uint8 facialHair)
15774 Tokens tokens;
15775 if(!LoadValuesArrayFromDB(tokens, guid))
15776 return;
15778 uint32 unit_bytes0 = GetUInt32ValueFromArray(tokens, UNIT_FIELD_BYTES_0);
15779 uint8 race = unit_bytes0 & 0xFF;
15780 uint8 class_ = (unit_bytes0 >> 8) & 0xFF;
15782 PlayerInfo const* info = objmgr.GetPlayerInfo(race, class_);
15783 if(!info)
15784 return;
15786 unit_bytes0 &= ~(0xFF << 16);
15787 unit_bytes0 |= (gender << 16);
15788 SetUInt32ValueInArray(tokens, UNIT_FIELD_BYTES_0, unit_bytes0);
15790 SetUInt32ValueInArray(tokens, UNIT_FIELD_DISPLAYID, gender ? info->displayId_f : info->displayId_m);
15791 SetUInt32ValueInArray(tokens, UNIT_FIELD_NATIVEDISPLAYID, gender ? info->displayId_f : info->displayId_m);
15793 SetUInt32ValueInArray(tokens, PLAYER_BYTES, (skin | (face << 8) | (hairStyle << 16) | (hairColor << 24)));
15795 uint32 player_bytes2 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_2);
15796 player_bytes2 &= ~0xFF;
15797 player_bytes2 |= facialHair;
15798 SetUInt32ValueInArray(tokens, PLAYER_BYTES_2, player_bytes2);
15800 uint32 player_bytes3 = GetUInt32ValueFromArray(tokens, PLAYER_BYTES_3);
15801 player_bytes3 &= ~0xFF;
15802 player_bytes3 |= gender;
15803 SetUInt32ValueInArray(tokens, PLAYER_BYTES_3, player_bytes3);
15805 SaveValuesArrayInDB(tokens, guid);
15808 void Player::SendAttackSwingNotStanding()
15810 WorldPacket data(SMSG_ATTACKSWING_NOTSTANDING, 0);
15811 GetSession()->SendPacket( &data );
15814 void Player::SendAttackSwingDeadTarget()
15816 WorldPacket data(SMSG_ATTACKSWING_DEADTARGET, 0);
15817 GetSession()->SendPacket( &data );
15820 void Player::SendAttackSwingCantAttack()
15822 WorldPacket data(SMSG_ATTACKSWING_CANT_ATTACK, 0);
15823 GetSession()->SendPacket( &data );
15826 void Player::SendAttackSwingCancelAttack()
15828 WorldPacket data(SMSG_CANCEL_COMBAT, 0);
15829 GetSession()->SendPacket( &data );
15832 void Player::SendAttackSwingBadFacingAttack()
15834 WorldPacket data(SMSG_ATTACKSWING_BADFACING, 0);
15835 GetSession()->SendPacket( &data );
15838 void Player::SendAutoRepeatCancel()
15840 WorldPacket data(SMSG_CANCEL_AUTO_REPEAT, GetPackGUID().size());
15841 data.append(GetPackGUID()); // may be it's target guid
15842 GetSession()->SendPacket( &data );
15845 void Player::PlaySound(uint32 Sound, bool OnlySelf)
15847 WorldPacket data(SMSG_PLAY_SOUND, 4);
15848 data << Sound;
15849 if (OnlySelf)
15850 GetSession()->SendPacket( &data );
15851 else
15852 SendMessageToSet( &data, true );
15855 void Player::SendExplorationExperience(uint32 Area, uint32 Experience)
15857 WorldPacket data( SMSG_EXPLORATION_EXPERIENCE, 8 );
15858 data << Area;
15859 data << Experience;
15860 GetSession()->SendPacket(&data);
15863 void Player::SendDungeonDifficulty(bool IsInGroup)
15865 uint8 val = 0x00000001;
15866 WorldPacket data(MSG_SET_DUNGEON_DIFFICULTY, 12);
15867 data << (uint32)GetDifficulty();
15868 data << uint32(val);
15869 data << uint32(IsInGroup);
15870 GetSession()->SendPacket(&data);
15873 void Player::SendResetFailedNotify(uint32 mapid)
15875 WorldPacket data(SMSG_RESET_FAILED_NOTIFY, 4);
15876 data << uint32(mapid);
15877 GetSession()->SendPacket(&data);
15880 /// Reset all solo instances and optionally send a message on success for each
15881 void Player::ResetInstances(uint8 method)
15883 // method can be INSTANCE_RESET_ALL, INSTANCE_RESET_CHANGE_DIFFICULTY, INSTANCE_RESET_GROUP_JOIN
15885 // we assume that when the difficulty changes, all instances that can be reset will be
15886 uint8 dif = GetDifficulty();
15888 for (BoundInstancesMap::iterator itr = m_boundInstances[dif].begin(); itr != m_boundInstances[dif].end();)
15890 InstanceSave *p = itr->second.save;
15891 const MapEntry *entry = sMapStore.LookupEntry(itr->first);
15892 if(!entry || !p->CanReset())
15894 ++itr;
15895 continue;
15898 if(method == INSTANCE_RESET_ALL)
15900 // the "reset all instances" method can only reset normal maps
15901 if(dif == DIFFICULTY_HEROIC || entry->map_type == MAP_RAID)
15903 ++itr;
15904 continue;
15908 // if the map is loaded, reset it
15909 Map *map = MapManager::Instance().FindMap(p->GetMapId(), p->GetInstanceId());
15910 if(map && map->IsDungeon())
15911 ((InstanceMap*)map)->Reset(method);
15913 // since this is a solo instance there should not be any players inside
15914 if(method == INSTANCE_RESET_ALL || method == INSTANCE_RESET_CHANGE_DIFFICULTY)
15915 SendResetInstanceSuccess(p->GetMapId());
15917 p->DeleteFromDB();
15918 m_boundInstances[dif].erase(itr++);
15920 // the following should remove the instance save from the manager and delete it as well
15921 p->RemovePlayer(this);
15925 void Player::SendResetInstanceSuccess(uint32 MapId)
15927 WorldPacket data(SMSG_INSTANCE_RESET, 4);
15928 data << MapId;
15929 GetSession()->SendPacket(&data);
15932 void Player::SendResetInstanceFailed(uint32 reason, uint32 MapId)
15934 // TODO: find what other fail reasons there are besides players in the instance
15935 WorldPacket data(SMSG_INSTANCE_RESET_FAILED, 4);
15936 data << reason;
15937 data << MapId;
15938 GetSession()->SendPacket(&data);
15941 /*********************************************************/
15942 /*** Update timers ***/
15943 /*********************************************************/
15945 ///checks the 15 afk reports per 5 minutes limit
15946 void Player::UpdateAfkReport(time_t currTime)
15948 if(m_bgAfkReportedTimer <= currTime)
15950 m_bgAfkReportedCount = 0;
15951 m_bgAfkReportedTimer = currTime+5*MINUTE;
15955 void Player::UpdateContestedPvP(uint32 diff)
15957 if(!m_contestedPvPTimer||isInCombat())
15958 return;
15959 if(m_contestedPvPTimer <= diff)
15961 ResetContestedPvP();
15963 else
15964 m_contestedPvPTimer -= diff;
15967 void Player::UpdatePvPFlag(time_t currTime)
15969 if(!IsPvP())
15970 return;
15971 if(pvpInfo.endTimer == 0 || currTime < (pvpInfo.endTimer + 300))
15972 return;
15974 UpdatePvP(false);
15977 void Player::UpdateDuelFlag(time_t currTime)
15979 if(!duel || duel->startTimer == 0 ||currTime < duel->startTimer + 3)
15980 return;
15982 SetUInt32Value(PLAYER_DUEL_TEAM, 1);
15983 duel->opponent->SetUInt32Value(PLAYER_DUEL_TEAM, 2);
15985 duel->startTimer = 0;
15986 duel->startTime = currTime;
15987 duel->opponent->duel->startTimer = 0;
15988 duel->opponent->duel->startTime = currTime;
15991 void Player::RemovePet(Pet* pet, PetSaveMode mode, bool returnreagent)
15993 if(!pet)
15994 pet = GetPet();
15996 if(returnreagent && (pet || m_temporaryUnsummonedPetNumber))
15998 //returning of reagents only for players, so best done here
15999 uint32 spellId = pet ? pet->GetUInt32Value(UNIT_CREATED_BY_SPELL) : m_oldpetspell;
16000 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spellId);
16002 if(spellInfo)
16004 for(uint32 i = 0; i < 7; ++i)
16006 if(spellInfo->Reagent[i] > 0)
16008 ItemPosCountVec dest; //for succubus, voidwalker, felhunter and felguard credit soulshard when despawn reason other than death (out of range, logout)
16009 uint8 msg = CanStoreNewItem( NULL_BAG, NULL_SLOT, dest, spellInfo->Reagent[i], spellInfo->ReagentCount[i] );
16010 if( msg == EQUIP_ERR_OK )
16012 Item* item = StoreNewItem( dest, spellInfo->Reagent[i], true);
16013 if(IsInWorld())
16014 SendNewItem(item,spellInfo->ReagentCount[i],true,false);
16019 m_temporaryUnsummonedPetNumber = 0;
16022 if(!pet || pet->GetOwnerGUID()!=GetGUID())
16023 return;
16025 // only if current pet in slot
16026 switch(pet->getPetType())
16028 case MINI_PET:
16029 m_miniPet = 0;
16030 break;
16031 case GUARDIAN_PET:
16032 m_guardianPets.erase(pet->GetGUID());
16033 break;
16034 default:
16035 if(GetPetGUID() == pet->GetGUID())
16036 SetPet(NULL);
16037 break;
16040 pet->CombatStop();
16042 if(returnreagent)
16044 switch(pet->GetEntry())
16046 //warlock pets except imp are removed(?) when logging out
16047 case 1860:
16048 case 1863:
16049 case 417:
16050 case 17252:
16051 mode = PET_SAVE_NOT_IN_SLOT;
16052 break;
16056 pet->SavePetToDB(mode);
16058 pet->CleanupsBeforeDelete();
16059 pet->AddObjectToRemoveList();
16060 pet->m_removed = true;
16062 if(pet->isControlled())
16064 WorldPacket data(SMSG_PET_SPELLS, 8);
16065 data << uint64(0);
16066 data << uint32(0);
16067 GetSession()->SendPacket(&data);
16069 if(GetGroup())
16070 SetGroupUpdateFlag(GROUP_UPDATE_PET);
16074 void Player::RemoveMiniPet()
16076 if(Pet* pet = GetMiniPet())
16078 pet->Remove(PET_SAVE_AS_DELETED);
16079 m_miniPet = 0;
16083 Pet* Player::GetMiniPet()
16085 if(!m_miniPet)
16086 return NULL;
16087 return ObjectAccessor::GetPet(m_miniPet);
16090 void Player::RemoveGuardians()
16092 while(!m_guardianPets.empty())
16094 uint64 guid = *m_guardianPets.begin();
16095 if(Pet* pet = ObjectAccessor::GetPet(guid))
16096 pet->Remove(PET_SAVE_AS_DELETED);
16098 m_guardianPets.erase(guid);
16102 bool Player::HasGuardianWithEntry(uint32 entry)
16104 // pet guid middle part is entry (and creature also)
16105 // and in guardian list must be guardians with same entry _always_
16106 for(GuardianPetList::const_iterator itr = m_guardianPets.begin(); itr != m_guardianPets.end(); ++itr)
16107 if(GUID_ENPART(*itr)==entry)
16108 return true;
16110 return false;
16113 void Player::Uncharm()
16115 Unit* charm = GetCharm();
16116 if(!charm)
16117 return;
16119 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_CHARM);
16120 charm->RemoveSpellsCausingAura(SPELL_AURA_MOD_POSSESS);
16123 void Player::BuildPlayerChat(WorldPacket *data, uint8 msgtype, const std::string& text, uint32 language) const
16125 *data << (uint8)msgtype;
16126 *data << (uint32)language;
16127 *data << (uint64)GetGUID();
16128 *data << (uint32)language; //language 2.1.0 ?
16129 *data << (uint64)GetGUID();
16130 *data << (uint32)(text.length()+1);
16131 *data << text;
16132 *data << (uint8)chatTag();
16135 void Player::Say(const std::string& text, const uint32 language)
16137 WorldPacket data(SMSG_MESSAGECHAT, 200);
16138 BuildPlayerChat(&data, CHAT_MSG_SAY, text, language);
16139 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_SAY),true);
16142 void Player::Yell(const std::string& text, const uint32 language)
16144 WorldPacket data(SMSG_MESSAGECHAT, 200);
16145 BuildPlayerChat(&data, CHAT_MSG_YELL, text, language);
16146 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_YELL),true);
16149 void Player::TextEmote(const std::string& text)
16151 WorldPacket data(SMSG_MESSAGECHAT, 200);
16152 BuildPlayerChat(&data, CHAT_MSG_EMOTE, text, LANG_UNIVERSAL);
16153 SendMessageToSetInRange(&data,sWorld.getConfig(CONFIG_LISTEN_RANGE_TEXTEMOTE),true, !sWorld.getConfig(CONFIG_ALLOW_TWO_SIDE_INTERACTION_CHAT) );
16156 void Player::Whisper(const std::string& text, uint32 language,uint64 receiver)
16158 if (language != LANG_ADDON) // if not addon data
16159 language = LANG_UNIVERSAL; // whispers should always be readable
16161 Player *rPlayer = objmgr.GetPlayer(receiver);
16163 // when player you are whispering to is dnd, he cannot receive your message, unless you are in gm mode
16164 if(!rPlayer->isDND() || isGameMaster())
16166 WorldPacket data(SMSG_MESSAGECHAT, 200);
16167 BuildPlayerChat(&data, CHAT_MSG_WHISPER, text, language);
16168 rPlayer->GetSession()->SendPacket(&data);
16170 data.Initialize(SMSG_MESSAGECHAT, 200);
16171 rPlayer->BuildPlayerChat(&data, CHAT_MSG_REPLY, text, language);
16172 GetSession()->SendPacket(&data);
16174 else
16176 // announce to player that player he is whispering to is dnd and cannot receive his message
16177 ChatHandler(this).PSendSysMessage(LANG_PLAYER_DND, rPlayer->GetName(), rPlayer->dndMsg.c_str());
16180 if(!isAcceptWhispers())
16182 SetAcceptWhispers(true);
16183 ChatHandler(this).SendSysMessage(LANG_COMMAND_WHISPERON);
16186 // announce to player that player he is whispering to is afk
16187 if(rPlayer->isAFK())
16188 ChatHandler(this).PSendSysMessage(LANG_PLAYER_AFK, rPlayer->GetName(), rPlayer->afkMsg.c_str());
16190 // if player whisper someone, auto turn of dnd to be able to receive an answer
16191 if(isDND() && !rPlayer->isGameMaster())
16192 ToggleDND();
16195 void Player::PetSpellInitialize()
16197 Pet* pet = GetPet();
16199 if(!pet)
16200 return;
16202 sLog.outDebug("Pet Spells Groups");
16204 CharmInfo *charmInfo = pet->GetCharmInfo();
16206 WorldPacket data(SMSG_PET_SPELLS, 8+4+4+4+10*4);
16207 data << uint64(pet->GetGUID());
16208 data << uint32(pet->GetCreatureInfo()->family); // creature family (required for pet talents)
16209 data << uint32(0);
16210 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState()) << uint16(0);
16212 // action bar loop
16213 for(uint32 i = 0; i < 10; i++)
16215 data << uint32(charmInfo->GetActionBarEntry(i)->Raw);
16218 size_t spellsCountPos = data.wpos();
16220 // spells count
16221 uint8 addlist = 0;
16222 data << uint8(addlist); // placeholder
16224 if(pet->isControlled() && ((pet->getPetType() == HUNTER_PET) || ((pet->GetCreatureInfo()->type == CREATURE_TYPE_DEMON) && (getClass() == CLASS_WARLOCK))))
16226 // spells loop
16227 for (PetSpellMap::iterator itr = pet->m_spells.begin(); itr != pet->m_spells.end(); ++itr)
16229 if(itr->second->state == PETSPELL_REMOVED)
16230 continue;
16232 data << uint16(itr->first);
16233 data << uint16(itr->second->active); // pet spell active state isn't boolean
16234 ++addlist;
16238 data.put<uint8>(spellsCountPos, addlist);
16240 uint8 cooldownsCount = pet->m_CreatureSpellCooldowns.size() + pet->m_CreatureCategoryCooldowns.size();
16241 data << uint8(cooldownsCount);
16243 time_t curTime = time(NULL);
16245 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureSpellCooldowns.begin(); itr != pet->m_CreatureSpellCooldowns.end(); ++itr)
16247 time_t cooldown = 0;
16249 if(itr->second > curTime)
16250 cooldown = (itr->second - curTime) * 1000;
16252 data << uint16(itr->first); // spellid
16253 data << uint16(0); // spell category?
16254 data << uint32(itr->second); // cooldown
16255 data << uint32(0); // category cooldown
16258 for(CreatureSpellCooldowns::const_iterator itr = pet->m_CreatureCategoryCooldowns.begin(); itr != pet->m_CreatureCategoryCooldowns.end(); ++itr)
16260 time_t cooldown = 0;
16262 if(itr->second > curTime)
16263 cooldown = (itr->second - curTime) * 1000;
16265 data << uint16(itr->first); // spellid
16266 data << uint16(0); // spell category?
16267 data << uint32(0); // cooldown
16268 data << uint32(itr->second); // category cooldown
16271 GetSession()->SendPacket(&data);
16274 void Player::PossessSpellInitialize()
16276 Unit* charm = GetCharm();
16278 if(!charm)
16279 return;
16281 CharmInfo *charmInfo = charm->GetCharmInfo();
16283 if(!charmInfo)
16285 sLog.outError("Player::PossessSpellInitialize(): charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16286 return;
16289 uint8 addlist = 0;
16290 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16292 //16
16293 data << uint64(charm->GetGUID());
16294 data << uint32(0x00000000);
16295 data << uint32(0);
16296 data << uint8(0) << uint8(0) << uint16(0);
16298 for(uint32 i = 0; i < 10; i++) //40
16300 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16303 data << uint8(addlist); //1
16305 uint8 count = 0;
16306 data << uint8(count); // cooldowns count
16308 GetSession()->SendPacket(&data);
16311 void Player::CharmSpellInitialize()
16313 Unit* charm = GetCharm();
16315 if(!charm)
16316 return;
16318 CharmInfo *charmInfo = charm->GetCharmInfo();
16319 if(!charmInfo)
16321 sLog.outError("Player::CharmSpellInitialize(): the player's charm ("I64FMTD") has no charminfo!", charm->GetGUID());
16322 return;
16325 uint8 addlist = 0;
16327 if(charm->GetTypeId() != TYPEID_PLAYER)
16329 CreatureInfo const *cinfo = ((Creature*)charm)->GetCreatureInfo();
16331 if(cinfo && cinfo->type == CREATURE_TYPE_DEMON && getClass() == CLASS_WARLOCK)
16333 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16335 if(charmInfo->GetCharmSpell(i)->spellId)
16336 ++addlist;
16341 WorldPacket data(SMSG_PET_SPELLS, 16+40+1+4*addlist+25);// first line + actionbar + spellcount + spells + last adds
16343 data << uint64(charm->GetGUID());
16344 data << uint32(0x00000000);
16345 data << uint32(0);
16346 if(charm->GetTypeId() != TYPEID_PLAYER)
16347 data << uint8(charmInfo->GetReactState()) << uint8(charmInfo->GetCommandState());
16348 else
16349 data << uint8(0) << uint8(0);
16350 data << uint16(0);
16352 for(uint32 i = 0; i < 10; i++) //40
16354 data << uint16(charmInfo->GetActionBarEntry(i)->SpellOrAction) << uint16(charmInfo->GetActionBarEntry(i)->Type);
16357 data << uint8(addlist); //1
16359 if(addlist)
16361 for(uint32 i = 0; i < CREATURE_MAX_SPELLS; ++i)
16363 CharmSpellEntry *cspell = charmInfo->GetCharmSpell(i);
16364 if(cspell->spellId)
16366 data << uint16(cspell->spellId);
16367 data << uint16(cspell->active);
16372 uint8 count = 0;
16373 data << uint8(count); // cooldowns count
16375 GetSession()->SendPacket(&data);
16378 bool Player::IsAffectedBySpellmod(SpellEntry const *spellInfo, SpellModifier *mod, Spell const* spell)
16380 if (!mod || !spellInfo)
16381 return false;
16383 if(mod->charges == -1 && mod->lastAffected ) // marked as expired but locked until spell casting finish
16385 // prevent apply to any spell except spell that trigger expire
16386 if(spell)
16388 if(mod->lastAffected != spell)
16389 return false;
16391 else if(mod->lastAffected != FindCurrentSpellBySpellId(spellInfo->Id))
16392 return false;
16395 return spellmgr.IsAffectedByMod(spellInfo, mod);
16398 void Player::AddSpellMod(SpellModifier* mod, bool apply)
16400 uint16 Opcode= (mod->type == SPELLMOD_FLAT) ? SMSG_SET_FLAT_SPELL_MODIFIER : SMSG_SET_PCT_SPELL_MODIFIER;
16402 for(int eff=0;eff<96;++eff)
16404 uint64 _mask = 0;
16405 uint64 _mask2= 0;
16406 if (eff<64) _mask = uint64(1) << (eff- 0);
16407 else _mask2= uint64(1) << (eff-64);
16408 if ( mod->mask & _mask || mod->mask2 & _mask2)
16410 int32 val = 0;
16411 for (SpellModList::iterator itr = m_spellMods[mod->op].begin(); itr != m_spellMods[mod->op].end(); ++itr)
16413 if ((*itr)->type == mod->type && ((*itr)->mask & _mask || (*itr)->mask2 & _mask2))
16414 val += (*itr)->value;
16416 val += apply ? mod->value : -(mod->value);
16417 WorldPacket data(Opcode, (1+1+4));
16418 data << uint8(eff);
16419 data << uint8(mod->op);
16420 data << int32(val);
16421 SendDirectMessage(&data);
16425 if (apply)
16426 m_spellMods[mod->op].push_back(mod);
16427 else
16429 if (mod->charges == -1)
16430 --m_SpellModRemoveCount;
16431 m_spellMods[mod->op].remove(mod);
16432 delete mod;
16436 void Player::RemoveSpellMods(Spell const* spell)
16438 if(!spell || (m_SpellModRemoveCount == 0))
16439 return;
16441 for(int i=0;i<MAX_SPELLMOD;++i)
16443 for (SpellModList::iterator itr = m_spellMods[i].begin(); itr != m_spellMods[i].end();)
16445 SpellModifier *mod = *itr;
16446 ++itr;
16448 if (mod && mod->charges == -1 && (mod->lastAffected == spell || mod->lastAffected==NULL))
16450 RemoveAurasDueToSpell(mod->spellId);
16451 if (m_spellMods[i].empty())
16452 break;
16453 else
16454 itr = m_spellMods[i].begin();
16460 // send Proficiency
16461 void Player::SendProficiency(uint8 pr1, uint32 pr2)
16463 WorldPacket data(SMSG_SET_PROFICIENCY, 8);
16464 data << pr1 << pr2;
16465 GetSession()->SendPacket (&data);
16468 void Player::RemovePetitionsAndSigns(uint64 guid, uint32 type)
16470 QueryResult *result = NULL;
16471 if(type==10)
16472 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16473 else
16474 result = CharacterDatabase.PQuery("SELECT ownerguid,petitionguid FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16475 if(result)
16477 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.
16478 { // and SendPetitionQueryOpcode reads data from the DB
16479 Field *fields = result->Fetch();
16480 uint64 ownerguid = MAKE_NEW_GUID(fields[0].GetUInt32(), 0, HIGHGUID_PLAYER);
16481 uint64 petitionguid = MAKE_NEW_GUID(fields[1].GetUInt32(), 0, HIGHGUID_ITEM);
16483 // send update if charter owner in game
16484 Player* owner = objmgr.GetPlayer(ownerguid);
16485 if(owner)
16486 owner->GetSession()->SendPetitionQueryOpcode(petitionguid);
16488 } while ( result->NextRow() );
16490 delete result;
16492 if(type==10)
16493 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u'", GUID_LOPART(guid));
16494 else
16495 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE playerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16498 CharacterDatabase.BeginTransaction();
16499 if(type == 10)
16501 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u'", GUID_LOPART(guid));
16502 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u'", GUID_LOPART(guid));
16504 else
16506 CharacterDatabase.PExecute("DELETE FROM petition WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16507 CharacterDatabase.PExecute("DELETE FROM petition_sign WHERE ownerguid = '%u' AND type = '%u'", GUID_LOPART(guid), type);
16509 CharacterDatabase.CommitTransaction();
16512 void Player::SetRestBonus (float rest_bonus_new)
16514 // Prevent resting on max level
16515 if(getLevel() >= sWorld.getConfig(CONFIG_MAX_PLAYER_LEVEL))
16516 rest_bonus_new = 0;
16518 if(rest_bonus_new < 0)
16519 rest_bonus_new = 0;
16521 float rest_bonus_max = (float)GetUInt32Value(PLAYER_NEXT_LEVEL_XP)*1.5/2;
16523 if(rest_bonus_new > rest_bonus_max)
16524 m_rest_bonus = rest_bonus_max;
16525 else
16526 m_rest_bonus = rest_bonus_new;
16528 // update data for client
16529 if(m_rest_bonus>10)
16530 SetByteValue(PLAYER_BYTES_2, 3, 0x01); // Set Reststate = Rested
16531 else if(m_rest_bonus<=1)
16532 SetByteValue(PLAYER_BYTES_2, 3, 0x02); // Set Reststate = Normal
16534 //RestTickUpdate
16535 SetUInt32Value(PLAYER_REST_STATE_EXPERIENCE, uint32(m_rest_bonus));
16538 void Player::HandleStealthedUnitsDetection()
16540 std::list<Unit*> stealthedUnits;
16542 CellPair p(MaNGOS::ComputeCellPair(GetPositionX(),GetPositionY()));
16543 Cell cell(p);
16544 cell.data.Part.reserved = ALL_DISTRICT;
16545 cell.SetNoCreate();
16547 MaNGOS::AnyStealthedCheck u_check;
16548 MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck > searcher(stealthedUnits, u_check);
16550 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, WorldTypeMapContainer > world_unit_searcher(searcher);
16551 TypeContainerVisitor<MaNGOS::UnitListSearcher<MaNGOS::AnyStealthedCheck >, GridTypeMapContainer > grid_unit_searcher(searcher);
16553 CellLock<GridReadGuard> cell_lock(cell, p);
16554 cell_lock->Visit(cell_lock, world_unit_searcher, *GetMap());
16555 cell_lock->Visit(cell_lock, grid_unit_searcher, *GetMap());
16557 for (std::list<Unit*>::iterator i = stealthedUnits.begin(); i != stealthedUnits.end();)
16559 if((*i)==this)
16561 i = stealthedUnits.erase(i);
16562 continue;
16565 if ((*i)->isVisibleForOrDetect(this,true))
16568 (*i)->SendUpdateToPlayer(this);
16569 m_clientGUIDs.insert((*i)->GetGUID());
16571 #ifdef MANGOS_DEBUG
16572 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
16573 sLog.outDebug("Object %u (Type: %u) is detected in stealth by player %u. Distance = %f",(*i)->GetGUIDLow(),(*i)->GetTypeId(),GetGUIDLow(),GetDistance(*i));
16574 #endif
16576 // target aura duration for caster show only if target exist at caster client
16577 // send data at target visibility change (adding to client)
16578 if((*i)!=this && (*i)->isType(TYPEMASK_UNIT))
16579 SendAurasForTarget(*i);
16581 i = stealthedUnits.erase(i);
16582 continue;
16585 ++i;
16589 bool Player::ActivateTaxiPathTo(std::vector<uint32> const& nodes, uint32 mount_id, Creature* npc)
16591 if(nodes.size() < 2)
16592 return false;
16594 // not let cheating with start flight mounted
16595 if(IsMounted())
16597 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16598 data << uint32(ERR_TAXIPLAYERALREADYMOUNTED);
16599 GetSession()->SendPacket(&data);
16600 return false;
16603 if( m_ShapeShiftFormSpellId && m_form != FORM_BATTLESTANCE && m_form != FORM_BERSERKERSTANCE && m_form != FORM_DEFENSIVESTANCE && m_form != FORM_SHADOW )
16605 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16606 data << uint32(ERR_TAXIPLAYERSHAPESHIFTED);
16607 GetSession()->SendPacket(&data);
16608 return false;
16611 // 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
16612 if(GetSession()->isLogingOut() ||
16613 (!m_currentSpells[CURRENT_GENERIC_SPELL] ||
16614 m_currentSpells[CURRENT_GENERIC_SPELL]->m_spellInfo->Effect[0] != SPELL_EFFECT_SEND_TAXI)&&
16615 IsNonMeleeSpellCasted(false) ||
16616 isInCombat())
16618 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16619 data << uint32(ERR_TAXIPLAYERBUSY);
16620 GetSession()->SendPacket(&data);
16621 return false;
16624 if(HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE))
16625 return false;
16627 uint32 sourcenode = nodes[0];
16629 // starting node too far away (cheat?)
16630 TaxiNodesEntry const* node = sTaxiNodesStore.LookupEntry(sourcenode);
16631 if( !node || node->map_id != GetMapId() ||
16632 (node->x - GetPositionX())*(node->x - GetPositionX())+
16633 (node->y - GetPositionY())*(node->y - GetPositionY())+
16634 (node->z - GetPositionZ())*(node->z - GetPositionZ()) >
16635 (2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE)*(2*INTERACTION_DISTANCE) )
16637 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16638 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16639 GetSession()->SendPacket(&data);
16640 return false;
16643 // Prepare to flight start now
16645 // stop combat at start taxi flight if any
16646 CombatStop();
16648 // stop trade (client cancel trade at taxi map open but cheating tools can be used for reopen it)
16649 TradeCancel(true);
16651 // clean not finished taxi path if any
16652 m_taxi.ClearTaxiDestinations();
16654 // 0 element current node
16655 m_taxi.AddTaxiDestination(sourcenode);
16657 // fill destinations path tail
16658 uint32 sourcepath = 0;
16659 uint32 totalcost = 0;
16661 uint32 prevnode = sourcenode;
16662 uint32 lastnode = 0;
16664 for(uint32 i = 1; i < nodes.size(); ++i)
16666 uint32 path, cost;
16668 lastnode = nodes[i];
16669 objmgr.GetTaxiPath(prevnode, lastnode, path, cost);
16671 if(!path)
16673 m_taxi.ClearTaxiDestinations();
16674 return false;
16677 totalcost += cost;
16679 if(prevnode == sourcenode)
16680 sourcepath = path;
16682 m_taxi.AddTaxiDestination(lastnode);
16684 prevnode = lastnode;
16687 if(!mount_id) // if not provide then attempt use default.
16688 mount_id = objmgr.GetTaxiMount(sourcenode, GetTeam());
16690 if (mount_id == 0 || sourcepath == 0)
16692 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16693 data << uint32(ERR_TAXIUNSPECIFIEDSERVERERROR);
16694 GetSession()->SendPacket(&data);
16695 m_taxi.ClearTaxiDestinations();
16696 return false;
16699 uint32 money = GetMoney();
16701 if(npc)
16703 totalcost = (uint32)ceil(totalcost*GetReputationPriceDiscount(npc));
16706 if(money < totalcost)
16708 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16709 data << uint32(ERR_TAXINOTENOUGHMONEY);
16710 GetSession()->SendPacket(&data);
16711 m_taxi.ClearTaxiDestinations();
16712 return false;
16715 //Checks and preparations done, DO FLIGHT
16716 ModifyMoney(-(int32)totalcost);
16718 // prevent stealth flight
16719 RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH);
16721 WorldPacket data(SMSG_ACTIVATETAXIREPLY, 4);
16722 data << uint32(ERR_TAXIOK);
16723 GetSession()->SendPacket(&data);
16725 sLog.outDebug("WORLD: Sent SMSG_ACTIVATETAXIREPLY");
16727 GetSession()->SendDoFlight(mount_id, sourcepath);
16729 return true;
16732 void Player::ProhibitSpellScholl(SpellSchoolMask idSchoolMask, uint32 unTimeMs )
16734 // last check 2.0.10
16735 WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+m_spells.size()*8);
16736 data << GetGUID();
16737 data << uint8(0x0); // flags (0x1, 0x2)
16738 time_t curTime = time(NULL);
16739 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
16741 if (itr->second->state == PLAYERSPELL_REMOVED)
16742 continue;
16743 uint32 unSpellId = itr->first;
16744 SpellEntry const *spellInfo = sSpellStore.LookupEntry(unSpellId);
16745 if (!spellInfo)
16747 ASSERT(spellInfo);
16748 continue;
16751 // Not send cooldown for this spells
16752 if (spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE)
16753 continue;
16755 if((idSchoolMask & GetSpellSchoolMask(spellInfo)) && GetSpellCooldownDelay(unSpellId) < unTimeMs )
16757 data << unSpellId;
16758 data << unTimeMs; // in m.secs
16759 AddSpellCooldown(unSpellId, 0, curTime + unTimeMs/1000);
16762 GetSession()->SendPacket(&data);
16765 void Player::InitDataForForm(bool reapplyMods)
16767 SpellShapeshiftEntry const* ssEntry = sSpellShapeshiftStore.LookupEntry(m_form);
16768 if(ssEntry && ssEntry->attackSpeed)
16770 SetAttackTime(BASE_ATTACK,ssEntry->attackSpeed);
16771 SetAttackTime(OFF_ATTACK,ssEntry->attackSpeed);
16772 SetAttackTime(RANGED_ATTACK, BASE_ATTACK_TIME);
16774 else
16775 SetRegularAttackTime();
16777 switch(m_form)
16779 case FORM_CAT:
16781 if(getPowerType()!=POWER_ENERGY)
16782 setPowerType(POWER_ENERGY);
16783 break;
16785 case FORM_BEAR:
16786 case FORM_DIREBEAR:
16788 if(getPowerType()!=POWER_RAGE)
16789 setPowerType(POWER_RAGE);
16790 break;
16792 default: // 0, for example
16794 ChrClassesEntry const* cEntry = sChrClassesStore.LookupEntry(getClass());
16795 if(cEntry && cEntry->powerType < MAX_POWERS && uint32(getPowerType()) != cEntry->powerType)
16796 setPowerType(Powers(cEntry->powerType));
16797 break;
16801 // update auras at form change, ignore this at mods reapply (.reset stats/etc) when form not change.
16802 if (!reapplyMods)
16803 UpdateEquipSpellsAtFormChange();
16805 UpdateAttackPowerAndDamage();
16806 UpdateAttackPowerAndDamage(true);
16809 // Return true is the bought item has a max count to force refresh of window by caller
16810 bool Player::BuyItemFromVendor(uint64 vendorguid, uint32 item, uint8 count, uint64 bagguid, uint8 slot)
16812 // cheating attempt
16813 if(count < 1) count = 1;
16815 if(!isAlive())
16816 return false;
16818 ItemPrototype const *pProto = objmgr.GetItemPrototype( item );
16819 if( !pProto )
16821 SendBuyError( BUY_ERR_CANT_FIND_ITEM, NULL, item, 0);
16822 return false;
16825 Creature *pCreature = ObjectAccessor::GetNPCIfCanInteractWith(*this, vendorguid,UNIT_NPC_FLAG_VENDOR);
16826 if (!pCreature)
16828 sLog.outDebug( "WORLD: BuyItemFromVendor - Unit (GUID: %u) not found or you can't interact with him.", uint32(GUID_LOPART(vendorguid)) );
16829 SendBuyError( BUY_ERR_DISTANCE_TOO_FAR, NULL, item, 0);
16830 return false;
16833 VendorItemData const* vItems = pCreature->GetVendorItems();
16834 if(!vItems || vItems->Empty())
16836 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16837 return false;
16840 size_t vendor_slot = vItems->FindItemSlot(item);
16841 if(vendor_slot >= vItems->GetItemCount())
16843 SendBuyError( BUY_ERR_CANT_FIND_ITEM, pCreature, item, 0);
16844 return false;
16847 VendorItem const* crItem = vItems->m_items[vendor_slot];
16849 // check current item amount if it limited
16850 if( crItem->maxcount != 0 )
16852 if(pCreature->GetVendorItemCurrentCount(crItem) < pProto->BuyCount * count )
16854 SendBuyError( BUY_ERR_ITEM_ALREADY_SOLD, pCreature, item, 0);
16855 return false;
16859 if( uint32(GetReputationRank(pProto->RequiredReputationFaction)) < pProto->RequiredReputationRank)
16861 SendBuyError( BUY_ERR_REPUTATION_REQUIRE, pCreature, item, 0);
16862 return false;
16865 if(crItem->ExtendedCost)
16867 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16868 if(!iece)
16870 sLog.outError("Item %u have wrong ExtendedCost field value %u", pProto->ItemId, crItem->ExtendedCost);
16871 return false;
16874 // honor points price
16875 if(GetHonorPoints() < (iece->reqhonorpoints * count))
16877 SendEquipError(EQUIP_ERR_NOT_ENOUGH_HONOR_POINTS, NULL, NULL);
16878 return false;
16881 // arena points price
16882 if(GetArenaPoints() < (iece->reqarenapoints * count))
16884 SendEquipError(EQUIP_ERR_NOT_ENOUGH_ARENA_POINTS, NULL, NULL);
16885 return false;
16888 // item base price
16889 for (uint8 i = 0; i < 5; ++i)
16891 if(iece->reqitem[i] && !HasItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count)))
16893 SendEquipError(EQUIP_ERR_VENDOR_MISSING_TURNINS, NULL, NULL);
16894 return false;
16898 // check for personal arena rating requirement
16899 if( GetMaxPersonalArenaRatingRequirement() < iece->reqpersonalarenarating )
16901 // probably not the proper equip err
16902 SendEquipError(EQUIP_ERR_CANT_EQUIP_RANK,NULL,NULL);
16903 return false;
16907 uint32 price = pProto->BuyPrice * count;
16909 // reputation discount
16910 price = uint32(floor(price * GetReputationPriceDiscount(pCreature)));
16912 if( GetMoney() < price )
16914 SendBuyError( BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, item, 0);
16915 return false;
16918 uint8 bag = 0; // init for case invalid bagGUID
16920 if (bagguid != NULL_BAG && slot != NULL_SLOT)
16922 Bag *pBag;
16923 if( bagguid == GetGUID() )
16925 bag = INVENTORY_SLOT_BAG_0;
16927 else
16929 for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END;i++)
16931 pBag = (Bag*)GetItemByPos(INVENTORY_SLOT_BAG_0,i);
16932 if( pBag )
16934 if( bagguid == pBag->GetGUID() )
16936 bag = i;
16937 break;
16944 if( IsInventoryPos( bag, slot ) || (bagguid == NULL_BAG && slot == NULL_SLOT) )
16946 ItemPosCountVec dest;
16947 uint8 msg = CanStoreNewItem( bag, slot, dest, item, pProto->BuyCount * count );
16948 if( msg != EQUIP_ERR_OK )
16950 SendEquipError( msg, NULL, NULL );
16951 return false;
16954 ModifyMoney( -(int32)price );
16955 if(crItem->ExtendedCost) // case for new honor system
16957 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16958 if(iece->reqhonorpoints)
16959 ModifyHonorPoints( - int32(iece->reqhonorpoints * count));
16960 if(iece->reqarenapoints)
16961 ModifyArenaPoints( - int32(iece->reqarenapoints * count));
16962 for (uint8 i = 0; i < 5; ++i)
16964 if(iece->reqitem[i])
16965 DestroyItemCount(iece->reqitem[i], (iece->reqitemcount[i] * count), true);
16969 if(Item *it = StoreNewItem( dest, item, true ))
16971 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
16973 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
16974 data << pCreature->GetGUID();
16975 data << (uint32)(vendor_slot+1); // numbered from 1 at client
16976 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
16977 data << (uint32)count;
16978 GetSession()->SendPacket(&data);
16980 SendNewItem(it, pProto->BuyCount*count, true, false, false);
16983 else if( IsEquipmentPos( bag, slot ) )
16985 uint16 dest;
16986 uint8 msg = CanEquipNewItem( slot, dest, item, pProto->BuyCount * count, false );
16987 if( msg != EQUIP_ERR_OK )
16989 SendEquipError( msg, NULL, NULL );
16990 return false;
16993 ModifyMoney( -(int32)price );
16994 if(crItem->ExtendedCost) // case for new honor system
16996 ItemExtendedCostEntry const* iece = sItemExtendedCostStore.LookupEntry(crItem->ExtendedCost);
16997 if(iece->reqhonorpoints)
16998 ModifyHonorPoints( - int32(iece->reqhonorpoints));
16999 if(iece->reqarenapoints)
17000 ModifyArenaPoints( - int32(iece->reqarenapoints));
17001 for (uint8 i = 0; i < 5; ++i)
17003 if(iece->reqitem[i])
17004 DestroyItemCount(iece->reqitem[i], iece->reqitemcount[i], true);
17008 if(Item *it = EquipNewItem( dest, item, pProto->BuyCount * count, true ))
17010 uint32 new_count = pCreature->UpdateVendorItemCurrentCount(crItem,pProto->BuyCount * count);
17012 WorldPacket data(SMSG_BUY_ITEM, (8+4+4+4));
17013 data << pCreature->GetGUID();
17014 data << (uint32)(vendor_slot+1); // numbered from 1 at client
17015 data << (uint32)(crItem->maxcount > 0 ? new_count : 0xFFFFFFFF);
17016 data << (uint32)count;
17017 GetSession()->SendPacket(&data);
17019 SendNewItem(it, pProto->BuyCount*count, true, false, false);
17021 AutoUnequipOffhandIfNeed();
17024 else
17026 SendEquipError( EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, NULL, NULL );
17027 return false;
17030 return crItem->maxcount!=0;
17033 uint32 Player::GetMaxPersonalArenaRatingRequirement()
17035 // returns the maximal personal arena rating that can be used to purchase items requiring this condition
17036 // the personal rating of the arena team must match the required limit as well
17037 // so return max[in arenateams](min(personalrating[teamtype], teamrating[teamtype]))
17038 uint32 max_personal_rating = 0;
17039 for(int i = 0; i < MAX_ARENA_SLOT; ++i)
17041 if(ArenaTeam * at = objmgr.GetArenaTeamById(GetArenaTeamId(i)))
17043 uint32 p_rating = GetUInt32Value(PLAYER_FIELD_ARENA_TEAM_INFO_1_1 + (i * 6) + 5);
17044 uint32 t_rating = at->GetRating();
17045 p_rating = p_rating<t_rating? p_rating : t_rating;
17046 if(max_personal_rating < p_rating)
17047 max_personal_rating = p_rating;
17050 return max_personal_rating;
17053 void Player::UpdateHomebindTime(uint32 time)
17055 // GMs never get homebind timer online
17056 if (m_InstanceValid || isGameMaster())
17058 if(m_HomebindTimer) // instance valid, but timer not reset
17060 // hide reminder
17061 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17062 data << uint32(0);
17063 data << uint32(0);
17064 GetSession()->SendPacket(&data);
17066 // instance is valid, reset homebind timer
17067 m_HomebindTimer = 0;
17069 else if (m_HomebindTimer > 0)
17071 if (time >= m_HomebindTimer)
17073 // teleport to homebind location
17074 TeleportTo(m_homebindMapId, m_homebindX, m_homebindY, m_homebindZ, GetOrientation());
17076 else
17077 m_HomebindTimer -= time;
17079 else
17081 // instance is invalid, start homebind timer
17082 m_HomebindTimer = 60000;
17083 // send message to player
17084 WorldPacket data(SMSG_RAID_GROUP_ONLY, 4+4);
17085 data << m_HomebindTimer;
17086 data << uint32(1);
17087 GetSession()->SendPacket(&data);
17088 sLog.outDebug("PLAYER: Player '%s' (GUID: %u) will be teleported to homebind in 60 seconds", GetName(),GetGUIDLow());
17092 void Player::UpdatePvP(bool state, bool ovrride)
17094 if(!state || ovrride)
17096 SetPvP(state);
17097 if(Pet* pet = GetPet())
17098 pet->SetPvP(state);
17099 if(Unit* charmed = GetCharm())
17100 charmed->SetPvP(state);
17102 pvpInfo.endTimer = 0;
17104 else
17106 if(pvpInfo.endTimer != 0)
17107 pvpInfo.endTimer = time(NULL);
17108 else
17110 SetPvP(state);
17112 if(Pet* pet = GetPet())
17113 pet->SetPvP(state);
17114 if(Unit* charmed = GetCharm())
17115 charmed->SetPvP(state);
17120 void Player::AddSpellCooldown(uint32 spellid, uint32 itemid, time_t end_time)
17122 SpellCooldown sc;
17123 sc.end = end_time;
17124 sc.itemid = itemid;
17125 m_spellCooldowns[spellid] = sc;
17128 void Player::SendCooldownEvent(SpellEntry const *spellInfo)
17130 if ( !(spellInfo->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE) )
17131 return;
17133 // Get spell cooldown
17134 int32 cooldown = GetSpellRecoveryTime(spellInfo);
17135 // Apply spellmods
17136 ApplySpellMod(spellInfo->Id, SPELLMOD_COOLDOWN, cooldown);
17137 if (cooldown < 0)
17138 cooldown = 0;
17139 // Add cooldown
17140 AddSpellCooldown(spellInfo->Id, 0, time(NULL) + cooldown / 1000);
17141 // Send activate
17142 WorldPacket data(SMSG_COOLDOWN_EVENT, (4+8));
17143 data << spellInfo->Id;
17144 data << GetGUID();
17145 SendDirectMessage(&data);
17147 //slot to be excluded while counting
17148 bool Player::EnchantmentFitsRequirements(uint32 enchantmentcondition, int8 slot)
17150 if(!enchantmentcondition)
17151 return true;
17153 SpellItemEnchantmentConditionEntry const *Condition = sSpellItemEnchantmentConditionStore.LookupEntry(enchantmentcondition);
17155 if(!Condition)
17156 return true;
17158 uint8 curcount[4] = {0, 0, 0, 0};
17160 //counting current equipped gem colors
17161 for(uint8 i = EQUIPMENT_SLOT_START; i < EQUIPMENT_SLOT_END; ++i)
17163 if(i == slot)
17164 continue;
17165 Item *pItem2 = GetItemByPos( INVENTORY_SLOT_BAG_0, i );
17166 if(pItem2 && pItem2->GetProto()->Socket[0].Color)
17168 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17170 uint32 enchant_id = pItem2->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17171 if(!enchant_id)
17172 continue;
17174 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17175 if(!enchantEntry)
17176 continue;
17178 uint32 gemid = enchantEntry->GemID;
17179 if(!gemid)
17180 continue;
17182 ItemPrototype const* gemProto = sItemStorage.LookupEntry<ItemPrototype>(gemid);
17183 if(!gemProto)
17184 continue;
17186 GemPropertiesEntry const* gemProperty = sGemPropertiesStore.LookupEntry(gemProto->GemProperties);
17187 if(!gemProperty)
17188 continue;
17190 uint8 GemColor = gemProperty->color;
17192 for(uint8 b = 0, tmpcolormask = 1; b < 4; b++, tmpcolormask <<= 1)
17194 if(tmpcolormask & GemColor)
17195 ++curcount[b];
17201 bool activate = true;
17203 for(int i = 0; i < 5; i++)
17205 if(!Condition->Color[i])
17206 continue;
17208 uint32 _cur_gem = curcount[Condition->Color[i] - 1];
17210 // if have <CompareColor> use them as count, else use <value> from Condition
17211 uint32 _cmp_gem = Condition->CompareColor[i] ? curcount[Condition->CompareColor[i] - 1]: Condition->Value[i];
17213 switch(Condition->Comparator[i])
17215 case 2: // requires less <color> than (<value> || <comparecolor>) gems
17216 activate &= (_cur_gem < _cmp_gem) ? true : false;
17217 break;
17218 case 3: // requires more <color> than (<value> || <comparecolor>) gems
17219 activate &= (_cur_gem > _cmp_gem) ? true : false;
17220 break;
17221 case 5: // requires at least <color> than (<value> || <comparecolor>) gems
17222 activate &= (_cur_gem >= _cmp_gem) ? true : false;
17223 break;
17227 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");
17229 return activate;
17232 void Player::CorrectMetaGemEnchants(uint8 exceptslot, bool apply)
17234 //cycle all equipped items
17235 for(uint32 slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17237 //enchants for the slot being socketed are handled by Player::ApplyItemMods
17238 if(slot == exceptslot)
17239 continue;
17241 Item* pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17243 if(!pItem || !pItem->GetProto()->Socket[0].Color)
17244 continue;
17246 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17248 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17249 if(!enchant_id)
17250 continue;
17252 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17253 if(!enchantEntry)
17254 continue;
17256 uint32 condition = enchantEntry->EnchantmentCondition;
17257 if(condition)
17259 //was enchant active with/without item?
17260 bool wasactive = EnchantmentFitsRequirements(condition, apply ? exceptslot : -1);
17261 //should it now be?
17262 if(wasactive ^ EnchantmentFitsRequirements(condition, apply ? -1 : exceptslot))
17264 // ignore item gem conditions
17265 //if state changed, (dis)apply enchant
17266 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot),!wasactive,true,true);
17273 //if false -> then toggled off if was on| if true -> toggled on if was off AND meets requirements
17274 void Player::ToggleMetaGemsActive(uint8 exceptslot, bool apply)
17276 //cycle all equipped items
17277 for(int slot = EQUIPMENT_SLOT_START; slot < EQUIPMENT_SLOT_END; ++slot)
17279 //enchants for the slot being socketed are handled by WorldSession::HandleSocketOpcode(WorldPacket& recv_data)
17280 if(slot == exceptslot)
17281 continue;
17283 Item *pItem = GetItemByPos( INVENTORY_SLOT_BAG_0, slot );
17285 if(!pItem || !pItem->GetProto()->Socket[0].Color) //if item has no sockets or no item is equipped go to next item
17286 continue;
17288 //cycle all (gem)enchants
17289 for(uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT+3; ++enchant_slot)
17291 uint32 enchant_id = pItem->GetEnchantmentId(EnchantmentSlot(enchant_slot));
17292 if(!enchant_id) //if no enchant go to next enchant(slot)
17293 continue;
17295 SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(enchant_id);
17296 if(!enchantEntry)
17297 continue;
17299 //only metagems to be (de)activated, so only enchants with condition
17300 uint32 condition = enchantEntry->EnchantmentCondition;
17301 if(condition)
17302 ApplyEnchantment(pItem,EnchantmentSlot(enchant_slot), apply);
17307 void Player::LeaveBattleground(bool teleportToEntryPoint)
17309 if(BattleGround *bg = GetBattleGround())
17311 bool need_debuf = bg->isBattleGround() && (bg->GetStatus() == STATUS_IN_PROGRESS) && sWorld.getConfig(CONFIG_BATTLEGROUND_CAST_DESERTER);
17313 bg->RemovePlayerAtLeave(GetGUID(), teleportToEntryPoint, true);
17315 // call after remove to be sure that player resurrected for correct cast
17316 if(need_debuf)
17317 CastSpell(this, 26013, true); // Deserter
17321 bool Player::CanJoinToBattleground() const
17323 // check Deserter debuff
17324 if(GetDummyAura(26013))
17325 return false;
17327 return true;
17330 bool Player::CanReportAfkDueToLimit()
17332 // a player can complain about 15 people per 5 minutes
17333 if(m_bgAfkReportedCount >= 15)
17334 return false;
17335 ++m_bgAfkReportedCount;
17336 return true;
17339 ///This player has been blamed to be inactive in a battleground
17340 void Player::ReportedAfkBy(Player* reporter)
17342 BattleGround *bg = GetBattleGround();
17343 if(!bg || bg != reporter->GetBattleGround() || GetTeam() != reporter->GetTeam())
17344 return;
17346 // check if player has 'Idle' or 'Inactive' debuff
17347 if(m_bgAfkReporter.find(reporter->GetGUIDLow())==m_bgAfkReporter.end() && !HasAura(43680,0) && !HasAura(43681,0) && reporter->CanReportAfkDueToLimit())
17349 m_bgAfkReporter.insert(reporter->GetGUIDLow());
17350 // 3 players have to complain to apply debuff
17351 if(m_bgAfkReporter.size() >= 3)
17353 // cast 'Idle' spell
17354 CastSpell(this, 43680, true);
17355 m_bgAfkReporter.clear();
17360 bool Player::IsVisibleInGridForPlayer( Player* pl ) const
17362 // gamemaster in GM mode see all, including ghosts
17363 if(pl->isGameMaster() && GetSession()->GetSecurity() <= pl->GetSession()->GetSecurity())
17364 return true;
17366 // It seems in battleground everyone sees everyone, except the enemy-faction ghosts
17367 if (InBattleGround())
17369 if (!(isAlive() || m_deathTimer > 0) && !IsFriendlyTo(pl) )
17370 return false;
17371 return true;
17374 // Live player see live player or dead player with not realized corpse
17375 if(pl->isAlive() || pl->m_deathTimer > 0)
17377 return isAlive() || m_deathTimer > 0;
17380 // Ghost see other friendly ghosts, that's for sure
17381 if(!(isAlive() || m_deathTimer > 0) && IsFriendlyTo(pl))
17382 return true;
17384 // Dead player see live players near own corpse
17385 if(isAlive())
17387 Corpse *corpse = pl->GetCorpse();
17388 if(corpse)
17390 // 20 - aggro distance for same level, 25 - max additional distance if player level less that creature level
17391 if(corpse->IsWithinDistInMap(this,(20+25)*sWorld.getRate(RATE_CREATURE_AGGRO)))
17392 return true;
17396 // and not see any other
17397 return false;
17400 bool Player::IsVisibleGloballyFor( Player* u ) const
17402 if(!u)
17403 return false;
17405 // Always can see self
17406 if (u==this)
17407 return true;
17409 // Visible units, always are visible for all players
17410 if (GetVisibility() == VISIBILITY_ON)
17411 return true;
17413 // GMs are visible for higher gms (or players are visible for gms)
17414 if (u->GetSession()->GetSecurity() > SEC_PLAYER)
17415 return GetSession()->GetSecurity() <= u->GetSession()->GetSecurity();
17417 // non faction visibility non-breakable for non-GMs
17418 if (GetVisibility() == VISIBILITY_OFF)
17419 return false;
17421 // non-gm stealth/invisibility not hide from global player lists
17422 return true;
17425 void Player::UpdateVisibilityOf(WorldObject* target)
17427 if(HaveAtClient(target))
17429 if(!target->isVisibleForInState(this,true))
17431 target->DestroyForPlayer(this);
17432 m_clientGUIDs.erase(target->GetGUID());
17434 #ifdef MANGOS_DEBUG
17435 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17436 sLog.outDebug("Object %u (Type: %u) out of range for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17437 #endif
17440 else
17442 if(target->isVisibleForInState(this,false))
17444 target->SendUpdateToPlayer(this);
17445 if(target->GetTypeId()!=TYPEID_GAMEOBJECT||!((GameObject*)target)->IsTransport())
17446 m_clientGUIDs.insert(target->GetGUID());
17448 #ifdef MANGOS_DEBUG
17449 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17450 sLog.outDebug("Object %u (Type: %u) is visible now for player %u. Distance = %f",target->GetGUIDLow(),target->GetTypeId(),GetGUIDLow(),GetDistance(target));
17451 #endif
17453 // target aura duration for caster show only if target exist at caster client
17454 // send data at target visibility change (adding to client)
17455 if(target!=this && target->isType(TYPEMASK_UNIT))
17456 SendAurasForTarget((Unit*)target);
17458 if(target->GetTypeId()==TYPEID_UNIT && ((Creature*)target)->isAlive())
17459 ((Creature*)target)->SendMonsterMoveWithSpeedToCurrentDestination(this);
17464 template<class T>
17465 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, T* target)
17467 s64.insert(target->GetGUID());
17470 template<>
17471 inline void UpdateVisibilityOf_helper(std::set<uint64>& s64, GameObject* target)
17473 if(!target->IsTransport())
17474 s64.insert(target->GetGUID());
17477 template<class T>
17478 void Player::UpdateVisibilityOf(T* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow)
17480 if(HaveAtClient(target))
17482 if(!target->isVisibleForInState(this,true))
17484 target->BuildOutOfRangeUpdateBlock(&data);
17485 m_clientGUIDs.erase(target->GetGUID());
17487 #ifdef MANGOS_DEBUG
17488 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17489 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));
17490 #endif
17493 else
17495 if(target->isVisibleForInState(this,false))
17497 visibleNow.insert(target);
17498 target->BuildUpdate(data_updates);
17499 target->BuildCreateUpdateBlockForPlayer(&data, this);
17500 UpdateVisibilityOf_helper(m_clientGUIDs,target);
17502 #ifdef MANGOS_DEBUG
17503 if((sLog.getLogFilter() & LOG_FILTER_VISIBILITY_CHANGES)==0)
17504 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));
17505 #endif
17510 template void Player::UpdateVisibilityOf(Player* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17511 template void Player::UpdateVisibilityOf(Creature* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17512 template void Player::UpdateVisibilityOf(Corpse* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17513 template void Player::UpdateVisibilityOf(GameObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17514 template void Player::UpdateVisibilityOf(DynamicObject* target, UpdateData& data, UpdateDataMapType& data_updates, std::set<WorldObject*>& visibleNow);
17516 void Player::InitPrimaryProffesions()
17518 SetFreePrimaryProffesions(sWorld.getConfig(CONFIG_MAX_PRIMARY_TRADE_SKILL));
17521 void Player::SendComboPoints()
17523 Unit *combotarget = ObjectAccessor::GetUnit(*this, m_comboTarget);
17524 if (combotarget)
17526 WorldPacket data(SMSG_UPDATE_COMBO_POINTS, combotarget->GetPackGUID().size()+1);
17527 data.append(combotarget->GetPackGUID());
17528 data << uint8(m_comboPoints);
17529 GetSession()->SendPacket(&data);
17533 void Player::AddComboPoints(Unit* target, int8 count)
17535 if(!count)
17536 return;
17538 // without combo points lost (duration checked in aura)
17539 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17541 if(target->GetGUID() == m_comboTarget)
17543 m_comboPoints += count;
17545 else
17547 if(m_comboTarget)
17548 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17549 target->RemoveComboPointHolder(GetGUIDLow());
17551 m_comboTarget = target->GetGUID();
17552 m_comboPoints = count;
17554 target->AddComboPointHolder(GetGUIDLow());
17557 if (m_comboPoints > 5) m_comboPoints = 5;
17558 if (m_comboPoints < 0) m_comboPoints = 0;
17560 SendComboPoints();
17563 void Player::ClearComboPoints()
17565 if(!m_comboTarget)
17566 return;
17568 // without combopoints lost (duration checked in aura)
17569 RemoveSpellsCausingAura(SPELL_AURA_RETAIN_COMBO_POINTS);
17571 m_comboPoints = 0;
17573 SendComboPoints();
17575 if(Unit* target = ObjectAccessor::GetUnit(*this,m_comboTarget))
17576 target->RemoveComboPointHolder(GetGUIDLow());
17578 m_comboTarget = 0;
17581 void Player::SetGroup(Group *group, int8 subgroup)
17583 if(group == NULL) m_group.unlink();
17584 else
17586 // never use SetGroup without a subgroup unless you specify NULL for group
17587 assert(subgroup >= 0);
17588 m_group.link(group, this);
17589 m_group.setSubGroup((uint8)subgroup);
17593 void Player::SendInitialPacketsBeforeAddToMap()
17595 WorldPacket data(SMSG_SET_REST_START_OBSOLETE, 4);
17596 data << uint32(0); // unknown, may be rest state time or experience
17597 GetSession()->SendPacket(&data);
17599 // Homebind
17600 data.Initialize(SMSG_BINDPOINTUPDATE, 5*4);
17601 data << m_homebindX << m_homebindY << m_homebindZ;
17602 data << (uint32) m_homebindMapId;
17603 data << (uint32) m_homebindZoneId;
17604 GetSession()->SendPacket(&data);
17606 // SMSG_SET_PROFICIENCY
17607 // SMSG_UPDATE_AURA_DURATION
17609 // tutorial stuff
17610 data.Initialize(SMSG_TUTORIAL_FLAGS, 8*4);
17611 for (int i = 0; i < 8; ++i)
17612 data << uint32( GetTutorialInt(i) );
17613 GetSession()->SendPacket(&data);
17615 SendInitialSpells();
17617 data.Initialize(SMSG_SEND_UNLEARN_SPELLS, 4);
17618 data << uint32(0); // count, for(count) uint32;
17619 GetSession()->SendPacket(&data);
17621 SendInitialActionButtons();
17622 SendInitialReputations();
17623 m_achievementMgr.SendAllAchievementData();
17624 UpdateZone(GetZoneId());
17625 SendInitWorldStates();
17627 // SMSG_SET_AURA_SINGLE
17629 data.Initialize(SMSG_LOGIN_SETTIMESPEED, 8);
17630 data << uint32(secsToTimeBitFields(sWorld.GetGameTime()));
17631 data << (float)0.01666667f; // game speed
17632 GetSession()->SendPacket( &data );
17634 data.Initialize(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
17635 data << uint32(0x00000000); // on blizz it increments periodically
17636 GetSession()->SendPacket(&data);
17638 // set fly flag if in fly form or taxi flight to prevent visually drop at ground in showup moment
17639 if(HasAuraType(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED) || isInFlight())
17640 AddUnitMovementFlag(MOVEMENTFLAG_FLYING2);
17642 m_mover = this;
17645 void Player::SendInitialPacketsAfterAddToMap()
17647 WorldPacket data(SMSG_TIME_SYNC_REQ, 4); // new 2.0.x, enable movement
17648 data << uint32(0x00000000); // on blizz it increments periodically
17649 GetSession()->SendPacket(&data);
17651 CastSpell(this, 836, true); // LOGINEFFECT
17653 // set some aura effects that send packet to player client after add player to map
17654 // SendMessageToSet not send it to player not it map, only for aura that not changed anything at re-apply
17655 // same auras state lost at far teleport, send it one more time in this case also
17656 static const AuraType auratypes[] =
17658 SPELL_AURA_MOD_FEAR, SPELL_AURA_TRANSFORM, SPELL_AURA_WATER_WALK,
17659 SPELL_AURA_FEATHER_FALL, SPELL_AURA_HOVER, SPELL_AURA_SAFE_FALL,
17660 SPELL_AURA_FLY, SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED, SPELL_AURA_NONE
17662 for(AuraType const* itr = &auratypes[0]; itr && itr[0] != SPELL_AURA_NONE; ++itr)
17664 Unit::AuraList const& auraList = GetAurasByType(*itr);
17665 if(!auraList.empty())
17666 auraList.front()->ApplyModifier(true,true);
17669 if(HasAuraType(SPELL_AURA_MOD_STUN))
17670 SetMovement(MOVE_ROOT);
17672 // manual send package (have code in ApplyModifier(true,true); that don't must be re-applied.
17673 if(HasAuraType(SPELL_AURA_MOD_ROOT))
17675 WorldPacket data(SMSG_FORCE_MOVE_ROOT, 10);
17676 data.append(GetPackGUID());
17677 data << (uint32)2;
17678 SendMessageToSet(&data,true);
17681 SendAurasForTarget(this);
17682 SendEnchantmentDurations(); // must be after add to map
17683 SendItemDurations(); // must be after add to map
17686 void Player::SendUpdateToOutOfRangeGroupMembers()
17688 if (m_groupUpdateMask == GROUP_UPDATE_FLAG_NONE)
17689 return;
17690 if(Group* group = GetGroup())
17691 group->UpdatePlayerOutOfRange(this);
17693 m_groupUpdateMask = GROUP_UPDATE_FLAG_NONE;
17694 m_auraUpdateMask = 0;
17695 if(Pet *pet = GetPet())
17696 pet->ResetAuraUpdateMask();
17699 void Player::SendTransferAborted(uint32 mapid, uint8 reason, uint8 arg)
17701 WorldPacket data(SMSG_TRANSFER_ABORTED, 4+2);
17702 data << uint32(mapid);
17703 data << uint8(reason); // transfer abort reason
17704 switch(reason)
17706 case TRANSFER_ABORT_INSUF_EXPAN_LVL:
17707 case TRANSFER_ABORT_DIFFICULTY:
17708 case TRANSFER_ABORT_UNIQUE_MESSAGE:
17709 data << uint8(arg);
17710 break;
17712 GetSession()->SendPacket(&data);
17715 void Player::SendInstanceResetWarning(uint32 mapid, uint32 time)
17717 // type of warning, based on the time remaining until reset
17718 uint32 type;
17719 if(time > 3600)
17720 type = RAID_INSTANCE_WELCOME;
17721 else if(time > 900 && time <= 3600)
17722 type = RAID_INSTANCE_WARNING_HOURS;
17723 else if(time > 300 && time <= 900)
17724 type = RAID_INSTANCE_WARNING_MIN;
17725 else
17726 type = RAID_INSTANCE_WARNING_MIN_SOON;
17727 WorldPacket data(SMSG_RAID_INSTANCE_MESSAGE, 4+4+4);
17728 data << uint32(type);
17729 data << uint32(mapid);
17730 data << uint32(time);
17731 GetSession()->SendPacket(&data);
17734 void Player::ApplyEquipCooldown( Item * pItem )
17736 for(int i = 0; i <5; ++i)
17738 _Spell const& spellData = pItem->GetProto()->Spells[i];
17740 // no spell
17741 if( !spellData.SpellId )
17742 continue;
17744 // wrong triggering type (note: ITEM_SPELLTRIGGER_ON_NO_DELAY_USE not have cooldown)
17745 if( spellData.SpellTrigger != ITEM_SPELLTRIGGER_ON_USE )
17746 continue;
17748 AddSpellCooldown(spellData.SpellId, pItem->GetEntry(), time(NULL) + 30);
17750 WorldPacket data(SMSG_ITEM_COOLDOWN, 12);
17751 data << pItem->GetGUID();
17752 data << uint32(spellData.SpellId);
17753 GetSession()->SendPacket(&data);
17757 void Player::resetSpells()
17759 // not need after this call
17760 if(HasAtLoginFlag(AT_LOGIN_RESET_SPELLS))
17762 m_atLoginFlags = m_atLoginFlags & ~AT_LOGIN_RESET_SPELLS;
17763 CharacterDatabase.PExecute("UPDATE characters SET at_login = at_login & ~ %u WHERE guid ='%u'", uint32(AT_LOGIN_RESET_SPELLS), GetGUIDLow());
17766 // make full copy of map (spells removed and marked as deleted at another spell remove
17767 // and we can't use original map for safe iterative with visit each spell at loop end
17768 PlayerSpellMap smap = GetSpellMap();
17770 for(PlayerSpellMap::const_iterator iter = smap.begin();iter != smap.end(); ++iter)
17771 removeSpell(iter->first); // only iter->first can be accessed, object by iter->second can be deleted already
17773 learnDefaultSpells();
17774 learnQuestRewardedSpells();
17777 void Player::learnDefaultSpells(bool loading)
17779 // learn default race/class spells
17780 PlayerInfo const *info = objmgr.GetPlayerInfo(getRace(),getClass());
17781 std::list<CreateSpellPair>::const_iterator spell_itr;
17782 for (spell_itr = info->spell.begin(); spell_itr!=info->spell.end(); ++spell_itr)
17784 uint16 tspell = spell_itr->first;
17785 if (tspell)
17787 sLog.outDebug("PLAYER: Adding initial spell, id = %u",tspell);
17788 if(loading || !spell_itr->second) // not care about passive spells or loading case
17789 addSpell(tspell,spell_itr->second);
17790 else // but send in normal spell in game learn case
17791 learnSpell(tspell);
17796 void Player::learnQuestRewardedSpells(Quest const* quest)
17798 uint32 spell_id = quest->GetRewSpellCast();
17800 // skip quests without rewarded spell
17801 if( !spell_id )
17802 return;
17804 SpellEntry const *spellInfo = sSpellStore.LookupEntry(spell_id);
17805 if(!spellInfo)
17806 return;
17808 // check learned spells state
17809 bool found = false;
17810 for(int i=0; i < 3; ++i)
17812 if(spellInfo->Effect[i] == SPELL_EFFECT_LEARN_SPELL && !HasSpell(spellInfo->EffectTriggerSpell[i]))
17814 found = true;
17815 break;
17819 // skip quests with not teaching spell or already known spell
17820 if(!found)
17821 return;
17823 // prevent learn non first rank unknown profession and second specialization for same profession)
17824 uint32 learned_0 = spellInfo->EffectTriggerSpell[0];
17825 if( spellmgr.GetSpellRank(learned_0) > 1 && !HasSpell(learned_0) )
17827 // not have first rank learned (unlearned prof?)
17828 uint32 first_spell = spellmgr.GetFirstSpellInChain(learned_0);
17829 if( !HasSpell(first_spell) )
17830 return;
17832 SpellEntry const *learnedInfo = sSpellStore.LookupEntry(learned_0);
17833 if(!learnedInfo)
17834 return;
17836 // specialization
17837 if(learnedInfo->Effect[0]==SPELL_EFFECT_TRADE_SKILL && learnedInfo->Effect[1]==0)
17839 // search other specialization for same prof
17840 for(PlayerSpellMap::const_iterator itr = m_spells.begin(); itr != m_spells.end(); ++itr)
17842 if(itr->second->state == PLAYERSPELL_REMOVED || itr->first==learned_0)
17843 continue;
17845 SpellEntry const *itrInfo = sSpellStore.LookupEntry(itr->first);
17846 if(!itrInfo)
17847 return;
17849 // compare only specializations
17850 if(itrInfo->Effect[0]!=SPELL_EFFECT_TRADE_SKILL || itrInfo->Effect[1]!=0)
17851 continue;
17853 // compare same chain spells
17854 if(spellmgr.GetFirstSpellInChain(itr->first) != first_spell)
17855 continue;
17857 // now we have 2 specialization, learn possible only if found is lesser specialization rank
17858 if(!spellmgr.IsHighRankOfSpell(learned_0,itr->first))
17859 return;
17864 CastSpell( this, spell_id, true);
17867 void Player::learnQuestRewardedSpells()
17869 // learn spells received from quest completing
17870 for(QuestStatusMap::const_iterator itr = mQuestStatus.begin(); itr != mQuestStatus.end(); ++itr)
17872 // skip no rewarded quests
17873 if(!itr->second.m_rewarded)
17874 continue;
17876 Quest const* quest = objmgr.GetQuestTemplate(itr->first);
17877 if( !quest )
17878 continue;
17880 learnQuestRewardedSpells(quest);
17884 void Player::learnSkillRewardedSpells(uint32 skill_id )
17886 uint32 raceMask = getRaceMask();
17887 uint32 classMask = getClassMask();
17888 for (uint32 j=0; j<sSkillLineAbilityStore.GetNumRows(); ++j)
17890 SkillLineAbilityEntry const *pAbility = sSkillLineAbilityStore.LookupEntry(j);
17891 if (!pAbility || pAbility->skillId!=skill_id || pAbility->learnOnGetSkill != ABILITY_LEARNED_ON_GET_PROFESSION_SKILL)
17892 continue;
17893 // Check race if set
17894 if (pAbility->racemask && !(pAbility->racemask & raceMask))
17895 continue;
17896 // Check class if set
17897 if (pAbility->classmask && !(pAbility->classmask & classMask))
17898 continue;
17900 if (sSpellStore.LookupEntry(pAbility->spellId))
17902 // Ok need learn spell
17903 learnSpell(pAbility->spellId);
17908 void Player::learnSkillRewardedSpells()
17910 for (uint16 i=0; i < PLAYER_MAX_SKILLS; i++)
17912 if(!GetUInt32Value(PLAYER_SKILL_INDEX(i)))
17913 continue;
17915 uint32 pskill = GetUInt32Value(PLAYER_SKILL_INDEX(i)) & 0x0000FFFF;
17917 learnSkillRewardedSpells(pskill);
17921 void Player::SendAurasForTarget(Unit *target)
17923 if(target->GetVisibleAuras()->empty()) // speedup things
17924 return;
17926 WorldPacket data(SMSG_AURA_UPDATE_ALL);
17927 data.append(target->GetPackGUID());
17929 Unit::VisibleAuraMap const *visibleAuras = target->GetVisibleAuras();
17930 for(Unit::VisibleAuraMap::const_iterator itr = visibleAuras->begin(); itr != visibleAuras->end(); ++itr)
17932 for(uint32 j = 0; j < 3; ++j)
17934 if(Aura *aura = target->GetAura(itr->second, j))
17936 data << uint8(aura->GetAuraSlot());
17937 data << uint32(aura->GetId());
17939 if(aura->GetId())
17941 uint8 auraFlags = aura->GetAuraFlags();
17942 // flags
17943 data << uint8(auraFlags);
17944 // level
17945 data << uint8(aura->GetAuraLevel());
17946 // charges
17947 data << uint8(aura->m_procCharges >= 0 ? aura->m_procCharges : 0 );
17949 if(!(auraFlags & AFLAG_NOT_CASTER))
17951 data << uint8(0); // packed GUID of someone (caster?)
17954 if(auraFlags & AFLAG_DURATION) // include aura duration
17956 data << uint32(aura->GetAuraMaxDuration());
17957 data << uint32(aura->GetAuraDuration());
17960 break;
17965 GetSession()->SendPacket(&data);
17968 void Player::SetDailyQuestStatus( uint32 quest_id )
17970 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
17972 if(!GetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx))
17974 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,quest_id);
17975 m_lastDailyQuestTime = time(NULL); // last daily quest time
17976 m_DailyQuestChanged = true;
17977 break;
17982 void Player::ResetDailyQuestStatus()
17984 for(uint32 quest_daily_idx = 0; quest_daily_idx < PLAYER_MAX_DAILY_QUESTS; ++quest_daily_idx)
17985 SetUInt32Value(PLAYER_FIELD_DAILY_QUESTS_1+quest_daily_idx,0);
17987 // DB data deleted in caller
17988 m_DailyQuestChanged = false;
17989 m_lastDailyQuestTime = 0;
17992 BattleGround* Player::GetBattleGround() const
17994 if(GetBattleGroundId()==0)
17995 return NULL;
17997 return sBattleGroundMgr.GetBattleGround(GetBattleGroundId());
18000 bool Player::InArena() const
18002 BattleGround *bg = GetBattleGround();
18003 if(!bg || !bg->isArena())
18004 return false;
18006 return true;
18009 bool Player::GetBGAccessByLevel(uint32 bgTypeId) const
18011 BattleGround *bg = sBattleGroundMgr.GetBattleGround(bgTypeId);
18012 if(!bg)
18013 return false;
18015 if(getLevel() < bg->GetMinLevel() || getLevel() > bg->GetMaxLevel())
18016 return false;
18018 return true;
18021 uint32 Player::GetMinLevelForBattleGroundQueueId(uint32 queue_id)
18023 if(queue_id < 1)
18024 return 0;
18026 if(queue_id >=7)
18027 queue_id = 7;
18029 return 10*(queue_id+1);
18032 uint32 Player::GetMaxLevelForBattleGroundQueueId(uint32 queue_id)
18034 if(queue_id >=7)
18035 return 255; // hardcoded max level
18037 return 10*(queue_id+2)-1;
18040 uint32 Player::GetBattleGroundQueueIdFromLevel() const
18042 uint32 level = getLevel();
18043 if(level <= 19)
18044 return 0;
18045 else if (level > 79)
18046 return 7;
18047 else
18048 return level/10 - 1; // 20..29 -> 1, 30-39 -> 2, ...
18051 float Player::GetReputationPriceDiscount( Creature const* pCreature ) const
18053 FactionTemplateEntry const* vendor_faction = pCreature->getFactionTemplateEntry();
18054 if(!vendor_faction)
18055 return 1.0f;
18057 ReputationRank rank = GetReputationRank(vendor_faction->faction);
18058 if(rank <= REP_NEUTRAL)
18059 return 1.0f;
18061 return 1.0f - 0.05f* (rank - REP_NEUTRAL);
18064 bool Player::IsSpellFitByClassAndRace( uint32 spell_id ) const
18066 uint32 racemask = getRaceMask();
18067 uint32 classmask = getClassMask();
18069 SkillLineAbilityMap::const_iterator lower = spellmgr.GetBeginSkillLineAbilityMap(spell_id);
18070 SkillLineAbilityMap::const_iterator upper = spellmgr.GetEndSkillLineAbilityMap(spell_id);
18072 for(SkillLineAbilityMap::const_iterator _spell_idx = lower; _spell_idx != upper; ++_spell_idx)
18074 // skip wrong race skills
18075 if( _spell_idx->second->racemask && (_spell_idx->second->racemask & racemask) == 0)
18076 return false;
18078 // skip wrong class skills
18079 if( _spell_idx->second->classmask && (_spell_idx->second->classmask & classmask) == 0)
18080 return false;
18082 return true;
18085 bool Player::HasQuestForGO(int32 GOId)
18087 for( QuestStatusMap::iterator i = mQuestStatus.begin( ); i != mQuestStatus.end( ); ++i )
18089 QuestStatusData qs=i->second;
18090 if (qs.m_status == QUEST_STATUS_INCOMPLETE)
18092 Quest const* qinfo = objmgr.GetQuestTemplate(i->first);
18093 if(!qinfo)
18094 continue;
18096 if(GetGroup() && GetGroup()->isRaidGroup() && qinfo->GetType() != QUEST_TYPE_RAID)
18097 continue;
18099 for (int j = 0; j < QUEST_OBJECTIVES_COUNT; j++)
18101 if (qinfo->ReqCreatureOrGOId[j]>=0) //skip non GO case
18102 continue;
18104 if((-1)*GOId == qinfo->ReqCreatureOrGOId[j] && qs.m_creatureOrGOcount[j] < qinfo->ReqCreatureOrGOCount[j])
18105 return true;
18109 return false;
18112 void Player::UpdateForQuestsGO()
18114 if(m_clientGUIDs.empty())
18115 return;
18117 UpdateData udata;
18118 WorldPacket packet;
18119 for(ClientGUIDs::iterator itr=m_clientGUIDs.begin(); itr!=m_clientGUIDs.end(); ++itr)
18121 if(IS_GAMEOBJECT_GUID(*itr))
18123 GameObject *obj = HashMapHolder<GameObject>::Find(*itr);
18124 if(obj)
18125 obj->BuildValuesUpdateBlockForPlayer(&udata,this);
18128 udata.BuildPacket(&packet);
18129 GetSession()->SendPacket(&packet);
18132 void Player::SummonIfPossible(bool agree)
18134 if(!agree)
18136 m_summon_expire = 0;
18137 return;
18140 // expire and auto declined
18141 if(m_summon_expire < time(NULL))
18142 return;
18144 // stop taxi flight at summon
18145 if(isInFlight())
18147 GetMotionMaster()->MovementExpired();
18148 m_taxi.ClearTaxiDestinations();
18151 // drop flag at summon
18152 if(BattleGround *bg = GetBattleGround())
18153 bg->EventPlayerDroppedFlag(this);
18155 m_summon_expire = 0;
18157 TeleportTo(m_summon_mapid, m_summon_x, m_summon_y, m_summon_z,GetOrientation());
18160 void Player::RemoveItemDurations( Item *item )
18162 for(ItemDurationList::iterator itr = m_itemDuration.begin();itr != m_itemDuration.end(); ++itr)
18164 if(*itr==item)
18166 m_itemDuration.erase(itr);
18167 break;
18172 void Player::AddItemDurations( Item *item )
18174 if(item->GetUInt32Value(ITEM_FIELD_DURATION))
18176 m_itemDuration.push_back(item);
18177 item->SendTimeUpdate(this);
18181 void Player::AutoUnequipOffhandIfNeed()
18183 Item *offItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND );
18184 if(!offItem)
18185 return;
18187 Item *mainItem = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_MAINHAND );
18189 if(!mainItem || mainItem->GetProto()->InventoryType != INVTYPE_2HWEAPON)
18190 return;
18192 ItemPosCountVec off_dest;
18193 uint8 off_msg = CanStoreItem( NULL_BAG, NULL_SLOT, off_dest, offItem, false );
18194 if( off_msg == EQUIP_ERR_OK )
18196 RemoveItem(INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND, true);
18197 StoreItem( off_dest, offItem, true );
18199 else
18201 sLog.outError("Player::EquipItem: Can's store offhand item at 2hand item equip for player (GUID: %u).",GetGUIDLow());
18205 bool Player::HasItemFitToSpellReqirements(SpellEntry const* spellInfo, Item const* ignoreItem)
18207 if(spellInfo->EquippedItemClass < 0)
18208 return true;
18210 // scan other equipped items for same requirements (mostly 2 daggers/etc)
18211 // for optimize check 2 used cases only
18212 switch(spellInfo->EquippedItemClass)
18214 case ITEM_CLASS_WEAPON:
18216 for(int i= EQUIPMENT_SLOT_MAINHAND; i < EQUIPMENT_SLOT_TABARD; ++i)
18217 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18218 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18219 return true;
18220 break;
18222 case ITEM_CLASS_ARMOR:
18224 // tabard not have dependent spells
18225 for(int i= EQUIPMENT_SLOT_START; i< EQUIPMENT_SLOT_MAINHAND; ++i)
18226 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, i ))
18227 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18228 return true;
18230 // shields can be equipped to offhand slot
18231 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_OFFHAND))
18232 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18233 return true;
18235 // ranged slot can have some armor subclasses
18236 if(Item *item = GetItemByPos( INVENTORY_SLOT_BAG_0, EQUIPMENT_SLOT_RANGED))
18237 if(item!=ignoreItem && item->IsFitToSpellRequirements(spellInfo))
18238 return true;
18240 break;
18242 default:
18243 sLog.outError("HasItemFitToSpellReqirements: Not handled spell requirement for item class %u",spellInfo->EquippedItemClass);
18244 break;
18247 return false;
18250 void Player::RemoveItemDependentAurasAndCasts( Item * pItem )
18252 AuraMap& auras = GetAuras();
18253 for(AuraMap::iterator itr = auras.begin(); itr != auras.end(); )
18255 Aura* aura = itr->second;
18257 // skip passive (passive item dependent spells work in another way) and not self applied auras
18258 SpellEntry const* spellInfo = aura->GetSpellProto();
18259 if(aura->IsPassive() || aura->GetCasterGUID()!=GetGUID())
18261 ++itr;
18262 continue;
18265 // skip if not item dependent or have alternative item
18266 if(HasItemFitToSpellReqirements(spellInfo,pItem))
18268 ++itr;
18269 continue;
18272 // no alt item, remove aura, restart check
18273 RemoveAurasDueToSpell(aura->GetId());
18274 itr = auras.begin();
18277 // currently casted spells can be dependent from item
18278 for (uint32 i = 0; i < CURRENT_MAX_SPELL; i++)
18280 if( m_currentSpells[i] && m_currentSpells[i]->getState()!=SPELL_STATE_DELAYED &&
18281 !HasItemFitToSpellReqirements(m_currentSpells[i]->m_spellInfo,pItem) )
18282 InterruptSpell(i);
18286 uint32 Player::GetResurrectionSpellId()
18288 // search priceless resurrection possibilities
18289 uint32 prio = 0;
18290 uint32 spell_id = 0;
18291 AuraList const& dummyAuras = GetAurasByType(SPELL_AURA_DUMMY);
18292 for(AuraList::const_iterator itr = dummyAuras.begin(); itr != dummyAuras.end(); ++itr)
18294 // Soulstone Resurrection // prio: 3 (max, non death persistent)
18295 if( prio < 2 && (*itr)->GetSpellProto()->SpellVisual[0] == 99 && (*itr)->GetSpellProto()->SpellIconID == 92 )
18297 switch((*itr)->GetId())
18299 case 20707: spell_id = 3026; break; // rank 1
18300 case 20762: spell_id = 20758; break; // rank 2
18301 case 20763: spell_id = 20759; break; // rank 3
18302 case 20764: spell_id = 20760; break; // rank 4
18303 case 20765: spell_id = 20761; break; // rank 5
18304 case 27239: spell_id = 27240; break; // rank 6
18305 default:
18306 sLog.outError("Unhandled spell %%u: S.Resurrection",(*itr)->GetId());
18307 continue;
18310 prio = 3;
18312 // Twisting Nether // prio: 2 (max)
18313 else if((*itr)->GetId()==23701 && roll_chance_i(10))
18315 prio = 2;
18316 spell_id = 23700;
18320 // Reincarnation (passive spell) // prio: 1
18321 if(prio < 1 && HasSpell(20608) && !HasSpellCooldown(21169) && HasItemCount(17030,1))
18322 spell_id = 21169;
18324 return spell_id;
18327 bool Player::RewardPlayerAndGroupAtKill(Unit* pVictim)
18329 bool PvP = pVictim->isCharmedOwnedByPlayerOrPlayer();
18331 // prepare data for near group iteration (PvP and !PvP cases)
18332 uint32 xp = 0;
18333 bool honored_kill = false;
18335 if(Group *pGroup = GetGroup())
18337 uint32 count = 0;
18338 uint32 sum_level = 0;
18339 Player* member_with_max_level = NULL;
18340 Player* not_gray_member_with_max_level = NULL;
18342 pGroup->GetDataForXPAtKill(pVictim,count,sum_level,member_with_max_level,not_gray_member_with_max_level);
18344 if(member_with_max_level)
18346 /// not get Xp in PvP or no not gray players in group
18347 xp = (PvP || !not_gray_member_with_max_level) ? 0 : MaNGOS::XP::Gain(not_gray_member_with_max_level, pVictim);
18349 /// skip in check PvP case (for speed, not used)
18350 bool is_raid = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsRaid() && pGroup->isRaidGroup();
18351 bool is_dungeon = PvP ? false : sMapStore.LookupEntry(GetMapId())->IsDungeon();
18352 float group_rate = MaNGOS::XP::xp_in_group_rate(count,is_raid);
18354 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18356 Player* pGroupGuy = itr->getSource();
18357 if(!pGroupGuy)
18358 continue;
18360 if(!pGroupGuy->IsAtGroupRewardDistance(pVictim))
18361 continue; // member (alive or dead) or his corpse at req. distance
18363 // honor can be in PvP and !PvP (racial leader) cases (for alive)
18364 if(pGroupGuy->isAlive() && pGroupGuy->RewardHonor(pVictim,count) && pGroupGuy==this)
18365 honored_kill = true;
18367 // xp and reputation only in !PvP case
18368 if(!PvP)
18370 float rate = group_rate * float(pGroupGuy->getLevel()) / sum_level;
18372 // if is in dungeon then all receive full reputation at kill
18373 // rewarded any alive/dead/near_corpse group member
18374 pGroupGuy->RewardReputation(pVictim,is_dungeon ? 1.0f : rate);
18376 // XP updated only for alive group member
18377 if(pGroupGuy->isAlive() && not_gray_member_with_max_level &&
18378 pGroupGuy->getLevel() <= not_gray_member_with_max_level->getLevel())
18380 uint32 itr_xp = (member_with_max_level == not_gray_member_with_max_level) ? uint32(xp*rate) : uint32((xp*rate/2)+1);
18382 pGroupGuy->GiveXP(itr_xp, pVictim);
18383 if(Pet* pet = pGroupGuy->GetPet())
18384 pet->GivePetXP(itr_xp/2);
18387 // quest objectives updated only for alive group member or dead but with not released body
18388 if(pGroupGuy->isAlive()|| !pGroupGuy->GetCorpse())
18390 // normal creature (not pet/etc) can be only in !PvP case
18391 if(pVictim->GetTypeId()==TYPEID_UNIT)
18392 pGroupGuy->KilledMonster(pVictim->GetEntry(), pVictim->GetGUID());
18398 else // if (!pGroup)
18400 xp = PvP ? 0 : MaNGOS::XP::Gain(this, pVictim);
18402 // honor can be in PvP and !PvP (racial leader) cases
18403 if(RewardHonor(pVictim,1))
18404 honored_kill = true;
18406 // xp and reputation only in !PvP case
18407 if(!PvP)
18409 RewardReputation(pVictim,1);
18410 GiveXP(xp, pVictim);
18412 if(Pet* pet = GetPet())
18413 pet->GivePetXP(xp);
18415 // normal creature (not pet/etc) can be only in !PvP case
18416 if(pVictim->GetTypeId()==TYPEID_UNIT)
18417 KilledMonster(pVictim->GetEntry(),pVictim->GetGUID());
18420 return xp || honored_kill;
18423 bool Player::IsAtGroupRewardDistance(WorldObject const* pRewardSource) const
18425 if(pRewardSource->GetDistance(this) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE))
18426 return true;
18428 if(isAlive())
18429 return false;
18431 Corpse* corpse = GetCorpse();
18432 if(!corpse)
18433 return false;
18435 return pRewardSource->GetDistance(corpse) <= sWorld.getConfig(CONFIG_GROUP_XP_DISTANCE);
18438 uint32 Player::GetBaseWeaponSkillValue (WeaponAttackType attType) const
18440 Item* item = GetWeaponForAttack(attType,true);
18442 // unarmed only with base attack
18443 if(attType != BASE_ATTACK && !item)
18444 return 0;
18446 // weapon skill or (unarmed for base attack)
18447 uint32 skill = item ? item->GetSkill() : SKILL_UNARMED;
18448 return GetBaseSkillValue(skill);
18451 void Player::ResurectUsingRequestData()
18453 ResurrectPlayer(0.0f,false);
18455 if(GetMaxHealth() > m_resurrectHealth)
18456 SetHealth( m_resurrectHealth );
18457 else
18458 SetHealth( GetMaxHealth() );
18460 if(GetMaxPower(POWER_MANA) > m_resurrectMana)
18461 SetPower(POWER_MANA, m_resurrectMana );
18462 else
18463 SetPower(POWER_MANA, GetMaxPower(POWER_MANA) );
18465 SetPower(POWER_RAGE, 0 );
18467 SetPower(POWER_ENERGY, GetMaxPower(POWER_ENERGY) );
18469 SpawnCorpseBones();
18471 TeleportTo(m_resurrectMap, m_resurrectX, m_resurrectY, m_resurrectZ, GetOrientation());
18474 void Player::SetClientControl(Unit* target, uint8 allowMove)
18476 WorldPacket data(SMSG_CLIENT_CONTROL_UPDATE, target->GetPackGUID().size()+1);
18477 data.append(target->GetPackGUID());
18478 data << uint8(allowMove);
18479 GetSession()->SendPacket(&data);
18482 void Player::UpdateZoneDependentAuras( uint32 newZone )
18484 // remove new continent flight forms
18485 uint32 v_map = GetVirtualMapForMapAndZone(GetMapId(), newZone);
18486 if( !isGameMaster() && v_map != 530 && v_map != 571)
18488 RemoveSpellsCausingAura(SPELL_AURA_MOD_INCREASE_FLIGHT_SPEED);
18489 RemoveSpellsCausingAura(SPELL_AURA_FLY);
18492 // Some spells applied at enter into zone (with subzones)
18493 // Human Illusion
18494 // NOTE: these are removed by RemoveAurasWithInterruptFlags(AURA_INTERRUPT_FLAG_CHANGE_MAP);
18495 if ( newZone == 2367 ) // Old Hillsbrad Foothills
18497 uint32 spellid = 0;
18498 // all horde races
18499 if( GetTeam() == HORDE )
18500 spellid = getGender() == GENDER_FEMALE ? 35481 : 35480;
18501 // and some alliance races
18502 else if( getRace() == RACE_NIGHTELF || getRace() == RACE_DRAENEI )
18503 spellid = getGender() == GENDER_FEMALE ? 35483 : 35482;
18505 if(spellid && !HasAura(spellid,0) )
18506 CastSpell(this,spellid,true);
18510 void Player::UpdateAreaDependentAuras( uint32 newArea )
18512 // remove auras from spells with area limitations
18513 for(AuraMap::iterator iter = m_Auras.begin(); iter != m_Auras.end();)
18515 // use m_zoneUpdateId for speed: UpdateArea called from UpdateZone or instead UpdateZone in both cases m_zoneUpdateId up-to-date
18516 if(!IsSpellAllowedInLocation(iter->second->GetSpellProto(),GetMapId(),m_zoneUpdateId,newArea))
18517 RemoveAura(iter);
18518 else
18519 ++iter;
18522 // unmount if enter in this subzone
18523 if( newArea == 35)
18524 RemoveSpellsCausingAura(SPELL_AURA_MOUNTED);
18525 // Dragonmaw Illusion
18526 else if( newArea == 3759 || newArea == 3966 || newArea == 3939 )
18528 if( GetDummyAura(40214) )
18530 if( !HasAura(40216,0) )
18531 CastSpell(this,40216,true);
18532 if( !HasAura(42016,0) )
18533 CastSpell(this,42016,true);
18538 uint32 Player::GetCorpseReclaimDelay(bool pvp) const
18540 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18541 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18543 return copseReclaimDelay[0];
18546 time_t now = time(NULL);
18547 // 0..2 full period
18548 uint32 count = (now < m_deathExpireTime) ? (m_deathExpireTime - now)/DEATH_EXPIRE_STEP : 0;
18549 return copseReclaimDelay[count];
18552 void Player::UpdateCorpseReclaimDelay()
18554 bool pvp = m_ExtraFlags & PLAYER_EXTRA_PVP_DEATH;
18556 if( pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18557 !pvp && !sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18558 return;
18560 time_t now = time(NULL);
18561 if(now < m_deathExpireTime)
18563 // full and partly periods 1..3
18564 uint32 count = (m_deathExpireTime - now)/DEATH_EXPIRE_STEP +1;
18565 if(count < MAX_DEATH_COUNT)
18566 m_deathExpireTime = now+(count+1)*DEATH_EXPIRE_STEP;
18567 else
18568 m_deathExpireTime = now+MAX_DEATH_COUNT*DEATH_EXPIRE_STEP;
18570 else
18571 m_deathExpireTime = now+DEATH_EXPIRE_STEP;
18574 void Player::SendCorpseReclaimDelay(bool load)
18576 Corpse* corpse = GetCorpse();
18577 if(!corpse)
18578 return;
18580 uint32 delay;
18581 if(load)
18583 if(corpse->GetGhostTime() > m_deathExpireTime)
18584 return;
18586 bool pvp = corpse->GetType()==CORPSE_RESURRECTABLE_PVP;
18588 uint32 count;
18589 if( pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVP) ||
18590 !pvp && sWorld.getConfig(CONFIG_DEATH_CORPSE_RECLAIM_DELAY_PVE) )
18592 count = (m_deathExpireTime-corpse->GetGhostTime())/DEATH_EXPIRE_STEP;
18593 if(count>=MAX_DEATH_COUNT)
18594 count = MAX_DEATH_COUNT-1;
18596 else
18597 count=0;
18599 time_t expected_time = corpse->GetGhostTime()+copseReclaimDelay[count];
18601 time_t now = time(NULL);
18602 if(now >= expected_time)
18603 return;
18605 delay = expected_time-now;
18607 else
18608 delay = GetCorpseReclaimDelay(corpse->GetType()==CORPSE_RESURRECTABLE_PVP);
18610 //! corpse reclaim delay 30 * 1000ms or longer at often deaths
18611 WorldPacket data(SMSG_CORPSE_RECLAIM_DELAY, 4);
18612 data << uint32(delay*1000);
18613 GetSession()->SendPacket( &data );
18616 Player* Player::GetNextRandomRaidMember(float radius)
18618 Group *pGroup = GetGroup();
18619 if(!pGroup)
18620 return NULL;
18622 std::vector<Player*> nearMembers;
18623 nearMembers.reserve(pGroup->GetMembersCount());
18625 for(GroupReference *itr = pGroup->GetFirstMember(); itr != NULL; itr = itr->next())
18627 Player* Target = itr->getSource();
18629 // IsHostileTo check duel and controlled by enemy
18630 if( Target && Target != this && IsWithinDistInMap(Target, radius) &&
18631 !Target->HasInvisibilityAura() && !IsHostileTo(Target) )
18632 nearMembers.push_back(Target);
18635 if (nearMembers.empty())
18636 return NULL;
18638 uint32 randTarget = urand(0,nearMembers.size()-1);
18639 return nearMembers[randTarget];
18642 PartyResult Player::CanUninviteFromGroup() const
18644 const Group* grp = GetGroup();
18645 if(!grp)
18646 return PARTY_RESULT_YOU_NOT_IN_GROUP;
18648 if(!grp->IsLeader(GetGUID()) && !grp->IsAssistant(GetGUID()))
18649 return PARTY_RESULT_YOU_NOT_LEADER;
18651 if(InBattleGround())
18652 return PARTY_RESULT_INVITE_RESTRICTED;
18654 return PARTY_RESULT_OK;
18657 void Player::UpdateUnderwaterState( Map* m, float x, float y, float z )
18659 float water_z = m->GetWaterLevel(x,y);
18660 float height_z = m->GetHeight(x,y,z, false); // use .map base surface height
18661 uint8 flag1 = m->GetTerrainType(x,y);
18663 //!Underwater check, not in water if underground or above water level
18664 if (height_z <= INVALID_HEIGHT || z < (height_z-2) || z > (water_z - 2) )
18665 m_isunderwater &= 0x7A;
18666 else if ((z < (water_z - 2)) && (flag1 & 0x01))
18667 m_isunderwater |= 0x01;
18669 //!in lava check, anywhere under lava level
18670 if ((height_z <= INVALID_HEIGHT || z < (height_z - 0)) && (flag1 == 0x00) && IsInWater())
18671 m_isunderwater |= 0x80;
18674 void Player::SetCanParry( bool value )
18676 if(m_canParry==value)
18677 return;
18679 m_canParry = value;
18680 UpdateParryPercentage();
18683 void Player::SetCanBlock( bool value )
18685 if(m_canBlock==value)
18686 return;
18688 m_canBlock = value;
18689 UpdateBlockPercentage();
18692 bool ItemPosCount::isContainedIn(ItemPosCountVec const& vec) const
18694 for(ItemPosCountVec::const_iterator itr = vec.begin(); itr != vec.end();++itr)
18695 if(itr->pos == pos)
18696 return true;
18698 return false;
18701 bool Player::isAllowUseBattleGroundObject()
18703 return ( //InBattleGround() && // in battleground - not need, check in other cases
18704 !IsMounted() && // not mounted
18705 !HasStealthAura() && // not stealthed
18706 !HasInvisibilityAura() && // not invisible
18707 !HasAura(SPELL_RECENTLY_DROPPED_FLAG, 0) && // can't pickup
18708 isAlive() // live player
18712 uint32 Player::GetBarberShopCost(uint8 newhairstyle, uint8 newhaircolor, uint8 newfacialhair)
18714 uint32 level = getLevel();
18716 if(level > sGtBarberShopCostBaseStore.GetNumRows())
18717 level = GT_MAX_LEVEL; // max level in this dbc
18719 uint8 hairstyle = GetByteValue(PLAYER_BYTES, 2);
18720 uint8 haircolor = GetByteValue(PLAYER_BYTES, 3);
18721 uint8 facialhair = GetByteValue(PLAYER_BYTES_2, 0);
18723 if((hairstyle == newhairstyle) && (haircolor == newhaircolor) && (facialhair == newfacialhair))
18724 return 0;
18726 GtBarberShopCostBaseEntry const *bsc = sGtBarberShopCostBaseStore.LookupEntry(level - 1);
18728 if(!bsc) // shouldn't happen
18729 return 0xFFFFFFFF;
18731 float cost = 0;
18733 if(hairstyle != newhairstyle)
18734 cost += bsc->cost; // full price
18736 if((haircolor != newhaircolor) && (hairstyle == newhairstyle))
18737 cost += bsc->cost * 0.5f; // +1/2 of price
18739 if(facialhair != newfacialhair)
18740 cost += bsc->cost * 0.75f; // +3/4 of price
18742 return uint32(cost);
18745 void Player::InitGlyphsForLevel()
18747 uint32 level = getLevel();
18748 uint32 value = 0;
18750 // 0x3F = 0x01 | 0x02 | 0x04 | 0x08 | 0x10 | 0x20 for 80 level
18751 if(level >= 15)
18752 value |= (0x01 | 0x02);
18753 if(level >= 30)
18754 value |= 0x04;
18755 if(level >= 50)
18756 value |= 0x08;
18757 if(level >= 70)
18758 value |= 0x10;
18759 if(level >= 80)
18760 value |= 0x20;
18762 SetUInt32Value(PLAYER_GLYPHS_ENABLED, value);
18765 void Player::EnterVehicle(Vehicle *vehicle)
18767 VehicleEntry const *ve = sVehicleStore.LookupEntry(vehicle->GetVehicleId());
18768 if(!ve)
18769 return;
18771 VehicleSeatEntry const *veSeat = sVehicleSeatStore.LookupEntry(ve->m_seatID[0]);
18772 if(!veSeat)
18773 return;
18775 vehicle->SetCharmerGUID(GetGUID());
18776 vehicle->RemoveFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
18777 vehicle->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNKNOWN5);
18778 vehicle->setFaction(getFaction());
18780 SetCharm(vehicle); // charm
18781 SetFarSight(vehicle->GetGUID()); // set view
18783 SetClientControl(vehicle, 1); // redirect controls to vehicle
18785 WorldPacket data(SMSG_ON_CANCEL_EXPECTED_RIDE_VEHICLE_AURA, 0);
18786 GetSession()->SendPacket(&data);
18788 data.Initialize(MSG_MOVE_TELEPORT_ACK, 30);
18789 data.append(GetPackGUID());
18790 data << uint32(0); // counter?
18791 data << uint32(MOVEMENTFLAG_ONTRANSPORT); // transport
18792 data << uint16(0); // special flags
18793 data << uint32(getMSTime()); // time
18794 data << vehicle->GetPositionX(); // x
18795 data << vehicle->GetPositionY(); // y
18796 data << vehicle->GetPositionZ(); // z
18797 data << vehicle->GetOrientation(); // o
18798 // transport part, TODO: load/calculate seat offsets
18799 data << uint64(vehicle->GetGUID()); // transport guid
18800 data << float(veSeat->m_attachmentOffsetX); // transport offsetX
18801 data << float(veSeat->m_attachmentOffsetY); // transport offsetY
18802 data << float(veSeat->m_attachmentOffsetZ); // transport offsetZ
18803 data << float(0); // transport orientation
18804 data << uint32(getMSTime()); // transport time
18805 data << uint8(0); // seat
18806 // end of transport part
18807 data << uint32(0); // fall time
18808 GetSession()->SendPacket(&data);
18810 data.Initialize(SMSG_PET_SPELLS, 8+4+4+4+4*10+1+1);
18811 data << uint64(vehicle->GetGUID());
18812 data << uint32(0x00000000);
18813 data << uint32(0x00000000);
18814 data << uint32(0x00000101);
18816 for(uint32 i = 0; i < 10; ++i)
18817 data << uint16(0) << uint8(0) << uint8(i+8);
18819 data << uint8(0);
18820 data << uint8(0);
18821 GetSession()->SendPacket(&data);
18824 void Player::ExitVehicle(Vehicle *vehicle)
18826 vehicle->SetCharmerGUID(0);
18827 vehicle->SetFlag(UNIT_NPC_FLAGS, UNIT_NPC_FLAG_SPELLCLICK);
18828 vehicle->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_UNKNOWN5);
18829 vehicle->setFaction((GetTeam() == ALLIANCE) ? vehicle->GetCreatureInfo()->faction_A : vehicle->GetCreatureInfo()->faction_H);
18831 SetCharm(NULL);
18832 SetFarSight(NULL);
18834 SetClientControl(vehicle, 0);
18836 WorldPacket data(MSG_MOVE_TELEPORT_ACK, 30);
18837 data.append(GetPackGUID());
18838 data << uint32(0); // counter?
18839 data << uint32(MOVEMENTFLAG_FLY_UNK1); // fly unk
18840 data << uint16(0x40); // special flags
18841 data << uint32(getMSTime()); // time
18842 data << vehicle->GetPositionX(); // x
18843 data << vehicle->GetPositionY(); // y
18844 data << vehicle->GetPositionZ(); // z
18845 data << vehicle->GetOrientation(); // o
18846 data << uint32(0); // fall time
18847 GetSession()->SendPacket(&data);
18849 data.Initialize(SMSG_PET_SPELLS, 8+4);
18850 data << uint64(0);
18851 data << uint32(0);
18852 GetSession()->SendPacket(&data);
18854 // only for flyable vehicles?
18855 CastSpell(this, 45472, true); // Parachute
18858 bool Player::HasTitle(uint32 bitIndex)
18860 if (bitIndex > 128)
18861 return false;
18863 uint32 fieldIndexOffset = bitIndex/32;
18864 uint32 flag = 1 << (bitIndex%32);
18865 return HasFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
18868 void Player::SetTitle(CharTitlesEntry const* title)
18870 uint32 fieldIndexOffset = title->bit_index/32;
18871 uint32 flag = 1 << (title->bit_index%32);
18872 SetFlag(PLAYER__FIELD_KNOWN_TITLES+fieldIndexOffset, flag);
18875 void Player::ConvertRune(uint8 index, uint8 newType)
18877 SetCurrentRune(index, newType);
18879 WorldPacket data(SMSG_CONVERT_RUNE, 2);
18880 data << uint8(index);
18881 data << uint8(newType);
18882 GetSession()->SendPacket(&data);
18885 void Player::ResyncRunes(uint8 count)
18887 WorldPacket data(SMSG_RESYNC_RUNES, count * 2);
18888 for(uint32 i = 0; i < count; ++i)
18890 data << uint8(GetCurrentRune(i)); // rune type
18891 data << uint8(255 - (GetRuneCooldown(i) * 51)); // passed cooldown time (0-255)
18893 GetSession()->SendPacket(&data);
18896 void Player::AddRunePower(uint8 index)
18898 WorldPacket data(SMSG_ADD_RUNE_POWER, 4);
18899 data << uint32(1 << index); // mask (0x00-0x3F probably)
18900 GetSession()->SendPacket(&data);
18903 void Player::InitRunes()
18905 if(getClass() != CLASS_DEATH_KNIGHT)
18906 return;
18908 m_runes = new Runes;
18910 m_runes->runeState = 0;
18912 for(uint32 i = 0; i < MAX_RUNES; ++i)
18914 SetBaseRune(i, i / 2); // init base types
18915 SetCurrentRune(i, i / 2); // init current types
18916 SetRuneCooldown(i, 0); // reset cooldowns
18917 m_runes->SetRuneState(i);
18920 for(uint32 i = 0; i < NUM_RUNE_TYPES; ++i)
18921 SetFloatValue(PLAYER_RUNE_REGEN_1 + i, 0.1f);